diff --git "a/test.csv" "b/test.csv" new file mode 100644--- /dev/null +++ "b/test.csv" @@ -0,0 +1,118240 @@ +commit_id,project,commit_message,type,url,git_diff +4f8fa5ff72b1ae2ef4a5c2e4be4f9c8f749da9bb,Delta Spike,"DELTASPIKE-315 add more JavaDoc +",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java +index 45e94581f..5d16153c6 100644 +--- a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java ++++ b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java +@@ -35,7 +35,7 @@ + * EntityManagerFactoryProducer. + */ + @Target( { TYPE, METHOD, PARAMETER, FIELD }) +-@Retention(value= RetentionPolicy.RUNTIME) ++@Retention(value = RetentionPolicy.RUNTIME) + @Documented + @Qualifier + public @interface PersistenceUnitName +diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java +index 05129f3a5..002e28cb8 100644 +--- a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java ++++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java +@@ -32,7 +32,32 @@ + + + /** +- * TODO ++ *

Built in support for injecting EntityManagerFactories into own beans. ++ * The injection point must use the Qualifier {@link PersistenceUnitName} ++ * to express the desired persistence unit name.

++ * ++ *

The EntityManagerFactory for the given persistence unit will be produced ++ * as @Dependent scoped. It can be used to easily implement own ++ * EntityManagerProviders as shown in the following example which provides ++ * a producer according to the entitymanager-per-request design pattern:

++ *
++ * @ApplicationScoped
++ * public class SampleEntityManagerProducer {
++ *   @Inject
++ *   @PersistenceUnitName(""testPersistenceUnit"")
++ *   private EntityManagerFactory emf;
++ *
++ *   @Produces
++ *   @RequestScoped
++ *   public EntityManager createEntityManager() {
++ *     return emf.createEntityManager();
++ *   }
++ *
++ *   public void closeEm(@Disposes EntityManager em) {
++ *     em.close();
++ *   }
++ * }
++ *  
+ */ + public class EntityManagerFactoryProducer + { +@@ -44,7 +69,7 @@ public class EntityManagerFactoryProducer + + @Produces + @Dependent +- @PersistenceUnitName(""any"") // the value is nonbinding, thus this is just a dummy parameter here ++ @PersistenceUnitName(""any"") // the value is nonbinding, thus 'any' is just a dummy parameter here + public EntityManagerFactory createEntityManagerFactoryForUnit(InjectionPoint injectionPoint) + { + PersistenceUnitName unitNameAnnotation = injectionPoint.getAnnotated().getAnnotation(PersistenceUnitName.class);" +53c2131d4411fac6fbe43fc757bc6acea780e2a1,crashub$crash,"Add flexibility for plugin a custom class manager +",p,https://github.com/crashub/crash,"diff --git a/shell/core/src/main/java/org/crsh/shell/impl/command/AbstractClassManager.java b/shell/core/src/main/java/org/crsh/shell/impl/command/AbstractClassManager.java +new file mode 100644 +index 000000000..f9a8180ba +--- /dev/null ++++ b/shell/core/src/main/java/org/crsh/shell/impl/command/AbstractClassManager.java +@@ -0,0 +1,143 @@ ++/* ++ * Copyright (C) 2012 eXo Platform SAS. ++ * ++ * This is free software; you can redistribute it and/or modify it ++ * under the terms of the GNU Lesser General Public License as ++ * published by the Free Software Foundation; either version 2.1 of ++ * the License, or (at your option) any later version. ++ * ++ * This software is distributed in the hope that it will be useful, ++ * but WITHOUT ANY WARRANTY; without even the implied warranty of ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ++ * Lesser General Public License for more details. ++ * ++ * You should have received a copy of the GNU Lesser General Public ++ * License along with this software; if not, write to the Free ++ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA ++ * 02110-1301 USA, or see the FSF site: http://www.fsf.org. ++ */ ++ ++package org.crsh.shell.impl.command; ++ ++import groovy.lang.GroovyClassLoader; ++import groovy.lang.GroovyCodeSource; ++import groovy.lang.Script; ++import org.codehaus.groovy.control.CompilationFailedException; ++import org.codehaus.groovy.control.CompilerConfiguration; ++import org.crsh.command.CommandInvoker; ++import org.crsh.command.NoSuchCommandException; ++import org.crsh.plugin.PluginContext; ++import org.crsh.shell.ErrorType; ++import org.crsh.util.TimestampedObject; ++import org.crsh.vfs.Resource; ++ ++import java.io.UnsupportedEncodingException; ++ ++public abstract class AbstractClassManager { ++ ++ /** . */ ++ private final PluginContext context; ++ ++ /** . */ ++ private final CompilerConfiguration config; ++ ++ /** . */ ++ private final Class baseClass; ++ ++ protected AbstractClassManager(PluginContext context, Class baseClass, Class baseScriptClass) { ++ CompilerConfiguration config = new CompilerConfiguration(); ++ config.setRecompileGroovySource(true); ++ config.setScriptBaseClass(baseScriptClass.getName()); ++ ++ // ++ this.context = context; ++ this.config = config; ++ this.baseClass = baseClass; ++ } ++ ++ protected abstract TimestampedObject> loadClass(String name); ++ ++ protected abstract void saveClass(String name, TimestampedObject> clazz); ++ ++ protected abstract Resource getResource(String name); ++ ++ Class getClass(String name) throws NoSuchCommandException, NullPointerException { ++ if (name == null) { ++ throw new NullPointerException(""No null argument allowed""); ++ } ++ ++ TimestampedObject> providerRef = loadClass(name); ++ ++ // ++ Resource script = getResource(name); ++ ++ // ++ if (script != null) { ++ if (providerRef != null) { ++ if (script.getTimestamp() != providerRef.getTimestamp()) { ++ providerRef = null; ++ } ++ } ++ ++ // ++ if (providerRef == null) { ++ ++ // ++ String source; ++ try { ++ source = new String(script.getContent(), ""UTF-8""); ++ } ++ catch (UnsupportedEncodingException e) { ++ throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); ++ } ++ ++ // ++ Class clazz; ++ try { ++ GroovyCodeSource gcs = new GroovyCodeSource(source, name, ""/groovy/shell""); ++ GroovyClassLoader gcl = new GroovyClassLoader(context.getLoader(), config); ++ clazz = gcl.parseClass(gcs, false); ++ } ++ catch (NoClassDefFoundError e) { ++ throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); ++ } ++ catch (CompilationFailedException e) { ++ throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); ++ } ++ ++ // ++ if (baseClass.isAssignableFrom(clazz)) { ++ Class providerClass = clazz.asSubclass(baseClass); ++ providerRef = new TimestampedObject>(script.getTimestamp(), providerClass); ++ saveClass(name, providerRef); ++ } else { ++ throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Parsed script "" + clazz.getName() + ++ "" does not implements "" + CommandInvoker.class.getName()); ++ } ++ } ++ } ++ ++ // ++ if (providerRef == null) { ++ return null; ++ } ++ ++ // ++ return providerRef.getObject(); ++ } ++ ++ T getInstance(String name) throws NoSuchCommandException, NullPointerException { ++ Class clazz = getClass(name); ++ if (clazz == null) { ++ return null; ++ } ++ ++ // ++ try { ++ return clazz.newInstance(); ++ } ++ catch (Exception e) { ++ throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not create command "" + name + "" instance"", e); ++ } ++ } ++} +diff --git a/shell/core/src/main/java/org/crsh/shell/impl/command/CRaSH.java b/shell/core/src/main/java/org/crsh/shell/impl/command/CRaSH.java +index ce0d38949..35c96e519 100644 +--- a/shell/core/src/main/java/org/crsh/shell/impl/command/CRaSH.java ++++ b/shell/core/src/main/java/org/crsh/shell/impl/command/CRaSH.java +@@ -19,7 +19,6 @@ + + package org.crsh.shell.impl.command; + +-import groovy.lang.Script; + import org.crsh.command.GroovyScript; + import org.crsh.command.GroovyScriptCommand; + import org.crsh.command.NoSuchCommandException; +@@ -33,10 +32,10 @@ public class CRaSH { + + + /** . */ +- final ClassManager commandManager; ++ final AbstractClassManager commandManager; + + /** . */ +- final ClassManager scriptManager; ++ final AbstractClassManager scriptManager; + + /** . */ + final PluginContext context; +@@ -55,7 +54,7 @@ public CRaSH(PluginContext context) throws NullPointerException { + ); + } + +- public CRaSH(PluginContext context, ClassManager commandManager, ClassManager scriptManager) { ++ public CRaSH(PluginContext context, AbstractClassManager commandManager, AbstractClassManager scriptManager) { + this.context = context; + this.commandManager = commandManager; + this.scriptManager = scriptManager; +diff --git a/shell/core/src/main/java/org/crsh/shell/impl/command/ClassManager.java b/shell/core/src/main/java/org/crsh/shell/impl/command/ClassManager.java +index 1369cee1d..ddf3cfaea 100644 +--- a/shell/core/src/main/java/org/crsh/shell/impl/command/ClassManager.java ++++ b/shell/core/src/main/java/org/crsh/shell/impl/command/ClassManager.java +@@ -19,25 +19,16 @@ + + package org.crsh.shell.impl.command; + +-import groovy.lang.GroovyClassLoader; +-import groovy.lang.GroovyCodeSource; + import groovy.lang.Script; +-import org.codehaus.groovy.control.CompilationFailedException; +-import org.codehaus.groovy.control.CompilerConfiguration; +-import org.crsh.command.CommandInvoker; +-import org.crsh.command.GroovyScriptCommand; +-import org.crsh.command.NoSuchCommandException; + import org.crsh.plugin.PluginContext; + import org.crsh.plugin.ResourceKind; +-import org.crsh.shell.ErrorType; + import org.crsh.util.TimestampedObject; + import org.crsh.vfs.Resource; + +-import java.io.UnsupportedEncodingException; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; + +-class ClassManager { ++public class ClassManager extends AbstractClassManager { + + /** . */ + private final Map>> classes = new ConcurrentHashMap>>(); +@@ -45,104 +36,29 @@ class ClassManager { + /** . */ + private final PluginContext context; + +- /** . */ +- private final CompilerConfiguration config; +- +- /** . */ +- private final Class baseClass; +- + /** . */ + private final ResourceKind kind; + +- ClassManager(PluginContext context, ResourceKind kind, Class baseClass, Class baseScriptClass) { +- CompilerConfiguration config = new CompilerConfiguration(); +- config.setRecompileGroovySource(true); +- config.setScriptBaseClass(baseScriptClass.getName()); ++ public ClassManager(PluginContext context, ResourceKind kind, Class baseClass, Class baseScriptClass) { ++ super(context, baseClass, baseScriptClass); + + // + this.context = context; +- this.config = config; +- this.baseClass = baseClass; + this.kind = kind; + } + +- Class getClass(String name) throws NoSuchCommandException, NullPointerException { +- if (name == null) { +- throw new NullPointerException(""No null argument allowed""); +- } +- +- TimestampedObject> providerRef = classes.get(name); +- +- // +- Resource script = context.loadResource(name, kind); +- +- // +- if (script != null) { +- if (providerRef != null) { +- if (script.getTimestamp() != providerRef.getTimestamp()) { +- providerRef = null; +- } +- } +- +- // +- if (providerRef == null) { +- +- // +- String source; +- try { +- source = new String(script.getContent(), ""UTF-8""); +- } +- catch (UnsupportedEncodingException e) { +- throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); +- } +- +- // +- Class clazz; +- try { +- GroovyCodeSource gcs = new GroovyCodeSource(source, name, ""/groovy/shell""); +- GroovyClassLoader gcl = new GroovyClassLoader(context.getLoader(), config); +- clazz = gcl.parseClass(gcs, false); +- } +- catch (NoClassDefFoundError e) { +- throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); +- } +- catch (CompilationFailedException e) { +- throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not compile command script "" + name, e); +- } +- +- // +- if (baseClass.isAssignableFrom(clazz)) { +- Class providerClass = clazz.asSubclass(baseClass); +- providerRef = new TimestampedObject>(script.getTimestamp(), providerClass); +- classes.put(name, providerRef); +- } else { +- throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Parsed script "" + clazz.getName() + +- "" does not implements "" + CommandInvoker.class.getName()); +- } +- } +- } +- +- // +- if (providerRef == null) { +- return null; +- } +- +- // +- return providerRef.getObject(); ++ @Override ++ protected TimestampedObject> loadClass(String name) { ++ return classes.get(name); + } + +- T getInstance(String name) throws NoSuchCommandException, NullPointerException { +- Class clazz = getClass(name); +- if (clazz == null) { +- return null; +- } ++ @Override ++ protected void saveClass(String name, TimestampedObject> clazz) { ++ classes.put(name, clazz); ++ } + +- // +- try { +- return clazz.newInstance(); +- } +- catch (Exception e) { +- throw new NoSuchCommandException(name, ErrorType.INTERNAL, ""Could not create command "" + name + "" instance"", e); +- } ++ @Override ++ protected Resource getResource(String name) { ++ return context.loadResource(name, kind); + } + }" +5f232224c4de92467c4de6385590ec19e0568ba5,Mylyn Reviews,"322734: Display just the last review result for a task +",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java +index d1a7e91b..9cd94ab5 100644 +--- a/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java ++++ b/org.eclipse.mylyn.reviews.core/src/org/eclipse/mylyn/reviews/core/ReviewsUtil.java +@@ -148,12 +148,32 @@ public static List getReviewAttachmentFromTask( + List reviews = new ArrayList(); + TaskData taskData = taskDataManager.getTaskData(task); + if (taskData != null) { +- for (TaskAttribute attribute : getReviewAttachments( +- repositoryModel, taskData)) { +- reviews.addAll(parseAttachments(attribute, +- new NullProgressMonitor())); ++ List attributesByType = taskData ++ .getAttributeMapper().getAttributesByType(taskData, ++ TaskAttribute.TYPE_ATTACHMENT); ++ ITaskAttachment lastReview = null; ++ ++ for (TaskAttribute attribute : attributesByType) { ++ // TODO move RepositoryModel.createTaskAttachment to interface? ++ ITaskAttachment taskAttachment = ((RepositoryModel) repositoryModel) ++ .createTaskAttachment(attribute); ++ if (taskAttachment != null ++ && taskAttachment.getFileName().equals( ++ ReviewConstants.REVIEW_DATA_CONTAINER)) { ++ ++ if (lastReview == null ++ || lastReview.getCreationDate().before( ++ taskAttachment.getCreationDate())) { ++ lastReview = taskAttachment; ++ } ++ } + + } ++ ++ if (lastReview != null) { ++ reviews.addAll(parseAttachments(lastReview.getTaskAttribute(), ++ new NullProgressMonitor())); ++ } + + } + return reviews; +@@ -203,4 +223,5 @@ public static void markAsReview(ITask task) { + public static boolean hasReviewMarker(ITask task) { + return task.getAttribute(ReviewConstants.ATTR_REVIEW_FLAG) != null; + } ++ + }" +01e706466e561557d8591b3031cd85ae39b0559a,intellij-community,gradle: correctly set TestModuleProperties for- modules containing '-' in names (IDEA-151590)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java +index 4179681ab59ba..c2c06d2180435 100644 +--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java ++++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java +@@ -3,7 +3,6 @@ + import com.intellij.ide.highlighter.ModuleFileType; + import com.intellij.openapi.externalSystem.model.ProjectSystemId; + import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; +-import com.intellij.openapi.util.io.FileUtil; + import com.intellij.util.containers.ContainerUtil; + import org.jetbrains.annotations.NotNull; + import org.jetbrains.annotations.Nullable; +@@ -58,7 +57,7 @@ protected ModuleData(@NotNull String id, + @NotNull String internalName, + @NotNull String moduleFileDirectoryPath, + @NotNull String externalConfigPath) { +- super(owner, externalName, FileUtil.sanitizeFileName(internalName)); ++ super(owner, externalName, internalName); + myId = id; + myModuleTypeId = typeId; + myExternalConfigPath = externalConfigPath; +diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java +index 2a7f6b2eb6c25..9f67df07d6893 100644 +--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java ++++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java +@@ -234,8 +234,8 @@ public DataNode createModule(@NotNull IdeaModule gradleModule, @NotN + } + + @NotNull +- public String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { +- return gradleModule.getName() + ""_"" + sourceSetName; ++ private static String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { ++ return FileUtil.sanitizeFileName(gradleModule.getName() + ""_"" + sourceSetName); + } + + @Override +diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java +index c28a1745846c8..88c0cb575d438 100644 +--- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java ++++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java +@@ -59,6 +59,20 @@ public void testTestModuleProperties() throws Exception { + assertSame(productionModule, testModuleProperties.getProductionModule()); + } + ++ @Test ++ public void testTestModulePropertiesForModuleWithHyphenInName() throws Exception { ++ createSettingsFile(""rootProject.name='my-project'""); ++ importProject( ++ ""apply plugin: 'java'"" ++ ); ++ ++ assertModules(""my-project"", ""my_project_main"", ""my_project_test""); ++ ++ final Module testModule = getModule(""my_project_test""); ++ TestModuleProperties testModuleProperties = TestModuleProperties.getInstance(testModule); ++ assertEquals(""my_project_main"", testModuleProperties.getProductionModuleName()); ++ } ++ + @Test + public void testInheritProjectJdkForModules() throws Exception { + importProject(" +19152416a44473325a6c3605f9accc4fee379b63,elasticsearch,add an index level setting to disable/enable- purging of expired docs --,a,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java +index ae4a010e95c40..f000ba6987225 100644 +--- a/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java ++++ b/src/main/java/org/elasticsearch/indices/ttl/IndicesTTLService.java +@@ -31,6 +31,8 @@ + import org.elasticsearch.action.bulk.BulkResponse; + import org.elasticsearch.action.delete.DeleteRequest; + import org.elasticsearch.client.Client; ++import org.elasticsearch.cluster.ClusterService; ++import org.elasticsearch.cluster.metadata.IndexMetaData; + import org.elasticsearch.cluster.metadata.MetaData; + import org.elasticsearch.common.component.AbstractLifecycleComponent; + import org.elasticsearch.common.inject.Inject; +@@ -65,8 +67,13 @@ public class IndicesTTLService extends AbstractLifecycleComponent getShardsToPurge() { + List shardsToPurge = new ArrayList(); + for (IndexService indexService : indicesService) { ++ // check the value of disable_purge for this index ++ IndexMetaData indexMetaData = clusterService.state().metaData().index(indexService.index().name()); ++ boolean disablePurge = indexMetaData.settings().getAsBoolean(""index.ttl.disable_purge"", false); ++ if (disablePurge) { ++ continue; ++ } ++ + // should be optimized with the hasTTL flag + FieldMappers ttlFieldMappers = indexService.mapperService().name(TTLFieldMapper.NAME); + if (ttlFieldMappers == null) {" +c6f22949dc72af5edfd18bf4d350ae925fcc2d2c,Valadoc,"valadoc: LinkHelper: turn get_package_link into a virtual method +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +00db7d150b22031a0c030d55f1395e0ba41c1c76,kotlin,Fix KT-10472: compare all overloads including- varargs in a single pass.--,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +c1af71dbf3e85cba514b7cda53ffa20618f7cda3,hidendra$lwc,"FULL removal of Memory Database. Every single usage of it has been removed - gone. Still may be UNSTABLE and volatile; it has not be tested extensively just yet !! [#53] The current implementation will be smoothed out later on. +",p,https://github.com/hidendra/lwc,"diff --git a/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java b/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java +index 0ac0df12b..cf9c04c67 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/admin/AdminForceOwner.java +@@ -19,6 +19,7 @@ + + import com.griefcraft.lwc.LWC; + import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCBlockInteractEvent; +@@ -41,9 +42,9 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { + + LWC lwc = event.getLWC(); + Protection protection = event.getProtection(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + +- Action action = lwc.getMemoryDatabase().getAction(""forceowner"", player.getName()); ++ Action action = player.getAction(""forceowner""); + String newOwner = action.getData(); + + protection.setOwner(newOwner); +@@ -106,10 +107,15 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String newOwner = args[1]; + +- lwc.getMemoryDatabase().registerAction(""forceowner"", player.getName(), newOwner); ++ Action action = new Action(); ++ action.setName(""forceowner""); ++ action.setPlayer(player); ++ action.setData(newOwner); ++ player.addAction(action); ++ + lwc.sendLocale(sender, ""protection.admin.forceowner.finalize"", ""player"", newOwner); + + return; +diff --git a/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java b/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java +index 408b80120..32f56cd3d 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/create/CreateModule.java +@@ -20,6 +20,7 @@ + import com.griefcraft.lwc.LWC; + import com.griefcraft.model.AccessRight; + import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.model.ProtectionTypes; + import com.griefcraft.scripting.JavaModule; +@@ -29,7 +30,6 @@ + import com.griefcraft.scripting.event.LWCProtectionInteractEvent; + import com.griefcraft.scripting.event.LWCProtectionRegisterEvent; + import com.griefcraft.scripting.event.LWCProtectionRegistrationPostEvent; +-import com.griefcraft.sql.MemDB; + import com.griefcraft.sql.PhysDB; + import com.griefcraft.util.Colors; + import com.griefcraft.util.StringUtils; +@@ -76,16 +76,15 @@ public void onBlockInteract(LWCBlockInteractEvent event) { + + LWC lwc = event.getLWC(); + Block block = event.getBlock(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + + if (!lwc.isProtectable(block)) { + return; + } + + PhysDB physDb = lwc.getPhysicalDatabase(); +- MemDB memDb = lwc.getMemoryDatabase(); + +- Action action = memDb.getAction(""create"", player.getName()); ++ Action action = player.getAction(""create""); + String actionData = action.getData(); + String[] split = actionData.split("" ""); + String protectionType = split[0].toLowerCase(); +@@ -107,8 +106,8 @@ public void onBlockInteract(LWCBlockInteractEvent event) { + int blockZ = block.getZ(); + + lwc.removeModes(player); +- Result registerProtection = lwc.getModuleLoader().dispatchEvent(Event.REGISTER_PROTECTION, player, block); +- LWCProtectionRegisterEvent evt = new LWCProtectionRegisterEvent(player, block); ++ Result registerProtection = lwc.getModuleLoader().dispatchEvent(Event.REGISTER_PROTECTION, player.getBukkitPlayer(), block); ++ LWCProtectionRegisterEvent evt = new LWCProtectionRegisterEvent(player.getBukkitPlayer(), block); + lwc.getModuleLoader().dispatchEvent(evt); + + // another plugin cancelled the registration +@@ -126,7 +125,7 @@ public void onBlockInteract(LWCBlockInteractEvent event) { + String password = lwc.encrypt(protectionData); + + protection = physDb.registerProtection(block.getTypeId(), ProtectionTypes.PASSWORD, worldName, playerName, password, blockX, blockY, blockZ); +- memDb.registerPlayer(playerName, protection.getId()); ++ player.addAccessibleProtection(protection); + + lwc.sendLocale(player, ""protection.interact.create.finalize""); + lwc.sendLocale(player, ""protection.interact.create.password""); +@@ -234,7 +233,7 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + + String full = StringUtils.join(args, 0); + String type = args[0].toLowerCase(); +@@ -272,12 +271,15 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- MemDB db = lwc.getMemoryDatabase(); +- db.unregisterAllActions(player.getName()); +- db.registerAction(""create"", player.getName(), full); ++ Action action = new Action(); ++ action.setName(""create""); ++ action.setPlayer(player); ++ action.setData(full); ++ ++ player.removeAllActions(); ++ player.addAction(action); + + lwc.sendLocale(player, ""protection.create.finalize"", ""type"", lwc.getLocale(type)); +- return; + } + + } +diff --git a/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java b/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java +index 8d000e82f..92576dcde 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/flag/BaseFlagModule.java +@@ -19,13 +19,13 @@ + + import com.griefcraft.lwc.LWC; + import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCCommandEvent; + import com.griefcraft.scripting.event.LWCProtectionInteractEvent; + import com.griefcraft.util.StringUtils; + import org.bukkit.command.CommandSender; +-import org.bukkit.entity.Player; + + public class BaseFlagModule extends JavaModule { + +@@ -37,9 +37,9 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { + + LWC lwc = event.getLWC(); + Protection protection = event.getProtection(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + +- Action action = lwc.getMemoryDatabase().getAction(""flag"", player.getName()); ++ Action action = player.getAction(""flag""); + String data = action.getData(); + event.setResult(Result.CANCEL); + +@@ -99,7 +99,7 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String flagName = args[0]; + String type = args[1].toLowerCase(); + String internalType; // + or - +@@ -142,8 +142,14 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); +- lwc.getMemoryDatabase().registerAction(""flag"", player.getName(), internalType + flagName); ++ Action action = new Action(); ++ action.setName(""flag""); ++ action.setPlayer(player); ++ action.setData(internalType + flagName); ++ ++ player.removeAllActions(); ++ player.addAction(action); ++ + lwc.sendLocale(sender, ""protection.flag.finalize""); + + return; +diff --git a/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java b/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java +index d880ebc4f..86dca114e 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/free/FreeModule.java +@@ -18,6 +18,8 @@ + package com.griefcraft.modules.free; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCBlockInteractEvent; +@@ -110,19 +112,19 @@ public void onCommand(LWCCommandEvent event) { + } + + String type = args[0].toLowerCase(); +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + + if (type.equals(""protection"") || type.equals(""chest"") || type.equals(""furnace"") || type.equals(""dispenser"")) { +- if (lwc.getMemoryDatabase().hasPendingChest(player.getName())) { +- lwc.sendLocale(sender, ""protection.general.pending""); +- return; +- } ++ Action action = new Action(); ++ action.setName(""free""); ++ action.setPlayer(player); ++ ++ player.removeAllActions(); ++ player.addAction(action); + +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); +- lwc.getMemoryDatabase().registerAction(""free"", player.getName()); + lwc.sendLocale(sender, ""protection.remove.protection.finalize""); + } else if (type.equals(""modes"")) { +- lwc.getMemoryDatabase().unregisterAllModes(player.getName()); ++ player.disableAllModes(); + lwc.sendLocale(sender, ""protection.remove.modes.finalize""); + } else { + lwc.sendSimpleUsage(sender, ""/lwc -r ""); +diff --git a/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java b/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java +index 840d8e71d..24a8f6e21 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/info/InfoModule.java +@@ -18,6 +18,8 @@ + package com.griefcraft.modules.info; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCBlockInteractEvent; +@@ -99,7 +101,7 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String type = ""info""; + + if (args.length > 0) { +@@ -107,8 +109,13 @@ public void onCommand(LWCCommandEvent event) { + } + + if (type.equals(""info"")) { +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); +- lwc.getMemoryDatabase().registerAction(""info"", player.getName()); ++ Action action = new Action(); ++ action.setName(""info""); ++ action.setPlayer(player); ++ ++ player.removeAllActions(); ++ player.addAction(action); ++ + lwc.sendLocale(player, ""protection.info.finalize""); + } + +diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java +index 7e1e90db0..cbd0eb625 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/modes/DropTransferModule.java +@@ -18,6 +18,9 @@ + package com.griefcraft.modules.modes; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; ++import com.griefcraft.model.Mode; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCCommandEvent; +@@ -48,8 +51,8 @@ public void load(LWC lwc) { + * @param player + * @return + */ +- private boolean isPlayerDropTransferring(String player) { +- return lwc.getMemoryDatabase().hasMode(player, ""+dropTransfer""); ++ private boolean isPlayerDropTransferring(LWCPlayer player) { ++ return player.hasMode(""+dropTransfer""); + } + + /** +@@ -58,8 +61,9 @@ private boolean isPlayerDropTransferring(String player) { + * @param player + * @return + */ +- private int getPlayerDropTransferTarget(String player) { +- String target = lwc.getMemoryDatabase().getModeData(player, ""dropTransfer""); ++ private int getPlayerDropTransferTarget(LWCPlayer player) { ++ Mode mode = player.getMode(""dropTransfer""); ++ String target = mode.getData(); + + try { + return Integer.parseInt(target); +@@ -70,14 +74,15 @@ private int getPlayerDropTransferTarget(String player) { + } + + @Override +- public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) { +- int protectionId = getPlayerDropTransferTarget(player.getName()); ++ public Result onDropItem(LWC lwc, Player bPlayer, Item item, ItemStack itemStack) { ++ LWCPlayer player = lwc.wrapPlayer(bPlayer); ++ int protectionId = getPlayerDropTransferTarget(player); + + if (protectionId == -1) { + return DEFAULT; + } + +- if (!isPlayerDropTransferring(player.getName())) { ++ if (!isPlayerDropTransferring(player)) { + return DEFAULT; + } + +@@ -85,7 +90,7 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) + + if (protection == null) { + player.sendMessage(Colors.Red + ""Protection no longer exists""); +- lwc.getMemoryDatabase().unregisterMode(player.getName(), ""dropTransfer""); ++ player.disableMode(player.getMode(""dropTransfer"")); + return DEFAULT; + } + +@@ -94,7 +99,7 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) + + if (world == null) { + player.sendMessage(Colors.Red + ""Invalid world!""); +- lwc.getMemoryDatabase().unregisterMode(player.getName(), ""dropTransfer""); ++ player.disableMode(player.getMode(""dropTransfer"")); + return DEFAULT; + } + +@@ -105,36 +110,46 @@ public Result onDropItem(LWC lwc, Player player, Item item, ItemStack itemStack) + player.sendMessage(""Chest could not hold all the items! Have the remaining items back.""); + + for (ItemStack temp : remaining.values()) { +- player.getInventory().addItem(temp); ++ bPlayer.getInventory().addItem(temp); + } + } +- player.updateInventory(); // if they're in the chest and dropping items, this is required ++ bPlayer.updateInventory(); // if they're in the chest and dropping items, this is required + item.remove(); + + return DEFAULT; + } + + @Override +- public Result onProtectionInteract(LWC lwc, Player player, Protection protection, List actions, boolean canAccess, boolean canAdmin) { ++ public Result onProtectionInteract(LWC lwc, Player bPlayer, Protection protection, List actions, boolean canAccess, boolean canAdmin) { + if (!actions.contains(""dropTransferSelect"")) { + return DEFAULT; + } + ++ LWCPlayer player = lwc.wrapPlayer(bPlayer); ++ + if (!canAccess) { + lwc.sendLocale(player, ""protection.interact.dropxfer.noaccess""); + } else { + if (protection.getBlockId() != Material.CHEST.getId()) { + lwc.sendLocale(player, ""protection.interact.dropxfer.notchest""); +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); ++ player.removeAllActions(); + return CANCEL; + } + +- lwc.getMemoryDatabase().registerMode(player.getName(), ""dropTransfer"", protection.getId() + """"); +- lwc.getMemoryDatabase().registerMode(player.getName(), ""+dropTransfer""); ++ Mode mode = new Mode(); ++ mode.setName(""dropTransfer""); ++ mode.setData(protection.getId() + """"); ++ mode.setPlayer(bPlayer); ++ player.enableMode(mode); ++ mode = new Mode(); ++ mode.setName(""+dropTransfer""); ++ mode.setPlayer(bPlayer); ++ player.enableMode(mode); ++ + lwc.sendLocale(player, ""protection.interact.dropxfer.finalize""); + } + +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); // ignore the persist mode ++ player.removeAllActions(); // ignore the persist mode + return DEFAULT; + } + +@@ -145,7 +160,7 @@ public Result onBlockInteract(LWC lwc, Player player, Block block, List + } + + lwc.sendLocale(player, ""protection.interact.dropxfer.notprotected""); +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); ++ lwc.removeModes(player); + + return DEFAULT; + } +@@ -164,7 +179,7 @@ public void onCommand(LWCCommandEvent event) { + CommandSender sender = event.getSender(); + String[] args = event.getArgs(); + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String mode = args[0].toLowerCase(); + + if (!mode.equals(""droptransfer"")) { +@@ -185,40 +200,48 @@ public void onCommand(LWCCommandEvent event) { + String playerName = player.getName(); + + if (action.equals(""select"")) { +- if (isPlayerDropTransferring(playerName)) { ++ if (isPlayerDropTransferring(player)) { + lwc.sendLocale(player, ""protection.modes.dropxfer.select.error""); + return; + } + +- lwc.getMemoryDatabase().unregisterMode(playerName, mode); +- lwc.getMemoryDatabase().registerAction(""dropTransferSelect"", playerName, """"); ++ player.disableMode(player.getMode(mode)); + ++ Action temp = new Action(); ++ temp.setName(""dropTransferSelect""); ++ temp.setPlayer(player); ++ ++ player.addAction(temp); + lwc.sendLocale(player, ""protection.modes.dropxfer.select.finalize""); + } else if (action.equals(""on"")) { +- int target = getPlayerDropTransferTarget(playerName); ++ int target = getPlayerDropTransferTarget(player); + + if (target == -1) { + lwc.sendLocale(player, ""protection.modes.dropxfer.selectchest""); + return; + } + +- lwc.getMemoryDatabase().registerMode(playerName, ""+dropTransfer""); ++ Mode temp = new Mode(); ++ temp.setName(""+dropTransfer""); ++ temp.setPlayer(player.getBukkitPlayer()); ++ ++ player.enableMode(temp); + lwc.sendLocale(player, ""protection.modes.dropxfer.on.finalize""); + } else if (action.equals(""off"")) { +- int target = getPlayerDropTransferTarget(playerName); ++ int target = getPlayerDropTransferTarget(player); + + if (target == -1) { + lwc.sendLocale(player, ""protection.modes.dropxfer.selectchest""); + return; + } + +- lwc.getMemoryDatabase().unregisterMode(playerName, ""+dropTransfer""); ++ player.disableMode(player.getMode(""+dropTransfer"")); + lwc.sendLocale(player, ""protection.modes.dropxfer.off.finalize""); + } else if (action.equals(""status"")) { +- if (getPlayerDropTransferTarget(playerName) == -1) { ++ if (getPlayerDropTransferTarget(player) == -1) { + lwc.sendLocale(player, ""protection.modes.dropxfer.status.off""); + } else { +- if (isPlayerDropTransferring(playerName)) { ++ if (isPlayerDropTransferring(player)) { + lwc.sendLocale(player, ""protection.modes.dropxfer.status.active""); + } else { + lwc.sendLocale(player, ""protection.modes.dropxfer.status.inactive""); +diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java +index ef14c3da7..abf81768a 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/modes/NoSpamModule.java +@@ -18,13 +18,12 @@ + package com.griefcraft.modules.modes; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.LWCPlayer; ++import com.griefcraft.model.Mode; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCCommandEvent; + import com.griefcraft.scripting.event.LWCSendLocaleEvent; + import org.bukkit.command.CommandSender; +-import org.bukkit.entity.Player; +- +-import java.util.List; + + public class NoSpamModule extends JavaModule { + +@@ -42,37 +41,36 @@ public void onCommand(LWCCommandEvent event) { + CommandSender sender = event.getSender(); + String[] args = event.getArgs(); + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String mode = args[0].toLowerCase(); + + if (!mode.equals(""nospam"")) { + return; + } + +- List modes = lwc.getMemoryDatabase().getModes(player.getName()); ++ if (!player.hasMode(mode)) { ++ Mode temp = new Mode(); ++ temp.setName(mode); ++ temp.setPlayer(player.getBukkitPlayer()); + +- if (!modes.contains(mode)) { +- lwc.getMemoryDatabase().registerMode(player.getName(), mode); ++ player.enableMode(temp); + lwc.sendLocale(player, ""protection.modes.nospam.finalize""); + } else { +- lwc.getMemoryDatabase().unregisterMode(player.getName(), mode); ++ player.disableMode(player.getMode(mode)); + lwc.sendLocale(player, ""protection.modes.nospam.off""); + } + + event.setCancelled(true); +- return; + } + + @Override + public void onSendLocale(LWCSendLocaleEvent event) { + LWC lwc = event.getLWC(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + String locale = event.getLocale(); + +- List modes = lwc.getMemoryDatabase().getModes(player.getName()); +- + // they don't intrigue us +- if (!modes.contains(""nospam"")) { ++ if (!player.hasMode(""nospam"")) { + return; + } + +diff --git a/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java b/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java +index 6d082be9a..cd91987ad 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/modes/PersistModule.java +@@ -18,12 +18,11 @@ + package com.griefcraft.modules.modes; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.LWCPlayer; ++import com.griefcraft.model.Mode; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCCommandEvent; + import org.bukkit.command.CommandSender; +-import org.bukkit.entity.Player; +- +-import java.util.List; + + public class PersistModule extends JavaModule { + +@@ -41,25 +40,26 @@ public void onCommand(LWCCommandEvent event) { + CommandSender sender = event.getSender(); + String[] args = event.getArgs(); + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String mode = args[0].toLowerCase(); + + if (!mode.equals(""persist"")) { + return; + } + +- List modes = lwc.getMemoryDatabase().getModes(player.getName()); ++ if (!player.hasMode(mode)) { ++ Mode temp = new Mode(); ++ temp.setName(mode); ++ temp.setPlayer(player.getBukkitPlayer()); + +- if (!modes.contains(mode)) { +- lwc.getMemoryDatabase().registerMode(player.getName(), mode); ++ player.enableMode(temp); + lwc.sendLocale(player, ""protection.modes.persist.finalize""); + } else { +- lwc.getMemoryDatabase().unregisterMode(player.getName(), mode); ++ player.disableMode(player.getMode(mode)); + lwc.sendLocale(player, ""protection.modes.persist.off""); + } + + event.setCancelled(true); +- return; + } + + } +diff --git a/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java b/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java +index deed3ec5e..3a5e6e5fe 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/modify/ModifyModule.java +@@ -20,6 +20,7 @@ + import com.griefcraft.lwc.LWC; + import com.griefcraft.model.AccessRight; + import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCBlockInteractEvent; +@@ -46,11 +47,11 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { + + LWC lwc = event.getLWC(); + Protection protection = event.getProtection(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + event.setResult(Result.CANCEL); + +- if (lwc.canAdminProtection(player, protection)) { +- Action action = lwc.getMemoryDatabase().getAction(""modify"", player.getName()); ++ if (lwc.canAdminProtection(player.getBukkitPlayer(), protection)) { ++ Action action = player.getAction(""modify""); + + final String defaultEntities = action.getData(); + String[] entities = new String[0]; +@@ -172,10 +173,16 @@ public void onCommand(LWCCommandEvent event) { + } + + String full = join(args, 0); +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); ++ ++ Action action = new Action(); ++ action.setName(""modify""); ++ action.setPlayer(player); ++ action.setData(full); ++ ++ player.removeAllActions(); ++ player.addAction(action); + +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); +- lwc.getMemoryDatabase().registerAction(""modify"", player.getName(), full); + lwc.sendLocale(sender, ""protection.modify.finalize""); + return; + } +diff --git a/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java b/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java +index 7657f6176..f280e7379 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/owners/OwnersModule.java +@@ -20,6 +20,7 @@ + import com.griefcraft.lwc.LWC; + import com.griefcraft.model.AccessRight; + import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.JavaModule; + import com.griefcraft.scripting.event.LWCBlockInteractEvent; +@@ -46,10 +47,10 @@ public void onProtectionInteract(LWCProtectionInteractEvent event) { + + LWC lwc = event.getLWC(); + Protection protection = event.getProtection(); +- Player player = event.getPlayer(); ++ LWCPlayer player = lwc.wrapPlayer(event.getPlayer()); + event.setResult(Result.CANCEL); + +- Action action = lwc.getMemoryDatabase().getAction(""owners"", player.getName()); ++ Action action = player.getAction(""owners""); + int accessPage = Integer.parseInt(action.getData()); + + /* +@@ -142,7 +143,7 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + int page = 1; + + if (args.length > 0) { +@@ -154,8 +155,14 @@ public void onCommand(LWCCommandEvent event) { + } + } + +- lwc.getMemoryDatabase().unregisterAllActions(player.getName()); +- lwc.getMemoryDatabase().registerAction(""owners"", player.getName(), page + """"); ++ Action action = new Action(); ++ action.setName(""owners""); ++ action.setPlayer(player); ++ action.setData(page + """"); ++ ++ player.removeAllActions(); ++ player.addAction(action); ++ + lwc.sendLocale(sender, ""protection.owners.finalize""); + return; + } +diff --git a/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java b/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java +index 5475424e5..139deca8f 100644 +--- a/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java ++++ b/modules/core/src/main/java/com/griefcraft/modules/unlock/UnlockModule.java +@@ -18,6 +18,8 @@ + package com.griefcraft.modules.unlock; + + import com.griefcraft.lwc.LWC; ++import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.model.ProtectionTypes; + import com.griefcraft.scripting.JavaModule; +@@ -61,38 +63,35 @@ public void onCommand(LWCCommandEvent event) { + return; + } + +- Player player = (Player) sender; ++ LWCPlayer player = lwc.wrapPlayer(sender); + String password = join(args, 0); + password = encrypt(password); + +- if (!lwc.getMemoryDatabase().hasPendingUnlock(player.getName())) { ++ // see if they have the protection interaction action ++ Action action = player.getAction(""interacted""); ++ ++ if (action == null) { + player.sendMessage(Colors.Red + ""Nothing selected. Open a locked protection first.""); +- return; + } else { +- int protectionId = lwc.getMemoryDatabase().getUnlockID(player.getName()); ++ Protection protection = action.getProtection(); + +- if (protectionId == -1) { ++ if (protection == null) { + lwc.sendLocale(player, ""protection.internalerror"", ""id"", ""unlock""); + return; + } + +- Protection entity = lwc.getPhysicalDatabase().loadProtection(protectionId); +- +- if (entity.getType() != ProtectionTypes.PASSWORD) { ++ if (protection.getType() != ProtectionTypes.PASSWORD) { + lwc.sendLocale(player, ""protection.unlock.notpassword""); + return; + } + +- if (entity.getData().equals(password)) { +- lwc.getMemoryDatabase().unregisterUnlock(player.getName()); +- lwc.getMemoryDatabase().registerPlayer(player.getName(), protectionId); ++ if (protection.getData().equals(password)) { ++ player.addAccessibleProtection(protection); + lwc.sendLocale(player, ""protection.unlock.password.valid""); + } else { + lwc.sendLocale(player, ""protection.unlock.password.invalid""); + } + } +- +- return; + } + + } +diff --git a/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java b/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java +index 475d235f5..e6251cc9a 100644 +--- a/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java ++++ b/modules/spout/src/main/java/com/griefcraft/lwc/PasswordRequestModule.java +@@ -18,6 +18,8 @@ + package com.griefcraft.lwc; + + import com.griefcraft.bukkit.LWCSpoutPlugin; ++import com.griefcraft.model.Action; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.model.ProtectionTypes; + import com.griefcraft.scripting.JavaModule; +@@ -104,9 +106,12 @@ public void onButtonClicked(ButtonClickEvent event) { + Button button = event.getButton(); + SpoutPlayer player = event.getPlayer(); + LWC lwc = LWC.getInstance(); ++ LWCPlayer lwcPlayer = lwc.wrapPlayer(player); ++ ++ Action action = lwcPlayer.getAction(""interacted""); + + // if they don't have an unlock req, why is the screen open? +- if (!lwc.getMemoryDatabase().hasPendingUnlock(player.getName())) { ++ if (action == null) { + player.getMainScreen().closePopup(); + return; + } +@@ -117,24 +122,21 @@ public void onButtonClicked(ButtonClickEvent event) { + // check their password + String password = lwc.encrypt(textField.getText().trim()); + +- int protectionId = lwc.getMemoryDatabase().getUnlockID(player.getName()); ++ // load the protection they had clicked ++ Protection protection = action.getProtection(); + +- if (protectionId == -1) { ++ if (protection == null) { + lwc.sendLocale(player, ""protection.internalerror"", ""id"", ""unlock""); + return; + } + +- // load the protection they had clicked +- Protection protection = lwc.getPhysicalDatabase().loadProtection(protectionId); +- + if (protection.getType() != ProtectionTypes.PASSWORD) { + lwc.sendLocale(player, ""protection.unlock.notpassword""); + return; + } + + if (protection.getData().equals(password)) { +- lwc.getMemoryDatabase().unregisterUnlock(player.getName()); +- lwc.getMemoryDatabase().registerPlayer(player.getName(), protectionId); ++ lwcPlayer.addAccessibleProtection(protection); + player.getMainScreen().closePopup(); + + // open the chest that they clicked :P +diff --git a/skel/doors.yml b/skel/doors.yml +index c602913bc..4ce685a32 100644 +--- a/skel/doors.yml ++++ b/skel/doors.yml +@@ -10,7 +10,7 @@ doors: + # toggle: the door will just open if it's closed, or close if it's opened. Will not auto close. + # openAndClose: the door will automatically close after . If it was already opened, it will NOT re-open. + # +- action: toggle ++ name: toggle + +- # The amount of seconds after opening a door for it to close. No effect if openAndClose action is not being used. ++ # The amount of seconds after opening a door for it to close. No effect if openAndClose name is not being used. + interval: 3 +\ No newline at end of file +diff --git a/src/lang/lwc_cz.properties b/src/lang/lwc_cz.properties +index b52246589..737f1fae4 100644 +--- a/src/lang/lwc_cz.properties ++++ b/src/lang/lwc_cz.properties +@@ -45,7 +45,7 @@ protection.general.locked.password=\ + %red%Musis napsat %gold%%cunlock% %red% k odemknuti ! + protection.general.locked.private=%green%%block% %white%->%red% objekt je uzamknut magickym klicem ! %white%:-) + +-# Pending action ++# Pending name + protection.general.pending=%red%Jiz mas nevyrizeny prikaz s LWC! + + ################## +diff --git a/src/lang/lwc_da.properties b/src/lang/lwc_da.properties +index 8bee5fd15..6e43e768c 100644 +--- a/src/lang/lwc_da.properties ++++ b/src/lang/lwc_da.properties +@@ -44,7 +44,7 @@ protection.general.locked.password=\ + %red%Skriv %gold%%cunlock% %red% for at låse op. + protection.general.locked.private=%red%Denne %block% er låst med en trylleformular + +-# Pending action ++# Pending name + protection.general.pending=%red%Du har allerede en ventende handling. + + ################## +diff --git a/src/lang/lwc_de.properties b/src/lang/lwc_de.properties +index 0faeb46e9..6eee83e52 100644 +--- a/src/lang/lwc_de.properties ++++ b/src/lang/lwc_de.properties +@@ -45,7 +45,7 @@ protection.general.locked.password=\ + %red%Schreibe %gold%%cunlock% %red%zum entriegeln. + protection.general.locked.private=%red%Diese %block% ist abgeschlossen. + +-# Pending action ++# Pending name + protection.general.pending=%red%Du hast derzeit noch eine offene Anfrage. + + ################## +diff --git a/src/lang/lwc_en.properties b/src/lang/lwc_en.properties +index a9e491641..e641a3ba2 100644 +--- a/src/lang/lwc_en.properties ++++ b/src/lang/lwc_en.properties +@@ -44,8 +44,8 @@ protection.general.locked.password=\ + %red%Type %gold%%cunlock% %red% to unlock it. + protection.general.locked.private=%red%This %block% is locked with a magical spell + +-# Pending action +-protection.general.pending=%red%You already have a pending action. ++# Pending name ++protection.general.pending=%red%You already have a pending name. + + ################## + ## Commands ## +diff --git a/src/lang/lwc_es.properties b/src/lang/lwc_es.properties +index 00bd24fbc..f37e00bf5 100644 +--- a/src/lang/lwc_es.properties ++++ b/src/lang/lwc_es.properties +@@ -35,7 +35,7 @@ protection.general.locked.password=\ + %red%Escribe %gold%%cunlock% %red% para desbloquearlo. + protection.general.locked.private=%red%Este %block% esta protegido con un hechizo magico. + +-# Pending action ++# Pending name + protection.general.pending=%red%Ya tienes una accion pendiente. + + ################## +diff --git a/src/lang/lwc_fr.properties b/src/lang/lwc_fr.properties +index be4addd2b..3a78963f8 100644 +--- a/src/lang/lwc_fr.properties ++++ b/src/lang/lwc_fr.properties +@@ -31,8 +31,8 @@ protection.general.locked.password=\ + %red%Veuillez taper %gold%%cunlock% %red% pour le/la déverrouiller. + protection.general.locked.private=%red%Ce/Cette %block% est bloqué par un sort magique. + +-# Pending action +-protection.general.pending=%red%Vous avez déjà une action en cours. ++# Pending name ++protection.general.pending=%red%Vous avez déjà une name en cours. + + ################## + ## Commands ## +diff --git a/src/lang/lwc_nl.properties b/src/lang/lwc_nl.properties +index 813313d55..d7e779b01 100644 +--- a/src/lang/lwc_nl.properties ++++ b/src/lang/lwc_nl.properties +@@ -35,7 +35,7 @@ protection.general.locked.password=\ + %red%Typ %gold%%cunlock% %red% om er toegang tot te krijgen. + protection.general.locked.private=%red%deze %block% is beveiligd met een magische spreuk. + +-# Pending action ++# Pending name + protection.general.pending=%red%Er is al een actie bezig. + + ################## +diff --git a/src/lang/lwc_pl.properties b/src/lang/lwc_pl.properties +index e8657902c..d44c07529 100644 +--- a/src/lang/lwc_pl.properties ++++ b/src/lang/lwc_pl.properties +@@ -44,7 +44,7 @@ protection.general.locked.password=\ + %gold%%cunlock% %red%, aby odblokowac. + protection.general.locked.private=%red%Ten %block% jest zablokowany magicznym zakleciem. + +-# Pending action ++# Pending name + protection.general.pending=%red%Juz wykonujesz akcje. + + ################## +diff --git a/src/lang/lwc_ru.properties b/src/lang/lwc_ru.properties +index f9243536c..b312d7dc1 100644 +--- a/src/lang/lwc_ru.properties ++++ b/src/lang/lwc_ru.properties +@@ -43,7 +43,7 @@ protection.general.locked.password=\ + %red%Введите %gold%%cunlock% <Пароль>%red% чтобы открыть его. + protection.general.locked.private=%red%%block% защищён магией. + +-# Pending action ++# Pending name + protection.general.pending=%red%Вы уже выполняете это действие + + ################## +diff --git a/src/lang/lwc_sv.properties b/src/lang/lwc_sv.properties +index 7c025c889..d19e1f4d4 100644 +--- a/src/lang/lwc_sv.properties ++++ b/src/lang/lwc_sv.properties +@@ -44,7 +44,7 @@ protection.general.locked.password=\ + %red%Skriv %gold%%cunlock% %red% för att låsa upp den. + protection.general.locked.private=%red%Detta %block% är låst med en trollformel + +-# Pending action ++# Pending name + protection.general.pending=%red%Du har redan et pågående utspel. + + ################## +diff --git a/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java b/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java +index de6a125b9..2fd2c88a7 100644 +--- a/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java ++++ b/src/main/java/com/griefcraft/listeners/LWCPlayerListener.java +@@ -19,6 +19,7 @@ + + import com.griefcraft.lwc.LWC; + import com.griefcraft.lwc.LWCPlugin; ++import com.griefcraft.model.LWCPlayer; + import com.griefcraft.model.Protection; + import com.griefcraft.scripting.Module; + import com.griefcraft.scripting.Module.Result; +@@ -43,6 +44,7 @@ + import org.bukkit.event.player.PlayerQuitEvent; + import org.bukkit.inventory.ItemStack; + ++import java.util.ArrayList; + import java.util.List; + + public class LWCPlayerListener extends PlayerListener { +@@ -103,6 +105,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { + + LWC lwc = plugin.getLWC(); + Player player = event.getPlayer(); ++ LWCPlayer lwcPlayer = lwc.wrapPlayer(player); + Block clickedBlock = event.getClickedBlock(); + Location location = clickedBlock.getLocation(); + +@@ -122,12 +125,22 @@ public void onPlayerInteract(PlayerInteractEvent event) { + } + + try { +- List actions = lwc.getMemoryDatabase().getActions(player.getName()); ++ List actions = new ArrayList(lwcPlayer.getActionNames()); + Protection protection = lwc.findProtection(block); + Module.Result result = Module.Result.CANCEL; + boolean canAccess = lwc.canAccessProtection(player, protection); + boolean canAdmin = lwc.canAdminProtection(player, protection); + ++ // register in an action what protection they interacted with (if applicable.) ++ if (protection != null) { ++ com.griefcraft.model.Action action = new com.griefcraft.model.Action(); ++ action.setName(""interacted""); ++ action.setPlayer(lwcPlayer); ++ action.setProtection(protection); ++ ++ lwcPlayer.addAction(action); ++ } ++ + if (event.getAction() == Action.LEFT_CLICK_BLOCK) { + boolean ignoreLeftClick = Boolean.parseBoolean(lwc.resolveProtectionConfiguration(material, ""ignoreLeftClick"")); + +@@ -188,14 +201,10 @@ public void onPlayerQuit(PlayerQuitEvent event) { + return; + } + +- LWC lwc = plugin.getLWC(); +- String player = event.getPlayer().getName(); +- +- lwc.getMemoryDatabase().unregisterPlayer(player); +- lwc.getMemoryDatabase().unregisterUnlock(player); +- lwc.getMemoryDatabase().unregisterPendingLock(player); +- lwc.getMemoryDatabase().unregisterAllActions(player); +- lwc.getMemoryDatabase().unregisterAllModes(player); ++ LWCPlayer player = LWC.getInstance().wrapPlayer(event.getPlayer()); ++ player.removeAllAccessibleProtections(); ++ player.removeAllActions(); ++ player.disableAllModes(); + } + + } +diff --git a/src/main/java/com/griefcraft/lwc/LWC.java b/src/main/java/com/griefcraft/lwc/LWC.java +index 1081b9642..595656229 100644 +--- a/src/main/java/com/griefcraft/lwc/LWC.java ++++ b/src/main/java/com/griefcraft/lwc/LWC.java +@@ -66,7 +66,6 @@ + import com.griefcraft.scripting.ModuleLoader.Event; + import com.griefcraft.scripting.event.LWCSendLocaleEvent; + import com.griefcraft.sql.Database; +-import com.griefcraft.sql.MemDB; + import com.griefcraft.sql.PhysDB; + import com.griefcraft.util.Colors; + import com.griefcraft.util.Performance; +@@ -142,11 +141,6 @@ public class LWC { + */ + private CacheSet caches; + +- /** +- * Memory database instance +- */ +- private MemDB memoryDatabase; +- + /** + * Physical database instance + */ +@@ -205,11 +199,19 @@ public LWC(LWCPlugin plugin) { + /** + * Create an LWCPlayer object for a player + * +- * @param player ++ * @param sender + * @return + */ +- public LWCPlayer wrapPlayer(Player player) { +- return new LWCPlayer(this, player); ++ public LWCPlayer wrapPlayer(CommandSender sender) { ++ if (sender instanceof LWCPlayer) { ++ return (LWCPlayer) sender; ++ } ++ ++ if (!(sender instanceof Player)) { ++ return null; ++ } ++ ++ return LWCPlayer.getPlayer((Player) sender); + } + + /** +@@ -254,11 +256,17 @@ public CacheSet getCaches() { + /** + * Remove all modes if the player is not in persistent mode + * +- * @param player ++ * @param sender + */ +- public void removeModes(Player player) { +- if (notInPersistentMode(player.getName())) { +- memoryDatabase.unregisterAllActions(player.getName()); ++ public void removeModes(CommandSender sender) { ++ if (sender instanceof Player) { ++ Player bPlayer = (Player) sender; ++ ++ if (notInPersistentMode(bPlayer.getName())) { ++ wrapPlayer(bPlayer).getActions().clear(); ++ } ++ } else if (sender instanceof LWCPlayer) { ++ removeModes(((LWCPlayer) sender).getBukkitPlayer()); + } + } + +@@ -369,7 +377,7 @@ public boolean canAccessProtection(Player player, Protection protection) { + return true; + + case ProtectionTypes.PASSWORD: +- return memoryDatabase.hasAccess(player.getName(), protection); ++ return wrapPlayer(player).getAccessibleProtections().contains(protection); + + case ProtectionTypes.PRIVATE: + if (playerName.equalsIgnoreCase(protection.getOwner())) { +@@ -437,7 +445,7 @@ public boolean canAdminProtection(Player player, Protection protection) { + return player.getName().equalsIgnoreCase(protection.getOwner()); + + case ProtectionTypes.PASSWORD: +- return player.getName().equalsIgnoreCase(protection.getOwner()) && memoryDatabase.hasAccess(player.getName(), protection); ++ return player.getName().equalsIgnoreCase(protection.getOwner()) && wrapPlayer(player).getAccessibleProtections().contains(protection); + + case ProtectionTypes.PRIVATE: + if (playerName.equalsIgnoreCase(protection.getOwner())) { +@@ -483,12 +491,7 @@ public void destruct() { + physicalDatabase.dispose(); + } + +- if (memoryDatabase != null) { +- memoryDatabase.dispose(); +- } +- + physicalDatabase = null; +- memoryDatabase = null; + } + + /** +@@ -576,8 +579,7 @@ public boolean enforceAccess(Player player, Block block) { + switch (protection.getType()) { + case ProtectionTypes.PASSWORD: + if (!hasAccess) { +- getMemoryDatabase().unregisterUnlock(player.getName()); +- getMemoryDatabase().registerUnlock(player.getName(), protection.getId()); ++ wrapPlayer(player).addAccessibleProtection(protection); + + sendLocale(player, ""protection.general.locked.password"", ""block"", materialToString(block)); + } +@@ -778,13 +780,6 @@ public String getLocale(String key, Object... args) { + return value; + } + +- /** +- * @return memory database object +- */ +- public MemDB getMemoryDatabase() { +- return memoryDatabase; +- } +- + /** + * @return the Permissions handler + */ +@@ -1060,7 +1055,6 @@ public void load() { + Performance.init(); + + physicalDatabase = new PhysDB(); +- memoryDatabase = new MemDB(); + updateThread = new UpdateThread(this); + + // Permissions init +@@ -1114,10 +1108,7 @@ public void load() { + log(""Loading "" + Database.DefaultType); + try { + physicalDatabase.connect(); +- memoryDatabase.connect(); +- + physicalDatabase.load(); +- memoryDatabase.load(); + + log(""Using: "" + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); + } catch (Exception e) { +@@ -1257,7 +1248,7 @@ public ItemStack[] mergeInventories(List blocks) { + * @return true if the player is NOT in persistent mode + */ + public boolean notInPersistentMode(String player) { +- return !memoryDatabase.hasMode(player, ""persist""); ++ return !wrapPlayer(Bukkit.getServer().getPlayer(player)).hasMode(""persist""); + } + + /** +diff --git a/src/main/java/com/griefcraft/model/Action.java b/src/main/java/com/griefcraft/model/Action.java +index 5ea7d69f0..e5b68e884 100644 +--- a/src/main/java/com/griefcraft/model/Action.java ++++ b/src/main/java/com/griefcraft/model/Action.java +@@ -19,24 +19,23 @@ + + public class Action { + +- public int id; +- private String action; +- private int protectionId; ++ private String name; ++ private Protection protection; + private String data; +- private String player; ++ private LWCPlayer player; + + /** +- * @return the action ++ * @return the name + */ +- public String getAction() { +- return action; ++ public String getName() { ++ return name; + } + + /** +- * @return the protectionId ++ * @return the Protection associated with this action + */ +- public int getProtectionId() { +- return protectionId; ++ public Protection getProtection() { ++ return protection; + } + + /** +@@ -46,32 +45,25 @@ public String getData() { + return data; + } + +- /** +- * @return the id +- */ +- public int getId() { +- return id; +- } +- + /** + * @return the player + */ +- public String getPlayer() { ++ public LWCPlayer getPlayer() { + return player; + } + + /** +- * @param action the action to set ++ * @param name the name to set + */ +- public void setAction(String action) { +- this.action = action; ++ public void setName(String name) { ++ this.name = name; + } + + /** +- * @param protectionId the protectionId to set ++ * @param protection the Protection to set + */ +- public void setProtectionId(int protectionId) { +- this.protectionId = protectionId; ++ public void setProtection(Protection protection) { ++ this.protection = protection; + } + + /** +@@ -81,17 +73,10 @@ public void setData(String data) { + this.data = data; + } + +- /** +- * @param id the id to set +- */ +- public void setId(int id) { +- this.id = id; +- } +- + /** + * @param player the player to set + */ +- public void setPlayer(String player) { ++ public void setPlayer(LWCPlayer player) { + this.player = player; + } + +diff --git a/src/main/java/com/griefcraft/model/LWCPlayer.java b/src/main/java/com/griefcraft/model/LWCPlayer.java +index e0ad1e771..bc93c9aaa 100644 +--- a/src/main/java/com/griefcraft/model/LWCPlayer.java ++++ b/src/main/java/com/griefcraft/model/LWCPlayer.java +@@ -18,21 +18,269 @@ + package com.griefcraft.model; + + import com.griefcraft.lwc.LWC; ++import org.bukkit.Server; ++import org.bukkit.command.CommandSender; + import org.bukkit.entity.Player; ++import org.bukkit.permissions.Permission; ++import org.bukkit.permissions.PermissionAttachment; ++import org.bukkit.permissions.PermissionAttachmentInfo; ++import org.bukkit.plugin.Plugin; + + import java.util.ArrayList; ++import java.util.Collections; ++import java.util.HashMap; ++import java.util.HashSet; + import java.util.List; ++import java.util.Map; ++import java.util.Set; + +-public class LWCPlayer { ++public class LWCPlayer implements CommandSender { + ++ /** ++ * The LWC instance ++ */ + private LWC lwc; ++ ++ /** ++ * The player instance ++ */ + private Player player; + ++ /** ++ * Cache of LWCPlayer objects ++ */ ++ private final static Map players = new HashMap(); ++ ++ /** ++ * The modes bound to all players ++ */ ++ private final static Map> modes = Collections.synchronizedMap(new HashMap>()); ++ ++ /** ++ * The actions bound to all players ++ */ ++ private final static Map> actions = Collections.synchronizedMap(new HashMap>()); ++ ++ /** ++ * Map of protections a player can temporarily access ++ */ ++ private final static Map> accessibleProtections = Collections.synchronizedMap(new HashMap>()); ++ + public LWCPlayer(LWC lwc, Player player) { + this.lwc = lwc; + this.player = player; + } + ++ /** ++ * Get the LWCPlayer object from a Player object ++ * ++ * @param player ++ * @return ++ */ ++ public static LWCPlayer getPlayer(Player player) { ++ if (!players.containsKey(player)) { ++ players.put(player, new LWCPlayer(LWC.getInstance(), player)); ++ } ++ ++ return players.get(player); ++ } ++ ++ /** ++ * @return the Bukkit Player object ++ */ ++ public Player getBukkitPlayer() { ++ return player; ++ } ++ ++ /** ++ * @return the player's name ++ */ ++ public String getName() { ++ return player.getName(); ++ } ++ ++ /** ++ * Enable a mode on the player ++ * ++ * @param mode ++ * @return ++ */ ++ public boolean enableMode(Mode mode) { ++ return getModes().add(mode); ++ } ++ ++ /** ++ * Disable a mode on the player ++ * ++ * @param mode ++ * @return ++ */ ++ public boolean disableMode(Mode mode) { ++ return getModes().remove(mode); ++ } ++ ++ /** ++ * Disable all modes enabled by the player ++ * ++ * @return ++ */ ++ public void disableAllModes() { ++ getModes().clear(); ++ } ++ ++ /** ++ * Check if the player has an action ++ * ++ * @param name ++ * @return ++ */ ++ public boolean hasAction(String name) { ++ return getAction(name) != null; ++ } ++ ++ /** ++ * Get the action represented by the name ++ * ++ * @param name ++ * @return ++ */ ++ public Action getAction(String name) { ++ for (Action action : getActions()) { ++ if (action.getName().equals(name)) { ++ return action; ++ } ++ } ++ ++ return null; ++ } ++ ++ /** ++ * Add an action ++ * ++ * @param action ++ * @return ++ */ ++ public boolean addAction(Action action) { ++ return getActions().add(action); ++ } ++ ++ /** ++ * Remove an action ++ * ++ * @param action ++ * @return ++ */ ++ public boolean removeAction(Action action) { ++ return getActions().remove(action); ++ } ++ ++ /** ++ * Remove all actions ++ */ ++ public void removeAllActions() { ++ getActions().clear(); ++ } ++ ++ /** ++ * Retrieve a Mode object for a player ++ * ++ * @param name ++ * @return ++ */ ++ public Mode getMode(String name) { ++ for (Mode mode : getModes()) { ++ if (mode.getName().equals(name)) { ++ return mode; ++ } ++ } ++ ++ return null; ++ } ++ ++ /** ++ * Check if the player has the given mode ++ * ++ * @param name ++ * @return ++ */ ++ public boolean hasMode(String name) { ++ return getMode(name) != null; ++ } ++ ++ /** ++ * @return the Set of modes the player has activated ++ */ ++ public Set getModes() { ++ if (!modes.containsKey(this)) { ++ modes.put(this, new HashSet()); ++ } ++ ++ return modes.get(this); ++ } ++ ++ /** ++ * @return the Set of actions the player has ++ */ ++ public Set getActions() { ++ if (!actions.containsKey(this)) { ++ actions.put(this, new HashSet()); ++ } ++ ++ return actions.get(this); ++ } ++ ++ /** ++ * @return a Set containing all of the action names ++ */ ++ public Set getActionNames() { ++ Set actions = getActions(); ++ Set names = new HashSet(actions.size()); ++ ++ for (Action action : actions) { ++ names.add(action.getName()); ++ } ++ ++ return names; ++ } ++ ++ /** ++ * @return the set of protections the player can temporarily access ++ */ ++ public Set getAccessibleProtections() { ++ if (!accessibleProtections.containsKey(this)) { ++ accessibleProtections.put(this, new HashSet()); ++ } ++ ++ return accessibleProtections.get(this); ++ } ++ ++ /** ++ * Add an accessible protection for the player ++ * ++ * @param protection ++ * @return ++ */ ++ public boolean addAccessibleProtection(Protection protection) { ++ return getAccessibleProtections().add(protection); ++ } ++ ++ /** ++ * Remove an accessible protection from the player ++ * ++ * @param protection ++ * @return ++ */ ++ public boolean removeAccessibleProtection(Protection protection) { ++ return getAccessibleProtections().remove(protection); ++ } ++ ++ /** ++ * Remove all accessible protections ++ */ ++ public void removeAllAccessibleProtections() { ++ getAccessibleProtections().clear(); ++ } ++ + /** + * Create a History object that is attached to this protection + * +@@ -84,4 +332,63 @@ public List getRelatedHistory(History.Type type) { + return related; + } + ++ public void sendMessage(String s) { ++ player.sendMessage(s); ++ } ++ ++ public Server getServer() { ++ return player.getServer(); ++ } ++ ++ public boolean isPermissionSet(String s) { ++ return player.isPermissionSet(s); ++ } ++ ++ public boolean isPermissionSet(Permission permission) { ++ return player.isPermissionSet(permission); ++ } ++ ++ public boolean hasPermission(String s) { ++ return player.hasPermission(s); ++ } ++ ++ public boolean hasPermission(Permission permission) { ++ return player.hasPermission(permission); ++ } ++ ++ public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b) { ++ return player.addAttachment(plugin, s, b); ++ } ++ ++ public PermissionAttachment addAttachment(Plugin plugin) { ++ return player.addAttachment(plugin); ++ } ++ ++ public PermissionAttachment addAttachment(Plugin plugin, String s, boolean b, int i) { ++ return player.addAttachment(plugin, s, b, i); ++ } ++ ++ public PermissionAttachment addAttachment(Plugin plugin, int i) { ++ return player.addAttachment(plugin, i); ++ } ++ ++ public void removeAttachment(PermissionAttachment permissionAttachment) { ++ player.removeAttachment(permissionAttachment); ++ } ++ ++ public void recalculatePermissions() { ++ player.recalculatePermissions(); ++ } ++ ++ public Set getEffectivePermissions() { ++ return player.getEffectivePermissions(); ++ } ++ ++ public boolean isOp() { ++ return player.isOp(); ++ } ++ ++ public void setOp(boolean b) { ++ player.setOp(b); ++ } + } +diff --git a/src/main/java/com/griefcraft/model/Mode.java b/src/main/java/com/griefcraft/model/Mode.java +new file mode 100644 +index 000000000..75a5450cd +--- /dev/null ++++ b/src/main/java/com/griefcraft/model/Mode.java +@@ -0,0 +1,63 @@ ++/** ++ * This file is part of LWC (https://github.com/Hidendra/LWC) ++ * ++ * This program is free software: you can redistribute it and/or modify ++ * it under the terms of the GNU General Public License as published by ++ * the Free Software Foundation, either version 3 of the License, or ++ * (at your option) any later version. ++ * ++ * This program is distributed in the hope that it will be useful, ++ * but WITHOUT ANY WARRANTY; without even the implied warranty of ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ++ * GNU General Public License for more details. ++ * ++ * You should have received a copy of the GNU General Public License ++ * along with this program. If not, see . ++ */ ++ ++package com.griefcraft.model; ++ ++import org.bukkit.entity.Player; ++ ++public class Mode { ++ ++ /** ++ * The name of this mode ++ */ ++ private String name; ++ ++ /** ++ * The player this mode belongs to ++ */ ++ private Player player; ++ ++ /** ++ * Mode data ++ */ ++ private String data; ++ ++ public String getName() { ++ return name; ++ } ++ ++ public Player getPlayer() { ++ return player; ++ } ++ ++ public String getData() { ++ return data; ++ } ++ ++ public void setName(String name) { ++ this.name = name; ++ } ++ ++ public void setPlayer(Player player) { ++ this.player = player; ++ } ++ ++ public void setData(String data) { ++ this.data = data; ++ } ++ ++} +diff --git a/src/main/java/com/griefcraft/sql/MemDB.java b/src/main/java/com/griefcraft/sql/MemDB.java +deleted file mode 100755 +index b92531459..000000000 +--- a/src/main/java/com/griefcraft/sql/MemDB.java ++++ /dev/null +@@ -1,831 +0,0 @@ +-/** +- * This file is part of LWC (https://github.com/Hidendra/LWC) +- * +- * This program is free software: you can redistribute it and/or modify +- * it under the terms of the GNU General Public License as published by +- * the Free Software Foundation, either version 3 of the License, or +- * (at your option) any later version. +- * +- * This program is distributed in the hope that it will be useful, +- * but WITHOUT ANY WARRANTY; without even the implied warranty of +- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +- * GNU General Public License for more details. +- * +- * You should have received a copy of the GNU General Public License +- * along with this program. If not, see . +- */ +- +-package com.griefcraft.sql; +- +-import com.griefcraft.model.Action; +-import com.griefcraft.model.Protection; +-import com.griefcraft.util.Performance; +- +-import java.sql.PreparedStatement; +-import java.sql.ResultSet; +-import java.sql.Statement; +-import java.util.ArrayList; +-import java.util.List; +- +-public class MemDB extends Database { +- +- public MemDB() { +- super(); +- } +- +- public MemDB(Type currentType) { +- super(currentType); +- } +- +- @Override +- protected void postPrepare() { +- Performance.addMemDBQuery(); +- } +- +- public Action getAction(String action, String player) { +- try { +- PreparedStatement statement = prepare(""SELECT * FROM "" + prefix + ""actions WHERE player = ? AND action = ?""); +- statement.setString(1, player); +- statement.setString(2, action); +- +- ResultSet set = statement.executeQuery(); +- +- if (set.next()) { +- final int id = set.getInt(""id""); +- final String actionString = set.getString(""action""); +- final String playerString = set.getString(""player""); +- final int chestID = set.getInt(""chest""); +- final String data = set.getString(""data""); +- +- final Action act = new Action(); +- act.setId(id); +- act.setAction(actionString); +- act.setPlayer(playerString); +- act.setProtectionId(chestID); +- act.setData(data); +- +- return act; +- } +- +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return null; +- } +- +- /** +- * Get the chest ID associated with a player's unlock request +- * +- * @param player the player to lookup +- * @return the chest ID +- */ +- public int getActionID(String action, String player) { +- try { +- int chestID = -1; +- +- PreparedStatement statement = prepare(""SELECT chest FROM "" + prefix + ""actions WHERE action = ? AND player = ?""); +- statement.setString(1, action); +- statement.setString(2, player); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- chestID = set.getInt(""chest""); +- } +- +- +- return chestID; +- } catch (final Exception e) { +- printException(e); +- } +- +- return -1; +- } +- +- /** +- * Get all the active actions for a player +- * +- * @param player the player to get actions for +- * @return the List of actions +- */ +- public List getActions(String player) { +- final List actions = new ArrayList(); +- +- try { +- PreparedStatement statement = prepare(""SELECT action FROM "" + prefix + ""actions WHERE player = ?""); +- statement.setString(1, player); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- final String action = set.getString(""action""); +- +- actions.add(action); +- } +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return actions; +- } +- +- /** +- * @return the path where the database file should be saved +- */ +- @Override +- public String getDatabasePath() { +- // if we're using mysql, just open another connection +- if (currentType == Type.MySQL) { +- return super.getDatabasePath(); +- } +- +- return "":memory:""; +- } +- +- /** +- * Get the password submitted for a pending chest lock +- * +- * @param player the player to lookup +- * @return the password for the pending lock +- */ +- public String getLockPassword(String player) { +- try { +- String password = """"; +- +- PreparedStatement statement = prepare(""SELECT password FROM "" + prefix + ""locks WHERE player = ?""); +- statement.setString(1, player); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- password = set.getString(""password""); +- } +- +- +- return password; +- } catch (final Exception e) { +- printException(e); +- } +- +- return null; +- } +- +- /** +- * Get the mode data for a player's mode +- * +- * @param player +- * @param mode +- * @return +- */ +- public String getModeData(String player, String mode) { +- String ret = null; +- try { +- PreparedStatement statement = prepare(""SELECT data FROM "" + prefix + ""modes WHERE player = ? AND mode = ?""); +- statement.setString(1, player); +- statement.setString(2, mode); +- +- final ResultSet set = statement.executeQuery(); +- if (set.next()) { +- ret = set.getString(""data""); +- } +- +- +- } catch (final Exception e) { +- printException(e); +- } +- return ret; +- } +- +- /** +- * Get the modes a player has activated +- * +- * @param player the player to get +- * @return the List of modes the player is using +- */ +- public List getModes(String player) { +- final List modes = new ArrayList(); +- +- try { +- PreparedStatement statement = prepare(""SELECT * FROM "" + prefix + ""modes WHERE player = ?""); +- statement.setString(1, player); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- final String mode = set.getString(""mode""); +- +- modes.add(mode); +- } +- +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return modes; +- } +- +- /** +- * Get all of the users ""logged in"" to a chest +- * +- * @param chestID the chest ID to look at +- * @return +- */ +- public List getSessionUsers(int chestID) { +- final List sessionUsers = new ArrayList(); +- +- try { +- PreparedStatement statement = prepare(""SELECT player FROM "" + prefix + ""sessions WHERE chest = ?""); +- statement.setInt(1, chestID); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- final String player = set.getString(""player""); +- +- sessionUsers.add(player); +- } +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return sessionUsers; +- } +- +- /** +- * Get the chest ID associated with a player's unlock request +- * +- * @param player the player to lookup +- * @return the chest ID +- */ +- public int getUnlockID(String player) { +- return getActionID(""unlock"", player); +- } +- +- /** +- * Check if a player has an active chest session +- * +- * @param player the player to check +- * @param chestID the chest ID to check +- * @return true if the player has access +- */ +- public boolean hasAccess(String player, int chestID) { +- try { +- PreparedStatement statement = prepare(""SELECT player FROM "" + prefix + ""sessions WHERE chest = ?""); +- statement.setInt(1, chestID); +- +- final ResultSet set = statement.executeQuery(); +- +- while (set.next()) { +- final String player2 = set.getString(""player""); +- +- if (player.equals(player2)) { +- +- +- return true; +- } +- } +- +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return false; +- } +- +- /** +- * Check if a player has an active chest session +- * +- * @param player the player to check +- * @param chest the chest to check +- * @return true if the player has access +- */ +- public boolean hasAccess(String player, Protection chest) { +- return chest == null || hasAccess(player, chest.getId()); +- +- } +- +- /** +- * Return if a player has the mode +- * +- * @param player the player to check +- * @param mode the mode to check +- */ +- public boolean hasMode(String player, String mode) { +- List modes = getModes(player); +- +- return modes.size() > 0 && modes.contains(mode); +- } +- +- /** +- * Check if a player has a pending action +- * +- * @param player the player to check +- * @param action the action to check +- * @return true if they have a record +- */ +- public boolean hasPendingAction(String action, String player) { +- return getAction(action, player) != null; +- } +- +- /** +- * Check if a player has a pending chest request +- * +- * @param player The player to check +- * @return true if the player has a pending chest request +- */ +- public boolean hasPendingChest(String player) { +- try { +- PreparedStatement statement = prepare(""SELECT id FROM "" + prefix + ""locks WHERE player = ?""); +- statement.setString(1, player); +- +- ResultSet set = statement.executeQuery(); +- +- if (set.next()) { +- set.close(); +- return true; +- } +- +- set.close(); +- } catch (final Exception e) { +- printException(e); +- } +- +- return false; +- } +- +- /** +- * Check if a player has a pending unlock request +- * +- * @param player the player to check +- * @return true if the player has a pending unlock request +- */ +- public boolean hasPendingUnlock(String player) { +- return getUnlockID(player) != -1; +- } +- +- /** +- * create the in-memory table which hold sessions, users that have activated a chest. Not needed past a restart, so no need for extra disk i/o +- */ +- @Override +- public void load() { +- if (loaded) { +- return; +- } +- +- try { +- // reusable column +- Column column; +- +- Table sessions = new Table(this, ""sessions""); +- sessions.setMemory(true); +- +- { +- column = new Column(""id""); +- column.setType(""INTEGER""); +- column.setPrimary(true); +- sessions.add(column); +- +- column = new Column(""player""); +- column.setType(""VARCHAR(255)""); +- sessions.add(column); +- +- column = new Column(""chest""); +- column.setType(""INTEGER""); +- sessions.add(column); +- } +- +- Table locks = new Table(this, ""locks""); +- locks.setMemory(true); +- +- { +- column = new Column(""id""); +- column.setType(""INTEGER""); +- column.setPrimary(true); +- locks.add(column); +- +- column = new Column(""player""); +- column.setType(""VARCHAR(255)""); +- locks.add(column); +- +- column = new Column(""password""); +- column.setType(""VARCHAR(100)""); +- locks.add(column); +- } +- +- Table actions = new Table(this, ""actions""); +- actions.setMemory(true); +- +- { +- column = new Column(""id""); +- column.setType(""INTEGER""); +- column.setPrimary(true); +- actions.add(column); +- +- column = new Column(""action""); +- column.setType(""VARCHAR(255)""); +- actions.add(column); +- +- column = new Column(""player""); +- column.setType(""VARCHAR(255)""); +- actions.add(column); +- +- column = new Column(""chest""); +- column.setType(""INTEGER""); +- actions.add(column); +- +- column = new Column(""data""); +- column.setType(""VARCHAR(255)""); +- actions.add(column); +- } +- +- Table modes = new Table(this, ""modes""); +- modes.setMemory(true); +- +- { +- column = new Column(""id""); +- column.setType(""INTEGER""); +- column.setPrimary(true); +- modes.add(column); +- +- column = new Column(""player""); +- column.setType(""VARCHAR(255)""); +- modes.add(column); +- +- column = new Column(""mode""); +- column.setType(""VARCHAR(255)""); +- modes.add(column); +- +- column = new Column(""data""); +- column.setType(""VARCHAR(255)""); +- modes.add(column); +- } +- +- // now create all of the tables +- sessions.execute(); +- locks.execute(); +- actions.execute(); +- modes.execute(); +- } catch (final Exception e) { +- printException(e); +- } +- +- loaded = true; +- } +- +- /** +- * @return the number of pending chest locks +- */ +- public int pendingCount() { +- int count = 0; +- +- try { +- Statement statement = connection.createStatement(); +- final ResultSet set = statement.executeQuery(""SELECT id FROM "" + prefix + ""locks""); +- +- while (set.next()) { +- count++; +- } +- +- statement.close(); +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return count; +- } +- +- /** +- * Register a pending chest unlock, for when the player does /unlock +- * +- * @param action +- * @param player +- */ +- public void registerAction(String action, String player) { +- try { +- /* +- * We only want 1 action per player, no matter what! +- */ +- unregisterAction(action, player); +- +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""actions (action, player, chest) VALUES (?, ?, ?)""); +- statement.setString(1, action); +- statement.setString(2, player); +- statement.setInt(3, -1); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register a pending chest unlock, for when the player does /unlock +- * +- * @param player the player to register +- * @param chestID the chestID to unlock +- */ +- public void registerAction(String action, String player, int chestID) { +- try { +- /* +- * We only want 1 action per player, no matter what! +- */ +- unregisterAction(action, player); +- +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""actions (action, player, chest) VALUES (?, ?, ?)""); +- statement.setString(1, action); +- statement.setString(2, player); +- statement.setInt(3, chestID); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register an action, used for various actions (stating the obvious here) +- * +- * @param player the player to register +- * @param data data +- */ +- public void registerAction(String action, String player, String data) { +- try { +- /* +- * We only want 1 action per player, no matter what! +- */ +- unregisterAction(action, player); +- +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""actions (action, player, data) VALUES (?, ?, ?)""); +- statement.setString(1, action); +- statement.setString(2, player); +- statement.setString(3, data); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register a mode to a player (temporary) +- * +- * @param player the player to register the mode to +- * @param mode the mode to register +- */ +- public void registerMode(String player, String mode) { +- try { +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""modes (player, mode) VALUES (?, ?)""); +- statement.setString(1, player); +- statement.setString(2, mode); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register a mode with data to a player (temporary) +- * +- * @param player the player to register the mode to +- * @param mode the mode to register +- * @param data additional data +- */ +- public void registerMode(String player, String mode, String data) { +- try { +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""modes (player, mode, data) VALUES (?, ?, ?)""); +- statement.setString(1, player); +- statement.setString(2, mode); +- statement.setString(3, data); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register a pending lock request to a player +- * +- * @param player the player to assign the chest to +- * @param password the password to register with +- */ +- public void registerPendingLock(String player, String password) { +- try { +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""locks (player, password) VALUES (?, ?)""); +- statement.setString(1, player); +- statement.setString(2, password); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Add a player to be allowed to access a chest +- * +- * @param player the player to add +- * @param chestID the chest ID to allow them to access +- */ +- public void registerPlayer(String player, int chestID) { +- try { +- PreparedStatement statement = prepare(""INSERT INTO "" + prefix + ""sessions (player, chest) VALUES(?, ?)""); +- statement.setString(1, player); +- statement.setInt(2, chestID); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Register a pending chest unlock, for when the player does /unlock +- * +- * @param player the player to register +- * @param chestID the chestID to unlock +- */ +- public void registerUnlock(String player, int chestID) { +- registerAction(""unlock"", player, chestID); +- } +- +- /** +- * @return the number of active session +- */ +- public int sessionCount() { +- int count = 0; +- +- try { +- Statement statement = connection.createStatement(); +- final ResultSet set = statement.executeQuery(""SELECT id FROM "" + prefix + ""sessions""); +- +- while (set.next()) { +- count++; +- } +- +- statement.close(); +- +- } catch (final Exception e) { +- printException(e); +- } +- +- return count; +- } +- +- /** +- * Unregister a pending chest unlock +- * +- * @param player the player to unregister +- */ +- public void unregisterAction(String action, String player) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""actions WHERE action = ? AND player = ?""); +- statement.setString(1, action); +- statement.setString(2, player); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Unregister all of the actions for a player +- * +- * @param player the player to unregister +- */ +- public void unregisterAllActions(String player) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""actions WHERE player = ?""); +- statement.setString(1, player); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Remove all the pending chest requests +- */ +- public void unregisterAllChests() { +- try { +- Statement statement = connection.createStatement(); +- statement.executeUpdate(""DELETE FROM "" + prefix + ""locks""); +- +- statement.close(); +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Unregister all of the modes FROM "" + prefix + ""a player +- * +- * @param player the player to unregister all modes from +- */ +- public void unregisterAllModes(String player) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""modes WHERE player = ?""); +- statement.setString(1, player); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Unregister a mode FROM "" + prefix + ""a player +- * +- * @param player the player to register the mode to +- * @param mode the mode to unregister +- */ +- public void unregisterMode(String player, String mode) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""modes WHERE player = ? AND mode = ?""); +- statement.setString(1, player); +- statement.setString(2, mode); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Remove a pending lock request FROM "" + prefix + ""a player +- * +- * @param player the player to remove +- */ +- public void unregisterPendingLock(String player) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""locks WHERE player = ?""); +- statement.setString(1, player); +- +- statement.executeUpdate(); +- +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Remove a player FROM "" + prefix + ""any sessions +- * +- * @param player the player to remove +- */ +- public void unregisterPlayer(String player) { +- try { +- PreparedStatement statement = prepare(""DELETE FROM "" + prefix + ""sessions WHERE player = ?""); +- statement.setString(1, player); +- +- statement.executeUpdate(); +- +- } catch (final Exception e) { +- printException(e); +- } +- } +- +- /** +- * Unregister a pending chest unlock +- * +- * @param player the player to unregister +- */ +- public void unregisterUnlock(String player) { +- unregisterAction(""unlock"", player); +- } +- +-}" +c9d4924dcf129512dadd22dcd6fe0046cbcded43,drools,BZ-1039639 - GRE doesn't recognize MVEL inline- lists when opening rule--,c,https://github.com/kiegroup/drools,"diff --git a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java +index 05b7b836bf1..9da1dd93e78 100644 +--- a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java ++++ b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java +@@ -26,7 +26,9 @@ + import org.drools.workbench.models.datamodel.oracle.ModelField; + import org.drools.workbench.models.datamodel.oracle.PackageDataModelOracle; + import org.drools.workbench.models.datamodel.rule.ActionCallMethod; ++import org.drools.workbench.models.datamodel.rule.ActionFieldValue; + import org.drools.workbench.models.datamodel.rule.ActionGlobalCollectionAdd; ++import org.drools.workbench.models.datamodel.rule.ActionSetField; + import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint; + import org.drools.workbench.models.datamodel.rule.CEPWindow; + import org.drools.workbench.models.datamodel.rule.CompositeFactPattern; +@@ -36,6 +38,8 @@ + import org.drools.workbench.models.datamodel.rule.ExpressionVariable; + import org.drools.workbench.models.datamodel.rule.FactPattern; + import org.drools.workbench.models.datamodel.rule.FieldConstraint; ++import org.drools.workbench.models.datamodel.rule.FieldNature; ++import org.drools.workbench.models.datamodel.rule.FieldNatureType; + import org.drools.workbench.models.datamodel.rule.FreeFormLine; + import org.drools.workbench.models.datamodel.rule.IPattern; + import org.drools.workbench.models.datamodel.rule.RuleModel; +@@ -1982,6 +1986,43 @@ public void testExpressionWithListSize() throws Exception { + assertEquals(1,constraint.getConstraintValueType()); + } + ++ @Test ++ @Ignore(""https://bugzilla.redhat.com/show_bug.cgi?id=1039639 - GRE doesn't recognize MVEL inline lists when opening rule"") ++ public void testMVELInlineList() throws Exception { ++ String drl = """" + ++ ""rule \""Borked\""\n"" + ++ "" dialect \""mvel\""\n"" + ++ "" when\n"" + ++ "" c : Company( )\n"" + ++ "" then\n"" + ++ "" c.setEmps( [\""item1\"", \""item2\""] );\n"" + ++ ""end""; ++ ++ addModelField(""Company"", ++ ""emps"", ++ ""java.util.List"", ++ ""List""); ++ ++ RuleModel m = RuleModelDRLPersistenceImpl.getInstance().unmarshal( drl, ++ dmo ); ++ assertEquals( 1, ++ m.rhs.length ); ++ assertTrue( m.rhs[0] instanceof ActionSetField); ++ ActionSetField actionSetField = (ActionSetField) m.rhs[0]; ++ ++ assertEquals(""c"", actionSetField.getVariable()); ++ ++ assertEquals(1, actionSetField.getFieldValues().length); ++ ++ ActionFieldValue actionFieldValue = actionSetField.getFieldValues()[0]; ++ ++ assertEquals(""[\""item1\"", \""item2\""]"",actionFieldValue.getValue()); ++ assertEquals(""emps"",actionFieldValue.getField()); ++ assertEquals(FieldNatureType.TYPE_FORMULA, actionFieldValue.getNature()); ++ assertEquals(""Collection"",actionFieldValue.getType()); ++ ++ } ++ + private void assertEqualsIgnoreWhitespace( final String expected, + final String actual ) { + final String cleanExpected = expected.replaceAll( ""\\s+""," +83d5b1e6a0280cc78625bacc2d3f7d1676c7385e,kotlin,Supported propagation for subclass of- j.u.Collection and similar classes.--,a,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +7db30f8428ef341cc39b2758d3bd6dcccc25b080,hadoop,MAPREDUCE-3345. Fixed a race condition in- ResourceManager that was causing TestContainerManagerSecurity to fail- sometimes. Contributed by Hitesh Shah. svn merge -c r1199144- --ignore-ancestry ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1199145 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt +index 43cb6b7dd248c..e1034c880ef65 100644 +--- a/hadoop-mapreduce-project/CHANGES.txt ++++ b/hadoop-mapreduce-project/CHANGES.txt +@@ -39,6 +39,9 @@ Release 0.23.1 - Unreleased + MAPREDUCE-3342. Fixed JobHistoryServer to also show the job's queue + name. (Jonathan Eagles via vinodkv) + ++ MAPREDUCE-3345. Fixed a race condition in ResourceManager that was causing ++ TestContainerManagerSecurity to fail sometimes. (Hitesh Shah via vinodkv) ++ + Release 0.23.0 - 2011-11-01 + + INCOMPATIBLE CHANGES +diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +index 0d81f80121213..71dd982b607af 100644 +--- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java ++++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +@@ -595,8 +595,13 @@ public void transition(RMAppAttemptImpl appAttempt, + AM_CONTAINER_PRIORITY, ""*"", appAttempt.submissionContext + .getAMContainerSpec().getResource(), 1); + +- appAttempt.scheduler.allocate(appAttempt.applicationAttemptId, +- Collections.singletonList(request), EMPTY_CONTAINER_RELEASE_LIST); ++ Allocation amContainerAllocation = ++ appAttempt.scheduler.allocate(appAttempt.applicationAttemptId, ++ Collections.singletonList(request), EMPTY_CONTAINER_RELEASE_LIST); ++ if (amContainerAllocation != null ++ && amContainerAllocation.getContainers() != null) { ++ assert(amContainerAllocation.getContainers().size() == 0); ++ } + } + } + +diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java +index c61c7ab89f0ec..977150520a195 100644 +--- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java ++++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java +@@ -236,28 +236,30 @@ public Allocation allocate( + RMContainerEventType.RELEASED); + } + +- if (!ask.isEmpty()) { +- LOG.debug(""allocate: pre-update"" + +- "" applicationId="" + applicationAttemptId + +- "" application="" + application); +- application.showRequests(); +- +- // Update application requests +- application.updateResourceRequests(ask); +- +- LOG.debug(""allocate: post-update"" + +- "" applicationId="" + applicationAttemptId + +- "" application="" + application); +- application.showRequests(); ++ synchronized (application) { ++ if (!ask.isEmpty()) { ++ LOG.debug(""allocate: pre-update"" + ++ "" applicationId="" + applicationAttemptId + ++ "" application="" + application); ++ application.showRequests(); ++ ++ // Update application requests ++ application.updateResourceRequests(ask); ++ ++ LOG.debug(""allocate: post-update"" + ++ "" applicationId="" + applicationAttemptId + ++ "" application="" + application); ++ application.showRequests(); ++ ++ LOG.debug(""allocate:"" + ++ "" applicationId="" + applicationAttemptId + ++ "" #ask="" + ask.size()); ++ } + +- LOG.debug(""allocate:"" + +- "" applicationId="" + applicationAttemptId + +- "" #ask="" + ask.size()); ++ return new Allocation( ++ application.pullNewlyAllocatedContainers(), ++ application.getHeadroom()); + } +- +- return new Allocation( +- application.pullNewlyAllocatedContainers(), +- application.getHeadroom()); + } + + private SchedulerApp getApplication(" +7631ac6f526edf472d1383f7b82171c7ac29f0fb,Delta Spike,"DELTASPIKE-378 add getPropertyAwarePropertyValue + +feel free to propose a better name if you find one :) +",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +index 05cbc59df..6b3ada263 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +@@ -162,18 +162,110 @@ public static String getPropertyValue(String key) + *

Attention This method must only be used after all ConfigSources + * got registered and it also must not be used to determine the ProjectStage itself.

+ * @param key ++ * @return the configured value or if non found the defaultValue ++ * ++ */ ++ public static String getProjectStageAwarePropertyValue(String key) ++ { ++ ProjectStage ps = getProjectStage(); ++ ++ String value = getPropertyValue(key + '.' + ps); ++ if (value == null) ++ { ++ value = getPropertyValue(key); ++ } ++ ++ return value; ++ } ++ /** ++ * {@link #getProjectStageAwarePropertyValue(String)} which returns the defaultValue ++ * if the property is null or empty. ++ * @param key + * @param defaultValue + * @return the configured value or if non found the defaultValue + * + */ + public static String getProjectStageAwarePropertyValue(String key, String defaultValue) + { +- ProjectStage ps = getProjectStage(); ++ String value = getProjectStageAwarePropertyValue(key); ++ ++ if (value == null || value.length() == 0) ++ { ++ value = defaultValue; ++ } ++ ++ return value; ++ } ++ ++ /** ++ *

Search for the configured value in all {@link ConfigSource}s and take the ++ * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} ++ * and the value configured for the given property into account.

++ * ++ *

The first step is to resolve the value of the given property. This will ++ * take the current ProjectStage into account. E.g. given the property is 'dbvendor' ++ * and the ProjectStage is 'UnitTest', the first lookup is ++ *

  • 'dbvendor.UnitTest'
. ++ * If this value is not found then we will do a 2nd lookup for ++ *
  • 'dbvendor'

++ * ++ *

If a value was found for the given property (e.g. dbvendor = 'mysql' ++ * then we will use this value to lookup in the following order until we ++ * found a non-null value. If there was no value found for the property ++ * we will only do the key+ProjectStage and key lookup. ++ * In the following sample 'dataSource' is used as key parameter: ++ * ++ *

    ++ *
  • 'datasource.mysql.UnitTest'
  • ++ *
  • 'datasource.mysql'
  • ++ *
  • 'datasource.UnitTest'
  • ++ *
  • 'datasource'
  • ++ *
++ *

++ * ++ * ++ *

Attention This method must only be used after all ConfigSources ++ * got registered and it also must not be used to determine the ProjectStage itself.

++ * @param key ++ * @param property the property to look up first ++ * @return the configured value or if non found the defaultValue ++ * ++ */ ++ public static String getPropertyAwarePropertyValue(String key, String property) ++ { ++ String propertyValue = getProjectStageAwarePropertyValue(property); ++ ++ String value = null; ++ ++ if (propertyValue != null && propertyValue.length() > 0) ++ { ++ value = getProjectStageAwarePropertyValue(key + '.' + propertyValue); ++ } + +- String value = getPropertyValue(key + '.' + ps, defaultValue); + if (value == null) + { +- value = getPropertyValue(key, defaultValue); ++ value = getProjectStageAwarePropertyValue(key); ++ } ++ ++ return value; ++ } ++ ++ /* ++ *

Attention This method must only be used after all ConfigSources ++ * got registered and it also must not be used to determine the ProjectStage itself.

++ * @param key ++ * @param property the property to look up first ++ * @param defaultValue ++ * @return the configured value or if non found the defaultValue ++ * ++ */ ++ public static String getPropertyAwarePropertyValue(String key, String property, String defaultValue) ++ { ++ String value = getPropertyAwarePropertyValue(key, property); ++ ++ if (value == null || value.length() == 0) ++ { ++ value = defaultValue; + } + + return value; +diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +index 91ebb22dc..d30e7de52 100644 +--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java ++++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +@@ -28,6 +28,7 @@ + + public class ConfigResolverTest + { ++ private static final String DEFAULT_VALUE = ""defaultValue""; + @Test + public void testOverruledValue() + { +@@ -60,12 +61,43 @@ public void testGetProjectStageAwarePropertyValue() + Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue(""notexisting"", null)); + + Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey"", null)); ++ Assert.assertEquals(""unittestvalue"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey"")); + Assert.assertEquals(""unittestvalue"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey"", null)); + + Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey2"", null)); ++ Assert.assertEquals(""testvalue"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey2"")); + Assert.assertEquals(""testvalue"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey2"", null)); + + Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey3"", null)); +- Assert.assertEquals("""", ConfigResolver.getProjectStageAwarePropertyValue(""testkey3"", null)); ++ Assert.assertEquals("""", ConfigResolver.getProjectStageAwarePropertyValue(""testkey3"")); ++ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getProjectStageAwarePropertyValue(""testkey3"", DEFAULT_VALUE)); ++ } ++ ++ @Test ++ public void testGetPropertyAwarePropertyValue() { ++ ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); ++ ++ Assert.assertNull(ConfigResolver.getPropertyAwarePropertyValue(""notexisting"", null)); ++ ++ Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey"", null)); ++ Assert.assertEquals(""unittestvalue"", ConfigResolver.getPropertyAwarePropertyValue(""testkey"", ""dbvendor"")); ++ Assert.assertEquals(""unittestvalue"", ConfigResolver.getPropertyAwarePropertyValue(""testkey"", ""dbvendor"", null)); ++ ++ Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey2"", null)); ++ Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyAwarePropertyValue(""testkey2"", ""dbvendor"")); ++ Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyAwarePropertyValue(""testkey2"", ""dbvendor"", null)); ++ ++ Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey3"", null)); ++ Assert.assertEquals("""", ConfigResolver.getPropertyAwarePropertyValue(""testkey3"", ""dbvendor"")); ++ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue(""testkey3"", ""dbvendor"", DEFAULT_VALUE)); ++ ++ Assert.assertEquals(""TestDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendor"")); ++ Assert.assertEquals(""PostgreDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendor2"")); ++ Assert.assertEquals(""DefaultDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendorX"")); ++ ++ Assert.assertEquals(""TestDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendor"", null)); ++ Assert.assertEquals(""PostgreDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendor2"", null)); ++ Assert.assertEquals(""DefaultDataSource"", ConfigResolver.getPropertyAwarePropertyValue(""dataSource"", ""dbvendorX"", null)); ++ Assert.assertEquals(DEFAULT_VALUE, ConfigResolver.getPropertyAwarePropertyValue(""dataSourceX"", ""dbvendorX"", DEFAULT_VALUE)); + } + } +diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +index e9e066fba..d0f2c938b 100644 +--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java ++++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +@@ -48,6 +48,20 @@ public TestConfigSource() + // a value which got ProjectStage overloaded to an empty value + props.put(""testkey3"", ""testvalue""); + props.put(""testkey3.UnitTest"", """"); ++ ++ // now for the PropertyAware tests ++ props.put(""dbvendor.UnitTest"", ""mysql""); ++ props.put(""dbvendor"", ""postgresql""); ++ ++ props.put(""dataSource.mysql.Production"", ""java:/comp/env/MyDs""); ++ props.put(""dataSource.mysql.UnitTest"", ""TestDataSource""); ++ props.put(""dataSource.postgresql"", ""PostgreDataSource""); ++ props.put(""dataSource"", ""DefaultDataSource""); ++ ++ // another one ++ props.put(""dbvendor2.Production"", ""mysql""); ++ props.put(""dbvendor2"", ""postgresql""); ++ + } + + @Override" +3cf09ec9a51263838270cb5f62d5b34cb58f26bb,Vala,"clutter-1.0: add missing type_arguments for several new methods + +Partially fixes bug 609875. +",c,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +1cda4eacbf8e44d03ecdfb6f16ab523306677cbc,restlet-framework-java, - The Request-isConfidential() method has- been refactored to be supported by Message and Response as well.- The method Request-setConfidential() has been removed (back to- Restlet 1.0 state). Added Protocol-isConfidential() method to- support the new implementation which rely on Request-getProtocol().- Reported by Kevin Conaway.--,p,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt +index 3bb3740fe2..51208741e0 100644 +--- a/build/tmpl/text/changes.txt ++++ b/build/tmpl/text/changes.txt +@@ -44,6 +44,12 @@ Changes log + ""style"" attributes are required. + - Added the ability the give a title to WadlApplication or + WadlResource instances. Suggested by Jérôme Bernard. ++ - The Request#isConfidential() method has been refactored to ++ be supported by Message and Response as well. The method ++ Request#setConfidential() has been removed (back to Restlet ++ 1.0 state). Added Protocol#isConfidential() method to support ++ the new implementation which rely on Request#getProtocol(). ++ Reported by Kevin Conaway. + - Misc + - Updated JAX-RS API to version 1.0. The implementation of the + runtime environment is not fully finished yet. We are +diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ChildClientDispatcher.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ChildClientDispatcher.java +index 4239efb2cf..6d9f19d948 100644 +--- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ChildClientDispatcher.java ++++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ChildClientDispatcher.java +@@ -72,9 +72,6 @@ public void doHandle(Request request, Response response) { + final Protocol protocol = request.getProtocol(); + + if (protocol.equals(Protocol.RIAP)) { +- // Consider that the request is confidential +- request.setConfidential(true); +- + // Let's dispatch it + final LocalReference cr = new LocalReference(request + .getResourceRef()); +diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java +index fc66f6e836..d81f983b14 100644 +--- a/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java ++++ b/modules/com.noelios.restlet/src/com/noelios/restlet/component/ComponentClientDispatcher.java +@@ -64,9 +64,6 @@ protected void doHandle(Request request, Response response) { + final Protocol protocol = request.getProtocol(); + + if (protocol.equals(Protocol.RIAP)) { +- // Consider that the request is confidential +- request.setConfidential(true); +- + // Let's dispatch it + final LocalReference cr = new LocalReference(request + .getResourceRef()); +diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpRequest.java b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpRequest.java +index ab6f7fa405..120613d7f6 100644 +--- a/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpRequest.java ++++ b/modules/com.noelios.restlet/src/com/noelios/restlet/http/HttpRequest.java +@@ -103,14 +103,6 @@ public HttpRequest(Context context, HttpServerCall httpCall) { + // Set the properties + setMethod(Method.valueOf(httpCall.getMethod())); + +- if (getHttpCall().isConfidential()) { +- setConfidential(true); +- } else { +- // We don't want to autocreate the security data just for this +- // information, because that will by the default value of this +- // property if read by someone. +- } +- + // Set the host reference + final StringBuilder sb = new StringBuilder(); + sb.append(httpCall.getProtocol().getSchemeName()).append(""://""); +diff --git a/modules/org.restlet/src/org/restlet/data/Message.java b/modules/org.restlet/src/org/restlet/data/Message.java +index d5ba7847fc..72fdfcd15e 100644 +--- a/modules/org.restlet/src/org/restlet/data/Message.java ++++ b/modules/org.restlet/src/org/restlet/data/Message.java +@@ -78,49 +78,50 @@ public Message(Representation entity) { + this.saxRepresentation = null; + } + +-/** +- * Returns the modifiable map of attributes that can be used by developers +- * to save information relative to the message. Creates a new instance if no +- * one has been set. This is an easier alternative to the creation of a +- * wrapper instance around the whole message.
+- *
+- * +- * In addition, this map is a shared space between the developer and the +- * connectors. In this case, it is used to exchange information that is not +- * uniform across all protocols and couldn't therefore be directly included +- * in the API. For this purpose, all attribute names starting with +- * ""org.restlet"" are reserved. Currently the following attributes are used: +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- * +- *
Attribute nameClass nameDescription
org.restlet.http.headersorg.restlet.data.FormServer HTTP connectors must provide all request headers and client +- * HTTP connectors must provide all response headers, exactly as they were +- * received. In addition, developers can also use this attribute to specify +- * non-standard headers that should be added to the request or to +- * the response.
org.restlet.https.clientCertificatesListFor requests received via a secure connector, indicates the ordered +- * list of client certificates, if they are available and accessible.

+- * Most of the standard HTTP headers are directly supported via the Restlet +- * API. Thus, adding such HTTP headers is forbidden because it could +- * conflict with the connector's internal behavior, limit portability or +- * prevent future optimizations. The other standard HTTP headers (that are +- * not supported) can be added as attributes via the +- * ""org.restlet.http.headers"" key.
+- * +- * @return The modifiable attributes map. +- */ ++ /** ++ * Returns the modifiable map of attributes that can be used by developers ++ * to save information relative to the message. Creates a new instance if no ++ * one has been set. This is an easier alternative to the creation of a ++ * wrapper instance around the whole message.
++ *
++ * ++ * In addition, this map is a shared space between the developer and the ++ * connectors. In this case, it is used to exchange information that is not ++ * uniform across all protocols and couldn't therefore be directly included ++ * in the API. For this purpose, all attribute names starting with ++ * ""org.restlet"" are reserved. Currently the following attributes are used: ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ * ++ *
Attribute nameClass nameDescription
org.restlet.http.headersorg.restlet.data.FormServer HTTP connectors must provide all request headers and client ++ * HTTP connectors must provide all response headers, exactly as they were ++ * received. In addition, developers can also use this attribute to specify ++ * non-standard headers that should be added to the request or to the ++ * response.
org.restlet.https.clientCertificatesListFor requests received via a secure connector, indicates the ordered ++ * list of client certificates, if they are available and accessible.
++ *
++ * Most of the standard HTTP headers are directly supported via the Restlet ++ * API. Thus, adding such HTTP headers is forbidden because it could ++ * conflict with the connector's internal behavior, limit portability or ++ * prevent future optimizations. The other standard HTTP headers (that are ++ * not supported) can be added as attributes via the ++ * ""org.restlet.http.headers"" key.
++ * ++ * @return The modifiable attributes map. ++ */ + public Map getAttributes() { + if (this.attributes == null) { + this.attributes = new TreeMap(); +@@ -234,6 +235,14 @@ public SaxRepresentation getEntityAsSax() { + return this.saxRepresentation; + } + ++ /** ++ * Indicates if the message was or will be exchanged confidentially, for ++ * example via a SSL-secured connection. ++ * ++ * @return True if the message is confidential. ++ */ ++ public abstract boolean isConfidential(); ++ + /** + * Indicates if a content is available and can be sent. Several conditions + * must be met: the content must exists and have some available data. +diff --git a/modules/org.restlet/src/org/restlet/data/Protocol.java b/modules/org.restlet/src/org/restlet/data/Protocol.java +index f21d806ff5..65669bbd3e 100644 +--- a/modules/org.restlet/src/org/restlet/data/Protocol.java ++++ b/modules/org.restlet/src/org/restlet/data/Protocol.java +@@ -59,7 +59,7 @@ public final class Protocol extends Metadata { + * @see org.restlet.data.LocalReference + */ + public static final Protocol CLAP = new Protocol(""clap"", ""CLAP"", +- ""Class Loader Access Protocol"", UNKNOWN_PORT); ++ ""Class Loader Access Protocol"", UNKNOWN_PORT, true); + + /** + * FILE is a standard scheme to access to representations stored in the file +@@ -72,7 +72,7 @@ public final class Protocol extends Metadata { + * @see org.restlet.data.LocalReference + */ + public static final Protocol FILE = new Protocol(""file"", ""FILE"", +- ""Local File System Protocol"", UNKNOWN_PORT); ++ ""Local File System Protocol"", UNKNOWN_PORT, true); + + /** FTP protocol. */ + public static final Protocol FTP = new Protocol(""ftp"", ""FTP"", +@@ -84,7 +84,7 @@ public final class Protocol extends Metadata { + + /** HTTPS protocol (via SSL socket). */ + public static final Protocol HTTPS = new Protocol(""https"", ""HTTPS"", +- ""HyperText Transport Protocol (Secure)"", 443); ++ ""HyperText Transport Protocol (Secure)"", 443, true); + + /** + * JAR (Java ARchive) is a common scheme to access to representations inside +@@ -94,7 +94,7 @@ public final class Protocol extends Metadata { + * @see org.restlet.data.LocalReference + */ + public static final Protocol JAR = new Protocol(""jar"", ""JAR"", +- ""Java ARchive"", UNKNOWN_PORT); ++ ""Java ARchive"", UNKNOWN_PORT, true); + + /** JDBC protocol. */ + public static final Protocol JDBC = new Protocol(""jdbc"", ""JDBC"", +@@ -106,7 +106,7 @@ public final class Protocol extends Metadata { + + /** POPS protocol (via SSL/TLS socket).. */ + public static final Protocol POPS = new Protocol(""pops"", ""POPS"", +- ""Post Office Protocol (Secure)"", 995); ++ ""Post Office Protocol (Secure)"", 995, true); + + /** + * RIAP (Restlet Internal Access Protocol) is a custom scheme to access +@@ -120,7 +120,7 @@ public final class Protocol extends Metadata { + * @see org.restlet.data.LocalReference + */ + public static final Protocol RIAP = new Protocol(""riap"", ""RIAP"", +- ""Restlet Internal Access Protocol"", UNKNOWN_PORT); ++ ""Restlet Internal Access Protocol"", UNKNOWN_PORT, true); + + /** SMTP protocol. */ + public static final Protocol SMTP = new Protocol(""smtp"", ""SMTP"", +@@ -135,15 +135,16 @@ public final class Protocol extends Metadata { + @Deprecated + public static final Protocol SMTP_STARTTLS = new Protocol(""smtp"", + ""SMTP_STARTTLS"", +- ""Simple Mail Transfer Protocol (starting a TLS encryption)"", 25); ++ ""Simple Mail Transfer Protocol (starting a TLS encryption)"", 25, ++ true); + + /** SMTPS protocol (via SSL/TLS socket). */ + public static final Protocol SMTPS = new Protocol(""smtps"", ""SMTPS"", +- ""Simple Mail Transfer Protocol (Secure)"", 465); ++ ""Simple Mail Transfer Protocol (Secure)"", 465, true); + + /** Local Web Archive access protocol. */ + public static final Protocol WAR = new Protocol(""war"", ""WAR"", +- ""Web Archive Access Protocol"", UNKNOWN_PORT); ++ ""Web Archive Access Protocol"", UNKNOWN_PORT, true); + + /** + * Creates the protocol associated to a URI scheme name. If an existing +@@ -195,6 +196,9 @@ public static Protocol valueOf(final String name) { + return result; + } + ++ /** The confidentiality. */ ++ private volatile boolean confidential; ++ + /** The default port if known or -1. */ + private volatile int defaultPort; + +@@ -226,9 +230,30 @@ public Protocol(final String schemeName) { + */ + public Protocol(final String schemeName, final String name, + final String description, int defaultPort) { ++ this(schemeName, name, description, defaultPort, false); ++ } ++ ++ /** ++ * Constructor. ++ * ++ * @param schemeName ++ * The scheme name. ++ * @param name ++ * The unique name. ++ * @param description ++ * The description. ++ * @param defaultPort ++ * The default port. ++ * @param confidential ++ * The confidentiality. ++ */ ++ public Protocol(final String schemeName, final String name, ++ final String description, int defaultPort, ++ final boolean confidential) { + super(name, description); + this.schemeName = schemeName; + this.defaultPort = defaultPort; ++ this.confidential = confidential; + } + + /** {@inheritDoc} */ +@@ -261,4 +286,15 @@ public String getSchemeName() { + public int hashCode() { + return (getName() == null) ? 0 : getName().toLowerCase().hashCode(); + } ++ ++ /** ++ * Indicates if the protocol guarantees the confidentially of the messages ++ * exchanged, for example via a SSL-secured connection. ++ * ++ * @return True if the protocol is confidential. ++ */ ++ public boolean isConfidential() { ++ return this.confidential; ++ } ++ + } +diff --git a/modules/org.restlet/src/org/restlet/data/Request.java b/modules/org.restlet/src/org/restlet/data/Request.java +index 9c81cbd5d5..300e05e0ab 100644 +--- a/modules/org.restlet/src/org/restlet/data/Request.java ++++ b/modules/org.restlet/src/org/restlet/data/Request.java +@@ -109,9 +109,6 @@ public static Request getCurrent() { + /** The condition data. */ + private volatile Conditions conditions; + +- /** Indicates if the call came over a confidential channel. */ +- private volatile boolean confidential; +- + /** The cookies provided by the client. */ + private volatile Series cookies; + +@@ -140,7 +137,6 @@ public static Request getCurrent() { + * Constructor. + */ + public Request() { +- this.confidential = false; + } + + /** +@@ -387,13 +383,12 @@ public Reference getRootRef() { + } + + /** +- * Indicates if the call came over a confidential channel such as an +- * SSL-secured connection. +- * +- * @return True if the call came over a confidential channel. ++ * Implemented based on the {@link Protocol#isConfidential()} method for the ++ * request's protocol returned by {@link #getProtocol()}; + */ ++ @Override + public boolean isConfidential() { +- return this.confidential; ++ return (getProtocol() == null) ? false : getProtocol().isConfidential(); + } + + /** +@@ -444,17 +439,6 @@ public void setConditions(Conditions conditions) { + this.conditions = conditions; + } + +- /** +- * Indicates if the call came over a confidential channel such as an +- * SSL-secured connection. +- * +- * @param confidential +- * True if the call came over a confidential channel. +- */ +- public void setConfidential(boolean confidential) { +- this.confidential = confidential; +- } +- + /** + * Sets the cookies provided by the client. + * +diff --git a/modules/org.restlet/src/org/restlet/data/Response.java b/modules/org.restlet/src/org/restlet/data/Response.java +index cd34d0b5a1..b88c96c3ef 100644 +--- a/modules/org.restlet/src/org/restlet/data/Response.java ++++ b/modules/org.restlet/src/org/restlet/data/Response.java +@@ -307,6 +307,11 @@ public Status getStatus() { + return this.status; + } + ++ @Override ++ public boolean isConfidential() { ++ return getRequest().isConfidential(); ++ } ++ + /** + * Permanently redirects the client to a target URI. The client is expected + * to reuse the same method for the new request. +diff --git a/modules/org.restlet/src/org/restlet/util/WrapperRequest.java b/modules/org.restlet/src/org/restlet/util/WrapperRequest.java +index 039e608531..a8c52196d0 100644 +--- a/modules/org.restlet/src/org/restlet/util/WrapperRequest.java ++++ b/modules/org.restlet/src/org/restlet/util/WrapperRequest.java +@@ -315,18 +315,6 @@ public void setChallengeResponse(ChallengeResponse response) { + getWrappedRequest().setChallengeResponse(response); + } + +- /** +- * Indicates if the call came over a confidential channel such as an +- * SSL-secured connection. +- * +- * @param confidential +- * True if the call came over a confidential channel. +- */ +- @Override +- public void setConfidential(boolean confidential) { +- getWrappedRequest().setConfidential(confidential); +- } +- + /** + * Sets the entity from a higher-level object. This object is converted to a + * representation using the Application's converter service. If you want to +diff --git a/modules/org.restlet/src/org/restlet/util/WrapperResponse.java b/modules/org.restlet/src/org/restlet/util/WrapperResponse.java +index f75306c2c1..1fc4fdf01d 100644 +--- a/modules/org.restlet/src/org/restlet/util/WrapperResponse.java ++++ b/modules/org.restlet/src/org/restlet/util/WrapperResponse.java +@@ -301,6 +301,17 @@ protected Response getWrappedResponse() { + return this.wrappedResponse; + } + ++ /** ++ * Indicates if the call came over a confidential channel such as an ++ * SSL-secured connection. ++ * ++ * @return True if the call came over a confidential channel. ++ */ ++ @Override ++ public boolean isConfidential() { ++ return getWrappedResponse().isConfidential(); ++ } ++ + /** + * Indicates if a content is available and can be sent. Several conditions + * must be met: the content must exists and have some available data." +8ee632caa79b92b1af98684f83b01c3447a119ee,hadoop,YARN-2740. Fix NodeLabelsManager to properly handle- node label modifications when distributed node label configuration enabled.- (Naganarasimha G R via wangda)--(cherry picked from commit db1b674b50ddecf2774f4092d677c412722bdcb1)-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 20de1edb7efbe..ca9247f13eb2d 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -217,6 +217,9 @@ Release 2.8.0 - UNRELEASED + YARN-3530. ATS throws exception on trying to filter results without otherinfo. + (zhijie shen via xgong) + ++ YARN-2740. Fix NodeLabelsManager to properly handle node label modifications ++ when distributed node label configuration enabled. (Naganarasimha G R via wangda) ++ + Release 2.7.1 - UNRELEASED + + INCOMPATIBLE CHANGES +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +index c8f9648147fb3..4dd01d24bb8d9 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +@@ -1779,6 +1779,12 @@ private static void addDeprecatedKeys() { + public static final String DEFAULT_NODELABEL_CONFIGURATION_TYPE = + CENTALIZED_NODELABEL_CONFIGURATION_TYPE; + ++ @Private ++ public static boolean isDistributedNodeLabelConfiguration(Configuration conf) { ++ return DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE.equals(conf.get( ++ NODELABEL_CONFIGURATION_TYPE, DEFAULT_NODELABEL_CONFIGURATION_TYPE)); ++ } ++ + public YarnConfiguration() { + super(); + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java +index 7493169201ebc..f2ff0f629971c 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/CommonNodeLabelsManager.java +@@ -97,6 +97,8 @@ public class CommonNodeLabelsManager extends AbstractService { + protected NodeLabelsStore store; + private boolean nodeLabelsEnabled = false; + ++ private boolean isDistributedNodeLabelConfiguration = false; ++ + /** + * A Host can have multiple Nodes + */ +@@ -213,6 +215,10 @@ protected void serviceInit(Configuration conf) throws Exception { + nodeLabelsEnabled = + conf.getBoolean(YarnConfiguration.NODE_LABELS_ENABLED, + YarnConfiguration.DEFAULT_NODE_LABELS_ENABLED); ++ ++ isDistributedNodeLabelConfiguration = ++ YarnConfiguration.isDistributedNodeLabelConfiguration(conf); ++ + if (nodeLabelsEnabled) { + initNodeLabelStore(conf); + } +@@ -223,7 +229,7 @@ protected void serviceInit(Configuration conf) throws Exception { + protected void initNodeLabelStore(Configuration conf) throws Exception { + this.store = new FileSystemNodeLabelsStore(this); + this.store.init(conf); +- this.store.recover(); ++ this.store.recover(isDistributedNodeLabelConfiguration); + } + + // for UT purpose +@@ -613,7 +619,10 @@ protected void internalUpdateLabelsOnNodes( + } + } + +- if (null != dispatcher) { ++ if (null != dispatcher && !isDistributedNodeLabelConfiguration) { ++ // In case of DistributedNodeLabelConfiguration, no need to save the the ++ // NodeLabels Mapping to the back-end store, as on RM restart/failover ++ // NodeLabels are collected from NM through Register/Heartbeat again + dispatcher.getEventHandler().handle( + new UpdateNodeToLabelsMappingsEvent(newNMToLabels)); + } +@@ -799,8 +808,10 @@ public List getClusterNodeLabels() { + readLock.lock(); + List nodeLabels = new ArrayList<>(); + for (RMNodeLabel label : labelCollections.values()) { +- nodeLabels.add(NodeLabel.newInstance(label.getLabelName(), +- label.getIsExclusive())); ++ if (!label.getLabelName().equals(NO_LABEL)) { ++ nodeLabels.add(NodeLabel.newInstance(label.getLabelName(), ++ label.getIsExclusive())); ++ } + } + return nodeLabels; + } finally { +@@ -824,7 +835,6 @@ public boolean isExclusiveNodeLabel(String nodeLabel) throws IOException { + readLock.unlock(); + } + } +- + + private void checkAndThrowLabelName(String label) throws IOException { + if (label == null || label.isEmpty() || label.length() > MAX_LABEL_LENGTH) { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/FileSystemNodeLabelsStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/FileSystemNodeLabelsStore.java +index ea185f2c0a248..f26e2048a02cd 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/FileSystemNodeLabelsStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/FileSystemNodeLabelsStore.java +@@ -154,8 +154,12 @@ public void removeClusterNodeLabels(Collection labels) + ensureCloseEditlogFile(); + } + ++ /* (non-Javadoc) ++ * @see org.apache.hadoop.yarn.nodelabels.NodeLabelsStore#recover(boolean) ++ */ + @Override +- public void recover() throws YarnException, IOException { ++ public void recover(boolean ignoreNodeToLabelsMappings) throws YarnException, ++ IOException { + /* + * Steps of recover + * 1) Read from last mirror (from mirror or mirror.old) +@@ -222,7 +226,15 @@ public void recover() throws YarnException, IOException { + new ReplaceLabelsOnNodeRequestPBImpl( + ReplaceLabelsOnNodeRequestProto.parseDelimitedFrom(is)) + .getNodeToLabels(); +- mgr.replaceLabelsOnNode(map); ++ if (!ignoreNodeToLabelsMappings) { ++ /* ++ * In case of Distributed NodeLabels setup, ++ * ignoreNodeToLabelsMappings will be set to true and recover will ++ * be invoked. As RM will collect the node labels from NM through ++ * registration/HB ++ */ ++ mgr.replaceLabelsOnNode(map); ++ } + break; + } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelsStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelsStore.java +index 47b7370dff843..46b94fd0d5c9a 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelsStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NodeLabelsStore.java +@@ -56,9 +56,18 @@ public abstract void removeClusterNodeLabels(Collection labels) + throws IOException; + + /** +- * Recover labels and node to labels mappings from store ++ * Recover labels and node to labels mappings from store, but if ++ * ignoreNodeToLabelsMappings is true then node to labels mappings should not ++ * be recovered. In case of Distributed NodeLabels setup ++ * ignoreNodeToLabelsMappings will be set to true and recover will be invoked ++ * as RM will collect the node labels from NM through registration/HB ++ * ++ * @param ignoreNodeToLabelsMappings ++ * @throws IOException ++ * @throws YarnException + */ +- public abstract void recover() throws IOException, YarnException; ++ public abstract void recover(boolean ignoreNodeToLabelsMappings) ++ throws IOException, YarnException; + + public void init(Configuration conf) throws Exception {} + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/DummyCommonNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/DummyCommonNodeLabelsManager.java +index 48d6dc877154b..fce663a1c952c 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/DummyCommonNodeLabelsManager.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/DummyCommonNodeLabelsManager.java +@@ -39,7 +39,8 @@ public void initNodeLabelStore(Configuration conf) { + this.store = new NodeLabelsStore(this) { + + @Override +- public void recover() throws IOException { ++ public void recover(boolean ignoreNodeToLabelsMappings) ++ throws IOException { + } + + @Override +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestCommonNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestCommonNodeLabelsManager.java +index beb2cf8585851..09838b43ada1d 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestCommonNodeLabelsManager.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestCommonNodeLabelsManager.java +@@ -554,4 +554,29 @@ private void verifyNodeLabelAdded(Set expectedAddedLabelNames, + Assert.assertTrue(expectedAddedLabelNames.contains(label.getName())); + } + } ++ ++ @Test(timeout = 5000) ++ public void testReplaceLabelsOnNodeInDistributedMode() throws Exception { ++ //create new DummyCommonNodeLabelsManager than the one got from @before ++ mgr.stop(); ++ mgr = new DummyCommonNodeLabelsManager(); ++ Configuration conf = new YarnConfiguration(); ++ conf.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true); ++ conf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, ++ YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); ++ ++ mgr.init(conf); ++ mgr.start(); ++ ++ mgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet(""p1"", ""p2"", ""p3"")); ++ mgr.replaceLabelsOnNode(ImmutableMap.of(toNodeId(""n1""), toSet(""p1""))); ++ Set labelsByNode = mgr.getLabelsByNode(toNodeId(""n1"")); ++ ++ Assert.assertNull( ++ ""Labels are not expected to be written to the NodeLabelStore"", ++ mgr.lastNodeToLabels); ++ Assert.assertNotNull(""Updated labels should be available from the Mgr"", ++ labelsByNode); ++ Assert.assertTrue(labelsByNode.contains(""p1"")); ++ } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestFileSystemNodeLabelsStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestFileSystemNodeLabelsStore.java +index f070c205f5a1c..fb60cd6a6427c 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestFileSystemNodeLabelsStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/nodelabels/TestFileSystemNodeLabelsStore.java +@@ -144,6 +144,40 @@ public void testRecoverWithMirror() throws Exception { + mgr.stop(); + } + ++ @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) ++ @Test(timeout = 10000) ++ public void testRecoverWithDistributedNodeLabels() throws Exception { ++ mgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet(""p1"", ""p2"", ""p3"")); ++ mgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet(""p4"")); ++ mgr.addToCluserNodeLabelsWithDefaultExclusivity(toSet(""p5"", ""p6"")); ++ mgr.replaceLabelsOnNode((Map) ImmutableMap.of(toNodeId(""n1""), toSet(""p1""), ++ toNodeId(""n2""), toSet(""p2""))); ++ mgr.replaceLabelsOnNode((Map) ImmutableMap.of(toNodeId(""n3""), toSet(""p3""), ++ toNodeId(""n4""), toSet(""p4""), toNodeId(""n5""), toSet(""p5""), ++ toNodeId(""n6""), toSet(""p6""), toNodeId(""n7""), toSet(""p6""))); ++ ++ mgr.removeFromClusterNodeLabels(toSet(""p1"")); ++ mgr.removeFromClusterNodeLabels(Arrays.asList(""p3"", ""p5"")); ++ mgr.stop(); ++ ++ mgr = new MockNodeLabelManager(); ++ Configuration cf = new Configuration(conf); ++ cf.set(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, ++ YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE); ++ mgr.init(cf); ++ ++ // check variables ++ Assert.assertEquals(3, mgr.getClusterNodeLabels().size()); ++ Assert.assertTrue(mgr.getClusterNodeLabelNames().containsAll( ++ Arrays.asList(""p2"", ""p4"", ""p6""))); ++ ++ Assert.assertTrue(""During recovery in distributed node-labels setup, "" ++ + ""node to labels mapping should not be recovered "", mgr ++ .getNodeLabels().size() == 0); ++ ++ mgr.stop(); ++ } ++ + @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) + @Test(timeout = 10000) + public void testEditlogRecover() throws Exception { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java +index c921326fbdce3..0ad90c0ed4c6b 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/AdminService.java +@@ -112,6 +112,9 @@ public class AdminService extends CompositeService implements + private final RecordFactory recordFactory = + RecordFactoryProvider.getRecordFactory(null); + ++ @VisibleForTesting ++ boolean isDistributedNodeLabelConfiguration = false; ++ + public AdminService(ResourceManager rm, RMContext rmContext) { + super(AdminService.class.getName()); + this.rm = rm; +@@ -141,6 +144,10 @@ public void serviceInit(Configuration conf) throws Exception { + YarnConfiguration.DEFAULT_YARN_ADMIN_ACL)), UserGroupInformation + .getCurrentUser()); + rmId = conf.get(YarnConfiguration.RM_HA_ID); ++ ++ isDistributedNodeLabelConfiguration = ++ YarnConfiguration.isDistributedNodeLabelConfiguration(conf); ++ + super.serviceInit(conf); + } + +@@ -637,32 +644,35 @@ public AddToClusterNodeLabelsResponse addToClusterNodeLabels(AddToClusterNodeLab + @Override + public RemoveFromClusterNodeLabelsResponse removeFromClusterNodeLabels( + RemoveFromClusterNodeLabelsRequest request) throws YarnException, IOException { +- String argName = ""removeFromClusterNodeLabels""; ++ String operation = ""removeFromClusterNodeLabels""; + final String msg = ""remove labels.""; +- UserGroupInformation user = checkAcls(argName); + +- checkRMStatus(user.getShortUserName(), argName, msg); ++ UserGroupInformation user = checkAcls(operation); ++ ++ checkRMStatus(user.getShortUserName(), operation, msg); + + RemoveFromClusterNodeLabelsResponse response = + recordFactory.newRecordInstance(RemoveFromClusterNodeLabelsResponse.class); + try { + rmContext.getNodeLabelManager().removeFromClusterNodeLabels(request.getNodeLabels()); + RMAuditLogger +- .logSuccess(user.getShortUserName(), argName, ""AdminService""); ++ .logSuccess(user.getShortUserName(), operation, ""AdminService""); + return response; + } catch (IOException ioe) { +- throw logAndWrapException(ioe, user.getShortUserName(), argName, msg); ++ throw logAndWrapException(ioe, user.getShortUserName(), operation, msg); + } + } + + @Override + public ReplaceLabelsOnNodeResponse replaceLabelsOnNode( + ReplaceLabelsOnNodeRequest request) throws YarnException, IOException { +- String argName = ""replaceLabelsOnNode""; ++ String operation = ""replaceLabelsOnNode""; + final String msg = ""set node to labels.""; +- UserGroupInformation user = checkAcls(argName); + +- checkRMStatus(user.getShortUserName(), argName, msg); ++ checkAndThrowIfDistributedNodeLabelConfEnabled(operation); ++ UserGroupInformation user = checkAcls(operation); ++ ++ checkRMStatus(user.getShortUserName(), operation, msg); + + ReplaceLabelsOnNodeResponse response = + recordFactory.newRecordInstance(ReplaceLabelsOnNodeResponse.class); +@@ -670,30 +680,41 @@ public ReplaceLabelsOnNodeResponse replaceLabelsOnNode( + rmContext.getNodeLabelManager().replaceLabelsOnNode( + request.getNodeToLabels()); + RMAuditLogger +- .logSuccess(user.getShortUserName(), argName, ""AdminService""); ++ .logSuccess(user.getShortUserName(), operation, ""AdminService""); + return response; + } catch (IOException ioe) { +- throw logAndWrapException(ioe, user.getShortUserName(), argName, msg); ++ throw logAndWrapException(ioe, user.getShortUserName(), operation, msg); + } + } + +- private void checkRMStatus(String user, String argName, String msg) ++ private void checkRMStatus(String user, String operation, String msg) + throws StandbyException { + if (!isRMActive()) { +- RMAuditLogger.logFailure(user, argName, """", ++ RMAuditLogger.logFailure(user, operation, """", + ""AdminService"", ""ResourceManager is not active. Can not "" + msg); + throwStandbyException(); + } + } + + private YarnException logAndWrapException(Exception exception, String user, +- String argName, String msg) throws YarnException { ++ String operation, String msg) throws YarnException { + LOG.warn(""Exception "" + msg, exception); +- RMAuditLogger.logFailure(user, argName, """", ++ RMAuditLogger.logFailure(user, operation, """", + ""AdminService"", ""Exception "" + msg); + return RPCUtil.getRemoteException(exception); + } + ++ private void checkAndThrowIfDistributedNodeLabelConfEnabled(String operation) ++ throws YarnException { ++ if (isDistributedNodeLabelConfiguration) { ++ String msg = ++ String.format(""Error when invoke method=%s because of "" ++ + ""distributed node label configuration enabled."", operation); ++ LOG.error(msg); ++ throw RPCUtil.getRemoteException(new IOException(msg)); ++ } ++ } ++ + @Override + public CheckForDecommissioningNodesResponse checkForDecommissioningNodes( + CheckForDecommissioningNodesRequest checkForDecommissioningNodesRequest) +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java +index 5e2dc7e4f2543..16b6a890ac923 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceTrackerService.java +@@ -104,7 +104,7 @@ public class ResourceTrackerService extends AbstractService implements + private int minAllocMb; + private int minAllocVcores; + +- private boolean isDistributesNodeLabelsConf; ++ private boolean isDistributedNodeLabelsConf; + + static { + resync.setNodeAction(NodeAction.RESYNC); +@@ -155,13 +155,8 @@ protected void serviceInit(Configuration conf) throws Exception { + YarnConfiguration.RM_NODEMANAGER_MINIMUM_VERSION, + YarnConfiguration.DEFAULT_RM_NODEMANAGER_MINIMUM_VERSION); + +- String nodeLabelConfigurationType = +- conf.get(YarnConfiguration.NODELABEL_CONFIGURATION_TYPE, +- YarnConfiguration.DEFAULT_NODELABEL_CONFIGURATION_TYPE); +- +- isDistributesNodeLabelsConf = +- YarnConfiguration.DISTRIBUTED_NODELABEL_CONFIGURATION_TYPE +- .equals(nodeLabelConfigurationType); ++ isDistributedNodeLabelsConf = ++ YarnConfiguration.isDistributedNodeLabelConfiguration(conf); + + super.serviceInit(conf); + } +@@ -352,7 +347,7 @@ public RegisterNodeManagerResponse registerNodeManager( + + // Update node's labels to RM's NodeLabelManager. + Set nodeLabels = request.getNodeLabels(); +- if (isDistributesNodeLabelsConf && nodeLabels != null) { ++ if (isDistributedNodeLabelsConf && nodeLabels != null) { + try { + updateNodeLabelsFromNMReport(nodeLabels, nodeId); + response.setAreNodeLabelsAcceptedByRM(true); +@@ -470,7 +465,7 @@ public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) + this.rmContext.getDispatcher().getEventHandler().handle(nodeStatusEvent); + + // 5. Update node's labels to RM's NodeLabelManager. +- if (isDistributesNodeLabelsConf && request.getNodeLabels() != null) { ++ if (isDistributedNodeLabelsConf && request.getNodeLabels() != null) { + try { + updateNodeLabelsFromNMReport(request.getNodeLabels(), nodeId); + nodeHeartBeatResponse.setAreNodeLabelsAcceptedByRM(true); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebServices.java +index 6cd6d56281f66..9aea62d1c8408 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebServices.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/RMWebServices.java +@@ -149,6 +149,7 @@ + import org.apache.hadoop.yarn.webapp.NotFoundException; + import org.apache.hadoop.yarn.webapp.util.WebAppUtils; + ++import com.google.common.annotations.VisibleForTesting; + import com.google.inject.Inject; + import com.google.inject.Singleton; + +@@ -165,6 +166,9 @@ public class RMWebServices { + private final Configuration conf; + private @Context HttpServletResponse response; + ++ @VisibleForTesting ++ boolean isDistributedNodeLabelConfiguration = false; ++ + public final static String DELEGATION_TOKEN_HEADER = + ""Hadoop-YARN-RM-Delegation-Token""; + +@@ -172,6 +176,19 @@ public class RMWebServices { + public RMWebServices(final ResourceManager rm, Configuration conf) { + this.rm = rm; + this.conf = conf; ++ isDistributedNodeLabelConfiguration = ++ YarnConfiguration.isDistributedNodeLabelConfiguration(conf); ++ } ++ ++ private void checkAndThrowIfDistributedNodeLabelConfEnabled(String operation) ++ throws IOException { ++ if (isDistributedNodeLabelConfiguration) { ++ String msg = ++ String.format(""Error when invoke method=%s because of "" ++ + ""distributed node label configuration enabled."", operation); ++ LOG.error(msg); ++ throw new IOException(msg); ++ } + } + + RMWebServices(ResourceManager rm, Configuration conf, +@@ -816,38 +833,64 @@ public LabelsToNodesInfo getLabelsToNodes( + @POST + @Path(""/replace-node-to-labels"") + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +- public Response replaceLabelsOnNodes( +- final NodeToLabelsInfo newNodeToLabels, +- @Context HttpServletRequest hsr) +- throws IOException { ++ public Response replaceLabelsOnNodes(final NodeToLabelsInfo newNodeToLabels, ++ @Context HttpServletRequest hsr) throws IOException { ++ Map> nodeIdToLabels = ++ new HashMap>(); ++ ++ for (Map.Entry nitle : newNodeToLabels ++ .getNodeToLabels().entrySet()) { ++ nodeIdToLabels.put( ++ ConverterUtils.toNodeIdWithDefaultPort(nitle.getKey()), ++ new HashSet(nitle.getValue().getNodeLabels())); ++ } ++ ++ return replaceLabelsOnNode(nodeIdToLabels, hsr, ""/replace-node-to-labels""); ++ } ++ ++ @POST ++ @Path(""/nodes/{nodeId}/replace-labels"") ++ @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) ++ public Response replaceLabelsOnNode(NodeLabelsInfo newNodeLabelsInfo, ++ @Context HttpServletRequest hsr, @PathParam(""nodeId"") String nodeId) ++ throws Exception { ++ NodeId nid = ConverterUtils.toNodeIdWithDefaultPort(nodeId); ++ Map> newLabelsForNode = ++ new HashMap>(); ++ newLabelsForNode.put(nid, ++ new HashSet(newNodeLabelsInfo.getNodeLabels())); ++ ++ return replaceLabelsOnNode(newLabelsForNode, hsr, ""/nodes/nodeid/replace-labels""); ++ } ++ ++ private Response replaceLabelsOnNode( ++ Map> newLabelsForNode, HttpServletRequest hsr, ++ String operation) throws IOException { + init(); +- ++ ++ checkAndThrowIfDistributedNodeLabelConfEnabled(""replaceLabelsOnNode""); ++ + UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true); + if (callerUGI == null) { +- String msg = ""Unable to obtain user name, user not authenticated for"" +- + "" post to .../replace-node-to-labels""; ++ String msg = ++ ""Unable to obtain user name, user not authenticated for"" ++ + "" post to ..."" + operation; + throw new AuthorizationException(msg); + } ++ + if (!rm.getRMContext().getNodeLabelManager().checkAccess(callerUGI)) { +- String msg = ""User "" + callerUGI.getShortUserName() + "" not authorized"" +- + "" for post to .../replace-node-to-labels ""; ++ String msg = ++ ""User "" + callerUGI.getShortUserName() + "" not authorized"" ++ + "" for post to ..."" + operation; + throw new AuthorizationException(msg); + } +- +- Map> nodeIdToLabels = +- new HashMap>(); + +- for (Map.Entry nitle : +- newNodeToLabels.getNodeToLabels().entrySet()) { +- nodeIdToLabels.put(ConverterUtils.toNodeIdWithDefaultPort(nitle.getKey()), +- new HashSet(nitle.getValue().getNodeLabels())); +- } +- +- rm.getRMContext().getNodeLabelManager().replaceLabelsOnNode(nodeIdToLabels); ++ rm.getRMContext().getNodeLabelManager() ++ .replaceLabelsOnNode(newLabelsForNode); + + return Response.status(Status.OK).build(); + } +- ++ + @GET + @Path(""/get-node-labels"") + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +@@ -897,7 +940,7 @@ public Response removeFromCluserNodeLabels(final NodeLabelsInfo oldNodeLabels, + @Context HttpServletRequest hsr) + throws Exception { + init(); +- ++ + UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true); + if (callerUGI == null) { + String msg = ""Unable to obtain user name, user not authenticated for"" +@@ -931,40 +974,6 @@ public NodeLabelsInfo getLabelsOnNode(@Context HttpServletRequest hsr, + rm.getRMContext().getNodeLabelManager().getLabelsOnNode(nid)); + + } +- +- @POST +- @Path(""/nodes/{nodeId}/replace-labels"") +- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) +- public Response replaceLabelsOnNode(NodeLabelsInfo newNodeLabelsInfo, +- @Context HttpServletRequest hsr, @PathParam(""nodeId"") String nodeId) +- throws Exception { +- init(); +- +- UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true); +- if (callerUGI == null) { +- String msg = ""Unable to obtain user name, user not authenticated for"" +- + "" post to .../nodes/nodeid/replace-labels""; +- throw new AuthorizationException(msg); +- } +- +- if (!rm.getRMContext().getNodeLabelManager().checkAccess(callerUGI)) { +- String msg = ""User "" + callerUGI.getShortUserName() + "" not authorized"" +- + "" for post to .../nodes/nodeid/replace-labels""; +- throw new AuthorizationException(msg); +- } +- +- NodeId nid = ConverterUtils.toNodeIdWithDefaultPort(nodeId); +- +- Map> newLabelsForNode = new HashMap>(); +- +- newLabelsForNode.put(nid, new HashSet(newNodeLabelsInfo.getNodeLabels())); +- +- rm.getRMContext().getNodeLabelManager().replaceLabelsOnNode(newLabelsForNode); +- +- return Response.status(Status.OK).build(); +- +- } + + protected Response killApp(RMApp app, UserGroupInformation callerUGI, + HttpServletRequest hsr) throws IOException, InterruptedException { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java +index da04c9ec32b11..fe0b8a8d1ff35 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMAdminService.java +@@ -18,6 +18,7 @@ + + package org.apache.hadoop.yarn.server.resourcemanager; + ++import static org.junit.Assert.assertEquals; + import static org.junit.Assert.fail; + + import java.io.DataOutputStream; +@@ -44,6 +45,7 @@ + import org.apache.hadoop.security.authorize.ProxyUsers; + import org.apache.hadoop.security.authorize.ServiceAuthorizationManager; + import org.apache.hadoop.yarn.api.records.DecommissionType; ++import org.apache.hadoop.yarn.api.records.NodeId; + import org.apache.hadoop.yarn.conf.HAUtil; + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.exceptions.YarnException; +@@ -53,6 +55,9 @@ + import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest; + import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest; + import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest; ++import org.apache.hadoop.yarn.server.api.protocolrecords.RemoveFromClusterNodeLabelsRequest; ++import org.apache.hadoop.yarn.server.api.protocolrecords.ReplaceLabelsOnNodeRequest; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; + import org.junit.After; +@@ -60,6 +65,8 @@ + import org.junit.Before; + import org.junit.Test; + ++import com.google.common.collect.ImmutableMap; ++import com.google.common.collect.ImmutableSet; + + public class TestRMAdminService { + +@@ -754,6 +761,67 @@ public void testRMInitialsWithFileSystemBasedConfigurationProvider() + } + } + ++ @Test ++ public void testModifyLabelsOnNodesWithDistributedConfigurationDisabled() ++ throws IOException, YarnException { ++ // create RM and set it's ACTIVE ++ MockRM rm = new MockRM(); ++ ((RMContextImpl) rm.getRMContext()) ++ .setHAServiceState(HAServiceState.ACTIVE); ++ RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); ++ ++ // by default, distributed configuration for node label is disabled, this ++ // should pass ++ labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of(""x"", ""y"")); ++ rm.adminService.replaceLabelsOnNode(ReplaceLabelsOnNodeRequest ++ .newInstance(ImmutableMap.of(NodeId.newInstance(""host"", 0), ++ (Set) ImmutableSet.of(""x"")))); ++ rm.close(); ++ } ++ ++ @Test(expected = YarnException.class) ++ public void testModifyLabelsOnNodesWithDistributedConfigurationEnabled() ++ throws IOException, YarnException { ++ // create RM and set it's ACTIVE, and set distributed node label ++ // configuration to true ++ MockRM rm = new MockRM(); ++ rm.adminService.isDistributedNodeLabelConfiguration = true; ++ ++ ((RMContextImpl) rm.getRMContext()) ++ .setHAServiceState(HAServiceState.ACTIVE); ++ RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); ++ ++ // by default, distributed configuration for node label is disabled, this ++ // should pass ++ labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of(""x"", ""y"")); ++ rm.adminService.replaceLabelsOnNode(ReplaceLabelsOnNodeRequest ++ .newInstance(ImmutableMap.of(NodeId.newInstance(""host"", 0), ++ (Set) ImmutableSet.of(""x"")))); ++ rm.close(); ++ } ++ ++ @Test ++ public void testRemoveClusterNodeLabelsWithDistributedConfigurationEnabled() ++ throws IOException, YarnException { ++ // create RM and set it's ACTIVE ++ MockRM rm = new MockRM(); ++ ((RMContextImpl) rm.getRMContext()) ++ .setHAServiceState(HAServiceState.ACTIVE); ++ RMNodeLabelsManager labelMgr = rm.rmContext.getNodeLabelManager(); ++ rm.adminService.isDistributedNodeLabelConfiguration = true; ++ ++ // by default, distributed configuration for node label is disabled, this ++ // should pass ++ labelMgr.addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of(""x"", ""y"")); ++ rm.adminService ++ .removeFromClusterNodeLabels(RemoveFromClusterNodeLabelsRequest ++ .newInstance((Set) ImmutableSet.of(""x""))); ++ ++ Set clusterNodeLabels = labelMgr.getClusterNodeLabelNames(); ++ assertEquals(1,clusterNodeLabels.size()); ++ rm.close(); ++ } ++ + private String writeConfigurationXML(Configuration conf, String confXMLName) + throws IOException { + DataOutputStream output = null; +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/NullRMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/NullRMNodeLabelsManager.java +index 9548029d08769..2e21d261f615f 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/NullRMNodeLabelsManager.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/NullRMNodeLabelsManager.java +@@ -40,7 +40,8 @@ public void initNodeLabelStore(Configuration conf) { + this.store = new NodeLabelsStore(this) { + + @Override +- public void recover() throws IOException { ++ public void recover(boolean ignoreNodeToLabelsMappings) ++ throws IOException { + // do nothing + } + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServices.java +index 298246ca301e2..e4614f8c9ec7e 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServices.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServices.java +@@ -51,6 +51,7 @@ + import org.apache.hadoop.yarn.server.resourcemanager.MockRM; + import org.apache.hadoop.yarn.server.resourcemanager.RMContextImpl; + import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler; +@@ -623,6 +624,7 @@ public void testAppsRace() throws Exception { + null, null, null, null, null); + when(mockRM.getRMContext()).thenReturn(rmContext); + when(mockRM.getClientRMService()).thenReturn(mockClientSvc); ++ rmContext.setNodeLabelManager(mock(RMNodeLabelsManager.class)); + + RMWebServices webSvc = new RMWebServices(mockRM, new Configuration(), + mock(HttpServletResponse.class)); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesNodeLabels.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesNodeLabels.java +index 40c54a30a6a8d..2d5518dc03cf8 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesNodeLabels.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesNodeLabels.java +@@ -19,10 +19,10 @@ + package org.apache.hadoop.yarn.server.resourcemanager.webapp; + + import static org.junit.Assert.assertEquals; ++import static org.junit.Assert.assertFalse; + import static org.junit.Assert.assertTrue; + + import java.io.IOException; +-import java.io.StringReader; + import java.io.StringWriter; + + import javax.ws.rs.core.MediaType; +@@ -51,7 +51,6 @@ + import com.sun.jersey.api.client.WebResource; + import com.sun.jersey.api.json.JSONJAXBContext; + import com.sun.jersey.api.json.JSONMarshaller; +-import com.sun.jersey.api.json.JSONUnmarshaller; + import com.sun.jersey.core.util.MultivaluedMapImpl; + import com.sun.jersey.guice.spi.container.servlet.GuiceContainer; + import com.sun.jersey.test.framework.WebAppDescriptor; +@@ -66,13 +65,13 @@ public class TestRMWebServicesNodeLabels extends JerseyTestBase { + + private String userName; + private String notUserName; ++ private RMWebServices rmWebService; + + private Injector injector = Guice.createInjector(new ServletModule() { ++ + @Override + protected void configureServlets() { + bind(JAXBContextResolver.class); +- bind(RMWebServices.class); +- bind(GenericExceptionHandler.class); + try { + userName = UserGroupInformation.getCurrentUser().getShortUserName(); + } catch (IOException ioe) { +@@ -83,6 +82,9 @@ protected void configureServlets() { + conf = new YarnConfiguration(); + conf.set(YarnConfiguration.YARN_ADMIN_ACL, userName); + rm = new MockRM(conf); ++ rmWebService = new RMWebServices(rm,conf); ++ bind(RMWebServices.class).toInstance(rmWebService); ++ bind(GenericExceptionHandler.class); + bind(ResourceManager.class).toInstance(rm); + filter(""/*"").through( + TestRMWebServicesAppsModification.TestRMCustomAuthFilter.class); +@@ -113,7 +115,6 @@ public void testNodeLabels() throws JSONException, Exception { + ClientResponse response; + JSONObject json; + JSONArray jarr; +- String responseString; + + // Add a label + response = +@@ -386,6 +387,93 @@ public void testNodeLabels() throws JSONException, Exception { + assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); + String res = response.getEntity(String.class); + assertTrue(res.equals(""null"")); ++ ++ // Following test cases are to test replace when distributed node label ++ // configuration is on ++ // Reset for testing : add cluster labels ++ response = ++ r.path(""ws"") ++ .path(""v1"") ++ .path(""cluster"") ++ .path(""add-node-labels"") ++ .queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON) ++ .entity(""{\""nodeLabels\"":[\""x\"",\""y\""]}"", ++ MediaType.APPLICATION_JSON).post(ClientResponse.class); ++ // Reset for testing : Add labels to a node ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"").path(""nodes"").path(""nid:0"") ++ .path(""replace-labels"").queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON) ++ .entity(""{\""nodeLabels\"": [\""y\""]}"", MediaType.APPLICATION_JSON) ++ .post(ClientResponse.class); ++ LOG.info(""posted node nodelabel""); ++ ++ //setting rmWebService for Distributed NodeLabel Configuration ++ rmWebService.isDistributedNodeLabelConfiguration = true; ++ ++ // Case1 : Replace labels using node-to-labels ++ ntli = new NodeToLabelsInfo(); ++ nli = new NodeLabelsInfo(); ++ nli.getNodeLabels().add(""x""); ++ ntli.getNodeToLabels().put(""nid:0"", nli); ++ response = ++ r.path(""ws"") ++ .path(""v1"") ++ .path(""cluster"") ++ .path(""replace-node-to-labels"") ++ .queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON) ++ .entity(toJson(ntli, NodeToLabelsInfo.class), ++ MediaType.APPLICATION_JSON).post(ClientResponse.class); ++ ++ // Verify, using node-to-labels that previous operation has failed ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"").path(""get-node-to-labels"") ++ .queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); ++ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); ++ ntli = response.getEntity(NodeToLabelsInfo.class); ++ nli = ntli.getNodeToLabels().get(""nid:0""); ++ assertEquals(1, nli.getNodeLabels().size()); ++ assertFalse(nli.getNodeLabels().contains(""x"")); ++ ++ // Case2 : failure to Replace labels using replace-labels ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"").path(""nodes"").path(""nid:0"") ++ .path(""replace-labels"").queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON) ++ .entity(""{\""nodeLabels\"": [\""x\""]}"", MediaType.APPLICATION_JSON) ++ .post(ClientResponse.class); ++ LOG.info(""posted node nodelabel""); ++ ++ // Verify, using node-to-labels that previous operation has failed ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"").path(""get-node-to-labels"") ++ .queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); ++ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); ++ ntli = response.getEntity(NodeToLabelsInfo.class); ++ nli = ntli.getNodeToLabels().get(""nid:0""); ++ assertEquals(1, nli.getNodeLabels().size()); ++ assertFalse(nli.getNodeLabels().contains(""x"")); ++ ++ // Case3 : Remove cluster label should be successfull ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"") ++ .path(""remove-node-labels"") ++ .queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON) ++ .entity(""{\""nodeLabels\"":\""x\""}"", MediaType.APPLICATION_JSON) ++ .post(ClientResponse.class); ++ // Verify ++ response = ++ r.path(""ws"").path(""v1"").path(""cluster"") ++ .path(""get-node-labels"").queryParam(""user.name"", userName) ++ .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); ++ assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); ++ json = response.getEntity(JSONObject.class); ++ assertEquals(""y"", json.getString(""nodeLabels"")); + } + + @SuppressWarnings(""rawtypes"") +@@ -396,13 +484,4 @@ private String toJson(Object nsli, Class klass) throws Exception { + jm.marshallToJSON(nsli, sw); + return sw.toString(); + } +- +- @SuppressWarnings({ ""rawtypes"", ""unchecked"" }) +- private Object fromJson(String json, Class klass) throws Exception { +- StringReader sr = new StringReader(json); +- JSONJAXBContext ctx = new JSONJAXBContext(klass); +- JSONUnmarshaller jm = ctx.createJSONUnmarshaller(); +- return jm.unmarshalFromJSON(sr, klass); +- } +- + }" +62f5e2a99d4f5c8bebf2b7ad581cae83ac437d0b,orientdb,Minor optimization in RidBag--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +e98541030c5e0aadfdb194dbb55254f404219600,orientdb,Huge refactoring on GraphDB: - changed class- names in vertex and edge - Optimized memory consumption by removing nested- records - Optimized speed in ORecord.equals() and hashCode(): now avoid field- checks (experimental)--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +6d11a551dcf9bb2ed2bd10530b1fbaf6f6380804,ReactiveX-RxJava,Added create with initial capacity,a,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java b/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java +index 4ea3e6e385..ff7033c0c5 100644 +--- a/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java ++++ b/rxjava-core/src/main/java/rx/subjects/SubjectSubscriptionManager.java +@@ -17,8 +17,6 @@ + + import java.util.Arrays; + import java.util.Collection; +-import java.util.Collections; +-import java.util.List; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.atomic.AtomicReference; + +@@ -126,7 +124,7 @@ protected void terminate(Action1>> onTermi + */ + try { + // had to circumvent type check, we know what the array contains +- onTerminate.call((Collection)newState.observersList); ++ onTerminate.call((Collection)Arrays.asList(newState.observers)); + } finally { + // mark that termination is completed + newState.terminationLatch.countDown(); +@@ -141,25 +139,22 @@ public SubjectObserver[] rawSnapshot() { + return state.get().observers; + } + ++ @SuppressWarnings(""rawtypes"") + protected static class State { + final boolean terminated; + final CountDownLatch terminationLatch; + final Subscription[] subscriptions; +- final SubjectObserver[] observers; ++ final SubjectObserver[] observers; + // to avoid lots of empty arrays + final Subscription[] EMPTY_S = new Subscription[0]; +- @SuppressWarnings(""rawtypes"") + // to avoid lots of empty arrays + final SubjectObserver[] EMPTY_O = new SubjectObserver[0]; +- @SuppressWarnings(""rawtypes"") +- final List> observersList; + private State(boolean isTerminated, CountDownLatch terminationLatch, + Subscription[] subscriptions, SubjectObserver[] observers) { + this.terminationLatch = terminationLatch; + this.terminated = isTerminated; + this.subscriptions = subscriptions; + this.observers = observers; +- this.observersList = Arrays.asList(this.observers); + } + + State() { +@@ -167,7 +162,6 @@ private State(boolean isTerminated, CountDownLatch terminationLatch, + this.terminationLatch = null; + this.subscriptions = EMPTY_S; + this.observers = EMPTY_O; +- observersList = Collections.emptyList(); + } + + public State terminate() {" +7e1c2d454f76d7abc5c4c9af1b93aeae08231ba9,eclipse$bpmn2-modeler,"Working towards BRMS 5.3 profile - minimal functionality to support +BRMS 5.3 release.",p,,⚠️ Could not parse repo info +b0caefee80a42d6737b3a255316487b668fab104,Delta Spike,"DELTASPIKE-278 add category to Message API +",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java +index 04785736a..0cf3cb64e 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/message/Message.java +@@ -63,4 +63,30 @@ public interface Message extends Serializable + */ + String toString(MessageContext messageContext); + ++ /** ++ * Renders the Message to a String, using the {@link MessageContext} ++ * which created the Message. ++ * While resolving the message we will ++ * first search for a messageTemplate with the given category by ++ * just adding a dot '.' and the category String to the ++ * {@link #getTemplate()}. ++ * If no such a template exists we will fallback to the version ++ * without the category String ++ */ ++ String toString(String category); ++ ++ /** ++ * Renders the Message to a String, using an ++ * arbitrary {@link MessageContext}. ++ * While resolving the message we will ++ * first search for a messageTemplate with the given category by ++ * just adding a dot '.' and the category String to the ++ * {@link #getTemplate()}. ++ * If no such a template exists we will fallback to the version ++ * without the category String ++ */ ++ String toString(MessageContext messageContext, String category); ++ ++ ++ + } +diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java +index 10bb4d1ec..cae0f48ee 100644 +--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/message/DefaultMessage.java +@@ -84,8 +84,15 @@ public Serializable[] getArguments() + } + + ++ + @Override + public String toString() ++ { ++ return toString((String) null); ++ } ++ ++ @Override ++ public String toString(String category) + { + + // the string construction happens in 3 phases +@@ -141,11 +148,17 @@ private String markAsUnresolved(String template) + + @Override + public String toString(MessageContext messageContext) ++ { ++ return toString(messageContext, null); ++ } ++ ++ @Override ++ public String toString(MessageContext messageContext, String category) + { + return messageContext.message() + .template(getTemplate()) + .argument(getArguments()) +- .toString(); ++ .toString(category); + }" +dc9e9cb4cc87f132a32a00e6589d807350f0b8e0,elasticsearch,Aggregations: change to default shard_size in- terms aggregation--The default shard size in the terms aggregation now uses BucketUtils.suggestShardSideQueueSize() to set the shard size if the user does not specify it as a parameter.--Closes -6857-,p,https://github.com/elastic/elasticsearch,"diff --git a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java +index c4b57064e80eb..c38f136dd9b29 100644 +--- a/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java ++++ b/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsParser.java +@@ -21,6 +21,7 @@ + import org.elasticsearch.common.xcontent.XContentParser; + import org.elasticsearch.search.aggregations.Aggregator; + import org.elasticsearch.search.aggregations.AggregatorFactory; ++import org.elasticsearch.search.aggregations.bucket.BucketUtils; + import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude; + import org.elasticsearch.search.aggregations.support.ValuesSourceParser; + import org.elasticsearch.search.internal.SearchContext; +@@ -32,7 +33,6 @@ + */ + public class TermsParser implements Aggregator.Parser { + +- + @Override + public String type() { + return StringTerms.TYPE.name(); +@@ -41,19 +41,22 @@ public String type() { + @Override + public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException { + TermsParametersParser aggParser = new TermsParametersParser(); +- ValuesSourceParser vsParser = ValuesSourceParser.any(aggregationName, StringTerms.TYPE, context) +- .scriptable(true) +- .formattable(true) +- .requiresSortedValues(true) +- .requiresUniqueValues(true) +- .build(); ++ ValuesSourceParser vsParser = ValuesSourceParser.any(aggregationName, StringTerms.TYPE, context).scriptable(true).formattable(true) ++ .requiresSortedValues(true).requiresUniqueValues(true).build(); + IncludeExclude.Parser incExcParser = new IncludeExclude.Parser(aggregationName, StringTerms.TYPE, context); + aggParser.parse(aggregationName, parser, context, vsParser, incExcParser); + ++ InternalOrder order = resolveOrder(aggParser.getOrderKey(), aggParser.isOrderAsc()); + TermsAggregator.BucketCountThresholds bucketCountThresholds = aggParser.getBucketCountThresholds(); ++ if (!(order == InternalOrder.TERM_ASC || order == InternalOrder.TERM_DESC) ++ && bucketCountThresholds.getShardSize() == aggParser.getDefaultBucketCountThresholds().getShardSize()) { ++ // The user has not made a shardSize selection. Use default heuristic to avoid any wrong-ranking caused by distributed counting ++ bucketCountThresholds.setShardSize(BucketUtils.suggestShardSideQueueSize(bucketCountThresholds.getRequiredSize(), ++ context.numberOfShards())); ++ } + bucketCountThresholds.ensureValidity(); +- InternalOrder order = resolveOrder(aggParser.getOrderKey(), aggParser.isOrderAsc()); +- return new TermsAggregatorFactory(aggregationName, vsParser.config(), order, bucketCountThresholds, aggParser.getIncludeExclude(), aggParser.getExecutionHint(), aggParser.getCollectionMode()); ++ return new TermsAggregatorFactory(aggregationName, vsParser.config(), order, bucketCountThresholds, aggParser.getIncludeExclude(), ++ aggParser.getExecutionHint(), aggParser.getCollectionMode()); + } + + static InternalOrder resolveOrder(String key, boolean asc) { +diff --git a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java +index 7251617f374ee..4bdaecc646d0c 100644 +--- a/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java ++++ b/src/test/java/org/elasticsearch/search/aggregations/bucket/ShardSizeTermsTests.java +@@ -45,6 +45,31 @@ public void noShardSize_string() throws Exception { + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(""1"", 8l) ++ .put(""3"", 8l) ++ .put(""2"", 5l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsText().string()))); ++ } ++ } ++ ++ @Test ++ public void shardSizeEqualsSize_string() throws Exception { ++ createIdx(""type=string,index=not_analyzed""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) ++ .execute().actionGet(); ++ + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); +@@ -109,6 +134,31 @@ public void withShardSize_string_singleShard() throws Exception { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKey()))); + } + } ++ ++ @Test ++ public void noShardSizeTermOrder_string() throws Exception { ++ createIdx(""type=string,index=not_analyzed""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) ++ .execute().actionGet(); ++ ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(""1"", 8l) ++ .put(""2"", 5l) ++ .put(""3"", 8l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsText().string()))); ++ } ++ } + + @Test + public void noShardSize_long() throws Exception { +@@ -123,6 +173,32 @@ public void noShardSize_long() throws Exception { + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(1, 8l) ++ .put(3, 8l) ++ .put(2, 5l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); ++ } ++ } ++ ++ @Test ++ public void shardSizeEqualsSize_long() throws Exception { ++ ++ createIdx(""type=long""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) ++ .execute().actionGet(); ++ + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); +@@ -188,6 +264,32 @@ public void withShardSize_long_singleShard() throws Exception { + } + } + ++ @Test ++ public void noShardSizeTermOrder_long() throws Exception { ++ ++ createIdx(""type=long""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) ++ .execute().actionGet(); ++ ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(1, 8l) ++ .put(2, 5l) ++ .put(3, 8l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); ++ } ++ } ++ + @Test + public void noShardSize_double() throws Exception { + +@@ -201,6 +303,32 @@ public void noShardSize_double() throws Exception { + .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) + .execute().actionGet(); + ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(1, 8l) ++ .put(3, 8l) ++ .put(2, 5l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); ++ } ++ } ++ ++ @Test ++ public void shardSizeEqualsSize_double() throws Exception { ++ ++ createIdx(""type=double""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3).shardSize(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.count(false))) ++ .execute().actionGet(); ++ + Terms terms = response.getAggregations().get(""keys""); + Collection buckets = terms.getBuckets(); + assertThat(buckets.size(), equalTo(3)); +@@ -265,4 +393,30 @@ public void withShardSize_double_singleShard() throws Exception { + assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); + } + } ++ ++ @Test ++ public void noShardSizeTermOrder_double() throws Exception { ++ ++ createIdx(""type=double""); ++ ++ indexData(); ++ ++ SearchResponse response = client().prepareSearch(""idx"").setTypes(""type"") ++ .setQuery(matchAllQuery()) ++ .addAggregation(terms(""keys"").field(""key"").size(3) ++ .collectMode(randomFrom(SubAggCollectionMode.values())).order(Terms.Order.term(true))) ++ .execute().actionGet(); ++ ++ Terms terms = response.getAggregations().get(""keys""); ++ Collection buckets = terms.getBuckets(); ++ assertThat(buckets.size(), equalTo(3)); ++ Map expected = ImmutableMap.builder() ++ .put(1, 8l) ++ .put(2, 5l) ++ .put(3, 8l) ++ .build(); ++ for (Terms.Bucket bucket : buckets) { ++ assertThat(bucket.getDocCount(), equalTo(expected.get(bucket.getKeyAsNumber().intValue()))); ++ } ++ } + }" +d7929a40521731c53f510996bf9918ff3b158e3d,Delta Spike,"DELTASPIKE-378 add ProjectStageAware property handling + +Main entry point for this feature is +ConfigResolver#getProjectStageAwarePropertyValue +",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +index 43bb6602f..05cbc59df 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/api/config/ConfigResolver.java +@@ -31,9 +31,11 @@ + + import javax.enterprise.inject.Typed; + ++import org.apache.deltaspike.core.api.projectstage.ProjectStage; + import org.apache.deltaspike.core.spi.config.ConfigSource; + import org.apache.deltaspike.core.spi.config.ConfigSourceProvider; + import org.apache.deltaspike.core.util.ClassUtils; ++import org.apache.deltaspike.core.util.ProjectStageProducer; + import org.apache.deltaspike.core.util.ServiceUtils; + + /** +@@ -56,6 +58,8 @@ public final class ConfigResolver + private static Map configSources + = new ConcurrentHashMap(); + ++ private static volatile ProjectStage projectStage = null; ++ + private ConfigResolver() + { + // this is a utility class which doesn't get instantiated. +@@ -146,6 +150,35 @@ public static String getPropertyValue(String key) + return null; + } + ++ /** ++ *

Search for the configured value in all {@link ConfigSource}s and take the ++ * current {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} ++ * into account.

++ * ++ *

It first will search if there is a configured value of the given key prefixed ++ * with the current ProjectStage (e.g. 'myproject.myconfig.Production') and if this didn't ++ * find anything it will lookup the given key without any prefix.

++ * ++ *

Attention This method must only be used after all ConfigSources ++ * got registered and it also must not be used to determine the ProjectStage itself.

++ * @param key ++ * @param defaultValue ++ * @return the configured value or if non found the defaultValue ++ * ++ */ ++ public static String getProjectStageAwarePropertyValue(String key, String defaultValue) ++ { ++ ProjectStage ps = getProjectStage(); ++ ++ String value = getPropertyValue(key + '.' + ps, defaultValue); ++ if (value == null) ++ { ++ value = getPropertyValue(key, defaultValue); ++ } ++ ++ return value; ++ } ++ + /** + * Resolve all values for the given key, from all registered ConfigSources ordered by their + * ordinal value in ascending ways. If more {@link ConfigSource}s have the same ordinal, their +@@ -264,4 +297,17 @@ public int compare(ConfigSource configSource1, ConfigSource configSource2) + return configSources; + } + ++ private static ProjectStage getProjectStage() ++ { ++ if (projectStage == null) ++ { ++ synchronized (ConfigResolver.class) ++ { ++ projectStage = ProjectStageProducer.getInstance().getProjectStage(); ++ } ++ } ++ ++ return projectStage; ++ } ++ + } +diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java +index ba4ac6b28..f2e39bf53 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/ProjectStageProducer.java +@@ -47,6 +47,7 @@ + * } + * + * ++ *

Please note that there can only be one ProjectStage per EAR.

+ */ + @ApplicationScoped + public class ProjectStageProducer implements Serializable +diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +index 809ccc1df..70c00e802 100644 +--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java ++++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/ConfigResolverTest.java +@@ -19,6 +19,8 @@ + package org.apache.deltaspike.test.api.config; + + import org.apache.deltaspike.core.api.config.ConfigResolver; ++import org.apache.deltaspike.core.api.projectstage.ProjectStage; ++import org.apache.deltaspike.core.util.ProjectStageProducer; + import org.junit.Assert; + import org.junit.Test; + +@@ -50,4 +52,12 @@ public void testStandaloneConfigSource() + Assert.assertNull(ConfigResolver.getPropertyValue(""notexisting"")); + Assert.assertEquals(""testvalue"", ConfigResolver.getPropertyValue(""testkey"")); + } ++ ++ @Test ++ public void testGetProjectStageAwarePropertyValue() ++ { ++ ProjectStageProducer.setProjectStage(ProjectStage.UnitTest); ++ Assert.assertNull(ConfigResolver.getProjectStageAwarePropertyValue(""notexisting"", null)); ++ Assert.assertEquals(""unittestvalue"", ConfigResolver.getProjectStageAwarePropertyValue(""testkey"", null)); ++ } + } +diff --git a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +index 581c837e3..ed9dc8667 100644 +--- a/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java ++++ b/deltaspike/core/api/src/test/java/org/apache/deltaspike/test/api/config/TestConfigSource.java +@@ -33,6 +33,15 @@ public class TestConfigSource implements ConfigSource + + private int ordinal = 700; + ++ private Map props = new HashMap(); ++ ++ ++ public TestConfigSource() ++ { ++ props.put(""testkey"", ""testvalue""); ++ props.put(""testkey.UnitTest"", ""unittestvalue""); ++ } ++ + @Override + public String getConfigName() + { +@@ -48,15 +57,13 @@ public int getOrdinal() + @Override + public String getPropertyValue(String key) + { +- return ""testkey"".equals(key) ? ""testvalue"" : null; ++ return props.get(key); + } + + @Override + public Map getProperties() + { +- Map map = new HashMap(); +- map.put(""testkey"", ""testvalue""); +- return map; ++ return props; + } + + @Override" +aec021e668ad6786d20feaadf119f5407c2b3191,kotlin,Implemented better rendering for parameters with- default values in decompiler and descriptor renderer.-- -KT-1582 fixed-,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +1bd1c6fd062d26e776cabbaa2bab0ad009453af6,Valadoc,"libvaladoc: Allow conditional spaces in headlines +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +6236c422615cfe33795267214077551f3d9ffa6f,camel,CAMEL-1977: Http based components should filter- out camel internal headers.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@814567 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java +index a32be75c50c52..37e81e5c902f3 100644 +--- a/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java ++++ b/components/camel-http/src/main/java/org/apache/camel/component/http/HttpHeaderFilterStrategy.java +@@ -45,6 +45,7 @@ protected void initialize() { + setLowerCase(true); + + // filter headers begin with ""Camel"" or ""org.apache.camel"" +- setOutFilterPattern(""(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*""); ++ // must ignore case for Http based transports ++ setOutFilterPattern(""(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*""); + } + } +diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java +new file mode 100644 +index 0000000000000..40861c7fcc891 +--- /dev/null ++++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterCamelHeadersTest.java +@@ -0,0 +1,80 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.component.jetty; ++ ++import java.util.Map; ++ ++import org.apache.camel.Exchange; ++import org.apache.camel.Processor; ++import org.apache.camel.builder.RouteBuilder; ++import org.apache.camel.impl.JndiRegistry; ++import org.apache.camel.test.junit4.CamelTestSupport; ++import org.junit.Test; ++ ++/** ++ * @version $Revision$ ++ */ ++public class HttpFilterCamelHeadersTest extends CamelTestSupport { ++ ++ @Test ++ public void testFilterCamelHeaders() throws Exception { ++ Exchange out = template.send(""http://localhost:9090/test/filter"", new Processor() { ++ public void process(Exchange exchange) throws Exception { ++ exchange.getIn().setBody(""Claus""); ++ exchange.getIn().setHeader(""bar"", 123); ++ } ++ }); ++ ++ assertNotNull(out); ++ assertEquals(""Hi Claus"", out.getOut().getBody(String.class)); ++ ++ // there should be no internal Camel headers ++ // except for the response code ++ Map headers = out.getOut().getHeaders(); ++ for (String key : headers.keySet()) { ++ if (!key.equalsIgnoreCase(Exchange.HTTP_RESPONSE_CODE)) { ++ assertTrue(""Should not contain any Camel internal headers"", !key.toLowerCase().startsWith(""camel"")); ++ } else { ++ assertEquals(200, headers.get(Exchange.HTTP_RESPONSE_CODE)); ++ } ++ } ++ } ++ ++ @Override ++ protected JndiRegistry createRegistry() throws Exception { ++ JndiRegistry jndi = super.createRegistry(); ++ jndi.bind(""foo"", new MyFooBean()); ++ return jndi; ++ } ++ ++ @Override ++ protected RouteBuilder createRouteBuilder() throws Exception { ++ return new RouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ from(""jetty:http://localhost:9090/test/filter"").beanRef(""foo""); ++ } ++ }; ++ } ++ ++ public static class MyFooBean { ++ ++ public String hello(String name) { ++ return ""Hi "" + name; ++ } ++ } ++}" +91517fad3eae6b93ded1cb16a518b1a37ec06e5c,restlet-framework-java,Fixed potential NPE when the product name is null.- Reported by Vincent Ricard.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java b/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java +index 99e1c21761..7dbcab4ed7 100644 +--- a/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java ++++ b/modules/com.noelios.restlet/src/com/noelios/restlet/Engine.java +@@ -582,7 +582,7 @@ public String formatUserAgent(List products) + .hasNext();) { + final Product product = iterator.next(); + if ((product.getName() == null) +- && (product.getName().length() == 0)) { ++ || (product.getName().length() == 0)) { + throw new IllegalArgumentException( + ""Product name cannot be null.""); + } +diff --git a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java +index b52fa867bb..df932134a8 100644 +--- a/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java ++++ b/modules/org.restlet.gwt/src/org/restlet/gwt/internal/Engine.java +@@ -208,7 +208,7 @@ public String formatUserAgent(List products) + .hasNext();) { + final Product product = iterator.next(); + if ((product.getName() == null) +- && (product.getName().length() == 0)) { ++ || (product.getName().length() == 0)) { + throw new IllegalArgumentException( + ""Product name cannot be null.""); + }" +10d01bb9da84d588f57a824ef9dc048562af2f7a,Mylyn Reviews,"bug 386204: Allow users to include subtasks in changeset view + +Refactored part and introduced a model, which allows including subtasks. + +https://bugs.eclipse.org/bugs/show_bug.cgi?id=386204 + +Change-Id: I94af1aa42624b69f280d8dca54c8020f877a9f45 +",a,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java +index b1787d9b..2ca7ca10 100644 +--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java ++++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/ChangesetPart.java +@@ -14,25 +14,37 @@ + import java.util.List; + + import org.eclipse.core.runtime.CoreException; ++import org.eclipse.core.runtime.IStatus; + import org.eclipse.core.runtime.NullProgressMonitor; ++import org.eclipse.core.runtime.Status; + import org.eclipse.jface.action.MenuManager; ++import org.eclipse.jface.action.ToolBarManager; ++import org.eclipse.jface.dialogs.IMessageProvider; + import org.eclipse.jface.viewers.ArrayContentProvider; +-import org.eclipse.jface.viewers.ILabelProviderListener; +-import org.eclipse.jface.viewers.ITableLabelProvider; + import org.eclipse.jface.viewers.TableViewer; + import org.eclipse.jface.viewers.TableViewerColumn; ++import org.eclipse.mylyn.internal.tasks.ui.editors.Messages; ++import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; + import org.eclipse.mylyn.tasks.core.ITask; ++import org.eclipse.mylyn.tasks.core.ITaskContainer; + import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPart; + import org.eclipse.mylyn.versions.core.ChangeSet; + import org.eclipse.mylyn.versions.tasks.core.IChangeSetMapping; + import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; ++import org.eclipse.mylyn.versions.tasks.ui.internal.IChangesetModel; ++import org.eclipse.mylyn.versions.tasks.ui.internal.IncludeSubTasksAction; ++import org.eclipse.mylyn.versions.tasks.ui.internal.TaskChangesetLabelProvider; ++import org.eclipse.mylyn.versions.tasks.ui.internal.TaskVersionsUiPlugin; + import org.eclipse.swt.SWT; +-import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.custom.BusyIndicator; + import org.eclipse.swt.layout.FillLayout; + import org.eclipse.swt.layout.GridData; + import org.eclipse.swt.layout.GridLayout; + import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Display; + import org.eclipse.swt.widgets.Menu; ++import org.eclipse.ui.forms.events.HyperlinkAdapter; ++import org.eclipse.ui.forms.events.HyperlinkEvent; + import org.eclipse.ui.forms.widgets.FormToolkit; + import org.eclipse.ui.forms.widgets.Section; + +@@ -43,40 +55,8 @@ + */ + @SuppressWarnings(""restriction"") + public class ChangesetPart extends AbstractTaskEditorPart { +- private static final class TaskChangesetLabelProvider implements +- ITableLabelProvider { +- public void addListener(ILabelProviderListener listener) { +- } +- +- public void dispose() { +- } +- +- public boolean isLabelProperty(Object element, String property) { +- return false; +- } +- +- public void removeListener(ILabelProviderListener listener) { +- } +- +- public Image getColumnImage(Object element, int columnIndex) { +- return null; +- } +- +- public String getColumnText(Object element, int columnIndex) { +- TaskChangeSet cs = ((TaskChangeSet) element); +- switch (columnIndex) { +- case 0: +- return cs.getChangeset().getId(); +- case 1: +- return cs.getChangeset().getMessage(); +- case 2: +- return cs.getChangeset().getAuthor().getEmail(); +- case 3: +- return cs.getChangeset().getDate().toString(); +- } +- return element.toString() + "" "" + columnIndex; +- } +- } ++ private TableViewer table; ++ private ChangesetModel model = new ChangesetModel(); + + public ChangesetPart() { + setPartName(""Changeset""); +@@ -87,7 +67,7 @@ public ChangesetPart() { + public void createControl(Composite parent, FormToolkit toolkit) { + Section createSection = createSection(parent, toolkit); + Composite composite = createContentComposite(toolkit, createSection); +- ++ + createTable(composite); + } + +@@ -113,7 +93,7 @@ private Section createSection(Composite parent, FormToolkit toolkit) { + } + + private void createTable(Composite composite) { +- TableViewer table = new TableViewer(composite); ++ table = new TableViewer(composite); + table.getTable().setLinesVisible(true); + table.getTable().setHeaderVisible(true); + addColumn(table, ""Id""); +@@ -122,11 +102,22 @@ private void createTable(Composite composite) { + addColumn(table, ""Date""); + table.setContentProvider(ArrayContentProvider.getInstance()); + table.setLabelProvider(new TaskChangesetLabelProvider()); +- table.setInput(getInput()); ++ refreshInput(); ++ registerContextMenu(table); ++ } ++ ++ @Override ++ protected void fillToolBar(ToolBarManager toolBarManager) { ++ super.fillToolBar(toolBarManager); ++ toolBarManager.add(new IncludeSubTasksAction(model)); ++ } ++ ++ private void registerContextMenu(TableViewer table) { + MenuManager menuManager = new MenuManager(); + menuManager.setRemoveAllWhenShown(true); + getTaskEditorPage().getEditorSite().registerContextMenu( +- ""org.eclipse.mylyn.versions.changesets"", menuManager, table, true); ++ ""org.eclipse.mylyn.versions.changesets"", menuManager, table, ++ true); + Menu menu = menuManager.createContextMenu(table.getControl()); + table.getTable().setMenu(menu); + } +@@ -138,40 +129,88 @@ private void addColumn(TableViewer table, String name) { + tableViewerColumn.getColumn().setWidth(100); + } + +- private List getInput() { +- int score = Integer.MIN_VALUE; ++ private AbstractChangesetMappingProvider determineBestProvider( ++ final ITask task) { + AbstractChangesetMappingProvider bestProvider = null; +- final ITask task = getModel().getTask(); +- ++ int score = Integer.MIN_VALUE; + for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil + .getMappingProviders()) { +- if (score < mappingProvider.getScoreFor(task)) +- ; +- { ++ if (score < mappingProvider.getScoreFor(task)) { + bestProvider = mappingProvider; + } + } +- final List changesets = new ArrayList(); +- try { ++ return bestProvider; ++ } + +- IChangeSetMapping changesetsMapping = new IChangeSetMapping() { ++ private IChangeSetMapping createChangeSetMapping(final ITask task, ++ final List changesets) { ++ return new IChangeSetMapping() { + +- public ITask getTask() { +- return task; +- } ++ public ITask getTask() { ++ return task; ++ } ++ ++ public void addChangeSet(ChangeSet changeset) { ++ changesets.add(new TaskChangeSet(task, changeset)); ++ } ++ }; ++ } ++ ++ private void refreshInput() { ++ table.setInput(model.getInput()); ++ } ++ ++ private class ChangesetModel implements IChangesetModel { ++ ++ private boolean includeSubTasks; + +- public void addChangeSet(ChangeSet changeset) { +- changesets.add(new TaskChangeSet(task, changeset)); ++ public boolean isIncludeSubTasks() { ++ return includeSubTasks; ++ } ++ ++ public void setIncludeSubTasks(boolean includeSubTasks) { ++ boolean isChanged = this.includeSubTasks ^ includeSubTasks; ++ this.includeSubTasks = includeSubTasks; ++ if (isChanged) { ++ refreshInput(); ++ } ++ } ++ ++ public List getInput() { ++ final ITask task = getModel().getTask(); ++ ++ AbstractChangesetMappingProvider bestProvider = determineBestProvider(task); ++ final List changesets = new ArrayList(); ++ ++ final List changesetsMapping = new ArrayList(); ++ changesetsMapping.add(createChangeSetMapping(task, changesets)); ++ ; ++ if (includeSubTasks) { ++ if (task instanceof ITaskContainer) { ++ ITaskContainer taskContainer = (ITaskContainer) task; ++ for (ITask subTask : taskContainer.getChildren()) { ++ changesetsMapping.add(createChangeSetMapping(subTask, ++ changesets)); ++ } + } +- }; +- // FIXME progress monitor +- bestProvider.getChangesetsForTask(changesetsMapping, +- new NullProgressMonitor()); +- } catch (CoreException e) { +- // FIXME Auto-generated catch block +- e.printStackTrace(); ++ } ++ final AbstractChangesetMappingProvider provider = bestProvider; ++ BusyIndicator.showWhile(Display.getDefault(), new Runnable() { ++ ++ public void run() { ++ try { ++ for (IChangeSetMapping csm : changesetsMapping) { ++ provider.getChangesetsForTask(csm, ++ new NullProgressMonitor()); ++ } ++ } catch (CoreException e) { ++ getTaskEditorPage().getTaskEditor().setMessage(""An exception occurred "" + e.getMessage(), IMessageProvider.ERROR); ++ } ++ } ++ ++ }); ++ ++ return changesets; + } +- return changesets; + } +- + } +diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java +new file mode 100644 +index 00000000..8839451c +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IChangesetModel.java +@@ -0,0 +1,18 @@ ++/******************************************************************************* ++ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.versions.tasks.ui.internal; ++ ++/** ++ * @author Kilian Matt ++ */ ++public interface IChangesetModel { ++ public void setIncludeSubTasks(boolean includeSubTasks); ++} +\ No newline at end of file +diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java +new file mode 100644 +index 00000000..1ae383c8 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/IncludeSubTasksAction.java +@@ -0,0 +1,37 @@ ++/******************************************************************************* ++ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.versions.tasks.ui.internal; ++ ++import org.eclipse.jface.action.Action; ++import org.eclipse.mylyn.tasks.ui.TasksUiImages; ++import org.eclipse.swt.widgets.Event; ++ ++/** ++ * @author Kilian Matt ++ */ ++public class IncludeSubTasksAction extends Action { ++ private IChangesetModel model; ++ ++ public IncludeSubTasksAction(IChangesetModel model) { ++ super(""Include subtasks"",AS_CHECK_BOX); ++ setImageDescriptor(TasksUiImages.TASK_NEW_SUB); ++ this.model = model; ++ } ++ ++ public void run() { ++ model.setIncludeSubTasks(isChecked()); ++ } ++ ++ public void runWithEvent(Event event) { ++ model.setIncludeSubTasks(isChecked()); ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java +new file mode 100644 +index 00000000..966afc90 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/versions/tasks/ui/internal/TaskChangesetLabelProvider.java +@@ -0,0 +1,53 @@ ++/******************************************************************************* ++ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.versions.tasks.ui.internal; ++ ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.ITableLabelProvider; ++import org.eclipse.mylyn.versions.tasks.core.TaskChangeSet; ++import org.eclipse.swt.graphics.Image; ++ ++/** ++ * @author Kilian Matt ++ */ ++public class TaskChangesetLabelProvider implements ITableLabelProvider { ++ public void addListener(ILabelProviderListener listener) { ++ } ++ ++ public void dispose() { ++ } ++ ++ public boolean isLabelProperty(Object element, String property) { ++ return false; ++ } ++ ++ public void removeListener(ILabelProviderListener listener) { ++ } ++ ++ public Image getColumnImage(Object element, int columnIndex) { ++ return null; ++ } ++ ++ public String getColumnText(Object element, int columnIndex) { ++ TaskChangeSet cs = ((TaskChangeSet) element); ++ switch (columnIndex) { ++ case 0: ++ return cs.getChangeset().getId(); ++ case 1: ++ return cs.getChangeset().getMessage(); ++ case 2: ++ return cs.getChangeset().getAuthor().getEmail(); ++ case 3: ++ return cs.getChangeset().getDate().toString(); ++ } ++ return element.toString() + "" "" + columnIndex; ++ } ++}" +59f1ae7b2b15776314059123e26dc1563ca064c8,Vala,"tracker-indexer-module-1.0: regenerate +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +ce554e2810317d96078e68b4ab9379efe4c8db61,Vala,"vapigen: Improve support for type_arguments + +Fixes bug 609693. +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +3c4d64750b9fba05c95bb6cc359fe2e6fac9127f,brandonborkholder$glg2d,"Brand new functionality that repaints only child components, not the entire scene.",p,https://github.com/brandonborkholder/glg2d,"diff --git a/src/main/java/glg2d/G2DGLCanvas.java b/src/main/java/glg2d/G2DGLCanvas.java +index 5c74a7d7..5da5cfac 100644 +--- a/src/main/java/glg2d/G2DGLCanvas.java ++++ b/src/main/java/glg2d/G2DGLCanvas.java +@@ -21,14 +21,15 @@ + import java.awt.Dimension; + import java.awt.Graphics; + import java.awt.LayoutManager2; ++import java.awt.Rectangle; + import java.io.Serializable; ++import java.util.Map; + + import javax.media.opengl.GLAutoDrawable; + import javax.media.opengl.GLCanvas; + import javax.media.opengl.GLCapabilities; + import javax.media.opengl.GLContext; + import javax.media.opengl.GLDrawableFactory; +-import javax.media.opengl.GLEventListener; + import javax.media.opengl.GLJPanel; + import javax.media.opengl.GLPbuffer; + import javax.media.opengl.Threading; +@@ -41,17 +42,19 @@ public class G2DGLCanvas extends JComponent { + + protected GLAutoDrawable canvas; + +- protected boolean drawGL = true; ++ protected boolean drawGL; + + /** + * @see #removeNotify() + */ + protected GLPbuffer sideContext; + +- protected GLEventListener g2dglListener; ++ protected G2DGLEventListener g2dglListener; + + protected JComponent drawableComponent; + ++ GLGraphics2D g2d; ++ + public static GLCapabilities getDefaultCapabalities() { + GLCapabilities caps = new GLCapabilities(); + caps.setRedBits(8); +@@ -78,6 +81,7 @@ public G2DGLCanvas(GLCapabilities capabilities) { + add((Component) canvas); + + RepaintManager.setCurrentManager(GLAwareRepaintManager.INSTANCE); ++ setGLDrawing(true); + } + + public G2DGLCanvas(JComponent drawableComponent) { +@@ -120,6 +124,7 @@ public boolean isGLDrawing() { + public void setGLDrawing(boolean drawGL) { + this.drawGL = drawGL; + ((Component) canvas).setVisible(drawGL); ++ setOpaque(drawGL); + repaint(); + } + +@@ -130,6 +135,9 @@ public void setDrawableComponent(JComponent component) { + + if (g2dglListener != null) { + canvas.removeGLEventListener(g2dglListener); ++ if (sideContext != null) { ++ sideContext.removeGLEventListener(g2dglListener); ++ } + } + + if (drawableComponent != null) { +@@ -140,6 +148,10 @@ public void setDrawableComponent(JComponent component) { + if (drawableComponent != null) { + g2dglListener = createG2DListener(drawableComponent); + canvas.addGLEventListener(g2dglListener); ++ if (sideContext != null) { ++ sideContext.addGLEventListener(g2dglListener); ++ } ++ + add(drawableComponent); + + forceViewportToNativeDraw(drawableComponent); +@@ -150,7 +162,7 @@ public void setDrawableComponent(JComponent component) { + * Creates the GLEventListener that will draw the given component to the + * canvas. + */ +- protected GLEventListener createG2DListener(JComponent drawingComponent) { ++ protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { + return new G2DGLEventListener(drawingComponent); + } + +@@ -213,8 +225,12 @@ public void run() { + + @Override + public void paint(Graphics g) { +- if (drawGL && drawableComponent != null) { +- canvas.display(); ++ if (drawGL && drawableComponent != null && canvas != null) { ++ if (g2d == null) { ++ canvas.display(); ++ } else { ++ drawableComponent.paint(g2d); ++ } + } else { + super.paint(g); + } +@@ -257,6 +273,17 @@ protected void forceViewportToNativeDraw(Container parent) { + } + } + ++ @Override ++ public Graphics getGraphics() { ++ return g2d == null ? super.getGraphics() : g2d.create(); ++ } ++ ++ public void paintGLImmediately(Map r) { ++ g2dglListener.canvas = this; ++ g2dglListener.repaints = r; ++ canvas.display(); ++ } ++ + /** + * Implements a simple layout where all the components are the same size as + * the parent. +diff --git a/src/main/java/glg2d/G2DGLEventListener.java b/src/main/java/glg2d/G2DGLEventListener.java +index a65247f6..cf64d05d 100644 +--- a/src/main/java/glg2d/G2DGLEventListener.java ++++ b/src/main/java/glg2d/G2DGLEventListener.java +@@ -17,11 +17,15 @@ + package glg2d; + + import java.awt.Component; ++import java.awt.Rectangle; ++import java.util.Map; ++import java.util.Map.Entry; + + import javax.media.opengl.GL; + import javax.media.opengl.GLAutoDrawable; + import javax.media.opengl.GLContext; + import javax.media.opengl.GLEventListener; ++import javax.swing.JComponent; + import javax.swing.RepaintManager; + + /** +@@ -32,6 +36,10 @@ public class G2DGLEventListener implements GLEventListener { + + protected Component baseComponent; + ++ Map repaints; ++ ++ G2DGLCanvas canvas; ++ + /** + * Creates a new listener that will paint using the {@code GLGraphics2D} + * object on each call to {@link #display(GLAutoDrawable)}. The provided +@@ -130,10 +138,30 @@ protected void paintGL(GLGraphics2D g2d) { + RepaintManager mgr = RepaintManager.currentManager(baseComponent); + boolean doubleBuffer = mgr.isDoubleBufferingEnabled(); + mgr.setDoubleBufferingEnabled(false); +- baseComponent.paint(g2d); ++ ++ if (isPaintingDirtyRects()) { ++ paintDirtyRects(); ++ } else { ++ baseComponent.paint(g2d); ++ } ++ + mgr.setDoubleBufferingEnabled(doubleBuffer); + } + ++ protected boolean isPaintingDirtyRects() { ++ return repaints != null; ++ } ++ ++ protected void paintDirtyRects() { ++ canvas.g2d = g2d; ++ for (Entry entry : repaints.entrySet()) { ++ entry.getKey().paintImmediately(entry.getValue()); ++ } ++ ++ repaints = null; ++ canvas.g2d = null; ++ } ++ + @Override + public void init(GLAutoDrawable drawable) { + reshape(drawable, 0, 0, drawable.getWidth(), drawable.getWidth()); +diff --git a/src/main/java/glg2d/GLAwareRepaintManager.java b/src/main/java/glg2d/GLAwareRepaintManager.java +index 9251b7b4..1151bc59 100644 +--- a/src/main/java/glg2d/GLAwareRepaintManager.java ++++ b/src/main/java/glg2d/GLAwareRepaintManager.java +@@ -17,25 +17,78 @@ + package glg2d; + + import java.awt.Container; ++import java.awt.Rectangle; ++import java.util.IdentityHashMap; ++import java.util.Iterator; ++import java.util.Map; + ++import javax.media.opengl.GLAutoDrawable; + import javax.swing.JComponent; + import javax.swing.RepaintManager; ++import javax.swing.SwingUtilities; + + public class GLAwareRepaintManager extends RepaintManager { + public static RepaintManager INSTANCE = new GLAwareRepaintManager(); + ++ private Map rects = new IdentityHashMap(); ++ ++ private volatile boolean queued = false; ++ + @Override + public void addDirtyRegion(JComponent c, int x, int y, int w, int h) { +- G2DGLCanvas glDrawable = getGLParent(c); +- if (glDrawable != null) { +- super.addDirtyRegion(glDrawable, 0, 0, glDrawable.getWidth(), glDrawable.getHeight()); +- } else { ++ G2DGLCanvas canvas = getGLParent(c); ++ if (canvas == null || c instanceof GLAutoDrawable) { + super.addDirtyRegion(c, x, y, w, h); ++ } else { ++ synchronized (rects) { ++ if (!rects.containsKey(c)) { ++ rects.put(c, new Rectangle(0, 0, c.getWidth(), c.getHeight())); ++ } ++ ++ if (!queued && rects.size() > 0) { ++ queued = true; ++ queue(); ++ } ++ } ++ } ++ } ++ ++ private void queue() { ++ SwingUtilities.invokeLater(new Runnable() { ++ @Override ++ public void run() { ++ Map r; ++ synchronized (rects) { ++ r = new IdentityHashMap(rects); ++ queued = false; ++ ++ rects.clear(); ++ } ++ ++ r = filter(r); ++ G2DGLCanvas canvas = getGLParent(r.keySet().iterator().next()); ++ canvas.paintGLImmediately(r); ++ } ++ }); ++ } ++ ++ private Map filter(Map rects) { ++ Iterator itr = rects.keySet().iterator(); ++ while (itr.hasNext()) { ++ JComponent desc = itr.next(); ++ for (JComponent key : rects.keySet()) { ++ if (desc != key && SwingUtilities.isDescendingFrom(desc, key)) { ++ itr.remove(); ++ break; ++ } ++ } + } ++ ++ return rects; + } + + protected G2DGLCanvas getGLParent(JComponent component) { +- Container c = component; ++ Container c = component.getParent(); + while (true) { + if (c == null) { + return null; +diff --git a/src/main/java/glg2d/GLGraphics2D.java b/src/main/java/glg2d/GLGraphics2D.java +index afb517bc..eb8bb001 100644 +--- a/src/main/java/glg2d/GLGraphics2D.java ++++ b/src/main/java/glg2d/GLGraphics2D.java +@@ -139,8 +139,6 @@ protected void setCanvas(GLAutoDrawable drawable) { + protected void prePaint(GLAutoDrawable drawable, Component component) { + setCanvas(drawable); + setupState(component); +- +- gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); + } + + protected void setupState(Component component) { +diff --git a/src/test/java/glg2d/examples/shaders/CellShaderExample.java b/src/test/java/glg2d/examples/shaders/CellShaderExample.java +index 4cf8c5ba..2adb01b4 100644 +--- a/src/test/java/glg2d/examples/shaders/CellShaderExample.java ++++ b/src/test/java/glg2d/examples/shaders/CellShaderExample.java +@@ -13,7 +13,6 @@ + import java.awt.Dimension; + + import javax.media.opengl.GLAutoDrawable; +-import javax.media.opengl.GLEventListener; + import javax.swing.JComponent; + import javax.swing.JFrame; + import javax.swing.UIManager; +@@ -26,7 +25,7 @@ public static void main(String[] args) throws Exception { + JFrame frame = new JFrame(""Cell Shader Example""); + frame.setContentPane(new G2DGLCanvas(new UIDemo()) { + @Override +- protected GLEventListener createG2DListener(JComponent drawingComponent) { ++ protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { + return new G2DGLEventListener(drawingComponent) { + @Override + protected GLGraphics2D createGraphics2D(GLAutoDrawable drawable) { +diff --git a/src/test/java/glg2d/examples/shaders/DepthSimExample.java b/src/test/java/glg2d/examples/shaders/DepthSimExample.java +index 2428cbd2..db66ad4f 100644 +--- a/src/test/java/glg2d/examples/shaders/DepthSimExample.java ++++ b/src/test/java/glg2d/examples/shaders/DepthSimExample.java +@@ -11,7 +11,6 @@ + + import javax.media.opengl.GL; + import javax.media.opengl.GLAutoDrawable; +-import javax.media.opengl.GLEventListener; + import javax.swing.JComponent; + import javax.swing.JFrame; + import javax.swing.Timer; +@@ -25,7 +24,7 @@ public static void main(String[] args) throws Exception { + final JFrame frame = new JFrame(""Depth Shaker Example""); + frame.setContentPane(new G2DGLCanvas(new UIDemo()) { + @Override +- protected GLEventListener createG2DListener(JComponent drawingComponent) { ++ protected G2DGLEventListener createG2DListener(JComponent drawingComponent) { + return new G2DGLEventListener(drawingComponent) { + @Override + protected GLGraphics2D createGraphics2D(GLAutoDrawable drawable) { +diff --git a/src/test/java/glg2d/examples/shaders/UIDemo.java b/src/test/java/glg2d/examples/shaders/UIDemo.java +index 54f750fd..a0ef02cd 100644 +--- a/src/test/java/glg2d/examples/shaders/UIDemo.java ++++ b/src/test/java/glg2d/examples/shaders/UIDemo.java +@@ -66,7 +66,7 @@ public UIDemo() { + + JPanel rightSubPanel = new JPanel(new BorderLayout()); + rightPanel.add(rightSubPanel, BorderLayout.CENTER); +- rightSubPanel.add(createProgressComponent(), BorderLayout.NORTH); ++// rightSubPanel.add(createProgressComponent(), BorderLayout.NORTH); + + JSplitPane rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); + rightSplit.setDividerSize(10); +@@ -214,6 +214,11 @@ JComponent createListComponent() { + model.addElement(""golf""); + model.addElement(""hotel""); + model.addElement(""india""); ++ model.addElement(""juliet""); ++ model.addElement(""kilo""); ++ model.addElement(""limo""); ++ model.addElement(""mike""); ++ model.addElement(""november""); + return new JList(model); + } + +@@ -286,6 +291,7 @@ public static void main(String[] args) throws Exception { + + // frame.setContentPane(new UIDemo()); + frame.setContentPane(new G2DGLCanvas(new UIDemo())); ++// frame.setContentPane(new UIDemo().createTabComponent()); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setPreferredSize(new Dimension(1024, 768)); + frame.pack();" +5f2ee6ded78a158ec352a376b7d6ee5381e70599,drools,JBRULES-233 for leaps--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@4214 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java +index 6471a4b1fd2..82960c9491d 100644 +--- a/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java ++++ b/drools-compiler/src/test/java/org/drools/integrationtests/LeapsTest.java +@@ -162,9 +162,4 @@ public void testXorGroups() throws Exception { + assertTrue( ""rule2"", + list.contains( ""rule2"" ) ); + } +- +- public void testLogicalAssertionsDynamicRule() throws Exception { +- // TODO FIXME +- } +- + } +diff --git a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +index d561015325a..23a3167ef02 100644 +--- a/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java ++++ b/drools-core/src/main/java/org/drools/common/AbstractWorkingMemory.java +@@ -111,7 +111,9 @@ abstract public class AbstractWorkingMemory implements WorkingMemory, + protected long propagationIdCounter; + + private ReentrantLock lock = new ReentrantLock( ); +- ++ ++ private List factQueue = new ArrayList( ); ++ + public AbstractWorkingMemory(RuleBase ruleBase, + FactHandleFactory handleFactory) { + this.ruleBase = ruleBase; +@@ -377,8 +379,52 @@ public PrimitiveLongMap getJustified() { + return this.justified; + } + ++ public long getNextPropagationIdCounter() { ++ return this.propagationIdCounter++; ++ } ++ + abstract public void dispose(); + ++ public void removeLogicalDependencies(Activation activation, ++ PropagationContext context, ++ Rule rule) throws FactException { ++ org.drools.util.LinkedList list = activation.getLogicalDependencies(); ++ if ( list == null || list.isEmpty() ) { ++ return; ++ } ++ for ( LogicalDependency node = (LogicalDependency) list.getFirst(); node != null; node = (LogicalDependency) node.getNext() ) { ++ InternalFactHandle handle = (InternalFactHandle) node.getFactHandle(); ++ Set set = (Set) this.justified.get( handle.getId( ) ); ++ // check set for null because in some weird cases on logical assertion ++ // it comes back with the same activation/handle and tries on ++ // already cleaned this.justified. only happens on removal of rule ++ // from the working memory ++ if (set != null) { ++ set.remove( node ); ++ if (set.isEmpty( )) { ++ this.justified.remove( handle.getId( ) ); ++ // this needs to be scheduled so we don't upset the current ++ // working memory operation ++ this.factQueue.add( new WorkingMemoryRetractAction( handle, ++ false, ++ true, ++ context.getRuleOrigin( ), ++ context.getActivationOrigin( ) ) ); ++ } ++ } ++ } ++ } ++ ++ public void removeLogicalDependencies(FactHandle handle) throws FactException { ++ Set set = (Set) this.justified.remove( ((InternalFactHandle) handle).getId() ); ++ if ( set != null && !set.isEmpty() ) { ++ for ( Iterator it = set.iterator(); it.hasNext(); ) { ++ LogicalDependency node = (LogicalDependency) it.next(); ++ node.getJustifier().getLogicalDependencies().remove( node ); ++ } ++ } ++ } ++ + public void addLogicalDependency(FactHandle handle, + Activation activation, + PropagationContext context, +@@ -395,34 +441,12 @@ public void addLogicalDependency(FactHandle handle, + set.add( node ); + } + +- public void removeLogicalDependencies( Activation activation, +- PropagationContext context, +- Rule rule ) throws FactException { +- org.drools.util.LinkedList list = activation.getLogicalDependencies(); +- if (list == null || list.isEmpty( )) { +- return; +- } +- for (LogicalDependency node = (LogicalDependency) list.getFirst( ); node != null; node = (LogicalDependency) node.getNext( )) { +- InternalFactHandle handle = (InternalFactHandle) node.getFactHandle( ); +- Set set = (Set) this.justified.get( handle.getId( ) ); +- set.remove( node ); +- if (set.isEmpty( )) { +- this.justified.remove( handle.getId( ) ); +- retractObject( handle, +- false, +- true, +- context.getRuleOrigin( ), +- context.getActivationOrigin( ) ); +- } +- } +- } +- +- public void removeLogicalDependencies(FactHandle handle) throws FactException { +- Set set = (Set) this.justified.remove( ((InternalFactHandle) handle).getId() ); +- if ( set != null && !set.isEmpty() ) { +- for ( Iterator it = set.iterator(); it.hasNext(); ) { +- LogicalDependency node = (LogicalDependency) it.next(); +- node.getJustifier().getLogicalDependencies().remove( node ); ++ protected void propagateQueuedActions() { ++ if (!this.factQueue.isEmpty( )) { ++ for (Iterator it = this.factQueue.iterator( ); it.hasNext( );) { ++ WorkingMemoryAction action = (WorkingMemoryAction) it.next( ); ++ it.remove( ); ++ action.propagate( ); + } + } + } +@@ -431,6 +455,41 @@ public Lock getLock() { + return this.lock; + } + ++ private interface WorkingMemoryAction { ++ public void propagate(); ++ } ++ ++ private class WorkingMemoryRetractAction implements WorkingMemoryAction { ++ private InternalFactHandle factHandle; ++ private boolean removeLogical; ++ private boolean updateEqualsMap; ++ private Rule ruleOrigin; ++ private Activation activationOrigin; ++ ++ ++ ++ public WorkingMemoryRetractAction(InternalFactHandle factHandle, ++ boolean removeLogical, ++ boolean updateEqualsMap, ++ Rule ruleOrigin, ++ Activation activationOrigin) { ++ super(); ++ this.factHandle = factHandle; ++ this.removeLogical = removeLogical; ++ this.updateEqualsMap = updateEqualsMap; ++ this.ruleOrigin = ruleOrigin; ++ this.activationOrigin = activationOrigin; ++ } ++ ++ public void propagate() { ++ retractObject( this.factHandle, ++ this.removeLogical, ++ this.updateEqualsMap, ++ this.ruleOrigin, ++ this.activationOrigin ); ++ } ++ } ++ + protected static class FactStatus { + private int counter; + private String status; +diff --git a/drools-core/src/main/java/org/drools/leaps/FactTable.java b/drools-core/src/main/java/org/drools/leaps/FactTable.java +index 9da995d6a05..f57f08a5922 100644 +--- a/drools-core/src/main/java/org/drools/leaps/FactTable.java ++++ b/drools-core/src/main/java/org/drools/leaps/FactTable.java +@@ -46,7 +46,7 @@ class FactTable extends Table { + * Tuples that are either already on agenda or are very close (missing + * exists or have not facts matching) + */ +- private final LinkedList tuples; ++ private LinkedList tuples; + + /** + * initializes base LeapsTable with appropriate Comparator and positive and +@@ -67,9 +67,8 @@ public FactTable(ConflictResolver conflictResolver) { + * @param workingMemory + * @param ruleHandle + */ +- public void addRule(WorkingMemoryImpl workingMemory, +- RuleHandle ruleHandle) { +- if ( !this.rules.contains( ruleHandle ) ) { ++ public void addRule( WorkingMemoryImpl workingMemory, RuleHandle ruleHandle ) { ++ if (!this.rules.contains( ruleHandle )) { + this.rules.add( ruleHandle ); + // push facts back to stack if needed + this.checkAndAddFactsToStack( workingMemory ); +@@ -81,8 +80,18 @@ public void addRule(WorkingMemoryImpl workingMemory, + * + * @param ruleHandle + */ +- public void removeRule(RuleHandle ruleHandle) { ++ public void removeRule( RuleHandle ruleHandle ) { + this.rules.remove( ruleHandle ); ++ // remove tuples that are still there ++ LinkedList list = new LinkedList( ); ++ ++ for (Iterator it = this.getTuplesIterator( ); it.hasNext( );) { ++ LeapsTuple tuple = (LeapsTuple) it.next( ); ++ if (ruleHandle.getLeapsRule( ).getRule( ) != tuple.getLeapsRule( ).getRule( )) { ++ list.add( tuple ); ++ } ++ } ++ this.tuples = list; + } + + /** +diff --git a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java +index f0e796876df..8a12a47303d 100644 +--- a/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java ++++ b/drools-core/src/main/java/org/drools/leaps/WorkingMemoryImpl.java +@@ -74,6 +74,8 @@ class WorkingMemoryImpl extends AbstractWorkingMemory + + private final IdentityMap leapsRulesToHandlesMap = new IdentityMap( ); + ++ private final IdentityMap rulesActivationsMap = new IdentityMap( ); ++ + /** + * Construct. + * +@@ -214,11 +216,11 @@ public FactHandle assertObject( Object object, + boolean logical, + Rule rule, + Activation activation ) throws FactException { +- ++ FactHandleImpl handle ; + this.getLock().lock( ); + try { + // check if the object already exists in the WM +- FactHandleImpl handle = (FactHandleImpl) this.identityMap.get( object ); ++ handle = (FactHandleImpl) this.identityMap.get( object ); + + // lets see if the object is already logical asserted + FactStatus logicalState = (FactStatus) this.equalsMap.get( object ); +@@ -237,6 +239,7 @@ public FactHandle assertObject( Object object, + activation, + activation.getPropagationContext( ), + rule ); ++ + return logicalState.getHandle( ); + } + +@@ -294,7 +297,6 @@ public FactHandle assertObject( Object object, + activation, + activation.getPropagationContext( ), + rule ); +- + } + + // new leaps stack token +@@ -380,12 +382,13 @@ public FactHandle assertObject( Object object, + } + } + } +- +- return handle; ++ propagateQueuedActions( ); + } + finally { +- this.getLock().unlock( ); ++ this.getLock( ).unlock( ); + } ++ ++ return handle; + } + + /** +@@ -555,6 +558,8 @@ public void retractObject(FactHandle handle, + activation ); + + this.workingMemoryEventSupport.fireObjectRetracted( context, handle, oldObject ); ++ ++ propagateQueuedActions(); + } + finally { + this.getLock().unlock( ); +@@ -586,14 +591,37 @@ private final void invalidateActivation( LeapsTuple tuple ) { + } + } + ++ ++ ++ public void addLogicalDependency( FactHandle handle, ++ Activation activation, ++ PropagationContext context, ++ Rule rule ) throws FactException { ++ super.addLogicalDependency( handle, activation, context, rule ); ++ ++ LinkedList activations = (LinkedList) this.rulesActivationsMap.get( rule ); ++ if (activations == null) { ++ activations = new LinkedList( ); ++ this.rulesActivationsMap.put( rule, activations ); ++ } ++ activations.add( activation ); ++ } ++ ++ ++ public void removeLogicalDependencies( Activation activation, ++ PropagationContext context, ++ Rule rule ) throws FactException { ++ super.removeLogicalDependencies( activation, context, rule ); ++ } ++ + /** + * @see WorkingMemory + */ +- public void modifyObject(FactHandle handle, ++ public void modifyObject( FactHandle handle, + Object object, + Rule rule, + Activation activation ) throws FactException { +- this.getLock().lock( ); ++ this.getLock( ).lock( ); + try { + + this.retractObject( handle ); +@@ -624,9 +652,10 @@ public void modifyObject(FactHandle handle, + handle, + ( (FactHandleImpl) handle ).getObject( ), + object ); ++ propagateQueuedActions( ); + } + finally { +- this.getLock().unlock( ); ++ this.getLock( ).unlock( ); + } + } + +@@ -778,22 +807,36 @@ protected void removeRule( List rules ) { + this.getLock( ).lock( ); + try { + ArrayList ruleHandlesList; +- LeapsRule rule; ++ LeapsRule leapsRule; + RuleHandle ruleHandle; + for (Iterator it = rules.iterator( ); it.hasNext( );) { +- rule = (LeapsRule) it.next( ); ++ leapsRule = (LeapsRule) it.next( ); + // some times rules do not have ""normal"" constraints and only + // not and exists +- if (rule.getNumberOfColumns( ) > 0) { +- ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap.remove( rule ); ++ if (leapsRule.getNumberOfColumns( ) > 0) { ++ ruleHandlesList = (ArrayList) this.leapsRulesToHandlesMap.remove( leapsRule ); + for (int i = 0; i < ruleHandlesList.size( ); i++) { + ruleHandle = (RuleHandle) ruleHandlesList.get( i ); + // +- this.getFactTable( rule.getColumnClassObjectTypeAtPosition( i ) ) ++ this.getFactTable( leapsRule.getColumnClassObjectTypeAtPosition( i ) ) + .removeRule( ruleHandle ); + } + } ++ // ++ } ++ Rule rule = ((LeapsRule)rules.get(0)).getRule( ); ++ List activations = (List) this.rulesActivationsMap.remove( rule ); ++ if (activations != null) { ++ for (Iterator activationsIt = activations.iterator( ); activationsIt.hasNext( );) { ++ Activation activation = (Activation) activationsIt.next( ); ++ ((LeapsTuple)activation.getTuple()).setActivation(null); ++ this.removeLogicalDependencies( activation, ++ activation.getPropagationContext( ), ++ rule ); ++ } + } ++ ++ propagateQueuedActions(); + } + finally { + this.getLock( ).unlock( );" +17db0f11e85bb21def0af785e654db15120d874b,Delta Spike,"DELTASPIKE-339 don't lot the Exception as this is a normal operating situation +",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java +index 85fa77b79..9301da536 100644 +--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/util/JndiUtils.java +@@ -190,7 +190,7 @@ public static Map list(String name, Class type) + } + catch (NamingException e) + { +- LOG.log(Level.SEVERE, ""InitialContext#list failed!"", e); ++ // this is expected if there is no entry in JNDI for the requested name or type + } + return result; + }" +d2a76d6b71ad0a40daa420d1b4ca447f8fb3b0de,tapiji,"adds ui core +",a,https://github.com/tapiji/tapiji,"diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java +new file mode 100644 +index 00000000..59f26760 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/Activator.java +@@ -0,0 +1,50 @@ ++package org.eclipselabs.tapiji.tools.core.ui; ++ ++import org.eclipse.ui.plugin.AbstractUIPlugin; ++import org.osgi.framework.BundleContext; ++ ++/** ++ * The activator class controls the plug-in life cycle ++ */ ++public class Activator extends AbstractUIPlugin { ++ ++ // The plug-in ID ++ public static final String PLUGIN_ID = ""org.eclipselabs.tapiji.tools.core.ui""; //$NON-NLS-1$ ++ ++ // The shared instance ++ private static Activator plugin; ++ ++ /** ++ * The constructor ++ */ ++ public Activator() { ++ } ++ ++ /* ++ * (non-Javadoc) ++ * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) ++ */ ++ public void start(BundleContext context) throws Exception { ++ super.start(context); ++ plugin = this; ++ } ++ ++ /* ++ * (non-Javadoc) ++ * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) ++ */ ++ public void stop(BundleContext context) throws Exception { ++ plugin = null; ++ super.stop(context); ++ } ++ ++ /** ++ * Returns the shared instance ++ * ++ * @return the shared instance ++ */ ++ public static Activator getDefault() { ++ return plugin; ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java +new file mode 100644 +index 00000000..e0b12ca0 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/decorators/ExcludedResource.java +@@ -0,0 +1,105 @@ ++package org.eclipselabs.tapiji.tools.core.ui.decorators; ++ ++import java.util.ArrayList; ++import java.util.List; ++ ++import org.eclipse.core.resources.IFile; ++import org.eclipse.core.resources.IFolder; ++import org.eclipse.core.resources.IResource; ++import org.eclipse.jface.viewers.DecorationOverlayIcon; ++import org.eclipse.jface.viewers.IDecoration; ++import org.eclipse.jface.viewers.ILabelDecorator; ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.LabelProviderChangedEvent; ++import org.eclipse.swt.graphics.Image; ++import org.eclipselabs.tapiji.tools.core.Activator; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature; ++import org.eclipselabs.tapiji.tools.core.model.IResourceExclusionListener; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceExclusionEvent; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++ ++ ++public class ExcludedResource implements ILabelDecorator, ++ IResourceExclusionListener { ++ ++ private static final String ENTRY_SUFFIX = ""[no i18n]""; ++ private static final Image OVERLAY_IMAGE_ON = ++ ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_ON); ++ private static final Image OVERLAY_IMAGE_OFF = ++ ImageUtils.getImage(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF); ++ private final List label_provider_listener = ++ new ArrayList (); ++ ++ public boolean decorate(Object element) { ++ boolean needsDecoration = false; ++ if (element instanceof IFolder || ++ element instanceof IFile) { ++ IResource resource = (IResource) element; ++ if (!InternationalizationNature.hasNature(resource.getProject())) ++ return false; ++ try { ++ ResourceBundleManager manager = ResourceBundleManager.getManager(resource.getProject()); ++ if (!manager.isResourceExclusionListenerRegistered(this)) ++ manager.registerResourceExclusionListener(this); ++ if (ResourceBundleManager.isResourceExcluded(resource)) { ++ needsDecoration = true; ++ } ++ } catch (Exception e) { ++ Logger.logError(e); ++ } ++ } ++ return needsDecoration; ++ } ++ ++ @Override ++ public void addListener(ILabelProviderListener listener) { ++ label_provider_listener.add(listener); ++ } ++ ++ @Override ++ public void dispose() { ++ ResourceBundleManager.unregisterResourceExclusionListenerFromAllManagers (this); ++ } ++ ++ @Override ++ public boolean isLabelProperty(Object element, String property) { ++ return false; ++ } ++ ++ @Override ++ public void removeListener(ILabelProviderListener listener) { ++ label_provider_listener.remove(listener); ++ } ++ ++ @Override ++ public void exclusionChanged(ResourceExclusionEvent event) { ++ LabelProviderChangedEvent labelEvent = new LabelProviderChangedEvent(this, event.getChangedResources().toArray()); ++ for (ILabelProviderListener l : label_provider_listener) ++ l.labelProviderChanged(labelEvent); ++ } ++ ++ @Override ++ public Image decorateImage(Image image, Object element) { ++ if (decorate(element)) { ++ DecorationOverlayIcon overlayIcon = new DecorationOverlayIcon(image, ++ Activator.getImageDescriptor(ImageUtils.IMAGE_EXCLUDED_RESOURCE_OFF), ++ IDecoration.TOP_RIGHT); ++ return overlayIcon.createImage(); ++ } else { ++ return image; ++ } ++ } ++ ++ @Override ++ public String decorateText(String text, Object element) { ++ if (decorate(element)) { ++ return text + "" "" + ENTRY_SUFFIX; ++ } else ++ return text; ++ } ++ ++ ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java +new file mode 100644 +index 00000000..1ff6136d +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/AddLanguageDialoge.java +@@ -0,0 +1,153 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.Collections; ++import java.util.HashSet; ++import java.util.LinkedList; ++import java.util.List; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.jface.dialogs.Dialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.graphics.Font; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.util.LocaleUtils; ++ ++ ++public class AddLanguageDialoge extends Dialog{ ++ private Locale locale; ++ private Shell shell; ++ ++ private Text titelText; ++ private Text descriptionText; ++ private Combo cmbLanguage; ++ private Text language; ++ private Text country; ++ private Text variant; ++ ++ ++ ++ ++ public AddLanguageDialoge(Shell parentShell){ ++ super(parentShell); ++ shell = parentShell; ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite titelArea = new Composite(parent, SWT.NO_BACKGROUND); ++ Composite dialogArea = (Composite) super.createDialogArea(parent); ++ GridLayout layout = new GridLayout(1,true); ++ dialogArea.setLayout(layout); ++ ++ initDescription(titelArea); ++ initCombo(dialogArea); ++ initTextArea(dialogArea); ++ ++ titelArea.pack(); ++ dialogArea.pack(); ++ parent.pack(); ++ ++ return dialogArea; ++ } ++ ++ private void initDescription(Composite titelArea) { ++ titelArea.setEnabled(false); ++ titelArea.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, true, true, 1, 1)); ++ titelArea.setLayout(new GridLayout(1, true)); ++ titelArea.setBackground(new Color(shell.getDisplay(), 255, 255, 255)); ++ ++ titelText = new Text(titelArea, SWT.LEFT); ++ titelText.setFont(new Font(shell.getDisplay(),shell.getFont().getFontData()[0].getName(), 11, SWT.BOLD)); ++ titelText.setText(""Please, specify the desired language""); ++ ++ descriptionText = new Text(titelArea, SWT.WRAP); ++ descriptionText.setLayoutData(new GridData(450, 60)); //TODO improve ++ descriptionText.setText(""Note: "" + ++ ""In all ResourceBundles of the project/plug-in will be created a new properties-file with the basename of the ResourceBundle and the corresponding locale-extension. ""+ ++ ""If the locale is just provided of a ResourceBundle, no new file will be created.""); ++ } ++ ++ private void initCombo(Composite dialogArea) { ++ cmbLanguage = new Combo(dialogArea, SWT.DROP_DOWN); ++ cmbLanguage.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1)); ++ ++ final Locale[] locales = Locale.getAvailableLocales(); ++ final Set localeSet = new HashSet(); ++ List localeNames = new LinkedList(); ++ ++ for (Locale l : locales){ ++ localeNames.add(l.getDisplayName()); ++ localeSet.add(l); ++ } ++ ++ Collections.sort(localeNames); ++ ++ String[] s= new String[localeNames.size()]; ++ cmbLanguage.setItems(localeNames.toArray(s)); ++ cmbLanguage.add(ResourceBundleManager.defaultLocaleTag, 0); ++ ++ cmbLanguage.addSelectionListener(new SelectionListener() { ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ int selectIndex = ((Combo)e.getSource()).getSelectionIndex(); ++ if (!cmbLanguage.getItem(selectIndex).equals(ResourceBundleManager.defaultLocaleTag)){ ++ Locale l = LocaleUtils.getLocaleByDisplayName(localeSet, cmbLanguage.getItem(selectIndex)); ++ ++ language.setText(l.getLanguage()); ++ country.setText(l.getCountry()); ++ variant.setText(l.getVariant()); ++ }else { ++ language.setText(""""); ++ country.setText(""""); ++ variant.setText(""""); ++ } ++ } ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ // TODO Auto-generated method stub ++ } ++ }); ++ } ++ ++ private void initTextArea(Composite dialogArea) { ++ final Group group = new Group (dialogArea, SWT.SHADOW_ETCHED_IN); ++ group.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true, 1, 1)); ++ group.setLayout(new GridLayout(3, true)); ++ group.setText(""Locale""); ++ ++ Label languageLabel = new Label(group, SWT.SINGLE); ++ languageLabel.setText(""Language""); ++ Label countryLabel = new Label(group, SWT.SINGLE); ++ countryLabel.setText(""Country""); ++ Label variantLabel = new Label(group, SWT.SINGLE); ++ variantLabel.setText(""Variant""); ++ ++ language = new Text(group, SWT.SINGLE); ++ country = new Text(group, SWT.SINGLE); ++ variant = new Text(group, SWT.SINGLE); ++ } ++ ++ @Override ++ protected void okPressed() { ++ locale = new Locale(language.getText(), country.getText(), variant.getText()); ++ ++ super.okPressed(); ++ } ++ ++ public Locale getSelectedLanguage() { ++ return locale; ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java +new file mode 100644 +index 00000000..499fff0d +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreatePatternDialoge.java +@@ -0,0 +1,60 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import org.eclipse.jface.dialogs.Dialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++ ++public class CreatePatternDialoge extends Dialog{ ++ private String pattern; ++ private Text patternText; ++ ++ ++ public CreatePatternDialoge(Shell shell) { ++ this(shell,""""); ++ } ++ ++ public CreatePatternDialoge(Shell shell, String pattern) { ++ super(shell); ++ this.pattern = pattern; ++// setShellStyle(SWT.RESIZE); ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite composite = new Composite(parent, SWT.NONE); ++ composite.setLayout(new GridLayout(1, true)); ++ composite.setLayoutData(new GridData(SWT.FILL,SWT.TOP, false, false)); ++ ++ Label descriptionLabel = new Label(composite, SWT.NONE); ++ descriptionLabel.setText(""Enter a regular expression:""); ++ ++ patternText = new Text(composite, SWT.WRAP | SWT.MULTI); ++ GridData gData = new GridData(SWT.FILL, SWT.FILL, true, false); ++ gData.widthHint = 400; ++ gData.heightHint = 60; ++ patternText.setLayoutData(gData); ++ patternText.setText(pattern); ++ ++ ++ ++ return composite; ++ } ++ ++ @Override ++ protected void okPressed() { ++ pattern = patternText.getText(); ++ ++ super.okPressed(); ++ } ++ ++ public String getPattern(){ ++ return pattern; ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java +new file mode 100644 +index 00000000..f2cd09da +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/CreateResourceBundleEntryDialog.java +@@ -0,0 +1,377 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.Collection; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.jface.dialogs.TitleAreaDialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; ++import org.eclipse.swt.events.SelectionAdapter; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.util.LocaleUtils; ++import org.eclipselabs.tapiji.tools.core.util.ResourceUtils; ++ ++ ++public class CreateResourceBundleEntryDialog extends TitleAreaDialog { ++ ++ private static int WIDTH_LEFT_COLUMN = 100; ++ ++ private ResourceBundleManager manager; ++ private Collection availableBundles; ++ ++ private Text txtKey; ++ private Combo cmbRB; ++ private Text txtDefaultText; ++ private Combo cmbLanguage; ++ ++ private Button okButton; ++ private Button cancelButton; ++ ++ /*** Dialog Model ***/ ++ String selectedRB = """"; ++ String selectedLocale = """"; ++ String selectedKey = """"; ++ String selectedDefaultText = """"; ++ ++ /*** MODIFY LISTENER ***/ ++ ModifyListener rbModifyListener; ++ ++ public CreateResourceBundleEntryDialog(Shell parentShell, ++ ResourceBundleManager manager, ++ String preselectedKey, ++ String preselectedMessage, ++ String preselectedBundle, ++ String preselectedLocale) { ++ super(parentShell); ++ this.manager = manager; ++ this.availableBundles = manager.getResourceBundleNames(); ++ this.selectedKey = preselectedKey != null ? preselectedKey.trim() : preselectedKey; ++ this.selectedDefaultText = preselectedMessage; ++ this.selectedRB = preselectedBundle; ++ this.selectedLocale = preselectedLocale; ++ } ++ ++ public String getSelectedResourceBundle () { ++ return selectedRB; ++ } ++ ++ public String getSelectedKey () { ++ return selectedKey; ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite dialogArea = (Composite) super.createDialogArea(parent); ++ initLayout (dialogArea); ++ constructRBSection (dialogArea); ++ constructDefaultSection (dialogArea); ++ initContent (); ++ return dialogArea; ++ } ++ ++ protected void initContent() { ++ cmbRB.removeAll(); ++ int iSel = -1; ++ int index = 0; ++ ++ for (String bundle : availableBundles) { ++ cmbRB.add(bundle); ++ if (bundle.equals(selectedRB)) { ++ cmbRB.select(index); ++ iSel = index; ++ cmbRB.setEnabled(false); ++ } ++ index ++; ++ } ++ ++ if (availableBundles.size() > 0 && iSel < 0) { ++ cmbRB.select(0); ++ selectedRB = cmbRB.getText(); ++ cmbRB.setEnabled(true); ++ } ++ ++ rbModifyListener = new ModifyListener() { ++ ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedRB = cmbRB.getText(); ++ validate(); ++ } ++ }; ++ cmbRB.removeModifyListener(rbModifyListener); ++ cmbRB.addModifyListener(rbModifyListener); ++ ++ ++ cmbRB.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ selectedLocale = """"; ++ updateAvailableLanguages(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ ++ selectedLocale = """"; ++ updateAvailableLanguages(); ++ } ++ }); ++ updateAvailableLanguages(); ++ } ++ ++ protected void updateAvailableLanguages () { ++ cmbLanguage.removeAll(); ++ String selectedBundle = cmbRB.getText(); ++ ++ if (selectedBundle.trim().equals("""")) ++ return; ++ ++ // Retrieve available locales for the selected resource-bundle ++ Set locales = manager.getProvidedLocales(selectedBundle); ++ int index = 0; ++ int iSel = -1; ++ for (Locale l : manager.getProvidedLocales(selectedBundle)) { ++ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(); ++ if (displayName.equals(selectedLocale)) ++ iSel = index; ++ if (displayName.equals("""")) ++ displayName = ResourceBundleManager.defaultLocaleTag; ++ cmbLanguage.add(displayName); ++ if (index == iSel) ++ cmbLanguage.select(iSel); ++ index++; ++ } ++ ++ if (locales.size() > 0) { ++ cmbLanguage.select(0); ++ selectedLocale = cmbLanguage.getText(); ++ } ++ ++ cmbLanguage.addModifyListener(new ModifyListener() { ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedLocale = cmbLanguage.getText(); ++ validate(); ++ } ++ }); ++ } ++ ++ protected void initLayout(Composite parent) { ++ final GridLayout layout = new GridLayout(1, true); ++ parent.setLayout(layout); ++ } ++ ++ protected void constructRBSection(Composite parent) { ++ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ group.setText(""Resource Bundle""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ infoLabel.setText(""Specify the key of the new resource as well as the Resource-Bundle in\n"" + ++ ""which the resource"" + ++ ""should be added.\n""); ++ ++ // Schl�ssel ++ final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; ++ lblKey.setLayoutData(lblKeyGrid); ++ lblKey.setText(""Key:""); ++ ++ txtKey = new Text (group, SWT.BORDER); ++ txtKey.setText(selectedKey); ++ txtKey.setEditable(selectedKey.trim().length() == 0 || selectedKey.indexOf(""[Platzhalter]"")>=0); ++ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ txtKey.addModifyListener(new ModifyListener() { ++ ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedKey = txtKey.getText(); ++ validate(); ++ } ++ }); ++ ++ // Resource-Bundle ++ final Label lblRB = new Label (group, SWT.NONE); ++ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblRB.setText(""Resource-Bundle:""); ++ ++ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ } ++ ++ protected void constructDefaultSection(Composite parent) { ++ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1)); ++ group.setText(""Default-Text""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ infoLabel.setText(""Define a default text for the specified resource. Moreover, you need to\n"" + ++ ""select the locale for which the default text should be defined.""); ++ ++ // Text ++ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblTextGrid.heightHint = 80; ++ lblTextGrid.widthHint = 100; ++ lblText.setLayoutData(lblTextGrid); ++ lblText.setText(""Text:""); ++ ++ txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER); ++ txtDefaultText.setText(selectedDefaultText); ++ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1)); ++ txtDefaultText.addModifyListener(new ModifyListener() { ++ ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedDefaultText = txtDefaultText.getText(); ++ validate(); ++ } ++ }); ++ ++ // Sprache ++ final Label lblLanguage = new Label (group, SWT.NONE); ++ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblLanguage.setText(""Language (Country):""); ++ ++ cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ } ++ ++ @Override ++ protected void okPressed() { ++ super.okPressed(); ++ // TODO debug ++ ++ // Insert new Resource-Bundle reference ++ Locale locale = LocaleUtils.getLocaleByDisplayName( manager.getProvidedLocales(selectedRB), selectedLocale); // new Locale(""""); // retrieve locale ++ ++ try { ++ manager.addResourceBundleEntry (selectedRB, selectedKey, locale, selectedDefaultText); ++ } catch (ResourceBundleException e) { ++ Logger.logError(e); ++ } ++ } ++ ++ @Override ++ protected void configureShell(Shell newShell) { ++ super.configureShell(newShell); ++ newShell.setText(""Create Resource-Bundle entry""); ++ } ++ ++ @Override ++ public void create() { ++ // TODO Auto-generated method stub ++ super.create(); ++ this.setTitle(""New Resource-Bundle entry""); ++ this.setMessage(""Please, specify details about the new Resource-Bundle entry""); ++ } ++ ++ protected void validate () { ++ // Check Resource-Bundle ids ++ boolean keyValid = false; ++ boolean keyValidChar = ResourceUtils.isValidResourceKey(selectedKey); ++ boolean rbValid = false; ++ boolean textValid = false; ++ boolean localeValid = LocaleUtils.containsLocaleByDisplayName(manager.getProvidedLocales(selectedRB), selectedLocale); ++ ++ for (String rbId : this.availableBundles) { ++ if (rbId.equals(selectedRB)) { ++ rbValid = true; ++ break; ++ } ++ } ++ ++ if (!manager.isResourceExisting(selectedRB, selectedKey)) ++ keyValid = true; ++ ++ if (selectedDefaultText.trim().length() > 0) ++ textValid = true; ++ ++ // print Validation summary ++ String errorMessage = null; ++ if (selectedKey.trim().length() == 0) ++ errorMessage = ""No resource key specified.""; ++ else if (! keyValidChar) ++ errorMessage = ""The specified resource key contains invalid characters.""; ++ else if (! keyValid) ++ errorMessage = ""The specified resource key is already existing.""; ++ else if (! rbValid) ++ errorMessage = ""The specified Resource-Bundle does not exist.""; ++ else if (! localeValid) ++ errorMessage = ""The specified Locale does not exist for the selected Resource-Bundle.""; ++ else if (! textValid) ++ errorMessage = ""No default translation specified.""; ++ else { ++ if (okButton != null) ++ okButton.setEnabled(true); ++ } ++ ++ setErrorMessage(errorMessage); ++ if (okButton != null && errorMessage != null) ++ okButton.setEnabled(false); ++ } ++ ++ @Override ++ protected void createButtonsForButtonBar(Composite parent) { ++ okButton = createButton (parent, OK, ""Ok"", true); ++ okButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ // Set return code ++ setReturnCode(OK); ++ close(); ++ } ++ }); ++ ++ cancelButton = createButton (parent, CANCEL, ""Cancel"", false); ++ cancelButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ setReturnCode (CANCEL); ++ close(); ++ } ++ }); ++ ++ okButton.setEnabled(false); ++ cancelButton.setEnabled(true); ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java +new file mode 100644 +index 00000000..3540881a +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/FragmentProjectSelectionDialog.java +@@ -0,0 +1,117 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.ArrayList; ++import java.util.List; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.core.resources.IProject; ++import org.eclipse.jface.viewers.ILabelProvider; ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.IStructuredContentProvider; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.ui.ISharedImages; ++import org.eclipse.ui.PlatformUI; ++import org.eclipse.ui.dialogs.ListDialog; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++ ++ ++public class FragmentProjectSelectionDialog extends ListDialog{ ++ private IProject hostproject; ++ private List allProjects; ++ ++ ++ public FragmentProjectSelectionDialog(Shell parent, IProject hostproject, List fragmentprojects){ ++ super(parent); ++ this.hostproject = hostproject; ++ this.allProjects = new ArrayList(fragmentprojects); ++ allProjects.add(0,hostproject); ++ ++ init(); ++ } ++ ++ private void init() { ++ this.setAddCancelButton(true); ++ this.setMessage(""Select one of the following plug-ins:""); ++ this.setTitle(""Project Selector""); ++ this.setContentProvider(new IProjectContentProvider()); ++ this.setLabelProvider(new IProjectLabelProvider()); ++ ++ this.setInput(allProjects); ++ } ++ ++ public IProject getSelectedProject() { ++ Object[] selection = this.getResult(); ++ if (selection != null && selection.length > 0) ++ return (IProject) selection[0]; ++ return null; ++ } ++ ++ ++ //private classes-------------------------------------------------------- ++ class IProjectContentProvider implements IStructuredContentProvider { ++ ++ @Override ++ public Object[] getElements(Object inputElement) { ++ List resources = (List) inputElement; ++ return resources.toArray(); ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ++ // TODO Auto-generated method stub ++ } ++ ++ } ++ ++ class IProjectLabelProvider implements ILabelProvider { ++ ++ @Override ++ public Image getImage(Object element) { ++ return PlatformUI.getWorkbench().getSharedImages().getImage( ++ ISharedImages.IMG_OBJ_PROJECT); ++ } ++ ++ @Override ++ public String getText(Object element) { ++ IProject p = ((IProject) element); ++ String text = p.getName(); ++ if (p.equals(hostproject)) text += "" [host project]""; ++ else text += "" [fragment project]""; ++ return text; ++ } ++ ++ @Override ++ public void addListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public boolean isLabelProperty(Object element, String property) { ++ // TODO Auto-generated method stub ++ return false; ++ } ++ ++ @Override ++ public void removeListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java +new file mode 100644 +index 00000000..389121ba +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/GenerateBundleAccessorDialog.java +@@ -0,0 +1,131 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import org.eclipse.jface.dialogs.TitleAreaDialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++ ++public class GenerateBundleAccessorDialog extends TitleAreaDialog { ++ ++ private static int WIDTH_LEFT_COLUMN = 100; ++ ++ private Text bundleAccessor; ++ private Text packageName; ++ ++ public GenerateBundleAccessorDialog(Shell parentShell) { ++ super(parentShell); ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite dialogArea = (Composite) super.createDialogArea(parent); ++ initLayout (dialogArea); ++ constructBASection (dialogArea); ++ //constructDefaultSection (dialogArea); ++ initContent (); ++ return dialogArea; ++ } ++ ++ protected void initLayout(Composite parent) { ++ final GridLayout layout = new GridLayout(1, true); ++ parent.setLayout(layout); ++ } ++ ++ protected void constructBASection(Composite parent) { ++ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ group.setText(""Resource Bundle""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ infoLabel.setText(""Diese Zeile stellt einen Platzhalter für einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter für einen kurzen Infotext dar.""); ++ ++ // Schlüssel ++ final Label lblBA = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblBAGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblBAGrid.widthHint = WIDTH_LEFT_COLUMN; ++ lblBA.setLayoutData(lblBAGrid); ++ lblBA.setText(""Class-Name:""); ++ ++ bundleAccessor = new Text (group, SWT.BORDER); ++ bundleAccessor.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ ++ // Resource-Bundle ++ final Label lblPkg = new Label (group, SWT.NONE); ++ lblPkg.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblPkg.setText(""Package:""); ++ ++ packageName = new Text (group, SWT.BORDER); ++ packageName.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ } ++ ++ protected void initContent () { ++ bundleAccessor.setText(""BundleAccessor""); ++ packageName.setText(""a.b""); ++ } ++ ++ /* ++ protected void constructDefaultSection(Composite parent) { ++ final Group group = new Group (parent, SWT.SHADOW_ETCHED_IN); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, true, 1, 1)); ++ group.setText(""Basis-Text""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ infoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ infoLabel.setText(""Diese Zeile stellt einen Platzhalter für einen kurzen Infotext dar.\nDiese Zeile stellt einen Platzhalter für einen kurzen Infotext dar.""); ++ ++ // Text ++ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblTextGrid.heightHint = 80; ++ lblTextGrid.widthHint = 100; ++ lblText.setLayoutData(lblTextGrid); ++ lblText.setText(""Text:""); ++ ++ txtDefaultText = new Text (group, SWT.MULTI | SWT.BORDER); ++ txtDefaultText.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1)); ++ ++ // Sprache ++ final Label lblLanguage = new Label (group, SWT.NONE); ++ lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblLanguage.setText(""Sprache (Land):""); ++ ++ cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++ cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ } */ ++ ++ @Override ++ protected void configureShell(Shell newShell) { ++ super.configureShell(newShell); ++ newShell.setText(""Create Resource-Bundle Accessor""); ++ } ++ ++ ++} +\ No newline at end of file +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java +new file mode 100644 +index 00000000..304cf6e8 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/QueryResourceBundleEntryDialog.java +@@ -0,0 +1,425 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.Collection; ++import java.util.Iterator; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.jface.dialogs.TitleAreaDialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; ++import org.eclipse.swt.events.SelectionAdapter; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.ResourceSelector; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener; ++import org.eclipselabs.tapiji.tools.core.util.LocaleUtils; ++ ++ ++public class QueryResourceBundleEntryDialog extends TitleAreaDialog { ++ ++ private static int WIDTH_LEFT_COLUMN = 100; ++ private static int SEARCH_FULLTEXT = 0; ++ private static int SEARCH_KEY = 1; ++ ++ private ResourceBundleManager manager; ++ private Collection availableBundles; ++ private int searchOption = SEARCH_FULLTEXT; ++ private String resourceBundle = """"; ++ ++ private Combo cmbRB; ++ ++ private Text txtKey; ++ private Button btSearchText; ++ private Button btSearchKey; ++ private Combo cmbLanguage; ++ private ResourceSelector resourceSelector; ++ private Text txtPreviewText; ++ ++ private Button okButton; ++ private Button cancelButton; ++ ++ /*** DIALOG MODEL ***/ ++ private String selectedRB = """"; ++ private String preselectedRB = """"; ++ private Locale selectedLocale = null; ++ private String selectedKey = """"; ++ ++ ++ public QueryResourceBundleEntryDialog(Shell parentShell, ResourceBundleManager manager, String bundleName) { ++ super(parentShell); ++ this.manager = manager; ++ // init available resource bundles ++ this.availableBundles = manager.getResourceBundleNames(); ++ this.preselectedRB = bundleName; ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite dialogArea = (Composite) super.createDialogArea(parent); ++ initLayout (dialogArea); ++ constructSearchSection (dialogArea); ++ initContent (); ++ return dialogArea; ++ } ++ ++ protected void initContent() { ++ // init available resource bundles ++ cmbRB.removeAll(); ++ int i = 0; ++ for (String bundle : availableBundles) { ++ cmbRB.add(bundle); ++ if (bundle.equals(preselectedRB)) { ++ cmbRB.select(i); ++ cmbRB.setEnabled(false); ++ } ++ i++; ++ } ++ ++ if (availableBundles.size() > 0) { ++ if (preselectedRB.trim().length() == 0) { ++ cmbRB.select(0); ++ cmbRB.setEnabled(true); ++ } ++ } ++ ++ cmbRB.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ //updateAvailableLanguages(); ++ updateResourceSelector (); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ //updateAvailableLanguages(); ++ updateResourceSelector (); ++ } ++ }); ++ ++ // init available translations ++ //updateAvailableLanguages(); ++ ++ // init resource selector ++ updateResourceSelector(); ++ ++ // update search options ++ updateSearchOptions(); ++ } ++ ++ protected void updateResourceSelector () { ++ resourceBundle = cmbRB.getText(); ++ resourceSelector.setResourceBundle(resourceBundle); ++ } ++ ++ protected void updateSearchOptions () { ++ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT); ++// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); ++// lblLanguage.setEnabled(cmbLanguage.getEnabled()); ++ ++ // update ResourceSelector ++ resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS); ++ } ++ ++ protected void updateAvailableLanguages () { ++ cmbLanguage.removeAll(); ++ String selectedBundle = cmbRB.getText(); ++ ++ if (selectedBundle.trim().equals("""")) ++ return; ++ ++ // Retrieve available locales for the selected resource-bundle ++ Set locales = manager.getProvidedLocales(selectedBundle); ++ for (Locale l : locales) { ++ String displayName = l.getDisplayName(); ++ if (displayName.equals("""")) ++ displayName = ResourceBundleManager.defaultLocaleTag; ++ cmbLanguage.add(displayName); ++ } ++ ++// if (locales.size() > 0) { ++// cmbLanguage.select(0); ++ updateSelectedLocale(); ++// } ++ } ++ ++ protected void updateSelectedLocale () { ++ String selectedBundle = cmbRB.getText(); ++ ++ if (selectedBundle.trim().equals("""")) ++ return; ++ ++ Set locales = manager.getProvidedLocales(selectedBundle); ++ Iterator it = locales.iterator(); ++ String selectedLocale = cmbLanguage.getText(); ++ while (it.hasNext()) { ++ Locale l = it.next(); ++ if (l.getDisplayName().equals(selectedLocale)) { ++ resourceSelector.setDisplayLocale(l); ++ break; ++ } ++ } ++ } ++ ++ protected void initLayout(Composite parent) { ++ final GridLayout layout = new GridLayout(1, true); ++ parent.setLayout(layout); ++ } ++ ++ protected void constructSearchSection (Composite parent) { ++ final Group group = new Group (parent, SWT.NONE); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ group.setText(""Resource selection""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ // TODO export as help text ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1); ++ infoGrid.heightHint = 70; ++ infoLabel.setLayoutData(infoGrid); ++ infoLabel.setText(""Select the resource that needs to be refrenced. This is achieved in two\n"" + ++ ""steps. First select the Resource-Bundle in which the resource is located. \n"" + ++ ""In a last step you need to choose the required resource.""); ++ ++ // Resource-Bundle ++ final Label lblRB = new Label (group, SWT.NONE); ++ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblRB.setText(""Resource-Bundle:""); ++ ++ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ cmbRB.addModifyListener(new ModifyListener() { ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedRB = cmbRB.getText(); ++ validate(); ++ } ++ }); ++ ++ // Search-Options ++ final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ Composite searchOptions = new Composite(group, SWT.NONE); ++ searchOptions.setLayout(new GridLayout (2, true)); ++ ++ btSearchText = new Button (searchOptions, SWT.RADIO); ++ btSearchText.setText(""Full-text""); ++ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); ++ btSearchText.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ }); ++ ++ btSearchKey = new Button (searchOptions, SWT.RADIO); ++ btSearchKey.setText(""Key""); ++ btSearchKey.setSelection(searchOption == SEARCH_KEY); ++ btSearchKey.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ }); ++ ++ // Sprache ++// lblLanguage = new Label (group, SWT.NONE); ++// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++// lblLanguage.setText(""Language (Country):""); ++// ++// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++// cmbLanguage.addSelectionListener(new SelectionListener () { ++// ++// @Override ++// public void widgetDefaultSelected(SelectionEvent e) { ++// updateSelectedLocale(); ++// } ++// ++// @Override ++// public void widgetSelected(SelectionEvent e) { ++// updateSelectedLocale(); ++// } ++// ++// }); ++// cmbLanguage.addModifyListener(new ModifyListener() { ++// @Override ++// public void modifyText(ModifyEvent e) { ++// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText()); ++// validate(); ++// } ++// }); ++ ++ // Filter ++ final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; ++ lblKey.setLayoutData(lblKeyGrid); ++ lblKey.setText(""Filter:""); ++ ++ txtKey = new Text (group, SWT.BORDER); ++ txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ ++ // Add selector for property keys ++ final Label lblKeys = new Label (group, SWT.NONE); ++ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1)); ++ lblKeys.setText(""Resource:""); ++ ++ resourceSelector = new ResourceSelector (group, SWT.NONE, manager, cmbRB.getText(), searchOption, null, true); ++ GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1); ++ resourceSelectionData.heightHint = 150; ++ resourceSelectionData.widthHint = 400; ++ resourceSelector.setLayoutData(resourceSelectionData); ++ resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() { ++ ++ @Override ++ public void selectionChanged(ResourceSelectionEvent e) { ++ selectedKey = e.getSelectedKey(); ++ updatePreviewLabel(e.getSelectionSummary()); ++ validate(); ++ } ++ }); ++ ++// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL); ++// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1)); ++ ++ // Preview ++ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblTextGrid.heightHint = 120; ++ lblTextGrid.widthHint = 100; ++ lblText.setLayoutData(lblTextGrid); ++ lblText.setText(""Preview:""); ++ ++ txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); ++ txtPreviewText.setEditable(false); ++ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1); ++ txtPreviewText.setLayoutData(lblTextGrid2); ++ } ++ ++ @Override ++ protected void configureShell(Shell newShell) { ++ super.configureShell(newShell); ++ newShell.setText(""Insert Resource-Bundle-Reference""); ++ } ++ ++ @Override ++ public void create() { ++ // TODO Auto-generated method stub ++ super.create(); ++ this.setTitle(""Reference a Resource""); ++ this.setMessage(""Please, specify details about the required Resource-Bundle reference""); ++ } ++ ++ protected void updatePreviewLabel (String previewText) { ++ txtPreviewText.setText(previewText); ++ } ++ ++ protected void validate () { ++ // Check Resource-Bundle ids ++ boolean rbValid = false; ++ boolean localeValid = false; ++ boolean keyValid = false; ++ ++ for (String rbId : this.availableBundles) { ++ if (rbId.equals(selectedRB)) { ++ rbValid = true; ++ break; ++ } ++ } ++ ++ if (selectedLocale != null) ++ localeValid = true; ++ ++ if (manager.isResourceExisting(selectedRB, selectedKey)) ++ keyValid = true; ++ ++ // print Validation summary ++ String errorMessage = null; ++ if (! rbValid) ++ errorMessage = ""The specified Resource-Bundle does not exist""; ++// else if (! localeValid) ++// errorMessage = ""The specified Locale does not exist for the selecte Resource-Bundle""; ++ else if (! keyValid) ++ errorMessage = ""No resource selected""; ++ else { ++ if (okButton != null) ++ okButton.setEnabled(true); ++ } ++ ++ setErrorMessage(errorMessage); ++ if (okButton != null && errorMessage != null) ++ okButton.setEnabled(false); ++ } ++ ++ @Override ++ protected void createButtonsForButtonBar(Composite parent) { ++ okButton = createButton (parent, OK, ""Ok"", true); ++ okButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ // Set return code ++ setReturnCode(OK); ++ close(); ++ } ++ }); ++ ++ cancelButton = createButton (parent, CANCEL, ""Cancel"", false); ++ cancelButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ setReturnCode (CANCEL); ++ close(); ++ } ++ }); ++ ++ okButton.setEnabled(false); ++ cancelButton.setEnabled(true); ++ } ++ ++ public String getSelectedResourceBundle () { ++ return selectedRB; ++ } ++ ++ public String getSelectedResource () { ++ return selectedKey; ++ } ++ ++ public Locale getSelectedLocale () { ++ return selectedLocale; ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java +new file mode 100644 +index 00000000..8046819c +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/RemoveLanguageDialoge.java +@@ -0,0 +1,112 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.List; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.core.resources.IProject; ++import org.eclipse.jface.viewers.ILabelProvider; ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.IStructuredContentProvider; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.ui.dialogs.ListDialog; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++ ++ ++public class RemoveLanguageDialoge extends ListDialog{ ++ private IProject project; ++ ++ ++ public RemoveLanguageDialoge(IProject project, Shell shell) { ++ super(shell); ++ this.project=project; ++ ++ initDialog(); ++ } ++ ++ protected void initDialog () { ++ this.setAddCancelButton(true); ++ this.setMessage(""Select one of the following languages to delete:""); ++ this.setTitle(""Language Selector""); ++ this.setContentProvider(new RBContentProvider()); ++ this.setLabelProvider(new RBLabelProvider()); ++ ++ this.setInput(ResourceBundleManager.getManager(project).getProjectProvidedLocales()); ++ } ++ ++ public Locale getSelectedLanguage() { ++ Object[] selection = this.getResult(); ++ if (selection != null && selection.length > 0) ++ return (Locale) selection[0]; ++ return null; ++ } ++ ++ ++ //private classes------------------------------------------------------------------------------------- ++ class RBContentProvider implements IStructuredContentProvider { ++ ++ @Override ++ public Object[] getElements(Object inputElement) { ++ Set resources = (Set) inputElement; ++ return resources.toArray(); ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ } ++ ++ class RBLabelProvider implements ILabelProvider { ++ ++ @Override ++ public Image getImage(Object element) { ++ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); ++ } ++ ++ @Override ++ public String getText(Object element) { ++ Locale l = ((Locale) element); ++ String text = l.getDisplayName(); ++ if (text==null || text.equals("""")) text=""default""; ++ else text += "" - ""+l.getLanguage()+"" ""+l.getCountry()+"" ""+l.getVariant(); ++ return text; ++ } ++ ++ @Override ++ public void addListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public boolean isLabelProperty(Object element, String property) { ++ // TODO Auto-generated method stub ++ return false; ++ } ++ ++ @Override ++ public void removeListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java +new file mode 100644 +index 00000000..99ef6c33 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleEntrySelectionDialog.java +@@ -0,0 +1,423 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.Collection; ++import java.util.Iterator; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.jface.dialogs.TitleAreaDialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; ++import org.eclipse.swt.events.SelectionAdapter; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.swt.widgets.Text; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.ResourceSelector; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener; ++ ++ ++public class ResourceBundleEntrySelectionDialog extends TitleAreaDialog { ++ ++ private static int WIDTH_LEFT_COLUMN = 100; ++ private static int SEARCH_FULLTEXT = 0; ++ private static int SEARCH_KEY = 1; ++ ++ private ResourceBundleManager manager; ++ private Collection availableBundles; ++ private int searchOption = SEARCH_FULLTEXT; ++ private String resourceBundle = """"; ++ ++ private Combo cmbRB; ++ ++ private Button btSearchText; ++ private Button btSearchKey; ++ private Combo cmbLanguage; ++ private ResourceSelector resourceSelector; ++ private Text txtPreviewText; ++ ++ private Button okButton; ++ private Button cancelButton; ++ ++ /*** DIALOG MODEL ***/ ++ private String selectedRB = """"; ++ private String preselectedRB = """"; ++ private Locale selectedLocale = null; ++ private String selectedKey = """"; ++ ++ ++ public ResourceBundleEntrySelectionDialog(Shell parentShell, ResourceBundleManager manager, String bundleName) { ++ super(parentShell); ++ this.manager = manager; ++ // init available resource bundles ++ this.availableBundles = manager.getResourceBundleNames(); ++ this.preselectedRB = bundleName; ++ } ++ ++ @Override ++ protected Control createDialogArea(Composite parent) { ++ Composite dialogArea = (Composite) super.createDialogArea(parent); ++ initLayout (dialogArea); ++ constructSearchSection (dialogArea); ++ initContent (); ++ return dialogArea; ++ } ++ ++ protected void initContent() { ++ // init available resource bundles ++ cmbRB.removeAll(); ++ int i = 0; ++ for (String bundle : availableBundles) { ++ cmbRB.add(bundle); ++ if (bundle.equals(preselectedRB)) { ++ cmbRB.select(i); ++ cmbRB.setEnabled(false); ++ } ++ i++; ++ } ++ ++ if (availableBundles.size() > 0) { ++ if (preselectedRB.trim().length() == 0) { ++ cmbRB.select(0); ++ cmbRB.setEnabled(true); ++ } ++ } ++ ++ cmbRB.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ //updateAvailableLanguages(); ++ updateResourceSelector (); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ //updateAvailableLanguages(); ++ updateResourceSelector (); ++ } ++ }); ++ ++ // init available translations ++ //updateAvailableLanguages(); ++ ++ // init resource selector ++ updateResourceSelector(); ++ ++ // update search options ++ updateSearchOptions(); ++ } ++ ++ protected void updateResourceSelector () { ++ resourceBundle = cmbRB.getText(); ++ resourceSelector.setResourceBundle(resourceBundle); ++ } ++ ++ protected void updateSearchOptions () { ++ searchOption = (btSearchKey.getSelection() ? SEARCH_KEY : SEARCH_FULLTEXT); ++// cmbLanguage.setEnabled(searchOption == SEARCH_FULLTEXT); ++// lblLanguage.setEnabled(cmbLanguage.getEnabled()); ++ ++ // update ResourceSelector ++ resourceSelector.setDisplayMode(searchOption == SEARCH_FULLTEXT ? ResourceSelector.DISPLAY_TEXT : ResourceSelector.DISPLAY_KEYS); ++ } ++ ++ protected void updateAvailableLanguages () { ++ cmbLanguage.removeAll(); ++ String selectedBundle = cmbRB.getText(); ++ ++ if (selectedBundle.trim().equals("""")) ++ return; ++ ++ // Retrieve available locales for the selected resource-bundle ++ Set locales = manager.getProvidedLocales(selectedBundle); ++ for (Locale l : locales) { ++ String displayName = l.getDisplayName(); ++ if (displayName.equals("""")) ++ displayName = ResourceBundleManager.defaultLocaleTag; ++ cmbLanguage.add(displayName); ++ } ++ ++// if (locales.size() > 0) { ++// cmbLanguage.select(0); ++ updateSelectedLocale(); ++// } ++ } ++ ++ protected void updateSelectedLocale () { ++ String selectedBundle = cmbRB.getText(); ++ ++ if (selectedBundle.trim().equals("""")) ++ return; ++ ++ Set locales = manager.getProvidedLocales(selectedBundle); ++ Iterator it = locales.iterator(); ++ String selectedLocale = cmbLanguage.getText(); ++ while (it.hasNext()) { ++ Locale l = it.next(); ++ if (l.getDisplayName().equals(selectedLocale)) { ++ resourceSelector.setDisplayLocale(l); ++ break; ++ } ++ } ++ } ++ ++ protected void initLayout(Composite parent) { ++ final GridLayout layout = new GridLayout(1, true); ++ parent.setLayout(layout); ++ } ++ ++ protected void constructSearchSection (Composite parent) { ++ final Group group = new Group (parent, SWT.NONE); ++ group.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ group.setText(""Resource selection""); ++ ++ // define grid data for this group ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ group.setLayoutData(gridData); ++ group.setLayout(new GridLayout(2, false)); ++ // TODO export as help text ++ ++ final Label spacer = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ final Label infoLabel = new Label (group, SWT.NONE | SWT.LEFT); ++ GridData infoGrid = new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 1, 1); ++ infoGrid.heightHint = 70; ++ infoLabel.setLayoutData(infoGrid); ++ infoLabel.setText(""Select the resource that needs to be refrenced. This is accomplished in two\n"" + ++ ""steps. First select the Resource-Bundle in which the resource is located. \n"" + ++ ""In a last step you need to choose a particular resource.""); ++ ++ // Resource-Bundle ++ final Label lblRB = new Label (group, SWT.NONE); ++ lblRB.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++ lblRB.setText(""Resource-Bundle:""); ++ ++ cmbRB = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++ cmbRB.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ cmbRB.addModifyListener(new ModifyListener() { ++ @Override ++ public void modifyText(ModifyEvent e) { ++ selectedRB = cmbRB.getText(); ++ validate(); ++ } ++ }); ++ ++ // Search-Options ++ final Label spacer2 = new Label (group, SWT.NONE | SWT.LEFT); ++ spacer2.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, false, false, 1, 1)); ++ ++ Composite searchOptions = new Composite(group, SWT.NONE); ++ searchOptions.setLayout(new GridLayout (2, true)); ++ ++ btSearchText = new Button (searchOptions, SWT.RADIO); ++ btSearchText.setText(""Flat""); ++ btSearchText.setSelection(searchOption == SEARCH_FULLTEXT); ++ btSearchText.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ }); ++ ++ btSearchKey = new Button (searchOptions, SWT.RADIO); ++ btSearchKey.setText(""Hierarchical""); ++ btSearchKey.setSelection(searchOption == SEARCH_KEY); ++ btSearchKey.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSearchOptions(); ++ } ++ }); ++ ++ // Sprache ++// lblLanguage = new Label (group, SWT.NONE); ++// lblLanguage.setLayoutData(new GridData(GridData.END, GridData.CENTER, false, false, 1, 1)); ++// lblLanguage.setText(""Language (Country):""); ++// ++// cmbLanguage = new Combo (group, SWT.DROP_DOWN | SWT.SIMPLE); ++// cmbLanguage.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++// cmbLanguage.addSelectionListener(new SelectionListener () { ++// ++// @Override ++// public void widgetDefaultSelected(SelectionEvent e) { ++// updateSelectedLocale(); ++// } ++// ++// @Override ++// public void widgetSelected(SelectionEvent e) { ++// updateSelectedLocale(); ++// } ++// ++// }); ++// cmbLanguage.addModifyListener(new ModifyListener() { ++// @Override ++// public void modifyText(ModifyEvent e) { ++// selectedLocale = LocaleUtils.getLocaleByDisplayName(manager.getProvidedLocales(selectedRB), cmbLanguage.getText()); ++// validate(); ++// } ++// }); ++ ++ // Filter ++// final Label lblKey = new Label (group, SWT.NONE | SWT.RIGHT); ++// GridData lblKeyGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++// lblKeyGrid.widthHint = WIDTH_LEFT_COLUMN; ++// lblKey.setLayoutData(lblKeyGrid); ++// lblKey.setText(""Filter:""); ++// ++// txtKey = new Text (group, SWT.BORDER); ++// txtKey.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1)); ++ ++ // Add selector for property keys ++ final Label lblKeys = new Label (group, SWT.NONE); ++ lblKeys.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1)); ++ lblKeys.setText(""Resource:""); ++ ++ resourceSelector = new ResourceSelector (group, SWT.NONE, manager, cmbRB.getText(), searchOption, null, true); ++ GridData resourceSelectionData = new GridData(GridData.FILL, GridData.CENTER, true, false, 1, 1); ++ resourceSelectionData.heightHint = 150; ++ resourceSelectionData.widthHint = 400; ++ resourceSelector.setLayoutData(resourceSelectionData); ++ resourceSelector.addSelectionChangedListener(new IResourceSelectionListener() { ++ ++ @Override ++ public void selectionChanged(ResourceSelectionEvent e) { ++ selectedKey = e.getSelectedKey(); ++ updatePreviewLabel(e.getSelectionSummary()); ++ validate(); ++ } ++ }); ++ ++// final Label spacer = new Label (group, SWT.SEPARATOR | SWT.HORIZONTAL); ++// spacer.setLayoutData(new GridData(GridData.BEGINNING, GridData.CENTER, true, false, 2, 1)); ++ ++ // Preview ++ final Label lblText = new Label (group, SWT.NONE | SWT.RIGHT); ++ GridData lblTextGrid = new GridData(GridData.END, GridData.CENTER, false, false, 1, 1); ++ lblTextGrid.heightHint = 120; ++ lblTextGrid.widthHint = 100; ++ lblText.setLayoutData(lblTextGrid); ++ lblText.setText(""Preview:""); ++ ++ txtPreviewText = new Text (group, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL); ++ txtPreviewText.setEditable(false); ++ GridData lblTextGrid2 = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 1); ++ txtPreviewText.setLayoutData(lblTextGrid2); ++ } ++ ++ @Override ++ protected void configureShell(Shell newShell) { ++ super.configureShell(newShell); ++ newShell.setText(""Select Resource-Bundle entry""); ++ } ++ ++ @Override ++ public void create() { ++ // TODO Auto-generated method stub ++ super.create(); ++ this.setTitle(""Select a Resource-Bundle entry""); ++ this.setMessage(""Please, select a resource of a particular Resource-Bundle""); ++ } ++ ++ protected void updatePreviewLabel (String previewText) { ++ txtPreviewText.setText(previewText); ++ } ++ ++ protected void validate () { ++ // Check Resource-Bundle ids ++ boolean rbValid = false; ++ boolean localeValid = false; ++ boolean keyValid = false; ++ ++ for (String rbId : this.availableBundles) { ++ if (rbId.equals(selectedRB)) { ++ rbValid = true; ++ break; ++ } ++ } ++ ++ if (selectedLocale != null) ++ localeValid = true; ++ ++ if (manager.isResourceExisting(selectedRB, selectedKey)) ++ keyValid = true; ++ ++ // print Validation summary ++ String errorMessage = null; ++ if (! rbValid) ++ errorMessage = ""The specified Resource-Bundle does not exist""; ++// else if (! localeValid) ++// errorMessage = ""The specified Locale does not exist for the selecte Resource-Bundle""; ++ else if (! keyValid) ++ errorMessage = ""No resource selected""; ++ else { ++ if (okButton != null) ++ okButton.setEnabled(true); ++ } ++ ++ setErrorMessage(errorMessage); ++ if (okButton != null && errorMessage != null) ++ okButton.setEnabled(false); ++ } ++ ++ @Override ++ protected void createButtonsForButtonBar(Composite parent) { ++ okButton = createButton (parent, OK, ""Ok"", true); ++ okButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ // Set return code ++ setReturnCode(OK); ++ close(); ++ } ++ }); ++ ++ cancelButton = createButton (parent, CANCEL, ""Cancel"", false); ++ cancelButton.addSelectionListener (new SelectionAdapter() { ++ public void widgetSelected(SelectionEvent e) { ++ setReturnCode (CANCEL); ++ close(); ++ } ++ }); ++ ++ okButton.setEnabled(false); ++ cancelButton.setEnabled(true); ++ } ++ ++ public String getSelectedResourceBundle () { ++ return selectedRB; ++ } ++ ++ public String getSelectedResource () { ++ return selectedKey; ++ } ++ ++ public Locale getSelectedLocale () { ++ return selectedLocale; ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java +new file mode 100644 +index 00000000..5d73db2e +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/dialogs/ResourceBundleSelectionDialog.java +@@ -0,0 +1,110 @@ ++package org.eclipselabs.tapiji.tools.core.ui.dialogs; ++ ++import java.util.List; ++ ++import org.eclipse.core.resources.IProject; ++import org.eclipse.jface.viewers.ILabelProvider; ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.IStructuredContentProvider; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.ui.dialogs.ListDialog; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++ ++ ++public class ResourceBundleSelectionDialog extends ListDialog { ++ ++ private IProject project; ++ ++ public ResourceBundleSelectionDialog(Shell parent, IProject project) { ++ super(parent); ++ this.project = project; ++ ++ initDialog (); ++ } ++ ++ protected void initDialog () { ++ this.setAddCancelButton(true); ++ this.setMessage(""Select one of the following Resource-Bundle to open:""); ++ this.setTitle(""Resource-Bundle Selector""); ++ this.setContentProvider(new RBContentProvider()); ++ this.setLabelProvider(new RBLabelProvider()); ++ this.setBlockOnOpen(true); ++ ++ if (project != null) ++ this.setInput(ResourceBundleManager.getManager(project).getResourceBundleNames()); ++ else ++ this.setInput(ResourceBundleManager.getAllResourceBundleNames()); ++ } ++ ++ public String getSelectedBundleId () { ++ Object[] selection = this.getResult(); ++ if (selection != null && selection.length > 0) ++ return (String) selection[0]; ++ return null; ++ } ++ ++ class RBContentProvider implements IStructuredContentProvider { ++ ++ @Override ++ public Object[] getElements(Object inputElement) { ++ List resources = (List) inputElement; ++ return resources.toArray(); ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ } ++ ++ class RBLabelProvider implements ILabelProvider { ++ ++ @Override ++ public Image getImage(Object element) { ++ // TODO Auto-generated method stub ++ return ImageUtils.getImage(ImageUtils.IMAGE_RESOURCE_BUNDLE); ++ } ++ ++ @Override ++ public String getText(Object element) { ++ // TODO Auto-generated method stub ++ return ((String) element); ++ } ++ ++ @Override ++ public void addListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ public boolean isLabelProperty(Object element, String property) { ++ // TODO Auto-generated method stub ++ return false; ++ } ++ ++ @Override ++ public void removeListener(ILabelProviderListener listener) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java +new file mode 100644 +index 00000000..cf92e76f +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/filters/PropertiesFileFilter.java +@@ -0,0 +1,31 @@ ++package org.eclipselabs.tapiji.tools.core.ui.filters; ++ ++import org.eclipse.core.resources.IFile; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.jface.viewers.ViewerFilter; ++ ++public class PropertiesFileFilter extends ViewerFilter { ++ ++ private boolean debugEnabled = true; ++ ++ public PropertiesFileFilter() { ++ ++ } ++ ++ @Override ++ public boolean select(Viewer viewer, Object parentElement, Object element) { ++ if (debugEnabled) ++ return true; ++ ++ if (element.getClass().getSimpleName().equals(""CompilationUnit"")) ++ return false; ++ ++ if (!(element instanceof IFile)) ++ return true; ++ ++ IFile file = (IFile) element; ++ ++ return file.getFileExtension().equalsIgnoreCase(""properties""); ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java +new file mode 100644 +index 00000000..8d6e57cd +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/markers/StringLiterals.java +@@ -0,0 +1,5 @@ ++package org.eclipselabs.tapiji.tools.core.ui.markers; ++ ++public class StringLiterals { ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java +new file mode 100644 +index 00000000..3f6493fd +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/menus/InternationalizationMenu.java +@@ -0,0 +1,373 @@ ++package org.eclipselabs.tapiji.tools.core.ui.menus; ++ ++import java.util.Collection; ++import java.util.HashSet; ++import java.util.Iterator; ++import java.util.List; ++import java.util.Locale; ++ ++import org.eclipse.core.resources.IProject; ++import org.eclipse.core.resources.IResource; ++import org.eclipse.core.runtime.IAdaptable; ++import org.eclipse.core.runtime.IProgressMonitor; ++import org.eclipse.jdt.core.IJavaElement; ++import org.eclipse.jdt.core.IPackageFragment; ++import org.eclipse.jface.action.ContributionItem; ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.jface.dialogs.MessageDialog; ++import org.eclipse.jface.operation.IRunnableWithProgress; ++import org.eclipse.jface.viewers.ISelection; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.custom.BusyIndicator; ++import org.eclipse.swt.events.MenuAdapter; ++import org.eclipse.swt.events.MenuEvent; ++import org.eclipse.swt.events.SelectionAdapter; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.Menu; ++import org.eclipse.swt.widgets.MenuItem; ++import org.eclipse.swt.widgets.Shell; ++import org.eclipse.ui.IWorkbench; ++import org.eclipse.ui.IWorkbenchWindow; ++import org.eclipse.ui.PlatformUI; ++import org.eclipse.ui.progress.IProgressService; ++import org.eclipselabs.tapiji.tools.core.builder.InternationalizationNature; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.AddLanguageDialoge; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.FragmentProjectSelectionDialog; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.GenerateBundleAccessorDialog; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.RemoveLanguageDialoge; ++import org.eclipselabs.tapiji.tools.core.util.FragmentProjectUtils; ++import org.eclipselabs.tapiji.tools.core.util.LanguageUtils; ++ ++ ++public class InternationalizationMenu extends ContributionItem { ++ private boolean excludeMode = true; ++ private boolean internationalizationEnabled = false; ++ ++ private MenuItem mnuToggleInt; ++ private MenuItem excludeResource; ++ private MenuItem addLanguage; ++ private MenuItem removeLanguage; ++ ++ public InternationalizationMenu() {} ++ ++ public InternationalizationMenu(String id) { ++ super(id); ++ } ++ ++ @Override ++ public void fill(Menu menu, int index) { ++ if (getSelectedProjects().size() == 0 || ++ !projectsSupported()) ++ return; ++ ++ // Toggle Internatinalization ++ mnuToggleInt = new MenuItem (menu, SWT.PUSH); ++ mnuToggleInt.addSelectionListener(new SelectionAdapter () { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ runToggleInt(); ++ } ++ ++ }); ++ ++ // Exclude Resource ++ excludeResource = new MenuItem (menu, SWT.PUSH); ++ excludeResource.addSelectionListener(new SelectionAdapter () { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ runExclude(); ++ } ++ ++ }); ++ ++ new MenuItem(menu, SWT.SEPARATOR); ++ ++ // Add Language ++ addLanguage = new MenuItem(menu, SWT.PUSH); ++ addLanguage.addSelectionListener(new SelectionAdapter() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ runAddLanguage(); ++ } ++ ++ }); ++ ++ // Remove Language ++ removeLanguage = new MenuItem(menu, SWT.PUSH); ++ removeLanguage.addSelectionListener(new SelectionAdapter() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ runRemoveLanguage(); ++ } ++ ++ }); ++ ++ menu.addMenuListener(new MenuAdapter () { ++ public void menuShown (MenuEvent e) { ++ updateStateToggleInt (mnuToggleInt); ++ //updateStateGenRBAccessor (generateAccessor); ++ updateStateExclude (excludeResource); ++ updateStateAddLanguage (addLanguage); ++ updateStateRemoveLanguage (removeLanguage); ++ } ++ }); ++ } ++ ++ protected void runGenRBAccessor () { ++ GenerateBundleAccessorDialog dlg = new GenerateBundleAccessorDialog(Display.getDefault().getActiveShell()); ++ if (dlg.open() != InputDialog.OK) ++ return; ++ } ++ ++ protected void updateStateGenRBAccessor (MenuItem menuItem) { ++ Collection frags = getSelectedPackageFragments(); ++ menuItem.setEnabled(frags.size() > 0); ++ } ++ ++ protected void updateStateToggleInt (MenuItem menuItem) { ++ Collection projects = getSelectedProjects(); ++ boolean enabled = projects.size() > 0; ++ menuItem.setEnabled(enabled); ++ setVisible(enabled); ++ internationalizationEnabled = InternationalizationNature.hasNature(projects.iterator().next()); ++ //menuItem.setSelection(enabled && internationalizationEnabled); ++ ++ if (internationalizationEnabled) ++ menuItem.setText(""Disable Internationalization""); ++ else ++ menuItem.setText(""Enable Internationalization""); ++ } ++ ++ private Collection getSelectedPackageFragments () { ++ Collection frags = new HashSet (); ++ IWorkbenchWindow window = ++ PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ++ ISelection selection = window.getActivePage().getSelection (); ++ if (selection instanceof IStructuredSelection) { ++ for (Iterator iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) { ++ Object elem = iter.next(); ++ if (elem instanceof IPackageFragment) { ++ IPackageFragment frag = (IPackageFragment) elem; ++ if (!frag.isReadOnly()) ++ frags.add (frag); ++ } ++ } ++ } ++ return frags; ++ } ++ ++ private Collection getSelectedProjects () { ++ Collection projects = new HashSet (); ++ IWorkbenchWindow window = ++ PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ++ ISelection selection = window.getActivePage().getSelection (); ++ if (selection instanceof IStructuredSelection) { ++ for (Iterator iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) { ++ Object elem = iter.next(); ++ if (!(elem instanceof IResource)) { ++ if (!(elem instanceof IAdaptable)) ++ continue; ++ elem = ((IAdaptable) elem).getAdapter (IResource.class); ++ if (!(elem instanceof IResource)) ++ continue; ++ } ++ if (!(elem instanceof IProject)) { ++ elem = ((IResource) elem).getProject(); ++ if (!(elem instanceof IProject)) ++ continue; ++ } ++ if (((IProject)elem).isAccessible()) ++ projects.add ((IProject)elem); ++ ++ } ++ } ++ return projects; ++ } ++ ++ protected boolean projectsSupported() { ++ Collection projects = getSelectedProjects (); ++ for (IProject project : projects) { ++ if (!InternationalizationNature.supportsNature(project)) ++ return false; ++ } ++ ++ return true; ++ } ++ ++ protected void runToggleInt () { ++ Collection projects = getSelectedProjects (); ++ for (IProject project : projects) { ++ toggleNature (project); ++ } ++ } ++ ++ private void toggleNature (IProject project) { ++ if (InternationalizationNature.hasNature (project)) { ++ InternationalizationNature.removeNature (project); ++ } else { ++ InternationalizationNature.addNature (project); ++ } ++ } ++ protected void updateStateExclude (MenuItem menuItem) { ++ Collection resources = getSelectedResources(); ++ menuItem.setEnabled(resources.size() > 0 && internationalizationEnabled); ++ ResourceBundleManager manager = null; ++ excludeMode = false; ++ ++ for (IResource res : resources) { ++ if (manager == null || (manager.getProject() != res.getProject())) ++ manager = ResourceBundleManager.getManager(res.getProject()); ++ try { ++ if (!ResourceBundleManager.isResourceExcluded(res)) { ++ excludeMode = true; ++ } ++ } catch (Exception e) { } ++ } ++ ++ if (!excludeMode) ++ menuItem.setText(""Include Resource""); ++ else ++ menuItem.setText(""Exclude Resource""); ++ } ++ ++ private Collection getSelectedResources () { ++ Collection resources = new HashSet (); ++ IWorkbenchWindow window = ++ PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ++ ISelection selection = window.getActivePage().getSelection (); ++ if (selection instanceof IStructuredSelection) { ++ for (Iterator iter = ((IStructuredSelection)selection).iterator(); iter.hasNext();) { ++ Object elem = iter.next(); ++ if (elem instanceof IProject) ++ continue; ++ ++ if (elem instanceof IResource) { ++ resources.add ((IResource)elem); ++ } else if (elem instanceof IJavaElement) { ++ resources.add (((IJavaElement)elem).getResource()); ++ } ++ } ++ } ++ return resources; ++ } ++ ++ protected void runExclude () { ++ final Collection selectedResources = getSelectedResources (); ++ ++ IWorkbench wb = PlatformUI.getWorkbench(); ++ IProgressService ps = wb.getProgressService(); ++ try { ++ ps.busyCursorWhile(new IRunnableWithProgress() { ++ public void run(IProgressMonitor pm) { ++ ++ ResourceBundleManager manager = null; ++ pm.beginTask(""Including resources to Internationalization"", selectedResources.size()); ++ ++ for (IResource res : selectedResources) { ++ if (manager == null || (manager.getProject() != res.getProject())) ++ manager = ResourceBundleManager.getManager(res.getProject()); ++ if (excludeMode) ++ manager.excludeResource(res, pm); ++ else ++ manager.includeResource(res, pm); ++ pm.worked(1); ++ } ++ pm.done(); ++ } ++ }); ++ } catch (Exception e) {} ++ } ++ ++ protected void updateStateAddLanguage(MenuItem menuItem){ ++ Collection projects = getSelectedProjects(); ++ boolean hasResourceBundles=false; ++ for (IProject p : projects){ ++ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(p); ++ hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false; ++ } ++ ++ menuItem.setText(""Add Language To Project""); ++ menuItem.setEnabled(projects.size() > 0 && hasResourceBundles); ++ } ++ ++ protected void runAddLanguage() { ++ AddLanguageDialoge dialog = new AddLanguageDialoge(new Shell(Display.getCurrent())); ++ if (dialog.open() == InputDialog.OK) { ++ final Locale locale = dialog.getSelectedLanguage(); ++ ++ Collection selectedProjects = getSelectedProjects(); ++ for (IProject project : selectedProjects){ ++ //check if project is fragmentproject and continue working with the hostproject, if host not member of selectedProjects ++ if (FragmentProjectUtils.isFragment(project)){ ++ IProject host = FragmentProjectUtils.getFragmentHost(project); ++ if (!selectedProjects.contains(host)) ++ project = host; ++ else ++ continue; ++ } ++ ++ List fragments = FragmentProjectUtils.getFragments(project); ++ ++ if (!fragments.isEmpty()) { ++ FragmentProjectSelectionDialog fragmentDialog = new FragmentProjectSelectionDialog( ++ Display.getCurrent().getActiveShell(), project, ++ fragments); ++ ++ if (fragmentDialog.open() == InputDialog.OK) ++ project = fragmentDialog.getSelectedProject(); ++ } ++ ++ final IProject selectedProject = project; ++ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { ++ @Override ++ public void run() { ++ LanguageUtils.addLanguageToProject(selectedProject, locale); ++ } ++ ++ }); ++ ++ } ++ } ++ } ++ ++ ++ protected void updateStateRemoveLanguage(MenuItem menuItem) { ++ Collection projects = getSelectedProjects(); ++ boolean hasResourceBundles=false; ++ if (projects.size() == 1){ ++ IProject project = projects.iterator().next(); ++ ResourceBundleManager rbmanager = ResourceBundleManager.getManager(project); ++ hasResourceBundles = rbmanager.getResourceBundleIdentifiers().size() > 0 ? true : false; ++ } ++ menuItem.setText(""Remove Language From Project""); ++ menuItem.setEnabled(projects.size() == 1 && hasResourceBundles/*&& more than one common languages contained*/); ++ } ++ ++ protected void runRemoveLanguage() { ++ final IProject project = getSelectedProjects().iterator().next(); ++ RemoveLanguageDialoge dialog = new RemoveLanguageDialoge(project, new Shell(Display.getCurrent())); ++ ++ ++ if (dialog.open() == InputDialog.OK) { ++ final Locale locale = dialog.getSelectedLanguage(); ++ if (locale != null) { ++ if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), ""Confirm"", ""Do you really want remove all properties-files for ""+locale.getDisplayName()+""?"")) ++ BusyIndicator.showWhile(Display.getCurrent(), new Runnable() { ++ @Override ++ public void run() { ++ LanguageUtils.removeLanguageFromProject(project, locale); ++ } ++ }); ++ ++ } ++ } ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java +new file mode 100644 +index 00000000..e43aef21 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/BuilderPreferencePage.java +@@ -0,0 +1,129 @@ ++package org.eclipselabs.tapiji.tools.core.ui.prefrences; ++ ++import org.eclipse.jface.preference.IPreferenceStore; ++import org.eclipse.jface.preference.PreferencePage; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.SelectionAdapter; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.ui.IWorkbench; ++import org.eclipse.ui.IWorkbenchPreferencePage; ++import org.eclipselabs.tapiji.tools.core.Activator; ++import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences; ++ ++public class BuilderPreferencePage extends PreferencePage implements ++ IWorkbenchPreferencePage { ++ private static final int INDENT = 20; ++ ++ private Button checkSameValueButton; ++ private Button checkMissingValueButton; ++ private Button checkMissingLanguageButton; ++ ++ private Button rbAuditButton; ++ ++ private Button sourceAuditButton; ++ ++ ++ @Override ++ public void init(IWorkbench workbench) { ++ setPreferenceStore(Activator.getDefault().getPreferenceStore()); ++ } ++ ++ @Override ++ protected Control createContents(Composite parent) { ++ IPreferenceStore prefs = getPreferenceStore(); ++ Composite composite = new Composite(parent, SWT.SHADOW_OUT); ++ ++ composite.setLayout(new GridLayout(1,false)); ++ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); ++ ++ Composite field = createComposite(parent, 0, 10); ++ Label descriptionLabel = new Label(composite, SWT.NONE); ++ descriptionLabel.setText(""Select types of reported problems:""); ++ ++ field = createComposite(composite, 0, 0); ++ sourceAuditButton = new Button(field, SWT.CHECK); ++ sourceAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RESOURCE)); ++ sourceAuditButton.setText(""Check source code for non externalizated Strings""); ++ ++ field = createComposite(composite, 0, 0); ++ rbAuditButton = new Button(field, SWT.CHECK); ++ rbAuditButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_RB)); ++ rbAuditButton.setText(""Check ResourceBundles on the following problems:""); ++ rbAuditButton.addSelectionListener(new SelectionAdapter() { ++ @Override ++ public void widgetSelected(SelectionEvent event) { ++ setRBAudits(); ++ } ++ }); ++ ++ field = createComposite(composite, INDENT, 0); ++ checkMissingValueButton = new Button(field, SWT.CHECK); ++ checkMissingValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); ++ checkMissingValueButton.setText(""Missing translation for a key""); ++ ++ field = createComposite(composite, INDENT, 0); ++ checkSameValueButton = new Button(field, SWT.CHECK); ++ checkSameValueButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); ++ checkSameValueButton.setText(""Same translations for one key in diffrent languages""); ++ ++ field = createComposite(composite, INDENT, 0); ++ checkMissingLanguageButton = new Button(field, SWT.CHECK); ++ checkMissingLanguageButton.setSelection(prefs.getBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); ++ checkMissingLanguageButton.setText(""Missing languages in a ResourceBundle""); ++ ++ setRBAudits(); ++ ++ composite.pack(); ++ ++ return composite; ++ } ++ ++ @Override ++ protected void performDefaults() { ++ IPreferenceStore prefs = getPreferenceStore(); ++ ++ sourceAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RESOURCE)); ++ rbAuditButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_RB)); ++ checkMissingValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY)); ++ checkSameValueButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_SAME_VALUE)); ++ checkMissingLanguageButton.setSelection(prefs.getDefaultBoolean(TapiJIPreferences.AUDIT_MISSING_LANGUAGE)); ++ } ++ ++ @Override ++ public boolean performOk() { ++ IPreferenceStore prefs = getPreferenceStore(); ++ ++ prefs.setValue(TapiJIPreferences.AUDIT_RESOURCE, sourceAuditButton.getSelection()); ++ prefs.setValue(TapiJIPreferences.AUDIT_RB, rbAuditButton.getSelection()); ++ prefs.setValue(TapiJIPreferences.AUDIT_UNSPEZIFIED_KEY, checkMissingValueButton.getSelection()); ++ prefs.setValue(TapiJIPreferences.AUDIT_SAME_VALUE, checkSameValueButton.getSelection()); ++ prefs.setValue(TapiJIPreferences.AUDIT_MISSING_LANGUAGE, checkMissingLanguageButton.getSelection()); ++ ++ return super.performOk(); ++ } ++ ++ private Composite createComposite(Composite parent, int marginWidth, int marginHeight) { ++ Composite composite = new Composite(parent, SWT.NONE); ++ ++ GridLayout indentLayout = new GridLayout(1, false); ++ indentLayout.marginWidth = marginWidth; ++ indentLayout.marginHeight = marginHeight; ++ indentLayout.verticalSpacing = 0; ++ composite.setLayout(indentLayout); ++ ++ return composite; ++ } ++ ++ protected void setRBAudits() { ++ boolean selected = rbAuditButton.getSelection(); ++ checkMissingValueButton.setEnabled(selected); ++ checkSameValueButton.setEnabled(selected); ++ checkMissingLanguageButton.setEnabled(selected); ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java +new file mode 100644 +index 00000000..ff6c1cbe +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/FilePreferencePage.java +@@ -0,0 +1,192 @@ ++package org.eclipselabs.tapiji.tools.core.ui.prefrences; ++ ++import java.util.LinkedList; ++import java.util.List; ++ ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.jface.preference.IPreferenceStore; ++import org.eclipse.jface.preference.PreferencePage; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.MouseEvent; ++import org.eclipse.swt.events.MouseListener; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Table; ++import org.eclipse.swt.widgets.TableItem; ++import org.eclipse.ui.IWorkbench; ++import org.eclipse.ui.IWorkbenchPreferencePage; ++import org.eclipselabs.tapiji.tools.core.Activator; ++import org.eclipselabs.tapiji.tools.core.model.preferences.CheckItem; ++import org.eclipselabs.tapiji.tools.core.model.preferences.TapiJIPreferences; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreatePatternDialoge; ++ ++public class FilePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { ++ ++ private Table table; ++ protected Object dialoge; ++ ++ private Button editPatternButton; ++ private Button removePatternButton; ++ ++ @Override ++ public void init(IWorkbench workbench) { ++ setPreferenceStore(Activator.getDefault().getPreferenceStore()); ++ } ++ ++ @Override ++ protected Control createContents(Composite parent) { ++ IPreferenceStore prefs = getPreferenceStore(); ++ Composite composite = new Composite(parent, SWT.SHADOW_OUT); ++ ++ composite.setLayout(new GridLayout(2,false)); ++ composite.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); ++ ++ Label descriptionLabel = new Label(composite, SWT.WRAP); ++ GridData descriptionData = new GridData(SWT.FILL, SWT.TOP, false, false); ++ descriptionData.horizontalSpan=2; ++ descriptionLabel.setLayoutData(descriptionData); ++ descriptionLabel.setText(""Properties-files which match the following pattern, will not be interpreted as ResourceBundle-files""); ++ ++ table = new Table (composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION | SWT.CHECK); ++ GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); ++ table.setLayoutData(data); ++ ++ table.addSelectionListener(new SelectionListener() { ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ TableItem[] selection = table.getSelection(); ++ if (selection.length > 0){ ++ editPatternButton.setEnabled(true); ++ removePatternButton.setEnabled(true); ++ }else{ ++ editPatternButton.setEnabled(false); ++ removePatternButton.setEnabled(false); ++ } ++ } ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ // TODO Auto-generated method stub ++ } ++ }); ++ ++ List patternItems = TapiJIPreferences.getNonRbPatternAsList(); ++ for (CheckItem s : patternItems){ ++ s.toTableItem(table); ++ } ++ ++ Composite sitebar = new Composite(composite, SWT.NONE); ++ sitebar.setLayout(new GridLayout(1,false)); ++ sitebar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true)); ++ ++ Button addPatternButton = new Button(sitebar, SWT.NONE); ++ addPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); ++ addPatternButton.setText(""Add Pattern""); ++ addPatternButton.addMouseListener(new MouseListener() { ++ @Override ++ public void mouseUp(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ @Override ++ public void mouseDown(MouseEvent e) { ++ String pattern = ""^.*/""+""((_[a-z]{2,3})|(_[a-z]{2,3}_[A-Z]{2})|(_[a-z]{2,3}_[A-Z]{2}_\\w*))?""+ ""\\.properties$""; ++ CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(),pattern); ++ if (dialog.open() == InputDialog.OK) { ++ pattern = dialog.getPattern(); ++ ++ TableItem item = new TableItem(table, SWT.NONE); ++ item.setText(pattern); ++ item.setChecked(true); ++ } ++ } ++ @Override ++ public void mouseDoubleClick(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ }); ++ ++ editPatternButton = new Button(sitebar, SWT.NONE); ++ editPatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); ++ editPatternButton.setText(""Edit""); ++ editPatternButton.addMouseListener(new MouseListener() { ++ @Override ++ public void mouseUp(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ @Override ++ public void mouseDown(MouseEvent e) { ++ TableItem[] selection = table.getSelection(); ++ if (selection.length > 0){ ++ String pattern = selection[0].getText(); ++ ++ CreatePatternDialoge dialog = new CreatePatternDialoge(Display.getDefault().getActiveShell(), pattern); ++ if (dialog.open() == InputDialog.OK) { ++ pattern = dialog.getPattern(); ++ TableItem item = selection[0]; ++ item.setText(pattern); ++ } ++ } ++ } ++ @Override ++ public void mouseDoubleClick(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ }); ++ ++ ++ removePatternButton = new Button(sitebar, SWT.NONE); ++ removePatternButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true)); ++ removePatternButton.setText(""Remove""); ++ removePatternButton.addMouseListener(new MouseListener() { ++ @Override ++ public void mouseUp(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ @Override ++ public void mouseDown(MouseEvent e) { ++ TableItem[] selection = table.getSelection(); ++ if (selection.length > 0) ++ table.remove(table.indexOf(selection[0])); ++ } ++ @Override ++ public void mouseDoubleClick(MouseEvent e) { ++ // TODO Auto-generated method stub ++ } ++ }); ++ ++ composite.pack(); ++ ++ return composite; ++ } ++ ++ @Override ++ protected void performDefaults() { ++ IPreferenceStore prefs = getPreferenceStore(); ++ ++ table.removeAll(); ++ ++ List patterns = TapiJIPreferences.convertStringToList(prefs.getDefaultString(TapiJIPreferences.NON_RB_PATTERN)); ++ for (CheckItem s : patterns){ ++ s.toTableItem(table); ++ } ++ } ++ ++ @Override ++ public boolean performOk() { ++ IPreferenceStore prefs = getPreferenceStore(); ++ List patterns =new LinkedList(); ++ for (TableItem i : table.getItems()){ ++ patterns.add(new CheckItem(i.getText(), i.getChecked())); ++ } ++ ++ prefs.setValue(TapiJIPreferences.NON_RB_PATTERN, TapiJIPreferences.convertListToString(patterns)); ++ ++ return super.performOk(); ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java +new file mode 100644 +index 00000000..42450adf +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/prefrences/TapiHomePreferencePage.java +@@ -0,0 +1,34 @@ ++package org.eclipselabs.tapiji.tools.core.ui.prefrences; ++ ++import org.eclipse.jface.preference.PreferencePage; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Control; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.ui.IWorkbench; ++import org.eclipse.ui.IWorkbenchPreferencePage; ++ ++public class TapiHomePreferencePage extends PreferencePage implements ++ IWorkbenchPreferencePage { ++ ++ @Override ++ public void init(IWorkbench workbench) { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ @Override ++ protected Control createContents(Composite parent) { ++ Composite composite = new Composite(parent, SWT.NONE); ++ composite.setLayout(new GridLayout(1,true)); ++ composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); ++ ++ Label description = new Label(composite, SWT.WRAP); ++ description.setText(""See sub-pages for settings.""); ++ ++ return parent; ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +new file mode 100644 +index 00000000..aad8e719 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/quickfix/CreateResourceBundleEntry.java +@@ -0,0 +1,82 @@ ++package org.eclipselabs.tapiji.tools.core.ui.quickfix; ++ ++import org.eclipse.core.filebuffers.FileBuffers; ++import org.eclipse.core.filebuffers.ITextFileBuffer; ++import org.eclipse.core.filebuffers.ITextFileBufferManager; ++import org.eclipse.core.resources.IMarker; ++import org.eclipse.core.resources.IResource; ++import org.eclipse.core.runtime.CoreException; ++import org.eclipse.core.runtime.IPath; ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.jface.text.IDocument; ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.ui.IMarkerResolution2; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.builder.StringLiteralAuditor; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog; ++ ++ ++public class CreateResourceBundleEntry implements IMarkerResolution2 { ++ ++ private String key; ++ private String bundleId; ++ ++ public CreateResourceBundleEntry (String key, ResourceBundleManager manager, String bundleId) { ++ this.key = key; ++ this.bundleId = bundleId; ++ } ++ ++ @Override ++ public String getDescription() { ++ return ""Creates a new Resource-Bundle entry for the property-key '"" + key + ""'""; ++ } ++ ++ @Override ++ public Image getImage() { ++ // TODO Auto-generated method stub ++ return null; ++ } ++ ++ @Override ++ public String getLabel() { ++ return ""Create Resource-Bundle entry for '"" + key + ""'""; ++ } ++ ++ @Override ++ public void run(IMarker marker) { ++ int startPos = marker.getAttribute(IMarker.CHAR_START, 0); ++ int endPos = marker.getAttribute(IMarker.CHAR_END, 0) - startPos; ++ IResource resource = marker.getResource(); ++ ++ ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); ++ IPath path = resource.getRawLocation(); ++ try { ++ bufferManager.connect(path, null); ++ ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path); ++ IDocument document = textFileBuffer.getDocument(); ++ ++ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( ++ Display.getDefault().getActiveShell(), ++ ResourceBundleManager.getManager(resource.getProject()), ++ key != null ? key : """", ++ """", ++ bundleId, ++ """"); ++ if (dialog.open() != InputDialog.OK) ++ return; ++ } catch (Exception e) { ++ Logger.logError(e); ++ } finally { ++ try { ++ (new StringLiteralAuditor()).buildResource(resource, null); ++ bufferManager.disconnect(path, null); ++ } catch (CoreException e) { ++ Logger.logError(e); ++ } ++ } ++ ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java +new file mode 100644 +index 00000000..b2d18efa +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/MessagesView.java +@@ -0,0 +1,513 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview; ++ ++import java.util.ArrayList; ++import java.util.List; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.core.runtime.IProgressMonitor; ++import org.eclipse.core.runtime.IStatus; ++import org.eclipse.core.runtime.Status; ++import org.eclipse.jface.action.Action; ++import org.eclipse.jface.action.IMenuListener; ++import org.eclipse.jface.action.IMenuManager; ++import org.eclipse.jface.action.IToolBarManager; ++import org.eclipse.jface.action.MenuManager; ++import org.eclipse.jface.action.Separator; ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.Event; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Listener; ++import org.eclipse.swt.widgets.Menu; ++import org.eclipse.swt.widgets.Scale; ++import org.eclipse.swt.widgets.Text; ++import org.eclipse.ui.IActionBars; ++import org.eclipse.ui.IMemento; ++import org.eclipse.ui.IViewSite; ++import org.eclipse.ui.PartInitException; ++import org.eclipse.ui.part.ViewPart; ++import org.eclipse.ui.progress.UIJob; ++import org.eclipselabs.tapiji.tools.core.Activator; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.model.view.MessagesViewState; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.ResourceBundleSelectionDialog; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++ ++ ++public class MessagesView extends ViewPart implements IResourceBundleChangedListener { ++ ++ /** ++ * The ID of the view as specified by the extension. ++ */ ++ public static final String ID = ""org.eclipselabs.tapiji.tools.core.views.MessagesView""; ++ ++ // View State ++ private IMemento memento; ++ private MessagesViewState viewState; ++ ++ // Search-Bar ++ private Text filter; ++ ++ // Property-Key widget ++ private PropertyKeySelectionTree treeViewer; ++ private Scale fuzzyScaler; ++ private Label lblScale; ++ ++ /*** ACTIONS ***/ ++ private List visibleLocaleActions; ++ private Action selectResourceBundle; ++ private Action enableFuzzyMatching; ++ private Action editable; ++ ++ // Parent component ++ Composite parent; ++ ++ // context-dependent menu actions ++ ResourceBundleEntry contextDependentMenu; ++ ++ /** ++ * The constructor. ++ */ ++ public MessagesView() { ++ } ++ ++ /** ++ * This is a callback that will allow us ++ * to create the viewer and initialize it. ++ */ ++ public void createPartControl(Composite parent) { ++ this.parent = parent; ++ ++ initLayout (parent); ++ initSearchBar (parent); ++ initMessagesTree (parent); ++ makeActions(); ++ hookContextMenu(); ++ contributeToActionBars(); ++ initListener (parent); ++ } ++ ++ protected void initListener (Composite parent) { ++ filter.addModifyListener(new ModifyListener() { ++ ++ @Override ++ public void modifyText(ModifyEvent e) { ++ treeViewer.setSearchString(filter.getText()); ++ } ++ }); ++ } ++ ++ protected void initLayout (Composite parent) { ++ GridLayout mainLayout = new GridLayout (); ++ mainLayout.numColumns = 1; ++ parent.setLayout(mainLayout); ++ ++ } ++ ++ protected void initSearchBar (Composite parent) { ++ // Construct a new parent container ++ Composite parentComp = new Composite(parent, SWT.BORDER); ++ parentComp.setLayout(new GridLayout(4, false)); ++ parentComp.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); ++ ++ Label lblSearchText = new Label (parentComp, SWT.NONE); ++ lblSearchText.setText(""Search expression:""); ++ ++ // define the grid data for the layout ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = false; ++ gridData.horizontalSpan = 1; ++ lblSearchText.setLayoutData(gridData); ++ ++ filter = new Text (parentComp, SWT.SINGLE | SWT.LEFT | SWT.BORDER); ++ if (viewState.getSearchString() != null) { ++ if (viewState.getSearchString().length() > 1 && ++ viewState.getSearchString().startsWith(""*"") && viewState.getSearchString().endsWith(""*"")) ++ filter.setText(viewState.getSearchString().substring(1).substring(0, viewState.getSearchString().length()-2)); ++ else ++ filter.setText(viewState.getSearchString()); ++ ++ } ++ GridData gridDatas = new GridData(); ++ gridDatas.horizontalAlignment = SWT.FILL; ++ gridDatas.grabExcessHorizontalSpace = true; ++ gridDatas.horizontalSpan = 3; ++ filter.setLayoutData(gridDatas); ++ ++ lblScale = new Label (parentComp, SWT.None); ++ lblScale.setText(""\nPrecision:""); ++ GridData gdScaler = new GridData(); ++ gdScaler.verticalAlignment = SWT.CENTER; ++ gdScaler.grabExcessVerticalSpace = true; ++ gdScaler.horizontalSpan = 1; ++// gdScaler.widthHint = 150; ++ lblScale.setLayoutData(gdScaler); ++ ++ // Add a scale for specification of fuzzy Matching precision ++ fuzzyScaler = new Scale (parentComp, SWT.None); ++ fuzzyScaler.setMaximum(100); ++ fuzzyScaler.setMinimum(0); ++ fuzzyScaler.setIncrement(1); ++ fuzzyScaler.setPageIncrement(5); ++ fuzzyScaler.setSelection(Math.round((treeViewer != null ? treeViewer.getMatchingPrecision() : viewState.getMatchingPrecision())*100.f)); ++ fuzzyScaler.addListener (SWT.Selection, new Listener() { ++ public void handleEvent (Event event) { ++ float val = 1f-(Float.parseFloat( ++ (fuzzyScaler.getMaximum() - ++ fuzzyScaler.getSelection() + ++ fuzzyScaler.getMinimum()) + """") / 100.f); ++ treeViewer.setMatchingPrecision (val); ++ } ++ }); ++ fuzzyScaler.setSize(100, 10); ++ ++ GridData gdScalers = new GridData(); ++ gdScalers.verticalAlignment = SWT.BEGINNING; ++ gdScalers.horizontalAlignment = SWT.FILL; ++ gdScalers.horizontalSpan = 3; ++ fuzzyScaler.setLayoutData(gdScalers); ++ refreshSearchbarState(); ++ } ++ ++ protected void refreshSearchbarState () { ++ lblScale.setVisible(treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); ++ fuzzyScaler.setVisible(treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()); ++ if (treeViewer != null ? treeViewer.isFuzzyMatchingEnabled() : viewState.isFuzzyMatchingEnabled()) { ++ ((GridData)lblScale.getLayoutData()).heightHint = 40; ++ ((GridData)fuzzyScaler.getLayoutData()).heightHint = 40; ++ } else { ++ ((GridData)lblScale.getLayoutData()).heightHint = 0; ++ ((GridData)fuzzyScaler.getLayoutData()).heightHint = 0; ++ } ++ ++ lblScale.getParent().layout(); ++ lblScale.getParent().getParent().layout(); ++ } ++ ++ protected void initMessagesTree(Composite parent) { ++ if (viewState.getSelectedProjectName() != null && viewState.getSelectedProjectName().trim().length() > 0 ) { ++ try { ++ ResourceBundleManager.getManager(viewState.getSelectedProjectName()) ++ .registerResourceBundleChangeListener(viewState.getSelectedBundleId(), this); ++ ++ } catch (Exception e) {} ++ } ++ treeViewer = new PropertyKeySelectionTree(getViewSite(), getSite(), parent, SWT.NONE, ++ viewState.getSelectedProjectName(), viewState.getSelectedBundleId(), ++ viewState.getVisibleLocales()); ++ if (viewState.getSelectedProjectName() != null && viewState.getSelectedProjectName().trim().length() > 0 ) { ++ if (viewState.getVisibleLocales() == null) ++ viewState.setVisibleLocales(treeViewer.getVisibleLocales()); ++ ++ if (viewState.getSortings() != null) ++ treeViewer.setSortInfo(viewState.getSortings()); ++ ++ treeViewer.enableFuzzyMatching(viewState.isFuzzyMatchingEnabled()); ++ treeViewer.setMatchingPrecision(viewState.getMatchingPrecision()); ++ treeViewer.setEditable(viewState.isEditable()); ++ ++ if (viewState.getSearchString() != null) ++ treeViewer.setSearchString(viewState.getSearchString()); ++ } ++ // define the grid data for the layout ++ GridData gridData = new GridData(); ++ gridData.horizontalAlignment = SWT.FILL; ++ gridData.verticalAlignment = SWT.FILL; ++ gridData.grabExcessHorizontalSpace = true; ++ gridData.grabExcessVerticalSpace = true; ++ treeViewer.setLayoutData(gridData); ++ } ++ ++ /** ++ * Passing the focus request to the viewer's control. ++ */ ++ public void setFocus() { ++ treeViewer.setFocus(); ++ } ++ ++ protected void redrawTreeViewer () { ++ parent.setRedraw(false); ++ treeViewer.dispose(); ++ try { ++ initMessagesTree(parent); ++ makeActions(); ++ contributeToActionBars(); ++ hookContextMenu(); ++ } catch (Exception e) { ++ Logger.logError(e); ++ } ++ parent.setRedraw(true); ++ parent.layout(true); ++ treeViewer.layout(true); ++ refreshSearchbarState(); ++ } ++ ++ /*** ACTIONS ***/ ++ private void makeVisibleLocalesActions () { ++ if (viewState.getSelectedProjectName() == null) { ++ return; ++ } ++ ++ visibleLocaleActions = new ArrayList(); ++ Set locales = ResourceBundleManager.getManager( ++ viewState.getSelectedProjectName()).getProvidedLocales(viewState.getSelectedBundleId()); ++ List visibleLocales = treeViewer.getVisibleLocales(); ++ for (final Locale locale : locales) { ++ Action langAction = new Action () { ++ ++ @Override ++ public void run() { ++ super.run(); ++ List visibleL = treeViewer.getVisibleLocales(); ++ if (this.isChecked()) { ++ if (!visibleL.contains(locale)) { ++ visibleL.add(locale); ++ } ++ } else { ++ visibleL.remove(locale); ++ } ++ viewState.setVisibleLocales(visibleL); ++ redrawTreeViewer(); ++ } ++ ++ }; ++ if (locale != null && locale.getDisplayName().trim().length() > 0) { ++ langAction.setText(locale.getDisplayName(Locale.US)); ++ } else { ++ langAction.setText(""Default""); ++ } ++ langAction.setChecked(visibleLocales.contains(locale)); ++ visibleLocaleActions.add(langAction); ++ } ++ } ++ ++ private void makeActions() { ++ makeVisibleLocalesActions(); ++ ++ selectResourceBundle = new Action () { ++ ++ @Override ++ public void run() { ++ super.run(); ++ ResourceBundleSelectionDialog sd = new ResourceBundleSelectionDialog (getViewSite().getShell(), null); ++ if (sd.open() == InputDialog.OK) { ++ String resourceBundle = sd.getSelectedBundleId(); ++ ++ if (resourceBundle != null) { ++ int iSep = resourceBundle.indexOf(""/""); ++ viewState.setSelectedProjectName(resourceBundle.substring(0, iSep)); ++ viewState.setSelectedBundleId(resourceBundle.substring(iSep +1)); ++ viewState.setVisibleLocales(null); ++ redrawTreeViewer(); ++ } ++ } ++ } ++ }; ++ ++ selectResourceBundle.setText(""Resource-Bundle ...""); ++ selectResourceBundle.setDescription(""Allows you to select the Resource-Bundle which is used as message-source.""); ++ selectResourceBundle.setImageDescriptor(Activator.getImageDescriptor(ImageUtils.IMAGE_RESOURCE_BUNDLE)); ++ ++ contextDependentMenu = new ResourceBundleEntry(treeViewer, !treeViewer.getViewer().getSelection().isEmpty()); ++ ++ enableFuzzyMatching = new Action () { ++ public void run () { ++ super.run(); ++ treeViewer.enableFuzzyMatching(!treeViewer.isFuzzyMatchingEnabled()); ++ viewState.setFuzzyMatchingEnabled(treeViewer.isFuzzyMatchingEnabled()); ++ refreshSearchbarState(); ++ } ++ }; ++ enableFuzzyMatching.setText(""Fuzzy-Matching""); ++ enableFuzzyMatching.setDescription(""Enables Fuzzy matching for searching Resource-Bundle entries.""); ++ enableFuzzyMatching.setChecked(viewState.isFuzzyMatchingEnabled()); ++ enableFuzzyMatching.setToolTipText(enableFuzzyMatching.getDescription()); ++ ++ editable = new Action () { ++ public void run () { ++ super.run(); ++ treeViewer.setEditable(!treeViewer.isEditable()); ++ viewState.setEditable(treeViewer.isEditable()); ++ } ++ }; ++ editable.setText(""Editable""); ++ editable.setDescription(""Allows you to edit Resource-Bundle entries.""); ++ editable.setChecked(viewState.isEditable()); ++ editable.setToolTipText(editable.getDescription()); ++ } ++ ++ private void contributeToActionBars() { ++ IActionBars bars = getViewSite().getActionBars(); ++ fillLocalPullDown(bars.getMenuManager()); ++ fillLocalToolBar(bars.getToolBarManager()); ++ } ++ ++ private void fillLocalPullDown(IMenuManager manager) { ++ manager.removeAll(); ++ manager.add(selectResourceBundle); ++ manager.add(enableFuzzyMatching); ++ manager.add(editable); ++ manager.add(new Separator()); ++ ++ manager.add(contextDependentMenu); ++ manager.add(new Separator()); ++ ++ if (visibleLocaleActions == null) return; ++ ++ for (Action loc : visibleLocaleActions) { ++ manager.add(loc); ++ } ++ } ++ ++ /*** CONTEXT MENU ***/ ++ private void hookContextMenu() { ++ new UIJob(""set PopupMenu""){ ++ @Override ++ public IStatus runInUIThread(IProgressMonitor monitor) { ++ MenuManager menuMgr = new MenuManager(""#PopupMenu""); ++ menuMgr.setRemoveAllWhenShown(true); ++ menuMgr.addMenuListener(new IMenuListener() { ++ public void menuAboutToShow(IMenuManager manager) { ++ fillContextMenu(manager); ++ } ++ }); ++ Menu menu = menuMgr.createContextMenu(treeViewer.getViewer().getControl()); ++ treeViewer.getViewer().getControl().setMenu(menu); ++ getViewSite().registerContextMenu(menuMgr, treeViewer.getViewer()); ++ ++ return Status.OK_STATUS; ++ } ++ }.schedule(); ++ } ++ ++ private void fillContextMenu(IMenuManager manager) { ++ manager.removeAll(); ++ manager.add(selectResourceBundle); ++ manager.add(enableFuzzyMatching); ++ manager.add(editable); ++ manager.add(new Separator()); ++ ++ manager.add(new ResourceBundleEntry(treeViewer, !treeViewer.getViewer().getSelection().isEmpty())); ++ manager.add(new Separator()); ++ ++ for (Action loc : visibleLocaleActions) { ++ manager.add(loc); ++ } ++ // Other plug-ins can contribute there actions here ++ //manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); ++ } ++ ++ private void fillLocalToolBar(IToolBarManager manager) { ++ manager.add(selectResourceBundle); ++ } ++ ++ @Override ++ public void saveState (IMemento memento) { ++ super.saveState(memento); ++ try { ++ viewState.setEditable (treeViewer.isEditable()); ++ viewState.setSortings(treeViewer.getSortInfo()); ++ viewState.setSearchString(treeViewer.getSearchString()); ++ viewState.setFuzzyMatchingEnabled(treeViewer.isFuzzyMatchingEnabled()); ++ viewState.setMatchingPrecision (treeViewer.getMatchingPrecision()); ++ viewState.saveState(memento); ++ } catch (Exception e) {} ++ } ++ ++ @Override ++ public void init(IViewSite site, IMemento memento) throws PartInitException { ++ super.init(site, memento); ++ this.memento = memento; ++ ++ // init Viewstate ++ viewState = new MessagesViewState(null, null, false, null); ++ viewState.init(memento); ++ } ++ ++ @Override ++ public void resourceBundleChanged(ResourceBundleChangedEvent event) { ++ try { ++ if (!event.getBundle().equals(treeViewer.getResourceBundle())) ++ return; ++ ++ switch (event.getType()) { ++ /*case ResourceBundleChangedEvent.ADDED: ++ if ( viewState.getSelectedProjectName().trim().length() > 0 ) { ++ try { ++ ResourceBundleManager.getManager(viewState.getSelectedProjectName()) ++ .unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this); ++ } catch (Exception e) {} ++ } ++ ++ new Thread(new Runnable() { ++ ++ public void run() { ++ try { Thread.sleep(500); } catch (Exception e) { } ++ Display.getDefault().asyncExec(new Runnable() { ++ public void run() { ++ try { ++ redrawTreeViewer(); ++ } catch (Exception e) { e.printStackTrace(); } ++ } ++ }); ++ ++ } ++ }).start(); ++ break; */ ++ case ResourceBundleChangedEvent.ADDED: ++ // update visible locales within the context menu ++ makeVisibleLocalesActions(); ++ hookContextMenu(); ++ break; ++ case ResourceBundleChangedEvent.DELETED: ++ case ResourceBundleChangedEvent.EXCLUDED: ++ if ( viewState.getSelectedProjectName().trim().length() > 0 ) { ++ try { ++ ResourceBundleManager.getManager(viewState.getSelectedProjectName()) ++ .unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this); ++ ++ } catch (Exception e) {} ++ } ++ viewState = new MessagesViewState(null, null, false, null); ++ ++ new Thread(new Runnable() { ++ ++ public void run() { ++ try { Thread.sleep(500); } catch (Exception e) { } ++ Display.getDefault().asyncExec(new Runnable() { ++ public void run() { ++ try { ++ redrawTreeViewer(); ++ } catch (Exception e) { Logger.logError(e); } ++ } ++ }); ++ ++ } ++ }).start(); ++ } ++ } catch (Exception e) { ++ Logger.logError(e); ++ } ++ } ++ ++ @Override ++ public void dispose(){ ++ try { ++ super.dispose(); ++ treeViewer.dispose(); ++ ResourceBundleManager.getManager(viewState.getSelectedProjectName()).unregisterResourceBundleChangeListener(viewState.getSelectedBundleId(), this); ++ } catch (Exception e) {} ++ } ++} +\ No newline at end of file +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java +new file mode 100644 +index 00000000..b86f66c2 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/ResourceBundleEntry.java +@@ -0,0 +1,111 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview; ++ ++import org.eclipse.jface.action.ContributionItem; ++import org.eclipse.jface.viewers.ISelectionChangedListener; ++import org.eclipse.jface.viewers.SelectionChangedEvent; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.widgets.Menu; ++import org.eclipse.swt.widgets.MenuItem; ++import org.eclipse.ui.ISharedImages; ++import org.eclipse.ui.PlatformUI; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.PropertyKeySelectionTree; ++ ++ ++public class ResourceBundleEntry extends ContributionItem implements ++ ISelectionChangedListener { ++ ++ private PropertyKeySelectionTree parentView; ++ private boolean legalSelection = false; ++ ++ // Menu-Items ++ private MenuItem addItem; ++ private MenuItem editItem; ++ private MenuItem removeItem; ++ ++ public ResourceBundleEntry() { ++ } ++ ++ public ResourceBundleEntry(PropertyKeySelectionTree view, boolean legalSelection) { ++ this.legalSelection = legalSelection; ++ this.parentView = view; ++ parentView.addSelectionChangedListener(this); ++ } ++ ++ @Override ++ public void fill(Menu menu, int index) { ++ ++ // MenuItem for adding a new entry ++ addItem = new MenuItem(menu, SWT.NONE, index); ++ addItem.setText(""Add ...""); ++ addItem.setImage(PlatformUI.getWorkbench().getSharedImages() ++ .getImageDescriptor(ISharedImages.IMG_OBJ_ADD).createImage()); ++ addItem.addSelectionListener( new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ parentView.addNewItem(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ ++ } ++ }); ++ ++ if ((parentView == null && legalSelection) || parentView != null) { ++ // MenuItem for editing the currently selected entry ++ editItem = new MenuItem(menu, SWT.NONE, index + 1); ++ editItem.setText(""Edit""); ++ editItem.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ parentView.editSelectedItem(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ ++ } ++ }); ++ ++ // MenuItem for deleting the currently selected entry ++ removeItem = new MenuItem(menu, SWT.NONE, index + 2); ++ removeItem.setText(""Remove""); ++ removeItem.setImage(PlatformUI.getWorkbench().getSharedImages() ++ .getImageDescriptor(ISharedImages.IMG_ETOOL_DELETE) ++ .createImage()); ++ removeItem.addSelectionListener( new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ parentView.deleteSelectedItems(); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ ++ } ++ }); ++ enableMenuItems(); ++ } ++ } ++ ++ protected void enableMenuItems() { ++ try { ++ editItem.setEnabled(legalSelection); ++ removeItem.setEnabled(legalSelection); ++ } catch (Exception e) { ++ // silent catch ++ } ++ } ++ ++ @Override ++ public void selectionChanged(SelectionChangedEvent event) { ++ legalSelection = !event.getSelection().isEmpty(); ++ // enableMenuItems (); ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java +new file mode 100644 +index 00000000..e1aa4c64 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemDropTarget.java +@@ -0,0 +1,107 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd; ++ ++import org.eclipse.babel.editor.api.MessagesBundleFactory; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.swt.dnd.DND; ++import org.eclipse.swt.dnd.DropTargetAdapter; ++import org.eclipse.swt.dnd.DropTargetEvent; ++import org.eclipse.swt.dnd.TextTransfer; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.TreeItem; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.model.exception.ResourceBundleException; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++ ++public class KeyTreeItemDropTarget extends DropTargetAdapter { ++ private final TreeViewer target; ++ ++ public KeyTreeItemDropTarget (TreeViewer viewer) { ++ super(); ++ this.target = viewer; ++ } ++ ++ public void dragEnter (DropTargetEvent event) { ++// if (((DropTarget)event.getSource()).getControl() instanceof Tree) ++// event.detail = DND.DROP_MOVE; ++ } ++ ++ private void addBundleEntry (final String keyPrefix, // new prefix ++ final String key, // leaf ++ final String oldKey, // f.q. key ++ final IMessagesBundleGroup bundleGroup, ++ final boolean removeOld) { ++ ++ try { ++ String newKey = keyPrefix + ""."" + key; ++ boolean rem = keyPrefix.contains(oldKey) ? false : removeOld; ++ ++ for (IMessage message : bundleGroup.getMessages(oldKey)) { ++ IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(message.getLocale()); ++ IMessage m = MessagesBundleFactory.createMessage(newKey, message.getLocale()); ++ m.setText(message.getValue()); ++ m.setComment(message.getComment()); ++ messagesBundle.addMessage(m); ++ } ++ ++ if (rem) { ++ bundleGroup.removeMessages(oldKey); ++ } ++ ++ } catch (Exception e) { Logger.logError(e); } ++ ++ } ++ ++ public void drop (final DropTargetEvent event) { ++ Display.getDefault().asyncExec(new Runnable() { ++ public void run() { ++ try { ++ ++ if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) { ++ String newKeyPrefix = """"; ++ ++ if (event.item instanceof TreeItem && ++ ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { ++ newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item).getData()).getMessageKey(); ++ } ++ ++ String message = (String)event.data; ++ String oldKey = message.replaceAll(""\"""", """"); ++ ++ String[] keyArr = (oldKey).split(""\\.""); ++ String key = keyArr[keyArr.length-1]; ++ ++ ResKeyTreeContentProvider contentProvider = (ResKeyTreeContentProvider) target.getContentProvider(); ++ IAbstractKeyTreeModel keyTree = (IAbstractKeyTreeModel) target.getInput(); ++ ++ IMessagesBundleGroup bundleGroup = contentProvider.getBundle(); ++ if (!bundleGroup.containsKey(oldKey)) { ++ event.detail = DND.DROP_COPY; ++ return; ++ } ++ ++ // Adopt and add new bundle entries ++ addBundleEntry (newKeyPrefix, key, oldKey, bundleGroup, event.detail == DND.DROP_MOVE); ++ ++ // Store changes ++ ResourceBundleManager manager = contentProvider.getManager(); ++ try { ++ manager.saveResourceBundle(contentProvider.getBundleId(), bundleGroup); ++ } catch (ResourceBundleException e) { ++ Logger.logError(e); ++ } ++ ++ target.refresh(); ++ } else ++ event.detail = DND.DROP_NONE; ++ ++ } catch (Exception e) { Logger.logError(e); } ++ } ++ }); ++ } ++} +\ No newline at end of file +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java +new file mode 100644 +index 00000000..5bb6d5cd +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/KeyTreeItemTransfer.java +@@ -0,0 +1,106 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd; ++ ++import java.io.ByteArrayInputStream; ++import java.io.ByteArrayOutputStream; ++import java.io.IOException; ++import java.io.ObjectInputStream; ++import java.io.ObjectOutputStream; ++import java.util.ArrayList; ++import java.util.List; ++ ++import org.eclipse.swt.dnd.ByteArrayTransfer; ++import org.eclipse.swt.dnd.DND; ++import org.eclipse.swt.dnd.TransferData; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++ ++public class KeyTreeItemTransfer extends ByteArrayTransfer { ++ ++ private static final String KEY_TREE_ITEM = ""keyTreeItem""; ++ ++ private static final int TYPEID = registerType(KEY_TREE_ITEM); ++ ++ private static KeyTreeItemTransfer transfer = new KeyTreeItemTransfer(); ++ ++ public static KeyTreeItemTransfer getInstance() { ++ return transfer; ++ } ++ ++ public void javaToNative(Object object, TransferData transferData) { ++ if (!checkType(object) || !isSupportedType(transferData)) { ++ DND.error(DND.ERROR_INVALID_DATA); ++ } ++ IKeyTreeNode[] terms = (IKeyTreeNode[]) object; ++ try { ++ ByteArrayOutputStream out = new ByteArrayOutputStream(); ++ ObjectOutputStream oOut = new ObjectOutputStream(out); ++ for (int i = 0, length = terms.length; i < length; i++) { ++ oOut.writeObject(terms[i]); ++ } ++ byte[] buffer = out.toByteArray(); ++ oOut.close(); ++ ++ super.javaToNative(buffer, transferData); ++ } catch (IOException e) { ++ Logger.logError(e); ++ } ++ } ++ ++ public Object nativeToJava(TransferData transferData) { ++ if (isSupportedType(transferData)) { ++ ++ byte[] buffer; ++ try { ++ buffer = (byte[]) super.nativeToJava(transferData); ++ } catch (Exception e) { ++ Logger.logError(e); ++ buffer = null; ++ } ++ if (buffer == null) ++ return null; ++ ++ List terms = new ArrayList(); ++ try { ++ ByteArrayInputStream in = new ByteArrayInputStream(buffer); ++ ObjectInputStream readIn = new ObjectInputStream(in); ++ //while (readIn.available() > 0) { ++ IKeyTreeNode newTerm = (IKeyTreeNode) readIn.readObject(); ++ terms.add(newTerm); ++ //} ++ readIn.close(); ++ } catch (Exception ex) { ++ Logger.logError(ex); ++ return null; ++ } ++ return terms.toArray(new IKeyTreeNode[terms.size()]); ++ } ++ ++ return null; ++ } ++ ++ protected String[] getTypeNames() { ++ return new String[] { KEY_TREE_ITEM }; ++ } ++ ++ protected int[] getTypeIds() { ++ return new int[] { TYPEID }; ++ } ++ ++ boolean checkType(Object object) { ++ if (object == null || !(object instanceof IKeyTreeNode[]) ++ || ((IKeyTreeNode[]) object).length == 0) { ++ return false; ++ } ++ IKeyTreeNode[] myTypes = (IKeyTreeNode[]) object; ++ for (int i = 0; i < myTypes.length; i++) { ++ if (myTypes[i] == null) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ protected boolean validate(Object object) { ++ return checkType(object); ++ } ++} +\ No newline at end of file +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java +new file mode 100644 +index 00000000..dfbed204 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDragSource.java +@@ -0,0 +1,42 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd; ++ ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.swt.dnd.DragSourceEvent; ++import org.eclipse.swt.dnd.DragSourceListener; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++ ++public class MessagesDragSource implements DragSourceListener { ++ ++ private final TreeViewer source; ++ private String bundleId; ++ ++ public MessagesDragSource (TreeViewer sourceView, String bundleId) { ++ source = sourceView; ++ this.bundleId = bundleId; ++ } ++ ++ @Override ++ public void dragFinished(DragSourceEvent event) { ++ ++ } ++ ++ @Override ++ public void dragSetData(DragSourceEvent event) { ++ IKeyTreeNode selectionObject = (IKeyTreeNode) ++ ((IStructuredSelection)source.getSelection()).toList().get(0); ++ ++ String key = selectionObject.getMessageKey(); ++ ++ // TODO Solve the problem that its not possible to retrieve the editor position of the drop event ++ ++// event.data = ""(new ResourceBundle(\"""" + bundleId + ""\"")).getString(\"""" + key + ""\"")""; ++ event.data = ""\"""" + key + ""\""""; ++ } ++ ++ @Override ++ public void dragStart(DragSourceEvent event) { ++ event.doit = !source.getSelection().isEmpty(); ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java +new file mode 100644 +index 00000000..57a65ef5 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/views/messagesview/dnd/MessagesDropTarget.java +@@ -0,0 +1,58 @@ ++package org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd; ++ ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.swt.dnd.DND; ++import org.eclipse.swt.dnd.DropTargetAdapter; ++import org.eclipse.swt.dnd.DropTargetEvent; ++import org.eclipse.swt.dnd.TextTransfer; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.TreeItem; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++ ++public class MessagesDropTarget extends DropTargetAdapter { ++ private final TreeViewer target; ++ private final ResourceBundleManager manager; ++ private String bundleName; ++ ++ public MessagesDropTarget (TreeViewer viewer, ResourceBundleManager manager, String bundleName) { ++ super(); ++ target = viewer; ++ this.manager = manager; ++ this.bundleName = bundleName; ++ } ++ ++ public void dragEnter (DropTargetEvent event) { ++ } ++ ++ public void drop (DropTargetEvent event) { ++ if (event.detail != DND.DROP_COPY) ++ return; ++ ++ if (TextTransfer.getInstance().isSupportedType (event.currentDataType)) { ++ //event.feedback = DND.FEEDBACK_INSERT_BEFORE; ++ String newKeyPrefix = """"; ++ ++ if (event.item instanceof TreeItem && ++ ((TreeItem) event.item).getData() instanceof IValuedKeyTreeNode) { ++ newKeyPrefix = ((IValuedKeyTreeNode) ((TreeItem) event.item).getData()).getMessageKey(); ++ } ++ ++ String message = (String)event.data; ++ ++ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog( ++ Display.getDefault().getActiveShell(), ++ manager, ++ newKeyPrefix.trim().length() > 0 ? newKeyPrefix + ""."" + ""[Platzhalter]"" : """", ++ message, ++ bundleName, ++ """" ++ ); ++ if (dialog.open() != InputDialog.OK) ++ return; ++ } else ++ event.detail = DND.DROP_NONE; ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java +new file mode 100644 +index 00000000..c0af7f62 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/MVTextTransfer.java +@@ -0,0 +1,10 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets; ++ ++import org.eclipse.swt.dnd.TextTransfer; ++ ++public class MVTextTransfer { ++ ++ private MVTextTransfer () { ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java +new file mode 100644 +index 00000000..064dbf54 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/PropertyKeySelectionTree.java +@@ -0,0 +1,659 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets; ++ ++import java.util.ArrayList; ++import java.util.Iterator; ++import java.util.List; ++import java.util.Locale; ++import java.util.SortedMap; ++import java.util.TreeMap; ++ ++import org.eclipse.babel.core.message.manager.IMessagesEditorListener; ++import org.eclipse.babel.core.message.manager.RBManager; ++import org.eclipse.babel.editor.api.KeyTreeFactory; ++import org.eclipse.jdt.ui.JavaUI; ++import org.eclipse.jface.action.Action; ++import org.eclipse.jface.dialogs.InputDialog; ++import org.eclipse.jface.layout.TreeColumnLayout; ++import org.eclipse.jface.viewers.CellEditor; ++import org.eclipse.jface.viewers.ColumnWeightData; ++import org.eclipse.jface.viewers.DoubleClickEvent; ++import org.eclipse.jface.viewers.EditingSupport; ++import org.eclipse.jface.viewers.IDoubleClickListener; ++import org.eclipse.jface.viewers.IElementComparer; ++import org.eclipse.jface.viewers.ISelection; ++import org.eclipse.jface.viewers.ISelectionChangedListener; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.StructuredViewer; ++import org.eclipse.jface.viewers.TextCellEditor; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.jface.viewers.TreeViewerColumn; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.dnd.DND; ++import org.eclipse.swt.dnd.DragSource; ++import org.eclipse.swt.dnd.DropTarget; ++import org.eclipse.swt.dnd.TextTransfer; ++import org.eclipse.swt.dnd.Transfer; ++import org.eclipse.swt.events.KeyAdapter; ++import org.eclipse.swt.events.KeyEvent; ++import org.eclipse.swt.events.SelectionEvent; ++import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.swt.widgets.Tree; ++import org.eclipse.swt.widgets.TreeColumn; ++import org.eclipse.ui.IViewSite; ++import org.eclipse.ui.IWorkbenchPartSite; ++import org.eclipse.ui.IWorkbenchWindow; ++import org.eclipse.ui.PlatformUI; ++import org.eclipselabs.tapiji.tools.core.Logger; ++import org.eclipselabs.tapiji.tools.core.model.IResourceBundleChangedListener; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleChangedEvent; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.model.view.SortInfo; ++import org.eclipselabs.tapiji.tools.core.ui.dialogs.CreateResourceBundleEntryDialog; ++import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.KeyTreeItemDropTarget; ++import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDragSource; ++import org.eclipselabs.tapiji.tools.core.ui.views.messagesview.dnd.MessagesDropTarget; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.ExactMatcher; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FuzzyMatcher; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.sorter.ValuedKeyTreeItemSorter; ++import org.eclipselabs.tapiji.tools.core.util.EditorUtils; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType; ++ ++public class PropertyKeySelectionTree extends Composite implements IResourceBundleChangedListener { ++ ++ private final int KEY_COLUMN_WEIGHT = 1; ++ private final int LOCALE_COLUMN_WEIGHT = 1; ++ ++ private ResourceBundleManager manager; ++ private String resourceBundle; ++ private List visibleLocales = new ArrayList(); ++ private boolean editable; ++ ++ private IWorkbenchPartSite site; ++ private TreeColumnLayout basicLayout; ++ private TreeViewer treeViewer; ++ private TreeColumn keyColumn; ++ private boolean grouped = true; ++ private boolean fuzzyMatchingEnabled = false; ++ private float matchingPrecision = .75f; ++ private Locale uiLocale = new Locale(""en""); ++ ++ private SortInfo sortInfo; ++ ++ private ResKeyTreeContentProvider contentProvider; ++ private ResKeyTreeLabelProvider labelProvider; ++ private TreeType treeType = TreeType.Tree; ++ ++ private IMessagesEditorListener editorListener; ++ ++ /*** MATCHER ***/ ++ ExactMatcher matcher; ++ ++ /*** SORTER ***/ ++ ValuedKeyTreeItemSorter sorter; ++ ++ /*** ACTIONS ***/ ++ private Action doubleClickAction; ++ ++ /*** LISTENERS ***/ ++ private ISelectionChangedListener selectionChangedListener; ++ ++ public PropertyKeySelectionTree(IViewSite viewSite, IWorkbenchPartSite site, Composite parent, int style, ++ String projectName, String resources, List locales) { ++ super(parent, style); ++ this.site = site; ++ resourceBundle = resources; ++ ++ if (resourceBundle != null && resourceBundle.trim().length() > 0) { ++ manager = ResourceBundleManager.getManager(projectName); ++ if (locales == null) ++ initVisibleLocales(); ++ else ++ this.visibleLocales = locales; ++ } ++ ++ constructWidget(); ++ ++ if (resourceBundle != null && resourceBundle.trim().length() > 0) { ++ initTreeViewer(); ++ initMatchers(); ++ initSorters(); ++ treeViewer.expandAll(); ++ } ++ ++ hookDragAndDrop(); ++ registerListeners(); ++ } ++ ++ @Override ++ public void dispose() { ++ super.dispose(); ++ unregisterListeners(); ++ } ++ ++ protected void initSorters() { ++ sorter = new ValuedKeyTreeItemSorter(treeViewer, sortInfo); ++ treeViewer.setSorter(sorter); ++ } ++ ++ public void enableFuzzyMatching(boolean enable) { ++ String pattern = """"; ++ if (matcher != null) { ++ pattern = matcher.getPattern(); ++ ++ if (!fuzzyMatchingEnabled && enable) { ++ if (matcher.getPattern().trim().length() > 1 && matcher.getPattern().startsWith(""*"") ++ && matcher.getPattern().endsWith(""*"")) ++ pattern = pattern.substring(1).substring(0, pattern.length() - 2); ++ matcher.setPattern(null); ++ } ++ } ++ fuzzyMatchingEnabled = enable; ++ initMatchers(); ++ ++ matcher.setPattern(pattern); ++ treeViewer.refresh(); ++ } ++ ++ public boolean isFuzzyMatchingEnabled() { ++ return fuzzyMatchingEnabled; ++ } ++ ++ protected void initMatchers() { ++ treeViewer.resetFilters(); ++ ++ if (fuzzyMatchingEnabled) { ++ matcher = new FuzzyMatcher(treeViewer); ++ ((FuzzyMatcher) matcher).setMinimumSimilarity(matchingPrecision); ++ } else ++ matcher = new ExactMatcher(treeViewer); ++ ++ } ++ ++ protected void initTreeViewer() { ++ this.setRedraw(false); ++ // init content provider ++ contentProvider = new ResKeyTreeContentProvider(manager.getResourceBundle(resourceBundle), visibleLocales, ++ manager, resourceBundle, treeType); ++ treeViewer.setContentProvider(contentProvider); ++ ++ // init label provider ++ labelProvider = new ResKeyTreeLabelProvider(visibleLocales); ++ treeViewer.setLabelProvider(labelProvider); ++ ++ // we need this to keep the tree expanded ++ treeViewer.setComparer(new IElementComparer() { ++ ++ @Override ++ public int hashCode(Object element) { ++ final int prime = 31; ++ int result = 1; ++ result = prime * result ++ + ((toString() == null) ? 0 : toString().hashCode()); ++ return result; ++ } ++ ++ @Override ++ public boolean equals(Object a, Object b) { ++ if (a == b) { ++ return true; ++ } ++ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { ++ IKeyTreeNode nodeA = (IKeyTreeNode) a; ++ IKeyTreeNode nodeB = (IKeyTreeNode) b; ++ return nodeA.equals(nodeB); ++ } ++ return false; ++ } ++ }); ++ ++ setTreeStructure(); ++ this.setRedraw(true); ++ } ++ ++ public void setTreeStructure() { ++ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle)); ++ if (treeViewer.getInput() == null) { ++ treeViewer.setUseHashlookup(true); ++ } ++ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = treeViewer.getExpandedTreePaths(); ++ treeViewer.setInput(model); ++ treeViewer.refresh(); ++ treeViewer.setExpandedTreePaths(expandedTreePaths); ++ } ++ ++ protected void refreshContent(ResourceBundleChangedEvent event) { ++ if (visibleLocales == null) ++ initVisibleLocales(); ++ ++ // update content provider ++ contentProvider.setLocales(visibleLocales); ++ contentProvider.setBundleGroup(manager.getResourceBundle(resourceBundle)); ++ ++ // init label provider ++ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); ++ labelProvider.setLocales(visibleLocales); ++ if (treeViewer.getLabelProvider() != labelProvider) ++ treeViewer.setLabelProvider(labelProvider); ++ ++ // define input of treeviewer ++ setTreeStructure(); ++ } ++ ++ protected void initVisibleLocales() { ++ SortedMap locSorted = new TreeMap(); ++ sortInfo = new SortInfo(); ++ visibleLocales.clear(); ++ if (resourceBundle != null) { ++ for (Locale l : manager.getProvidedLocales(resourceBundle)) { ++ if (l == null) { ++ locSorted.put(""Default"", null); ++ } else { ++ locSorted.put(l.getDisplayName(uiLocale), l); ++ } ++ } ++ } ++ ++ for (String lString : locSorted.keySet()) { ++ visibleLocales.add(locSorted.get(lString)); ++ } ++ sortInfo.setVisibleLocales(visibleLocales); ++ } ++ ++ protected void constructWidget() { ++ basicLayout = new TreeColumnLayout(); ++ this.setLayout(basicLayout); ++ ++ treeViewer = new TreeViewer(this, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER); ++ Tree tree = treeViewer.getTree(); ++ ++ if (resourceBundle != null) { ++ tree.setHeaderVisible(true); ++ tree.setLinesVisible(true); ++ ++ // create tree-columns ++ constructTreeColumns(tree); ++ } else { ++ tree.setHeaderVisible(false); ++ tree.setLinesVisible(false); ++ } ++ ++ makeActions(); ++ hookDoubleClickAction(); ++ ++ // register messages table as selection provider ++ site.setSelectionProvider(treeViewer); ++ } ++ ++ protected void constructTreeColumns(Tree tree) { ++ tree.removeAll(); ++ //tree.getColumns().length; ++ ++ // construct key-column ++ keyColumn = new TreeColumn(tree, SWT.NONE); ++ keyColumn.setText(""Key""); ++ keyColumn.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSorter(0); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSorter(0); ++ } ++ }); ++ basicLayout.setColumnData(keyColumn, new ColumnWeightData(KEY_COLUMN_WEIGHT)); ++ ++ if (visibleLocales != null) { ++ for (final Locale l : visibleLocales) { ++ TreeColumn col = new TreeColumn(tree, SWT.NONE); ++ ++ // Add editing support to this table column ++ TreeViewerColumn tCol = new TreeViewerColumn(treeViewer, col); ++ tCol.setEditingSupport(new EditingSupport(treeViewer) { ++ ++ TextCellEditor editor = null; ++ ++ @Override ++ protected void setValue(Object element, Object value) { ++ if (element instanceof IValuedKeyTreeNode) { ++ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; ++ String activeKey = vkti.getMessageKey(); ++ ++ if (activeKey != null) { ++ IMessagesBundleGroup bundleGroup = manager.getResourceBundle(resourceBundle); ++ IMessage entry = bundleGroup.getMessage(activeKey, l); ++ ++ if (entry == null || !value.equals(entry.getValue())) { ++ String comment = null; ++ if (entry != null) { ++ comment = entry.getComment(); ++ } ++ ++ IMessagesBundle messagesBundle = bundleGroup.getMessagesBundle(l); ++ IMessage message = messagesBundle.getMessage(activeKey); ++ if (message != null) { ++ message.setText(String.valueOf(value)); ++ message.setComment(comment); ++ } ++ // TODO: find a better way ++ setTreeStructure(); ++ ++ } ++ } ++ } ++ } ++ ++ @Override ++ protected Object getValue(Object element) { ++ return labelProvider.getColumnText(element, visibleLocales.indexOf(l) + 1); ++ } ++ ++ @Override ++ protected CellEditor getCellEditor(Object element) { ++ if (editor == null) { ++ Composite tree = (Composite) treeViewer.getControl(); ++ editor = new TextCellEditor(tree); ++ } ++ return editor; ++ } ++ ++ @Override ++ protected boolean canEdit(Object element) { ++ return editable; ++ } ++ }); ++ ++ String displayName = l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayName(uiLocale); ++ ++ col.setText(displayName); ++ col.addSelectionListener(new SelectionListener() { ++ ++ @Override ++ public void widgetSelected(SelectionEvent e) { ++ updateSorter(visibleLocales.indexOf(l) + 1); ++ } ++ ++ @Override ++ public void widgetDefaultSelected(SelectionEvent e) { ++ updateSorter(visibleLocales.indexOf(l) + 1); ++ } ++ }); ++ basicLayout.setColumnData(col, new ColumnWeightData(LOCALE_COLUMN_WEIGHT)); ++ } ++ } ++ } ++ ++ protected void updateSorter(int idx) { ++ SortInfo sortInfo = sorter.getSortInfo(); ++ if (idx == sortInfo.getColIdx()) ++ sortInfo.setDESC(!sortInfo.isDESC()); ++ else { ++ sortInfo.setColIdx(idx); ++ sortInfo.setDESC(false); ++ } ++ sortInfo.setVisibleLocales(visibleLocales); ++ sorter.setSortInfo(sortInfo); ++ treeType = idx == 0 ? TreeType.Tree : TreeType.Flat; ++ setTreeStructure(); ++ treeViewer.refresh(); ++ } ++ ++ @Override ++ public boolean setFocus() { ++ return treeViewer.getControl().setFocus(); ++ } ++ ++ /*** DRAG AND DROP ***/ ++ protected void hookDragAndDrop() { ++ //KeyTreeItemDragSource ktiSource = new KeyTreeItemDragSource (treeViewer); ++ KeyTreeItemDropTarget ktiTarget = new KeyTreeItemDropTarget(treeViewer); ++ MessagesDragSource source = new MessagesDragSource(treeViewer, this.resourceBundle); ++ MessagesDropTarget target = new MessagesDropTarget(treeViewer, manager, resourceBundle); ++ ++ // Initialize drag source for copy event ++ DragSource dragSource = new DragSource(treeViewer.getControl(), DND.DROP_COPY | DND.DROP_MOVE); ++ dragSource.setTransfer(new Transfer[] { TextTransfer.getInstance() }); ++ //dragSource.addDragListener(ktiSource); ++ dragSource.addDragListener(source); ++ ++ // Initialize drop target for copy event ++ DropTarget dropTarget = new DropTarget(treeViewer.getControl(), DND.DROP_MOVE | DND.DROP_COPY); ++ dropTarget.setTransfer(new Transfer[] { TextTransfer.getInstance(), JavaUI.getJavaElementClipboardTransfer() }); ++ dropTarget.addDropListener(ktiTarget); ++ dropTarget.addDropListener(target); ++ } ++ ++ /*** ACTIONS ***/ ++ ++ private void makeActions() { ++ doubleClickAction = new Action() { ++ ++ @Override ++ public void run() { ++ editSelectedItem(); ++ } ++ ++ }; ++ } ++ ++ private void hookDoubleClickAction() { ++ treeViewer.addDoubleClickListener(new IDoubleClickListener() { ++ ++ public void doubleClick(DoubleClickEvent event) { ++ doubleClickAction.run(); ++ } ++ }); ++ } ++ ++ /*** SELECTION LISTENER ***/ ++ ++ protected void registerListeners() { ++ ++ this.editorListener = new MessagesEditorListener(); ++ if (manager != null) { ++ RBManager.getInstance(manager.getProject()).addMessagesEditorListener(editorListener); ++ } ++ ++ treeViewer.getControl().addKeyListener(new KeyAdapter() { ++ ++ public void keyPressed(KeyEvent event) { ++ if (event.character == SWT.DEL && event.stateMask == 0) { ++ deleteSelectedItems(); ++ } ++ } ++ }); ++ } ++ ++ protected void unregisterListeners() { ++ if (manager != null) { ++ RBManager.getInstance(manager.getProject()).removeMessagesEditorListener(editorListener); ++ } ++ treeViewer.removeSelectionChangedListener(selectionChangedListener); ++ } ++ ++ public void addSelectionChangedListener(ISelectionChangedListener listener) { ++ treeViewer.addSelectionChangedListener(listener); ++ selectionChangedListener = listener; ++ } ++ ++ @Override ++ public void resourceBundleChanged(final ResourceBundleChangedEvent event) { ++ if (event.getType() != ResourceBundleChangedEvent.MODIFIED ++ || !event.getBundle().equals(this.getResourceBundle())) ++ return; ++ ++ if (Display.getCurrent() != null) { ++ refreshViewer(event, true); ++ return; ++ } ++ ++ Display.getDefault().asyncExec(new Runnable() { ++ ++ public void run() { ++ refreshViewer(event, true); ++ } ++ }); ++ } ++ ++ private void refreshViewer(ResourceBundleChangedEvent event, boolean computeVisibleLocales) { ++ //manager.loadResourceBundle(resourceBundle); ++ if (computeVisibleLocales) { ++ refreshContent(event); ++ } ++ ++ // Display.getDefault().asyncExec(new Runnable() { ++ // public void run() { ++ treeViewer.refresh(); ++ // } ++ // }); ++ } ++ ++ public StructuredViewer getViewer() { ++ return this.treeViewer; ++ } ++ ++ public void setSearchString(String pattern) { ++ matcher.setPattern(pattern); ++ treeType = matcher.getPattern().trim().length() > 0 ? TreeType.Flat : TreeType.Tree; ++ labelProvider.setSearchEnabled(treeType.equals(TreeType.Flat)); ++ // WTF? ++ treeType = treeType.equals(TreeType.Tree) && sorter.getSortInfo().getColIdx() == 0 ? TreeType.Tree : TreeType.Flat; ++ treeViewer.refresh(); ++ } ++ ++ public SortInfo getSortInfo() { ++ if (this.sorter != null) ++ return this.sorter.getSortInfo(); ++ else ++ return null; ++ } ++ ++ public void setSortInfo(SortInfo sortInfo) { ++ sortInfo.setVisibleLocales(visibleLocales); ++ if (sorter != null) { ++ sorter.setSortInfo(sortInfo); ++ treeType = sortInfo.getColIdx() == 0 ? TreeType.Tree : TreeType.Flat; ++ treeViewer.refresh(); ++ } ++ } ++ ++ public String getSearchString() { ++ return matcher.getPattern(); ++ } ++ ++ public boolean isEditable() { ++ return editable; ++ } ++ ++ public void setEditable(boolean editable) { ++ this.editable = editable; ++ } ++ ++ public List getVisibleLocales() { ++ return visibleLocales; ++ } ++ ++ public ResourceBundleManager getManager() { ++ return this.manager; ++ } ++ ++ public String getResourceBundle() { ++ return resourceBundle; ++ } ++ ++ public void editSelectedItem() { ++ EditorUtils.openEditor(site.getPage(), manager.getRandomFile(resourceBundle), ++ EditorUtils.RESOURCE_BUNDLE_EDITOR); ++ } ++ ++ public void deleteSelectedItems() { ++ List keys = new ArrayList(); ++ ++ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ++ ISelection selection = window.getActivePage().getSelection(); ++ if (selection instanceof IStructuredSelection) { ++ for (Iterator iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) { ++ Object elem = iter.next(); ++ if (elem instanceof IKeyTreeNode) { ++ addKeysToRemove((IKeyTreeNode)elem, keys); ++ } ++ } ++ } ++ ++ try { ++ manager.removeResourceBundleEntry(getResourceBundle(), keys); ++ } catch (Exception ex) { ++ Logger.logError(ex); ++ } ++ } ++ ++ private void addKeysToRemove(IKeyTreeNode node, List keys) { ++ keys.add(node.getMessageKey()); ++ for (IKeyTreeNode ktn : node.getChildren()) { ++ addKeysToRemove(ktn, keys); ++ } ++ } ++ ++ public void addNewItem() { ++ //event.feedback = DND.FEEDBACK_INSERT_BEFORE; ++ String newKeyPrefix = """"; ++ ++ IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); ++ ISelection selection = window.getActivePage().getSelection(); ++ if (selection instanceof IStructuredSelection) { ++ for (Iterator iter = ((IStructuredSelection) selection).iterator(); iter.hasNext();) { ++ Object elem = iter.next(); ++ if (elem instanceof IKeyTreeNode) { ++ newKeyPrefix = ((IKeyTreeNode) elem).getMessageKey(); ++ break; ++ } ++ } ++ } ++ ++ CreateResourceBundleEntryDialog dialog = new CreateResourceBundleEntryDialog(Display.getDefault() ++ .getActiveShell(), manager, newKeyPrefix.trim().length() > 0 ? newKeyPrefix + ""."" + ""[Platzhalter]"" ++ : """", """", getResourceBundle(), """"); ++ if (dialog.open() != InputDialog.OK) ++ return; ++ } ++ ++ public void setMatchingPrecision(float value) { ++ matchingPrecision = value; ++ if (matcher instanceof FuzzyMatcher) { ++ ((FuzzyMatcher) matcher).setMinimumSimilarity(value); ++ treeViewer.refresh(); ++ } ++ } ++ ++ public float getMatchingPrecision() { ++ return matchingPrecision; ++ } ++ ++ private class MessagesEditorListener implements IMessagesEditorListener { ++ @Override ++ public void onSave() { ++ if (resourceBundle != null) { ++ setTreeStructure(); ++ } ++ } ++ ++ @Override ++ public void onModify() { ++ if (resourceBundle != null) { ++ setTreeStructure(); ++ } ++ } ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java +new file mode 100644 +index 00000000..544d52bf +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/ResourceSelector.java +@@ -0,0 +1,233 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets; ++ ++import java.util.HashSet; ++import java.util.Iterator; ++import java.util.Locale; ++import java.util.Set; ++ ++import org.eclipse.babel.editor.api.KeyTreeFactory; ++import org.eclipse.jface.layout.TreeColumnLayout; ++import org.eclipse.jface.viewers.ColumnWeightData; ++import org.eclipse.jface.viewers.IElementComparer; ++import org.eclipse.jface.viewers.ISelection; ++import org.eclipse.jface.viewers.ISelectionChangedListener; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.SelectionChangedEvent; ++import org.eclipse.jface.viewers.StyledCellLabelProvider; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Tree; ++import org.eclipse.swt.widgets.TreeColumn; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.listener.IResourceSelectionListener; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeContentProvider; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ResKeyTreeLabelProvider; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.provider.ValueKeyTreeLabelProvider; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType; ++ ++ ++public class ResourceSelector extends Composite { ++ ++ public static final int DISPLAY_KEYS = 0; ++ public static final int DISPLAY_TEXT = 1; ++ ++ private Locale displayLocale; ++ private int displayMode; ++ private String resourceBundle; ++ private ResourceBundleManager manager; ++ private boolean showTree; ++ ++ private TreeViewer viewer; ++ private TreeColumnLayout basicLayout; ++ private TreeColumn entries; ++ private Set listeners = new HashSet(); ++ ++ // Viewer model ++ private TreeType treeType = TreeType.Tree; ++ private StyledCellLabelProvider labelProvider; ++ ++ public ResourceSelector(Composite parent, ++ int style, ++ ResourceBundleManager manager, ++ String resourceBundle, ++ int displayMode, ++ Locale displayLocale, ++ boolean showTree) { ++ super(parent, style); ++ this.manager = manager; ++ this.resourceBundle = resourceBundle; ++ this.displayMode = displayMode; ++ this.displayLocale = displayLocale; ++ this.showTree = showTree; ++ this.treeType = showTree ? TreeType.Tree : TreeType.Flat; ++ ++ initLayout (this); ++ initViewer (this); ++ ++ updateViewer (true); ++ } ++ ++ protected void updateContentProvider (IMessagesBundleGroup group) { ++ // define input of treeviewer ++ if (!showTree || displayMode == DISPLAY_TEXT) { ++ treeType = TreeType.Flat; ++ } ++ ++ IAbstractKeyTreeModel model = KeyTreeFactory.createModel(manager.getResourceBundle(resourceBundle)); ++ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setBundleGroup(manager.getResourceBundle(resourceBundle)); ++ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType); ++ if (viewer.getInput() == null) { ++ viewer.setUseHashlookup(true); ++ } ++ ++// viewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS); ++ org.eclipse.jface.viewers.TreePath[] expandedTreePaths = viewer.getExpandedTreePaths(); ++ viewer.setInput(model); ++ viewer.refresh(); ++ viewer.setExpandedTreePaths(expandedTreePaths); ++ } ++ ++ protected void updateViewer (boolean updateContent) { ++ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); ++ ++ if (group == null) ++ return; ++ ++ if (displayMode == DISPLAY_TEXT) { ++ labelProvider = new ValueKeyTreeLabelProvider(group.getMessagesBundle(displayLocale)); ++ treeType = TreeType.Flat; ++ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType); ++ } else { ++ labelProvider = new ResKeyTreeLabelProvider(null); ++ treeType = TreeType.Tree; ++ ((ResKeyTreeContentProvider)viewer.getContentProvider()).setTreeType(treeType); ++ } ++ ++ viewer.setLabelProvider(labelProvider); ++ if (updateContent) ++ updateContentProvider(group); ++ } ++ ++ protected void initLayout (Composite parent) { ++ basicLayout = new TreeColumnLayout(); ++ parent.setLayout(basicLayout); ++ } ++ ++ protected void initViewer (Composite parent) { ++ viewer = new TreeViewer (parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION); ++ Tree table = viewer.getTree(); ++ ++ // Init table-columns ++ entries = new TreeColumn (table, SWT.NONE); ++ basicLayout.setColumnData(entries, new ColumnWeightData(1)); ++ ++ viewer.setContentProvider(new ResKeyTreeContentProvider()); ++ viewer.addSelectionChangedListener(new ISelectionChangedListener() { ++ ++ @Override ++ public void selectionChanged(SelectionChangedEvent event) { ++ ISelection selection = event.getSelection(); ++ String selectionSummary = """"; ++ String selectedKey = """"; ++ ++ if (selection instanceof IStructuredSelection) { ++ Iterator itSel = ((IStructuredSelection) selection).iterator(); ++ if (itSel.hasNext()) { ++ IKeyTreeNode selItem = itSel.next(); ++ IMessagesBundleGroup group = manager.getResourceBundle(resourceBundle); ++ selectedKey = selItem.getMessageKey(); ++ ++ if (group == null) ++ return; ++ Iterator itLocales = manager.getProvidedLocales(resourceBundle).iterator(); ++ while (itLocales.hasNext()) { ++ Locale l = itLocales.next(); ++ try { ++ selectionSummary += (l == null ? ResourceBundleManager.defaultLocaleTag : l.getDisplayLanguage()) + "":\n""; ++ selectionSummary += ""\t"" + group.getMessagesBundle(l).getMessage(selItem.getMessageKey()).getValue() + ""\n""; ++ } catch (Exception e) {} ++ } ++ } ++ } ++ ++ // construct ResourceSelectionEvent ++ ResourceSelectionEvent e = new ResourceSelectionEvent(selectedKey, selectionSummary); ++ fireSelectionChanged(e); ++ } ++ }); ++ ++ // we need this to keep the tree expanded ++ viewer.setComparer(new IElementComparer() { ++ ++ @Override ++ public int hashCode(Object element) { ++ final int prime = 31; ++ int result = 1; ++ result = prime * result ++ + ((toString() == null) ? 0 : toString().hashCode()); ++ return result; ++ } ++ ++ @Override ++ public boolean equals(Object a, Object b) { ++ if (a == b) { ++ return true; ++ } ++ if (a instanceof IKeyTreeNode && b instanceof IKeyTreeNode) { ++ IKeyTreeNode nodeA = (IKeyTreeNode) a; ++ IKeyTreeNode nodeB = (IKeyTreeNode) b; ++ return nodeA.equals(nodeB); ++ } ++ return false; ++ } ++ }); ++ } ++ ++ public Locale getDisplayLocale() { ++ return displayLocale; ++ } ++ ++ public void setDisplayLocale(Locale displayLocale) { ++ this.displayLocale = displayLocale; ++ updateViewer(false); ++ } ++ ++ public int getDisplayMode() { ++ return displayMode; ++ } ++ ++ public void setDisplayMode(int displayMode) { ++ this.displayMode = displayMode; ++ updateViewer(true); ++ } ++ ++ public void setResourceBundle(String resourceBundle) { ++ this.resourceBundle = resourceBundle; ++ updateViewer(true); ++ } ++ ++ public String getResourceBundle() { ++ return resourceBundle; ++ } ++ ++ public void addSelectionChangedListener (IResourceSelectionListener l) { ++ listeners.add(l); ++ } ++ ++ public void removeSelectionChangedListener (IResourceSelectionListener l) { ++ listeners.remove(l); ++ } ++ ++ private void fireSelectionChanged (ResourceSelectionEvent event) { ++ Iterator itResList = listeners.iterator(); ++ while (itResList.hasNext()) { ++ itResList.next().selectionChanged(event); ++ } ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java +new file mode 100644 +index 00000000..349c385c +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/event/ResourceSelectionEvent.java +@@ -0,0 +1,31 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.event; ++ ++public class ResourceSelectionEvent { ++ ++ private String selectionSummary; ++ private String selectedKey; ++ ++ public ResourceSelectionEvent (String selectedKey, String selectionSummary) { ++ this.setSelectionSummary(selectionSummary); ++ this.setSelectedKey(selectedKey); ++ } ++ ++ public void setSelectedKey (String key) { ++ selectedKey = key; ++ } ++ ++ public void setSelectionSummary(String selectionSummary) { ++ this.selectionSummary = selectionSummary; ++ } ++ ++ public String getSelectionSummary() { ++ return selectionSummary; ++ } ++ ++ public String getSelectedKey() { ++ return selectedKey; ++ } ++ ++ ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java +new file mode 100644 +index 00000000..6d83fc3c +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/ExactMatcher.java +@@ -0,0 +1,77 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.filter; ++ ++import java.util.Locale; ++ ++import org.eclipse.jface.viewers.StructuredViewer; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.jface.viewers.ViewerFilter; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++ ++public class ExactMatcher extends ViewerFilter { ++ ++ protected final StructuredViewer viewer; ++ protected String pattern = """"; ++ protected StringMatcher matcher; ++ ++ public ExactMatcher (StructuredViewer viewer) { ++ this.viewer = viewer; ++ } ++ ++ public String getPattern () { ++ return pattern; ++ } ++ ++ public void setPattern (String p) { ++ boolean filtering = matcher != null; ++ if (p != null && p.trim().length() > 0) { ++ pattern = p; ++ matcher = new StringMatcher (""*"" + pattern + ""*"", true, false); ++ if (!filtering) ++ viewer.addFilter(this); ++ else ++ viewer.refresh(); ++ } else { ++ pattern = """"; ++ matcher = null; ++ if (filtering) { ++ viewer.removeFilter(this); ++ } ++ } ++ } ++ ++ @Override ++ public boolean select(Viewer viewer, Object parentElement, Object element) { ++ IValuedKeyTreeNode vEle = (IValuedKeyTreeNode) element; ++ FilterInfo filterInfo = new FilterInfo(); ++ boolean selected = matcher.match(vEle.getMessageKey()); ++ ++ if (selected) { ++ int start = -1; ++ while ((start = vEle.getMessageKey().toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) { ++ filterInfo.addKeyOccurrence(start, pattern.length()); ++ } ++ filterInfo.setFoundInKey(selected); ++ filterInfo.setFoundInKey(true); ++ } else ++ filterInfo.setFoundInKey(false); ++ ++ // Iterate translations ++ for (Locale l : vEle.getLocales()) { ++ String value = vEle.getValue(l); ++ if (matcher.match(value)) { ++ filterInfo.addFoundInLocale(l); ++ filterInfo.addSimilarity(l, 1d); ++ int start = -1; ++ while ((start = value.toLowerCase().indexOf(pattern.toLowerCase(), start+1)) >= 0) { ++ filterInfo.addFoundInLocaleRange(l, start, pattern.length()); ++ } ++ selected = true; ++ } ++ } ++ ++ vEle.setInfo(filterInfo); ++ return selected; ++ } ++ ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java +new file mode 100644 +index 00000000..cb02d50f +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FilterInfo.java +@@ -0,0 +1,85 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.filter; ++ ++import java.util.ArrayList; ++import java.util.HashMap; ++import java.util.List; ++import java.util.Locale; ++import java.util.Map; ++ ++import org.eclipse.jface.text.IRegion; ++import org.eclipse.jface.text.Region; ++ ++public class FilterInfo { ++ ++ private boolean foundInKey; ++ private List foundInLocales = new ArrayList (); ++ private List keyOccurrences = new ArrayList (); ++ private Double keySimilarity; ++ private Map> occurrences = new HashMap>(); ++ private Map localeSimilarity = new HashMap(); ++ ++ public FilterInfo() { ++ ++ } ++ ++ public void setKeySimilarity (Double similarity) { ++ keySimilarity = similarity; ++ } ++ ++ public Double getKeySimilarity () { ++ return keySimilarity; ++ } ++ ++ public void addSimilarity (Locale l, Double similarity) { ++ localeSimilarity.put (l, similarity); ++ } ++ ++ public Double getSimilarityLevel (Locale l) { ++ return localeSimilarity.get(l); ++ } ++ ++ public void setFoundInKey(boolean foundInKey) { ++ this.foundInKey = foundInKey; ++ } ++ ++ public boolean isFoundInKey() { ++ return foundInKey; ++ } ++ ++ public void addFoundInLocale (Locale loc) { ++ foundInLocales.add(loc); ++ } ++ ++ public void removeFoundInLocale (Locale loc) { ++ foundInLocales.remove(loc); ++ } ++ ++ public void clearFoundInLocale () { ++ foundInLocales.clear(); ++ } ++ ++ public boolean hasFoundInLocale (Locale l) { ++ return foundInLocales.contains(l); ++ } ++ ++ public List getFoundInLocaleRanges (Locale locale) { ++ List reg = occurrences.get(locale); ++ return (reg == null ? new ArrayList() : reg); ++ } ++ ++ public void addFoundInLocaleRange (Locale locale, int start, int length) { ++ List regions = occurrences.get(locale); ++ if (regions == null) ++ regions = new ArrayList(); ++ regions.add(new Region(start, length)); ++ occurrences.put(locale, regions); ++ } ++ ++ public List getKeyOccurrences () { ++ return keyOccurrences; ++ } ++ ++ public void addKeyOccurrence (int start, int length) { ++ keyOccurrences.add(new Region (start, length)); ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java +new file mode 100644 +index 00000000..227a2ba0 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/FuzzyMatcher.java +@@ -0,0 +1,54 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.filter; ++ ++import java.util.Locale; ++ ++import org.eclipse.babel.editor.api.AnalyzerFactory; ++import org.eclipse.jface.viewers.StructuredViewer; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.model.analyze.ILevenshteinDistanceAnalyzer; ++ ++public class FuzzyMatcher extends ExactMatcher { ++ ++ protected ILevenshteinDistanceAnalyzer lvda; ++ protected float minimumSimilarity = 0.75f; ++ ++ public FuzzyMatcher(StructuredViewer viewer) { ++ super(viewer); ++ lvda = AnalyzerFactory.getLevenshteinDistanceAnalyzer();; ++ } ++ ++ public double getMinimumSimilarity () { ++ return minimumSimilarity; ++ } ++ ++ public void setMinimumSimilarity (float similarity) { ++ this.minimumSimilarity = similarity; ++ } ++ ++ @Override ++ public boolean select(Viewer viewer, Object parentElement, Object element) { ++ boolean exactMatch = super.select(viewer, parentElement, element); ++ boolean match = exactMatch; ++ ++ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; ++ FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); ++ ++ for (Locale l : vkti.getLocales()) { ++ String value = vkti.getValue(l); ++ if (filterInfo.hasFoundInLocale(l)) ++ continue; ++ double dist = lvda.analyse(value, getPattern()); ++ if (dist >= minimumSimilarity) { ++ filterInfo.addFoundInLocale(l); ++ filterInfo.addSimilarity(l, dist); ++ match = true; ++ filterInfo.addFoundInLocaleRange(l, 0, value.length()); ++ } ++ } ++ ++ vkti.setInfo(filterInfo); ++ return match; ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java +new file mode 100644 +index 00000000..d48ea0e9 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/filter/StringMatcher.java +@@ -0,0 +1,441 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.filter; ++ ++import java.util.Vector; ++ ++/** ++ * A string pattern matcher, suppporting ""*"" and ""?"" wildcards. ++ */ ++public class StringMatcher { ++ protected String fPattern; ++ ++ protected int fLength; // pattern length ++ ++ protected boolean fIgnoreWildCards; ++ ++ protected boolean fIgnoreCase; ++ ++ protected boolean fHasLeadingStar; ++ ++ protected boolean fHasTrailingStar; ++ ++ protected String fSegments[]; //the given pattern is split into * separated segments ++ ++ /* boundary value beyond which we don't need to search in the text */ ++ protected int fBound = 0; ++ ++ protected static final char fSingleWildCard = '\u0000'; ++ ++ public static class Position { ++ int start; //inclusive ++ ++ int end; //exclusive ++ ++ public Position(int start, int end) { ++ this.start = start; ++ this.end = end; ++ } ++ ++ public int getStart() { ++ return start; ++ } ++ ++ public int getEnd() { ++ return end; ++ } ++ } ++ ++ /** ++ * StringMatcher constructor takes in a String object that is a simple ++ * pattern which may contain '*' for 0 and many characters and ++ * '?' for exactly one character. ++ * ++ * Literal '*' and '?' characters must be escaped in the pattern ++ * e.g., ""\*"" means literal ""*"", etc. ++ * ++ * Escaping any other character (including the escape character itself), ++ * just results in that character in the pattern. ++ * e.g., ""\a"" means ""a"" and ""\\"" means ""\"" ++ * ++ * If invoking the StringMatcher with string literals in Java, don't forget ++ * escape characters are represented by ""\\"". ++ * ++ * @param pattern the pattern to match text against ++ * @param ignoreCase if true, case is ignored ++ * @param ignoreWildCards if true, wild cards and their escape sequences are ignored ++ * (everything is taken literally). ++ */ ++ public StringMatcher(String pattern, boolean ignoreCase, ++ boolean ignoreWildCards) { ++ if (pattern == null) { ++ throw new IllegalArgumentException(); ++ } ++ fIgnoreCase = ignoreCase; ++ fIgnoreWildCards = ignoreWildCards; ++ fPattern = pattern; ++ fLength = pattern.length(); ++ ++ if (fIgnoreWildCards) { ++ parseNoWildCards(); ++ } else { ++ parseWildCards(); ++ } ++ } ++ ++ /** ++ * Find the first occurrence of the pattern between startend(exclusive). ++ * @param text the String object to search in ++ * @param start the starting index of the search range, inclusive ++ * @param end the ending index of the search range, exclusive ++ * @return an StringMatcher.Position object that keeps the starting ++ * (inclusive) and ending positions (exclusive) of the first occurrence of the ++ * pattern in the specified range of the text; return null if not found or subtext ++ * is empty (start==end). A pair of zeros is returned if pattern is empty string ++ * Note that for pattern like ""*abc*"" with leading and trailing stars, position of ""abc"" ++ * is returned. For a pattern like""*??*"" in text ""abcdf"", (1,3) is returned ++ */ ++ public StringMatcher.Position find(String text, int start, int end) { ++ if (text == null) { ++ throw new IllegalArgumentException(); ++ } ++ ++ int tlen = text.length(); ++ if (start < 0) { ++ start = 0; ++ } ++ if (end > tlen) { ++ end = tlen; ++ } ++ if (end < 0 || start >= end) { ++ return null; ++ } ++ if (fLength == 0) { ++ return new Position(start, start); ++ } ++ if (fIgnoreWildCards) { ++ int x = posIn(text, start, end); ++ if (x < 0) { ++ return null; ++ } ++ return new Position(x, x + fLength); ++ } ++ ++ int segCount = fSegments.length; ++ if (segCount == 0) { ++ return new Position(start, end); ++ } ++ ++ int curPos = start; ++ int matchStart = -1; ++ int i; ++ for (i = 0; i < segCount && curPos < end; ++i) { ++ String current = fSegments[i]; ++ int nextMatch = regExpPosIn(text, curPos, end, current); ++ if (nextMatch < 0) { ++ return null; ++ } ++ if (i == 0) { ++ matchStart = nextMatch; ++ } ++ curPos = nextMatch + current.length(); ++ } ++ if (i < segCount) { ++ return null; ++ } ++ return new Position(matchStart, curPos); ++ } ++ ++ /** ++ * match the given text with the pattern ++ * @return true if matched otherwise false ++ * @param text a String object ++ */ ++ public boolean match(String text) { ++ if(text == null) { ++ return false; ++ } ++ return match(text, 0, text.length()); ++ } ++ ++ /** ++ * Given the starting (inclusive) and the ending (exclusive) positions in the ++ * text, determine if the given substring matches with aPattern ++ * @return true if the specified portion of the text matches the pattern ++ * @param text a String object that contains the substring to match ++ * @param start marks the starting position (inclusive) of the substring ++ * @param end marks the ending index (exclusive) of the substring ++ */ ++ public boolean match(String text, int start, int end) { ++ if (null == text) { ++ throw new IllegalArgumentException(); ++ } ++ ++ if (start > end) { ++ return false; ++ } ++ ++ if (fIgnoreWildCards) { ++ return (end - start == fLength) ++ && fPattern.regionMatches(fIgnoreCase, 0, text, start, ++ fLength); ++ } ++ int segCount = fSegments.length; ++ if (segCount == 0 && (fHasLeadingStar || fHasTrailingStar)) { ++ return true; ++ } ++ if (start == end) { ++ return fLength == 0; ++ } ++ if (fLength == 0) { ++ return start == end; ++ } ++ ++ int tlen = text.length(); ++ if (start < 0) { ++ start = 0; ++ } ++ if (end > tlen) { ++ end = tlen; ++ } ++ ++ int tCurPos = start; ++ int bound = end - fBound; ++ if (bound < 0) { ++ return false; ++ } ++ int i = 0; ++ String current = fSegments[i]; ++ int segLength = current.length(); ++ ++ /* process first segment */ ++ if (!fHasLeadingStar) { ++ if (!regExpRegionMatches(text, start, current, 0, segLength)) { ++ return false; ++ } else { ++ ++i; ++ tCurPos = tCurPos + segLength; ++ } ++ } ++ if ((fSegments.length == 1) && (!fHasLeadingStar) ++ && (!fHasTrailingStar)) { ++ // only one segment to match, no wildcards specified ++ return tCurPos == end; ++ } ++ /* process middle segments */ ++ while (i < segCount) { ++ current = fSegments[i]; ++ int currentMatch; ++ int k = current.indexOf(fSingleWildCard); ++ if (k < 0) { ++ currentMatch = textPosIn(text, tCurPos, end, current); ++ if (currentMatch < 0) { ++ return false; ++ } ++ } else { ++ currentMatch = regExpPosIn(text, tCurPos, end, current); ++ if (currentMatch < 0) { ++ return false; ++ } ++ } ++ tCurPos = currentMatch + current.length(); ++ i++; ++ } ++ ++ /* process final segment */ ++ if (!fHasTrailingStar && tCurPos != end) { ++ int clen = current.length(); ++ return regExpRegionMatches(text, end - clen, current, 0, clen); ++ } ++ return i == segCount; ++ } ++ ++ /** ++ * This method parses the given pattern into segments seperated by wildcard '*' characters. ++ * Since wildcards are not being used in this case, the pattern consists of a single segment. ++ */ ++ private void parseNoWildCards() { ++ fSegments = new String[1]; ++ fSegments[0] = fPattern; ++ fBound = fLength; ++ } ++ ++ /** ++ * Parses the given pattern into segments seperated by wildcard '*' characters. ++ * @param p, a String object that is a simple regular expression with '*' and/or '?' ++ */ ++ private void parseWildCards() { ++ if (fPattern.startsWith(""*"")) { //$NON-NLS-1$ ++ fHasLeadingStar = true; ++ } ++ if (fPattern.endsWith(""*"")) {//$NON-NLS-1$ ++ /* make sure it's not an escaped wildcard */ ++ if (fLength > 1 && fPattern.charAt(fLength - 2) != '\\') { ++ fHasTrailingStar = true; ++ } ++ } ++ ++ Vector temp = new Vector(); ++ ++ int pos = 0; ++ StringBuffer buf = new StringBuffer(); ++ while (pos < fLength) { ++ char c = fPattern.charAt(pos++); ++ switch (c) { ++ case '\\': ++ if (pos >= fLength) { ++ buf.append(c); ++ } else { ++ char next = fPattern.charAt(pos++); ++ /* if it's an escape sequence */ ++ if (next == '*' || next == '?' || next == '\\') { ++ buf.append(next); ++ } else { ++ /* not an escape sequence, just insert literally */ ++ buf.append(c); ++ buf.append(next); ++ } ++ } ++ break; ++ case '*': ++ if (buf.length() > 0) { ++ /* new segment */ ++ temp.addElement(buf.toString()); ++ fBound += buf.length(); ++ buf.setLength(0); ++ } ++ break; ++ case '?': ++ /* append special character representing single match wildcard */ ++ buf.append(fSingleWildCard); ++ break; ++ default: ++ buf.append(c); ++ } ++ } ++ ++ /* add last buffer to segment list */ ++ if (buf.length() > 0) { ++ temp.addElement(buf.toString()); ++ fBound += buf.length(); ++ } ++ ++ fSegments = new String[temp.size()]; ++ temp.copyInto(fSegments); ++ } ++ ++ /** ++ * @param text a string which contains no wildcard ++ * @param start the starting index in the text for search, inclusive ++ * @param end the stopping point of search, exclusive ++ * @return the starting index in the text of the pattern , or -1 if not found ++ */ ++ protected int posIn(String text, int start, int end) {//no wild card in pattern ++ int max = end - fLength; ++ ++ if (!fIgnoreCase) { ++ int i = text.indexOf(fPattern, start); ++ if (i == -1 || i > max) { ++ return -1; ++ } ++ return i; ++ } ++ ++ for (int i = start; i <= max; ++i) { ++ if (text.regionMatches(true, i, fPattern, 0, fLength)) { ++ return i; ++ } ++ } ++ ++ return -1; ++ } ++ ++ /** ++ * @param text a simple regular expression that may only contain '?'(s) ++ * @param start the starting index in the text for search, inclusive ++ * @param end the stopping point of search, exclusive ++ * @param p a simple regular expression that may contains '?' ++ * @return the starting index in the text of the pattern , or -1 if not found ++ */ ++ protected int regExpPosIn(String text, int start, int end, String p) { ++ int plen = p.length(); ++ ++ int max = end - plen; ++ for (int i = start; i <= max; ++i) { ++ if (regExpRegionMatches(text, i, p, 0, plen)) { ++ return i; ++ } ++ } ++ return -1; ++ } ++ ++ /** ++ * ++ * @return boolean ++ * @param text a String to match ++ * @param start int that indicates the starting index of match, inclusive ++ * @param end int that indicates the ending index of match, exclusive ++ * @param p String, String, a simple regular expression that may contain '?' ++ * @param ignoreCase boolean indicating wether code>p is case sensitive ++ */ ++ protected boolean regExpRegionMatches(String text, int tStart, String p, ++ int pStart, int plen) { ++ while (plen-- > 0) { ++ char tchar = text.charAt(tStart++); ++ char pchar = p.charAt(pStart++); ++ ++ /* process wild cards */ ++ if (!fIgnoreWildCards) { ++ /* skip single wild cards */ ++ if (pchar == fSingleWildCard) { ++ continue; ++ } ++ } ++ if (pchar == tchar) { ++ continue; ++ } ++ if (fIgnoreCase) { ++ if (Character.toUpperCase(tchar) == Character ++ .toUpperCase(pchar)) { ++ continue; ++ } ++ // comparing after converting to upper case doesn't handle all cases; ++ // also compare after converting to lower case ++ if (Character.toLowerCase(tchar) == Character ++ .toLowerCase(pchar)) { ++ continue; ++ } ++ } ++ return false; ++ } ++ return true; ++ } ++ ++ /** ++ * @param text the string to match ++ * @param start the starting index in the text for search, inclusive ++ * @param end the stopping point of search, exclusive ++ * @param p a pattern string that has no wildcard ++ * @return the starting index in the text of the pattern , or -1 if not found ++ */ ++ protected int textPosIn(String text, int start, int end, String p) { ++ ++ int plen = p.length(); ++ int max = end - plen; ++ ++ if (!fIgnoreCase) { ++ int i = text.indexOf(p, start); ++ if (i == -1 || i > max) { ++ return -1; ++ } ++ return i; ++ } ++ ++ for (int i = start; i <= max; ++i) { ++ if (text.regionMatches(true, i, p, 0, plen)) { ++ return i; ++ } ++ } ++ ++ return -1; ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java +new file mode 100644 +index 00000000..7cb6f96d +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/listener/IResourceSelectionListener.java +@@ -0,0 +1,9 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.listener; ++ ++import org.eclipselabs.tapiji.tools.core.ui.widgets.event.ResourceSelectionEvent; ++ ++public interface IResourceSelectionListener { ++ ++ public void selectionChanged (ResourceSelectionEvent e); ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java +new file mode 100644 +index 00000000..62d1aa3b +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/KeyTreeLabelProvider.java +@@ -0,0 +1,166 @@ ++ /* +++ * Copyright (C) 2003, 2004 Pascal Essiembre, Essiembre Consultant Inc. ++ * ++ * This file is part of Essiembre ResourceBundle Editor. ++ * ++ * Essiembre ResourceBundle Editor is free software; you can redistribute it ++ * and/or modify it under the terms of the GNU Lesser General Public ++ * License as published by the Free Software Foundation; either ++ * version 2.1 of the License, or (at your option) any later version. ++ * ++ * Essiembre ResourceBundle Editor is distributed in the hope that it will be ++ * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ++ * Lesser General Public License for more details. ++ * ++ * You should have received a copy of the GNU Lesser General Public ++ * License along with Essiembre ResourceBundle Editor; if not, write to the ++ * Free Software Foundation, Inc., 59 Temple Place, Suite 330, ++ * Boston, MA 02111-1307 USA ++ */ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.provider; ++ ++import org.eclipse.jface.resource.ImageRegistry; ++import org.eclipse.jface.viewers.ILabelProvider; ++import org.eclipse.jface.viewers.StyledCellLabelProvider; ++import org.eclipse.jface.viewers.ViewerCell; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.graphics.Font; ++import org.eclipse.swt.graphics.Image; ++import org.eclipselabs.tapiji.tools.core.Activator; ++import org.eclipselabs.tapiji.tools.core.util.FontUtils; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++ ++/** ++ * Label provider for key tree viewer. ++ * @author Pascal Essiembre (essiembre@users.sourceforge.net) ++ * @version $Author: nl_carnage $ $Revision: 1.11 $ $Date: 2007/09/11 16:11:09 $ ++ */ ++public class KeyTreeLabelProvider ++ extends StyledCellLabelProvider /*implements IFontProvider, IColorProvider*/ { ++ ++ private static final int KEY_DEFAULT = 1 << 1; ++ private static final int KEY_COMMENTED = 1 << 2; ++ private static final int KEY_NOT = 1 << 3; ++ private static final int WARNING = 1 << 4; ++ private static final int WARNING_GREY = 1 << 5; ++ ++ /** Registry instead of UIUtils one for image not keyed by file name. */ ++ private static ImageRegistry imageRegistry = new ImageRegistry(); ++ ++ private Color commentedColor = FontUtils.getSystemColor(SWT.COLOR_GRAY); ++ ++ /** Group font. */ ++ private Font groupFontKey = FontUtils.createFont(SWT.BOLD); ++ private Font groupFontNoKey = FontUtils.createFont(SWT.BOLD | SWT.ITALIC); ++ ++ ++ /** ++ * @see ILabelProvider#getImage(Object) ++ */ ++ public Image getImage(Object element) { ++ IKeyTreeNode treeItem = ((IKeyTreeNode) element); ++ ++ int iconFlags = 0; ++ ++ // Figure out background icon ++ if (treeItem.getMessagesBundleGroup() != null && ++ treeItem.getMessagesBundleGroup().isKey(treeItem.getMessageKey())) { ++ iconFlags += KEY_DEFAULT; ++ } else { ++ iconFlags += KEY_NOT; ++ } ++ ++ return generateImage(iconFlags); ++ } ++ ++ /** ++ * @see ILabelProvider#getText(Object) ++ */ ++ public String getText(Object element) { ++ return ((IKeyTreeNode) element).getName(); ++ } ++ ++ /** ++ * @see org.eclipse.jface.viewers.IBaseLabelProvider#dispose() ++ */ ++ public void dispose() { ++ groupFontKey.dispose(); ++ groupFontNoKey.dispose(); ++ } ++ ++ /** ++ * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object) ++ */ ++ public Font getFont(Object element) { ++ IKeyTreeNode item = (IKeyTreeNode) element; ++ if (item.getChildren().length > 0 && item.getMessagesBundleGroup() != null) { ++ if (item.getMessagesBundleGroup().isKey(item.getMessageKey())) { ++ return groupFontKey; ++ } ++ return groupFontNoKey; ++ } ++ return null; ++ } ++ ++ /** ++ * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object) ++ */ ++ public Color getForeground(Object element) { ++ IKeyTreeNode treeItem = (IKeyTreeNode) element; ++ return null; ++ } ++ ++ /** ++ * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object) ++ */ ++ public Color getBackground(Object element) { ++ // TODO Auto-generated method stub ++ return null; ++ } ++ ++ /** ++ * Generates an image based on icon flags. ++ * @param iconFlags ++ * @return generated image ++ */ ++ private Image generateImage(int iconFlags) { ++ Image image = imageRegistry.get("""" + iconFlags); //$NON-NLS-1$ ++ if (image == null) { ++ // Figure background image ++ if ((iconFlags & KEY_COMMENTED) != 0) { ++ image = getRegistryImage(""keyCommented.gif""); //$NON-NLS-1$ ++ } else if ((iconFlags & KEY_NOT) != 0) { ++ image = getRegistryImage(""key.gif""); //$NON-NLS-1$ ++ } else { ++ image = getRegistryImage(""key.gif""); //$NON-NLS-1$ ++ } ++ ++ } ++ return image; ++ } ++ ++ ++ private Image getRegistryImage(String imageName) { ++ Image image = imageRegistry.get(imageName); ++ if (image == null) { ++ image = Activator.getImageDescriptor(imageName).createImage(); ++ imageRegistry.put(imageName, image); ++ } ++ return image; ++ } ++ ++ @Override ++ public void update(ViewerCell cell) { ++ cell.setBackground(getBackground(cell.getElement())); ++ cell.setFont(getFont(cell.getElement())); ++ cell.setForeground(getForeground(cell.getElement())); ++ ++ cell.setText(getText(cell.getElement())); ++ cell.setImage(getImage(cell.getElement())); ++ super.update(cell); ++ } ++ ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java +new file mode 100644 +index 00000000..b718f1c7 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/LightKeyTreeLabelProvider.java +@@ -0,0 +1,16 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.provider; ++ ++import org.eclipse.jface.viewers.ITableLabelProvider; ++import org.eclipse.swt.graphics.Image; ++ ++public class LightKeyTreeLabelProvider extends KeyTreeLabelProvider implements ITableLabelProvider { ++ @Override ++ public Image getColumnImage(Object element, int columnIndex) { ++ return null; ++ } ++ ++ @Override ++ public String getColumnText(Object element, int columnIndex) { ++ return super.getText(element); ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java +new file mode 100644 +index 00000000..1d8ac669 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeContentProvider.java +@@ -0,0 +1,246 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.provider; ++ ++import java.util.ArrayList; ++import java.util.Collection; ++import java.util.List; ++import java.util.Locale; ++ ++import org.eclipse.babel.editor.api.KeyTreeFactory; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.ITreeContentProvider; ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipselabs.tapiji.tools.core.model.manager.ResourceBundleManager; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IAbstractKeyTreeModel; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeVisitor; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundleGroup; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.TreeType; ++ ++ ++ ++public class ResKeyTreeContentProvider implements ITreeContentProvider { ++ ++ private IAbstractKeyTreeModel keyTreeModel; ++ private Viewer viewer; ++ ++ private TreeType treeType = TreeType.Tree; ++ ++ /** Represents empty objects. */ ++ private static Object[] EMPTY_ARRAY = new Object[0]; ++ /** Viewer this provided act upon. */ ++ protected TreeViewer treeViewer; ++ ++ private IMessagesBundleGroup bundle; ++ private List locales; ++ private ResourceBundleManager manager; ++ private String bundleId; ++ ++ ++ public ResKeyTreeContentProvider (IMessagesBundleGroup iBundleGroup, List locales, ++ ResourceBundleManager manager, String bundleId, TreeType treeType) { ++ this.bundle = iBundleGroup; ++ this.locales = locales; ++ this.manager = manager; ++ this.bundleId = bundleId; ++ this.treeType = treeType; ++ } ++ ++ public void setBundleGroup (IMessagesBundleGroup iBundleGroup) { ++ this.bundle = iBundleGroup; ++ } ++ ++ public ResKeyTreeContentProvider() { ++ locales = new ArrayList(); ++ } ++ ++ public void setLocales (List locales) { ++ this.locales = locales; ++ } ++ ++ @Override ++ public Object[] getChildren(Object parentElement) { ++ // brauche sie als VKTI ++// if(parentElement instanceof IAbstractKeyTreeModel) { ++// IAbstractKeyTreeModel model = (IAbstractKeyTreeModel) parentElement; ++// return convertKTItoVKTI(model.getRootNodes()); ++// } else if (parentElement instanceof IValuedKeyTreeNode) { // convert because we hold the children as IKeyTreeNodes ++// return convertKTItoVKTI(((IValuedKeyTreeNode) parentElement).getChildren()); ++// } ++ //new code ++ IKeyTreeNode parentNode = (IKeyTreeNode) parentElement; ++ switch (treeType) { ++ case Tree: ++ return convertKTItoVKTI(keyTreeModel.getChildren(parentNode)); ++ case Flat: ++ return new IKeyTreeNode[0]; ++ default: ++ // Should not happen ++ return new IKeyTreeNode[0]; ++ } ++ //new code ++// return EMPTY_ARRAY; ++ } ++ ++ protected Object[] convertKTItoVKTI (Object[] children) { ++ Collection items = new ArrayList(); ++ ++ for (Object o : children) { ++ if (o instanceof IValuedKeyTreeNode) ++ items.add((IValuedKeyTreeNode)o); ++ else { ++ IKeyTreeNode kti = (IKeyTreeNode) o; ++ IValuedKeyTreeNode vkti = KeyTreeFactory.createKeyTree(kti.getParent(), kti.getName(), kti.getMessageKey(), bundle); ++ ++ for (IKeyTreeNode k : kti.getChildren()) { ++ vkti.addChild(k); ++ } ++ ++ // init translations ++ for (Locale l : locales) { ++ try { ++ IMessage message = bundle.getMessagesBundle(l).getMessage(kti.getMessageKey()); ++ if (message != null) { ++ vkti.addValue(l, message.getValue()); ++ } ++ } catch (Exception e) {} ++ } ++ items.add(vkti); ++ } ++ } ++ ++ return items.toArray(); ++ } ++ ++ @Override ++ public Object[] getElements(Object inputElement) { ++// return getChildren(inputElement); ++ switch (treeType) { ++ case Tree: ++ return convertKTItoVKTI(keyTreeModel.getRootNodes()); ++ case Flat: ++ final Collection actualKeys = new ArrayList(); ++ IKeyTreeVisitor visitor = new IKeyTreeVisitor() { ++ public void visitKeyTreeNode(IKeyTreeNode node) { ++ if (node.isUsedAsKey()) { ++ actualKeys.add(node); ++ } ++ } ++ }; ++ keyTreeModel.accept(visitor, keyTreeModel.getRootNode()); ++ ++ return actualKeys.toArray(); ++ default: ++ // Should not happen ++ return new IKeyTreeNode[0]; ++ } ++ } ++ ++ @Override ++ public Object getParent(Object element) { ++// Object[] parent = new Object[1]; ++// ++// if(element instanceof IKeyTreeNode) { ++// return ((IKeyTreeNode) element).getParent(); ++// } ++// ++// if (parent[0] == null) ++// return null; ++// ++// Object[] result = convertKTItoVKTI(parent); ++// if (result.length > 0) ++// return result[0]; ++// else ++// return null; ++ ++ // new code ++ IKeyTreeNode node = (IKeyTreeNode) element; ++ switch (treeType) { ++ case Tree: ++ return keyTreeModel.getParent(node); ++ case Flat: ++ return keyTreeModel; ++ default: ++ // Should not happen ++ return null; ++ } ++ // new code ++ } ++ ++ /** ++ * @see ITreeContentProvider#hasChildren(Object) ++ */ ++ public boolean hasChildren(Object element) { ++// return countChildren(element) > 0; ++ ++ // new code ++ switch (treeType) { ++ case Tree: ++ return keyTreeModel.getChildren((IKeyTreeNode) element).length > 0; ++ case Flat: ++ return false; ++ default: ++ // Should not happen ++ return false; ++ } ++ // new code ++ } ++ ++ public int countChildren(Object element) { ++ ++ if (element instanceof IKeyTreeNode) { ++ return ((IKeyTreeNode)element).getChildren().length; ++ } else if (element instanceof IValuedKeyTreeNode) { ++ return ((IValuedKeyTreeNode)element).getChildren().length; ++ } else { ++ System.out.println(""wait a minute""); ++ return 1; ++ } ++ } ++ ++ /** ++ * Gets the selected key tree item. ++ * @return key tree item ++ */ ++ private IKeyTreeNode getTreeSelection() { ++ IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); ++ return ((IKeyTreeNode) selection.getFirstElement()); ++ } ++ ++ @Override ++ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { ++ this.viewer = (TreeViewer) viewer; ++ this.keyTreeModel = (IAbstractKeyTreeModel) newInput; ++ } ++ ++ public IMessagesBundleGroup getBundle() { ++ return bundle; ++ } ++ ++ public ResourceBundleManager getManager() { ++ return manager; ++ } ++ ++ public String getBundleId() { ++ return bundleId; ++ } ++ ++ @Override ++ public void dispose() { ++ // TODO Auto-generated method stub ++ ++ } ++ ++ public TreeType getTreeType() { ++ return treeType; ++ } ++ ++ public void setTreeType(TreeType treeType) { ++ if (this.treeType != treeType) { ++ this.treeType = treeType; ++ viewer.refresh(); ++ } ++ } ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java +new file mode 100644 +index 00000000..8ad7424d +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ResKeyTreeLabelProvider.java +@@ -0,0 +1,152 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.provider; ++ ++import java.util.ArrayList; ++import java.util.List; ++import java.util.Locale; ++ ++import org.eclipse.jface.text.Region; ++import org.eclipse.jface.viewers.ViewerCell; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.custom.StyleRange; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.graphics.Font; ++import org.eclipse.swt.graphics.Image; ++import org.eclipselabs.tapiji.tools.core.ui.widgets.filter.FilterInfo; ++import org.eclipselabs.tapiji.tools.core.util.FontUtils; ++import org.eclipselabs.tapiji.tools.core.util.ImageUtils; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++ ++ ++public class ResKeyTreeLabelProvider extends KeyTreeLabelProvider { ++ ++ private List locales; ++ private boolean searchEnabled = false; ++ ++ /*** COLORS ***/ ++ private Color gray = FontUtils.getSystemColor(SWT.COLOR_GRAY); ++ private Color black = FontUtils.getSystemColor(SWT.COLOR_BLACK); ++ private Color info_color = FontUtils.getSystemColor(SWT.COLOR_YELLOW); ++ ++ /*** FONTS ***/ ++ private Font bold = FontUtils.createFont(SWT.BOLD); ++ private Font bold_italic = FontUtils.createFont(SWT.BOLD | SWT.ITALIC); ++ ++ public ResKeyTreeLabelProvider (List locales) { ++ this.locales = locales; ++ } ++ ++ //@Override ++ public Image getColumnImage(Object element, int columnIndex) { ++ if (columnIndex == 0) { ++ IKeyTreeNode kti = (IKeyTreeNode) element; ++ IMessage[] be = kti.getMessagesBundleGroup().getMessages(kti.getMessageKey()); ++ boolean incomplete = false; ++ ++ if (be.length != kti.getMessagesBundleGroup().getMessagesBundleCount()) ++ incomplete = true; ++ else { ++ for (IMessage b : be) { ++ if (b.getValue() == null || b.getValue().trim().length() == 0) { ++ incomplete = true; ++ break; ++ } ++ } ++ } ++ ++ if (incomplete) ++ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE_INCOMPLETE); ++ else ++ return ImageUtils.getImage(ImageUtils.ICON_RESOURCE); ++ } ++ return null; ++ } ++ ++ //@Override ++ public String getColumnText(Object element, int columnIndex) { ++ if (columnIndex == 0) ++ return super.getText(element); ++ ++ if (columnIndex <= locales.size()) { ++ IValuedKeyTreeNode item = (IValuedKeyTreeNode) element; ++ String entry = item.getValue(locales.get(columnIndex-1)); ++ if (entry != null) ++ return entry; ++ } ++ return """"; ++ } ++ ++ public void setSearchEnabled (boolean enabled) { ++ this.searchEnabled = enabled; ++ } ++ ++ public boolean isSearchEnabled () { ++ return this.searchEnabled; ++ } ++ ++ public void setLocales(List visibleLocales) { ++ locales = visibleLocales; ++ } ++ ++ protected boolean isMatchingToPattern (Object element, int columnIndex) { ++ boolean matching = false; ++ ++ if (element instanceof IValuedKeyTreeNode) { ++ IValuedKeyTreeNode vkti = (IValuedKeyTreeNode) element; ++ ++ if (vkti.getInfo() == null) ++ return false; ++ ++ FilterInfo filterInfo = (FilterInfo) vkti.getInfo(); ++ ++ if (columnIndex == 0) { ++ matching = filterInfo.isFoundInKey(); ++ } else { ++ matching = filterInfo.hasFoundInLocale(locales.get(columnIndex-1)); ++ } ++ } ++ ++ return matching; ++ } ++ ++ protected boolean isSearchEnabled (Object element) { ++ return (element instanceof IValuedKeyTreeNode && searchEnabled ); ++ } ++ ++ @Override ++ public void update(ViewerCell cell) { ++ Object element = cell.getElement(); ++ int columnIndex = cell.getColumnIndex(); ++ ++ if (isSearchEnabled(element)) { ++ if (isMatchingToPattern(element, columnIndex) ) { ++ List styleRanges = new ArrayList(); ++ FilterInfo filterInfo = (FilterInfo) ((IValuedKeyTreeNode)element).getInfo(); ++ ++ if (columnIndex > 0) { ++ for (Region reg : filterInfo.getFoundInLocaleRanges(locales.get(columnIndex-1))) { ++ styleRanges.add(new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD)); ++ } ++ } else { ++ // check if the pattern has been found within the key section ++ if (filterInfo.isFoundInKey()) { ++ for (Region reg : filterInfo.getKeyOccurrences()) { ++ StyleRange sr = new StyleRange(reg.getOffset(), reg.getLength(), black, info_color, SWT.BOLD); ++ styleRanges.add(sr); ++ } ++ } ++ } ++ cell.setStyleRanges(styleRanges.toArray(new StyleRange[styleRanges.size()])); ++ } else { ++ cell.setForeground(gray); ++ } ++ } else if (columnIndex == 0) ++ super.update(cell); ++ ++ cell.setImage(this.getColumnImage(element, columnIndex)); ++ cell.setText(this.getColumnText(element, columnIndex)); ++ } ++ ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java +new file mode 100644 +index 00000000..1241bab4 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/provider/ValueKeyTreeLabelProvider.java +@@ -0,0 +1,69 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.provider; ++ ++import org.eclipse.jface.viewers.ITableColorProvider; ++import org.eclipse.jface.viewers.ITableFontProvider; ++import org.eclipse.jface.viewers.ViewerCell; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.graphics.Font; ++import org.eclipse.swt.graphics.Image; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IKeyTreeNode; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessage; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IMessagesBundle; ++ ++ ++public class ValueKeyTreeLabelProvider extends KeyTreeLabelProvider implements ++ ITableColorProvider, ITableFontProvider { ++ ++ private IMessagesBundle locale; ++ ++ public ValueKeyTreeLabelProvider(IMessagesBundle iBundle) { ++ this.locale = iBundle; ++ } ++ ++ //@Override ++ public Image getColumnImage(Object element, int columnIndex) { ++ return null; ++ } ++ ++ //@Override ++ public String getColumnText(Object element, int columnIndex) { ++ try { ++ IKeyTreeNode item = (IKeyTreeNode) element; ++ IMessage entry = locale.getMessage(item.getMessageKey()); ++ if (entry != null) { ++ String value = entry.getValue(); ++ if (value.length() > 40) ++ value = value.substring(0, 39) + ""...""; ++ } ++ } catch (Exception e) { ++ } ++ return """"; ++ } ++ ++ @Override ++ public Color getBackground(Object element, int columnIndex) { ++ return null;//return new Color(Display.getDefault(), 255, 0, 0); ++ } ++ ++ @Override ++ public Color getForeground(Object element, int columnIndex) { ++ // TODO Auto-generated method stub ++ return null; ++ } ++ ++ @Override ++ public Font getFont(Object element, int columnIndex) { ++ return null; //UIUtils.createFont(SWT.BOLD); ++ } ++ ++ @Override ++ public void update(ViewerCell cell) { ++ Object element = cell.getElement(); ++ int columnIndex = cell.getColumnIndex(); ++ cell.setImage(this.getColumnImage(element, columnIndex)); ++ cell.setText(this.getColumnText(element, columnIndex)); ++ ++ super.update(cell); ++ } ++ ++} +diff --git a/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java +new file mode 100644 +index 00000000..0650b1d7 +--- /dev/null ++++ b/org.eclipselabs.tapiji.tools.core.ui/src/org/eclipselabs/tapiji/tools/core/ui/widgets/sorter/ValuedKeyTreeItemSorter.java +@@ -0,0 +1,65 @@ ++package org.eclipselabs.tapiji.tools.core.ui.widgets.sorter; ++ ++import java.util.Locale; ++ ++import org.eclipse.jface.viewers.StructuredViewer; ++import org.eclipse.jface.viewers.Viewer; ++import org.eclipse.jface.viewers.ViewerSorter; ++import org.eclipselabs.tapiji.tools.core.model.view.SortInfo; ++import org.eclipselabs.tapiji.translator.rbe.babel.bundle.IValuedKeyTreeNode; ++ ++public class ValuedKeyTreeItemSorter extends ViewerSorter { ++ ++ private StructuredViewer viewer; ++ private SortInfo sortInfo; ++ ++ public ValuedKeyTreeItemSorter (StructuredViewer viewer, ++ SortInfo sortInfo) { ++ this.viewer = viewer; ++ this.sortInfo = sortInfo; ++ } ++ ++ public StructuredViewer getViewer() { ++ return viewer; ++ } ++ ++ public void setViewer(StructuredViewer viewer) { ++ this.viewer = viewer; ++ } ++ ++ public SortInfo getSortInfo() { ++ return sortInfo; ++ } ++ ++ public void setSortInfo(SortInfo sortInfo) { ++ this.sortInfo = sortInfo; ++ } ++ ++ @Override ++ public int compare(Viewer viewer, Object e1, Object e2) { ++ try { ++ if (!(e1 instanceof IValuedKeyTreeNode && e2 instanceof IValuedKeyTreeNode)) ++ return super.compare(viewer, e1, e2); ++ IValuedKeyTreeNode comp1 = (IValuedKeyTreeNode) e1; ++ IValuedKeyTreeNode comp2 = (IValuedKeyTreeNode) e2; ++ ++ int result = 0; ++ ++ if (sortInfo == null) ++ return 0; ++ ++ if (sortInfo.getColIdx() == 0) ++ result = comp1.getMessageKey().compareTo(comp2.getMessageKey()); ++ else { ++ Locale loc = sortInfo.getVisibleLocales().get(sortInfo.getColIdx()-1); ++ result = (comp1.getValue(loc) == null ? """" : comp1.getValue(loc)) ++ .compareTo((comp2.getValue(loc) == null ? """" : comp2.getValue(loc))); ++ } ++ ++ return result * (sortInfo.isDESC() ? -1 : 1); ++ } catch (Exception e) { ++ return 0; ++ } ++ } ++ ++}" +9ebbf1bfcea9942117727c08c6905dd444c230ae,hadoop,YARN-3361. CapacityScheduler side changes to- support non-exclusive node labels. Contributed by Wangda Tan (cherry picked- from commit 0fefda645bca935b87b6bb8ca63e6f18340d59f5)--,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 478d0aebacc5f..059c5a3d39e7d 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -24,6 +24,9 @@ Release 2.8.0 - UNRELEASED + YARN-3443. Create a 'ResourceHandler' subsystem to ease addition of support + for new resource types on the NM. (Sidharta Seethana via junping_du) + ++ YARN-3361. CapacityScheduler side changes to support non-exclusive node ++ labels. (Wangda Tan via jianhe) ++ + IMPROVEMENTS + + YARN-1880. Cleanup TestApplicationClientProtocolOnHA +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/utils/BuilderUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/utils/BuilderUtils.java +index 68d4ef9fe77aa..f2146c8b124be 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/utils/BuilderUtils.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/utils/BuilderUtils.java +@@ -313,6 +313,7 @@ public static ResourceRequest newResourceRequest(ResourceRequest r) { + request.setResourceName(r.getResourceName()); + request.setCapability(r.getCapability()); + request.setNumContainers(r.getNumContainers()); ++ request.setNodeLabelExpression(r.getNodeLabelExpression()); + return request; + } + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +index 1be1727e86599..1071831263ae1 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java +@@ -146,7 +146,7 @@ public class RMAppAttemptImpl implements RMAppAttempt, Recoverable { + private ConcurrentMap> + finishedContainersSentToAM = + new ConcurrentHashMap>(); +- private Container masterContainer; ++ private volatile Container masterContainer; + + private float progress = 0; + private String host = ""N/A""; +@@ -762,13 +762,7 @@ public List pullJustFinishedContainers() { + + @Override + public Container getMasterContainer() { +- this.readLock.lock(); +- +- try { +- return this.masterContainer; +- } finally { +- this.readLock.unlock(); +- } ++ return this.masterContainer; + } + + @InterfaceAudience.Private +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java +index 5521d47ed6076..5604f0f33965f 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java +@@ -73,10 +73,11 @@ public class AppSchedulingInfo { + /* Allocated by scheduler */ + boolean pending = true; // for app metrics + ++ private ResourceUsage appResourceUsage; + + public AppSchedulingInfo(ApplicationAttemptId appAttemptId, + String user, Queue queue, ActiveUsersManager activeUsersManager, +- long epoch) { ++ long epoch, ResourceUsage appResourceUsage) { + this.applicationAttemptId = appAttemptId; + this.applicationId = appAttemptId.getApplicationId(); + this.queue = queue; +@@ -84,6 +85,7 @@ public AppSchedulingInfo(ApplicationAttemptId appAttemptId, + this.user = user; + this.activeUsersManager = activeUsersManager; + this.containerIdCounter = new AtomicLong(epoch << EPOCH_BIT_SHIFT); ++ this.appResourceUsage = appResourceUsage; + } + + public ApplicationId getApplicationId() { +@@ -191,13 +193,19 @@ synchronized public void updateResourceRequests( + lastRequestCapability); + + // update queue: ++ Resource increasedResource = Resources.multiply(request.getCapability(), ++ request.getNumContainers()); + queue.incPendingResource( + request.getNodeLabelExpression(), +- Resources.multiply(request.getCapability(), +- request.getNumContainers())); ++ increasedResource); ++ appResourceUsage.incPending(request.getNodeLabelExpression(), increasedResource); + if (lastRequest != null) { ++ Resource decreasedResource = ++ Resources.multiply(lastRequestCapability, lastRequestContainers); + queue.decPendingResource(lastRequest.getNodeLabelExpression(), +- Resources.multiply(lastRequestCapability, lastRequestContainers)); ++ decreasedResource); ++ appResourceUsage.decPending(lastRequest.getNodeLabelExpression(), ++ decreasedResource); + } + } + } +@@ -385,6 +393,8 @@ synchronized private void decrementOutstanding( + checkForDeactivation(); + } + ++ appResourceUsage.decPending(offSwitchRequest.getNodeLabelExpression(), ++ offSwitchRequest.getCapability()); + queue.decPendingResource(offSwitchRequest.getNodeLabelExpression(), + offSwitchRequest.getCapability()); + } +@@ -492,9 +502,10 @@ public synchronized void recoverContainer(RMContainer rmContainer) { + } + + public ResourceRequest cloneResourceRequest(ResourceRequest request) { +- ResourceRequest newRequest = ResourceRequest.newInstance( +- request.getPriority(), request.getResourceName(), +- request.getCapability(), 1, request.getRelaxLocality()); ++ ResourceRequest newRequest = ++ ResourceRequest.newInstance(request.getPriority(), ++ request.getResourceName(), request.getCapability(), 1, ++ request.getRelaxLocality(), request.getNodeLabelExpression()); + return newRequest; + } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/ResourceUsage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/ResourceUsage.java +index 36ee4daa1edbc..5169b78dd582f 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/ResourceUsage.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/ResourceUsage.java +@@ -27,6 +27,7 @@ + + import org.apache.hadoop.yarn.api.records.Resource; + import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.util.resource.Resources; + + /** +@@ -250,6 +251,10 @@ private static Resource normalize(Resource res) { + } + + private Resource _get(String label, ResourceType type) { ++ if (label == null) { ++ label = RMNodeLabelsManager.NO_LABEL; ++ } ++ + try { + readLock.lock(); + UsageByLabel usage = usages.get(label); +@@ -263,6 +268,9 @@ private Resource _get(String label, ResourceType type) { + } + + private UsageByLabel getAndAddIfMissing(String label) { ++ if (label == null) { ++ label = RMNodeLabelsManager.NO_LABEL; ++ } + if (!usages.containsKey(label)) { + UsageByLabel u = new UsageByLabel(label); + usages.put(label, u); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApplicationAttempt.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApplicationAttempt.java +index 5e0bbc7f9b48e..fccf7661a2ad4 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApplicationAttempt.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApplicationAttempt.java +@@ -56,6 +56,8 @@ + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerReservedEvent; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; + import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeCleanContainerEvent; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.SchedulingMode; ++import org.apache.hadoop.yarn.util.resource.ResourceCalculator; + import org.apache.hadoop.yarn.util.resource.Resources; + + import com.google.common.base.Preconditions; +@@ -108,14 +110,24 @@ public class SchedulerApplicationAttempt { + private Set pendingRelease = null; + + /** +- * Count how many times the application has been given an opportunity +- * to schedule a task at each priority. Each time the scheduler +- * asks the application for a task at this priority, it is incremented, +- * and each time the application successfully schedules a task, it ++ * Count how many times the application has been given an opportunity to ++ * schedule a task at each priority. Each time the scheduler asks the ++ * application for a task at this priority, it is incremented, and each time ++ * the application successfully schedules a task (at rack or node local), it + * is reset to 0. + */ + Multiset schedulingOpportunities = HashMultiset.create(); + ++ /** ++ * Count how many times the application has been given an opportunity to ++ * schedule a non-partitioned resource request at each priority. Each time the ++ * scheduler asks the application for a task at this priority, it is ++ * incremented, and each time the application successfully schedules a task, ++ * it is reset to 0 when schedule any task at corresponding priority. ++ */ ++ Multiset missedNonPartitionedRequestSchedulingOpportunity = ++ HashMultiset.create(); ++ + // Time of the last container scheduled at the current allowed level + protected Map lastScheduledContainer = + new HashMap(); +@@ -132,7 +144,7 @@ public SchedulerApplicationAttempt(ApplicationAttemptId applicationAttemptId, + this.rmContext = rmContext; + this.appSchedulingInfo = + new AppSchedulingInfo(applicationAttemptId, user, queue, +- activeUsersManager, rmContext.getEpoch()); ++ activeUsersManager, rmContext.getEpoch(), attemptResourceUsage); + this.queue = queue; + this.pendingRelease = new HashSet(); + this.attemptId = applicationAttemptId; +@@ -489,6 +501,18 @@ public boolean isBlacklisted(String resourceName) { + return this.appSchedulingInfo.isBlacklisted(resourceName); + } + ++ public synchronized int addMissedNonPartitionedRequestSchedulingOpportunity( ++ Priority priority) { ++ missedNonPartitionedRequestSchedulingOpportunity.add(priority); ++ return missedNonPartitionedRequestSchedulingOpportunity.count(priority); ++ } ++ ++ public synchronized void ++ resetMissedNonPartitionedRequestSchedulingOpportunity(Priority priority) { ++ missedNonPartitionedRequestSchedulingOpportunity.setCount(priority, 0); ++ } ++ ++ + public synchronized void addSchedulingOpportunity(Priority priority) { + schedulingOpportunities.setCount(priority, + schedulingOpportunities.count(priority) + 1); +@@ -518,6 +542,7 @@ public synchronized int getSchedulingOpportunities(Priority priority) { + public synchronized void resetSchedulingOpportunities(Priority priority) { + resetSchedulingOpportunities(priority, System.currentTimeMillis()); + } ++ + // used for continuous scheduling + public synchronized void resetSchedulingOpportunities(Priority priority, + long currentTimeMs) { +@@ -669,4 +694,13 @@ public void recordContainerAllocationTime(long value) { + public Set getBlacklistedNodes() { + return this.appSchedulingInfo.getBlackListCopy(); + } ++ ++ @Private ++ public boolean hasPendingResourceRequest(ResourceCalculator rc, ++ String nodePartition, Resource cluster, ++ SchedulingMode schedulingMode) { ++ return SchedulerUtils.hasPendingResourceRequest(rc, ++ this.attemptResourceUsage, nodePartition, cluster, ++ schedulingMode); ++ } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java +index 248cc08b74853..7a1a5287a9959 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerUtils.java +@@ -37,11 +37,10 @@ + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; + import org.apache.hadoop.yarn.security.AccessType; + import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.SchedulingMode; + import org.apache.hadoop.yarn.util.resource.ResourceCalculator; + import org.apache.hadoop.yarn.util.resource.Resources; + +-import com.google.common.collect.Sets; +- + /** + * Utilities shared by schedulers. + */ +@@ -235,9 +234,13 @@ public static void validateResourceRequest(ResourceRequest resReq, + if (labelExp == null && queueInfo != null + && ResourceRequest.ANY.equals(resReq.getResourceName())) { + labelExp = queueInfo.getDefaultNodeLabelExpression(); +- resReq.setNodeLabelExpression(labelExp); + } + ++ // If labelExp still equals to null, set it to be NO_LABEL ++ resReq ++ .setNodeLabelExpression(labelExp == null ? RMNodeLabelsManager.NO_LABEL ++ : labelExp); ++ + // we don't allow specify label expression other than resourceName=ANY now + if (!ResourceRequest.ANY.equals(resReq.getResourceName()) + && labelExp != null && !labelExp.trim().isEmpty()) { +@@ -273,25 +276,6 @@ public static void validateResourceRequest(ResourceRequest resReq, + } + } + +- public static boolean checkQueueAccessToNode(Set queueLabels, +- Set nodeLabels) { +- // if queue's label is *, it can access any node +- if (queueLabels != null && queueLabels.contains(RMNodeLabelsManager.ANY)) { +- return true; +- } +- // any queue can access to a node without label +- if (nodeLabels == null || nodeLabels.isEmpty()) { +- return true; +- } +- // a queue can access to a node only if it contains any label of the node +- if (queueLabels != null +- && Sets.intersection(queueLabels, nodeLabels).size() > 0) { +- return true; +- } +- // sorry, you cannot access +- return false; +- } +- + public static void checkIfLabelInClusterNodeLabels(RMNodeLabelsManager mgr, + Set labels) throws IOException { + if (mgr == null) { +@@ -311,26 +295,6 @@ public static void checkIfLabelInClusterNodeLabels(RMNodeLabelsManager mgr, + } + } + } +- +- public static boolean checkNodeLabelExpression(Set nodeLabels, +- String labelExpression) { +- // empty label expression can only allocate on node with empty labels +- if (labelExpression == null || labelExpression.trim().isEmpty()) { +- if (!nodeLabels.isEmpty()) { +- return false; +- } +- } +- +- if (labelExpression != null) { +- for (String str : labelExpression.split(""&&"")) { +- if (!str.trim().isEmpty() +- && (nodeLabels == null || !nodeLabels.contains(str.trim()))) { +- return false; +- } +- } +- } +- return true; +- } + + public static boolean checkQueueLabelExpression(Set queueLabels, + String labelExpression) { +@@ -360,4 +324,43 @@ public static AccessType toAccessType(QueueACL acl) { + } + return null; + } ++ ++ public static boolean checkResourceRequestMatchingNodePartition( ++ ResourceRequest offswitchResourceRequest, String nodePartition, ++ SchedulingMode schedulingMode) { ++ // We will only look at node label = nodeLabelToLookAt according to ++ // schedulingMode and partition of node. ++ String nodePartitionToLookAt = null; ++ if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) { ++ nodePartitionToLookAt = nodePartition; ++ } else { ++ nodePartitionToLookAt = RMNodeLabelsManager.NO_LABEL; ++ } ++ ++ String askedNodePartition = offswitchResourceRequest.getNodeLabelExpression(); ++ if (null == askedNodePartition) { ++ askedNodePartition = RMNodeLabelsManager.NO_LABEL; ++ } ++ return askedNodePartition.equals(nodePartitionToLookAt); ++ } ++ ++ private static boolean hasPendingResourceRequest(ResourceCalculator rc, ++ ResourceUsage usage, String partitionToLookAt, Resource cluster) { ++ if (Resources.greaterThan(rc, cluster, ++ usage.getPending(partitionToLookAt), Resources.none())) { ++ return true; ++ } ++ return false; ++ } ++ ++ @Private ++ public static boolean hasPendingResourceRequest(ResourceCalculator rc, ++ ResourceUsage usage, String nodePartition, Resource cluster, ++ SchedulingMode schedulingMode) { ++ String partitionToLookAt = nodePartition; ++ if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { ++ partitionToLookAt = RMNodeLabelsManager.NO_LABEL; ++ } ++ return hasPendingResourceRequest(rc, usage, partitionToLookAt, cluster); ++ } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java +index 42ea089d72afa..d95c45c79be87 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/AbstractCSQueue.java +@@ -20,7 +20,6 @@ + + import java.io.IOException; + import java.util.HashMap; +-import java.util.HashSet; + import java.util.Map; + import java.util.Set; + +@@ -38,12 +37,12 @@ + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; + import org.apache.hadoop.yarn.security.AccessType; + import org.apache.hadoop.yarn.security.PrivilegedEntity; + import org.apache.hadoop.yarn.security.PrivilegedEntity.EntityType; + import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; + import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage; +@@ -56,6 +55,11 @@ + public abstract class AbstractCSQueue implements CSQueue { + private static final Log LOG = LogFactory.getLog(AbstractCSQueue.class); + ++ static final CSAssignment NULL_ASSIGNMENT = ++ new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); ++ ++ static final CSAssignment SKIP_ASSIGNMENT = new CSAssignment(true); ++ + CSQueue parent; + final String queueName; + volatile int numContainers; +@@ -343,16 +347,8 @@ public Resource getMinimumAllocation() { + } + + synchronized void allocateResource(Resource clusterResource, +- Resource resource, Set nodeLabels) { +- +- // Update usedResources by labels +- if (nodeLabels == null || nodeLabels.isEmpty()) { +- queueUsage.incUsed(resource); +- } else { +- for (String label : Sets.intersection(accessibleLabels, nodeLabels)) { +- queueUsage.incUsed(label, resource); +- } +- } ++ Resource resource, String nodePartition) { ++ queueUsage.incUsed(nodePartition, resource); + + ++numContainers; + CSQueueUtils.updateQueueStatistics(resourceCalculator, this, getParent(), +@@ -360,15 +356,8 @@ synchronized void allocateResource(Resource clusterResource, + } + + protected synchronized void releaseResource(Resource clusterResource, +- Resource resource, Set nodeLabels) { +- // Update usedResources by labels +- if (null == nodeLabels || nodeLabels.isEmpty()) { +- queueUsage.decUsed(resource); +- } else { +- for (String label : Sets.intersection(accessibleLabels, nodeLabels)) { +- queueUsage.decUsed(label, resource); +- } +- } ++ Resource resource, String nodePartition) { ++ queueUsage.decUsed(nodePartition, resource); + + CSQueueUtils.updateQueueStatistics(resourceCalculator, this, getParent(), + clusterResource, minimumAllocation); +@@ -434,103 +423,108 @@ private boolean isQueueHierarchyPreemptionDisabled(CSQueue q) { + parentQ.getPreemptionDisabled()); + } + +- private Resource getCurrentLimitResource(String nodeLabel, +- Resource clusterResource, ResourceLimits currentResourceLimits) { +- /* +- * Current limit resource: For labeled resource: limit = queue-max-resource +- * (TODO, this part need update when we support labeled-limit) For +- * non-labeled resource: limit = min(queue-max-resource, +- * limit-set-by-parent) +- */ +- Resource queueMaxResource = +- Resources.multiplyAndNormalizeDown(resourceCalculator, +- labelManager.getResourceByLabel(nodeLabel, clusterResource), +- queueCapacities.getAbsoluteMaximumCapacity(nodeLabel), minimumAllocation); +- if (nodeLabel.equals(RMNodeLabelsManager.NO_LABEL)) { +- return Resources.min(resourceCalculator, clusterResource, +- queueMaxResource, currentResourceLimits.getLimit()); ++ private Resource getCurrentLimitResource(String nodePartition, ++ Resource clusterResource, ResourceLimits currentResourceLimits, ++ SchedulingMode schedulingMode) { ++ if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) { ++ /* ++ * Current limit resource: For labeled resource: limit = queue-max-resource ++ * (TODO, this part need update when we support labeled-limit) For ++ * non-labeled resource: limit = min(queue-max-resource, ++ * limit-set-by-parent) ++ */ ++ Resource queueMaxResource = ++ Resources.multiplyAndNormalizeDown(resourceCalculator, ++ labelManager.getResourceByLabel(nodePartition, clusterResource), ++ queueCapacities.getAbsoluteMaximumCapacity(nodePartition), minimumAllocation); ++ if (nodePartition.equals(RMNodeLabelsManager.NO_LABEL)) { ++ return Resources.min(resourceCalculator, clusterResource, ++ queueMaxResource, currentResourceLimits.getLimit()); ++ } ++ return queueMaxResource; ++ } else if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { ++ // When we doing non-exclusive resource allocation, maximum capacity of ++ // all queues on this label equals to total resource with the label. ++ return labelManager.getResourceByLabel(nodePartition, clusterResource); + } +- return queueMaxResource; ++ ++ return Resources.none(); + } + + synchronized boolean canAssignToThisQueue(Resource clusterResource, +- Set nodeLabels, ResourceLimits currentResourceLimits, +- Resource nowRequired, Resource resourceCouldBeUnreserved) { +- // Get label of this queue can access, it's (nodeLabel AND queueLabel) +- Set labelCanAccess; +- if (null == nodeLabels || nodeLabels.isEmpty()) { +- labelCanAccess = new HashSet(); +- // Any queue can always access any node without label +- labelCanAccess.add(RMNodeLabelsManager.NO_LABEL); +- } else { +- labelCanAccess = new HashSet( +- accessibleLabels.contains(CommonNodeLabelsManager.ANY) ? nodeLabels +- : Sets.intersection(accessibleLabels, nodeLabels)); +- } +- +- for (String label : labelCanAccess) { +- // New total resource = used + required +- Resource newTotalResource = +- Resources.add(queueUsage.getUsed(label), nowRequired); +- +- Resource currentLimitResource = +- getCurrentLimitResource(label, clusterResource, currentResourceLimits); +- +- // if reservation continous looking enabled, check to see if could we +- // potentially use this node instead of a reserved node if the application +- // has reserved containers. +- // TODO, now only consider reservation cases when the node has no label +- if (this.reservationsContinueLooking +- && label.equals(RMNodeLabelsManager.NO_LABEL) +- && Resources.greaterThan(resourceCalculator, clusterResource, +- resourceCouldBeUnreserved, Resources.none())) { +- // resource-without-reserved = used - reserved +- Resource newTotalWithoutReservedResource = +- Resources.subtract(newTotalResource, resourceCouldBeUnreserved); +- +- // when total-used-without-reserved-resource < currentLimit, we still +- // have chance to allocate on this node by unreserving some containers +- if (Resources.lessThan(resourceCalculator, clusterResource, +- newTotalWithoutReservedResource, currentLimitResource)) { +- if (LOG.isDebugEnabled()) { +- LOG.debug(""try to use reserved: "" + getQueueName() +- + "" usedResources: "" + queueUsage.getUsed() +- + "", clusterResources: "" + clusterResource +- + "", reservedResources: "" + resourceCouldBeUnreserved +- + "", capacity-without-reserved: "" +- + newTotalWithoutReservedResource + "", maxLimitCapacity: "" +- + currentLimitResource); +- } +- return true; ++ String nodePartition, ResourceLimits currentResourceLimits, ++ Resource nowRequired, Resource resourceCouldBeUnreserved, ++ SchedulingMode schedulingMode) { ++ // New total resource = used + required ++ Resource newTotalResource = ++ Resources.add(queueUsage.getUsed(nodePartition), nowRequired); ++ ++ // Get current limited resource: ++ // - When doing RESPECT_PARTITION_EXCLUSIVITY allocation, we will respect ++ // queues' max capacity. ++ // - When doing IGNORE_PARTITION_EXCLUSIVITY allocation, we will not respect ++ // queue's max capacity, queue's max capacity on the partition will be ++ // considered to be 100%. Which is a queue can use all resource in the ++ // partition. ++ // Doing this because: for non-exclusive allocation, we make sure there's ++ // idle resource on the partition, to avoid wastage, such resource will be ++ // leveraged as much as we can, and preemption policy will reclaim it back ++ // when partitoned-resource-request comes back. ++ Resource currentLimitResource = ++ getCurrentLimitResource(nodePartition, clusterResource, ++ currentResourceLimits, schedulingMode); ++ ++ // if reservation continous looking enabled, check to see if could we ++ // potentially use this node instead of a reserved node if the application ++ // has reserved containers. ++ // TODO, now only consider reservation cases when the node has no label ++ if (this.reservationsContinueLooking ++ && nodePartition.equals(RMNodeLabelsManager.NO_LABEL) ++ && Resources.greaterThan(resourceCalculator, clusterResource, ++ resourceCouldBeUnreserved, Resources.none())) { ++ // resource-without-reserved = used - reserved ++ Resource newTotalWithoutReservedResource = ++ Resources.subtract(newTotalResource, resourceCouldBeUnreserved); ++ ++ // when total-used-without-reserved-resource < currentLimit, we still ++ // have chance to allocate on this node by unreserving some containers ++ if (Resources.lessThan(resourceCalculator, clusterResource, ++ newTotalWithoutReservedResource, currentLimitResource)) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""try to use reserved: "" + getQueueName() ++ + "" usedResources: "" + queueUsage.getUsed() ++ + "", clusterResources: "" + clusterResource ++ + "", reservedResources: "" + resourceCouldBeUnreserved ++ + "", capacity-without-reserved: "" ++ + newTotalWithoutReservedResource + "", maxLimitCapacity: "" ++ + currentLimitResource); + } ++ return true; + } +- +- // Otherwise, if any of the label of this node beyond queue limit, we +- // cannot allocate on this node. Consider a small epsilon here. +- if (Resources.greaterThan(resourceCalculator, clusterResource, +- newTotalResource, currentLimitResource)) { +- return false; +- } ++ } + +- if (LOG.isDebugEnabled()) { +- LOG.debug(getQueueName() +- + ""Check assign to queue, label="" + label +- + "" usedResources: "" + queueUsage.getUsed(label) +- + "" clusterResources: "" + clusterResource +- + "" currentUsedCapacity "" +- + Resources.divide(resourceCalculator, clusterResource, +- queueUsage.getUsed(label), +- labelManager.getResourceByLabel(label, clusterResource)) +- + "" max-capacity: "" +- + queueCapacities.getAbsoluteMaximumCapacity(label) +- + "")""); +- } +- return true; ++ // Check if we over current-resource-limit computed. ++ if (Resources.greaterThan(resourceCalculator, clusterResource, ++ newTotalResource, currentLimitResource)) { ++ return false; + } +- +- // Actually, this will not happen, since labelCanAccess will be always +- // non-empty +- return false; ++ ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(getQueueName() ++ + ""Check assign to queue, nodePartition="" ++ + nodePartition ++ + "" usedResources: "" ++ + queueUsage.getUsed(nodePartition) ++ + "" clusterResources: "" ++ + clusterResource ++ + "" currentUsedCapacity "" ++ + Resources.divide(resourceCalculator, clusterResource, ++ queueUsage.getUsed(nodePartition), ++ labelManager.getResourceByLabel(nodePartition, clusterResource)) ++ + "" max-capacity: "" ++ + queueCapacities.getAbsoluteMaximumCapacity(nodePartition) + "")""); ++ } ++ return true; + } + + @Override +@@ -556,4 +550,33 @@ public void decPendingResource(String nodeLabel, Resource resourceToDec) { + parent.decPendingResource(nodeLabel, resourceToDec); + } + } ++ ++ /** ++ * Return if the queue has pending resource on given nodePartition and ++ * schedulingMode. ++ */ ++ boolean hasPendingResourceRequest(String nodePartition, ++ Resource cluster, SchedulingMode schedulingMode) { ++ return SchedulerUtils.hasPendingResourceRequest(resourceCalculator, ++ queueUsage, nodePartition, cluster, schedulingMode); ++ } ++ ++ boolean accessibleToPartition(String nodePartition) { ++ // if queue's label is *, it can access any node ++ if (accessibleLabels != null ++ && accessibleLabels.contains(RMNodeLabelsManager.ANY)) { ++ return true; ++ } ++ // any queue can access to a node without label ++ if (nodePartition == null ++ || nodePartition.equals(RMNodeLabelsManager.NO_LABEL)) { ++ return true; ++ } ++ // a queue can access to a node only if it contains any label of the node ++ if (accessibleLabels != null && accessibleLabels.contains(nodePartition)) { ++ return true; ++ } ++ // sorry, you cannot access ++ return false; ++ } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueue.java +index 1a9448acaa148..b06a646cec973 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CSQueue.java +@@ -190,10 +190,13 @@ public void finishApplicationAttempt(FiCaSchedulerApp application, + * @param clusterResource the resource of the cluster. + * @param node node on which resources are available + * @param resourceLimits how much overall resource of this queue can use. ++ * @param schedulingMode Type of exclusive check when assign container on a ++ * NodeManager, see {@link SchedulingMode}. + * @return the assignment + */ + public CSAssignment assignContainers(Resource clusterResource, +- FiCaSchedulerNode node, ResourceLimits resourceLimits); ++ FiCaSchedulerNode node, ResourceLimits resourceLimits, ++ SchedulingMode schedulingMode); + + /** + * A container assigned to the queue has completed. +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java +index e93c5291f2905..cfeee37d1e6ac 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java +@@ -35,6 +35,7 @@ + import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; + ++import org.apache.commons.lang.StringUtils; + import org.apache.commons.logging.Log; + import org.apache.commons.logging.LogFactory; + import org.apache.hadoop.classification.InterfaceAudience.LimitedPrivate; +@@ -1114,28 +1115,30 @@ private synchronized void allocateContainersToNode(FiCaSchedulerNode node) { + if (reservedContainer != null) { + FiCaSchedulerApp reservedApplication = + getCurrentAttemptForContainer(reservedContainer.getContainerId()); +- ++ + // Try to fulfill the reservation +- LOG.info(""Trying to fulfill reservation for application "" + +- reservedApplication.getApplicationId() + "" on node: "" + +- node.getNodeID()); +- +- LeafQueue queue = ((LeafQueue)reservedApplication.getQueue()); +- assignment = queue.assignContainers( ++ LOG.info(""Trying to fulfill reservation for application "" ++ + reservedApplication.getApplicationId() + "" on node: "" ++ + node.getNodeID()); ++ ++ LeafQueue queue = ((LeafQueue) reservedApplication.getQueue()); ++ assignment = ++ queue.assignContainers( + clusterResource, + node, + // TODO, now we only consider limits for parent for non-labeled + // resources, should consider labeled resources as well. + new ResourceLimits(labelManager.getResourceByLabel( +- RMNodeLabelsManager.NO_LABEL, clusterResource))); ++ RMNodeLabelsManager.NO_LABEL, clusterResource)), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + if (assignment.isFulfilledReservation()) { + CSAssignment tmp = + new CSAssignment(reservedContainer.getReservedResource(), +- assignment.getType()); ++ assignment.getType()); + Resources.addTo(assignment.getAssignmentInformation().getAllocated(), +- reservedContainer.getReservedResource()); ++ reservedContainer.getReservedResource()); + tmp.getAssignmentInformation().addAllocationDetails( +- reservedContainer.getContainerId(), queue.getQueuePath()); ++ reservedContainer.getContainerId(), queue.getQueuePath()); + tmp.getAssignmentInformation().incrAllocations(); + updateSchedulerHealth(lastNodeUpdateTime, node, tmp); + schedulerHealth.updateSchedulerFulfilledReservationCounts(1); +@@ -1143,16 +1146,13 @@ private synchronized void allocateContainersToNode(FiCaSchedulerNode node) { + + RMContainer excessReservation = assignment.getExcessReservation(); + if (excessReservation != null) { +- Container container = excessReservation.getContainer(); +- queue.completedContainer( +- clusterResource, assignment.getApplication(), node, +- excessReservation, +- SchedulerUtils.createAbnormalContainerStatus( +- container.getId(), +- SchedulerUtils.UNRESERVED_CONTAINER), +- RMContainerEventType.RELEASED, null, true); ++ Container container = excessReservation.getContainer(); ++ queue.completedContainer(clusterResource, assignment.getApplication(), ++ node, excessReservation, SchedulerUtils ++ .createAbnormalContainerStatus(container.getId(), ++ SchedulerUtils.UNRESERVED_CONTAINER), ++ RMContainerEventType.RELEASED, null, true); + } +- + } + + // Try to schedule more if there are no reservations to fulfill +@@ -1163,22 +1163,61 @@ private synchronized void allocateContainersToNode(FiCaSchedulerNode node) { + LOG.debug(""Trying to schedule on node: "" + node.getNodeName() + + "", available: "" + node.getAvailableResource()); + } ++ + assignment = root.assignContainers( + clusterResource, + node, + // TODO, now we only consider limits for parent for non-labeled + // resources, should consider labeled resources as well. + new ResourceLimits(labelManager.getResourceByLabel( +- RMNodeLabelsManager.NO_LABEL, clusterResource))); ++ RMNodeLabelsManager.NO_LABEL, clusterResource)), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); ++ if (Resources.greaterThan(calculator, clusterResource, ++ assignment.getResource(), Resources.none())) { ++ updateSchedulerHealth(lastNodeUpdateTime, node, assignment); ++ return; ++ } ++ ++ // Only do non-exclusive allocation when node has node-labels. ++ if (StringUtils.equals(node.getPartition(), ++ RMNodeLabelsManager.NO_LABEL)) { ++ return; ++ } ++ ++ // Only do non-exclusive allocation when the node-label supports that ++ try { ++ if (rmContext.getNodeLabelManager().isExclusiveNodeLabel( ++ node.getPartition())) { ++ return; ++ } ++ } catch (IOException e) { ++ LOG.warn(""Exception when trying to get exclusivity of node label="" ++ + node.getPartition(), e); ++ return; ++ } ++ ++ // Try to use NON_EXCLUSIVE ++ assignment = root.assignContainers( ++ clusterResource, ++ node, ++ // TODO, now we only consider limits for parent for non-labeled ++ // resources, should consider labeled resources as well. ++ new ResourceLimits(labelManager.getResourceByLabel( ++ RMNodeLabelsManager.NO_LABEL, clusterResource)), ++ SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY); + updateSchedulerHealth(lastNodeUpdateTime, node, assignment); ++ if (Resources.greaterThan(calculator, clusterResource, ++ assignment.getResource(), Resources.none())) { ++ return; ++ } + } + } else { +- LOG.info(""Skipping scheduling since node "" + node.getNodeID() + +- "" is reserved by application "" + +- node.getReservedContainer().getContainerId().getApplicationAttemptId() +- ); ++ LOG.info(""Skipping scheduling since node "" ++ + node.getNodeID() ++ + "" is reserved by application "" ++ + node.getReservedContainer().getContainerId() ++ .getApplicationAttemptId()); + } +- + } + + @Override +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java +index 102e5539f162a..4e8d61769ecdf 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java +@@ -319,6 +319,11 @@ public float getMaximumApplicationMasterResourcePerQueuePercent(String queue) { + getMaximumApplicationMasterResourcePercent()); + } + ++ public void setMaximumApplicationMasterResourcePerQueuePercent(String queue, ++ float percent) { ++ setFloat(getQueuePrefix(queue) + MAXIMUM_AM_RESOURCE_SUFFIX, percent); ++ } ++ + public float getNonLabeledQueueCapacity(String queue) { + float capacity = queue.equals(""root"") ? 100.0f : getFloat( + getQueuePrefix(queue) + CAPACITY, UNDEFINED); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java +index 59a016f98140d..8a6a601f202f7 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java +@@ -24,7 +24,6 @@ + import java.util.Collections; + import java.util.Comparator; + import java.util.HashMap; +-import java.util.HashSet; + import java.util.Iterator; + import java.util.List; + import java.util.Map; +@@ -58,6 +57,7 @@ + import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; + import org.apache.hadoop.yarn.security.AccessType; + import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; +@@ -718,39 +718,11 @@ private synchronized FiCaSchedulerApp getApplication( + ApplicationAttemptId applicationAttemptId) { + return applicationAttemptMap.get(applicationAttemptId); + } +- +- private static final CSAssignment NULL_ASSIGNMENT = +- new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); +- +- private static final CSAssignment SKIP_ASSIGNMENT = new CSAssignment(true); +- +- private static Set getRequestLabelSetByExpression( +- String labelExpression) { +- Set labels = new HashSet(); +- if (null == labelExpression) { +- return labels; +- } +- for (String l : labelExpression.split(""&&"")) { +- if (l.trim().isEmpty()) { +- continue; +- } +- labels.add(l.trim()); +- } +- return labels; +- } +- +- private boolean checkResourceRequestMatchingNodeLabel(ResourceRequest offswitchResourceRequest, +- FiCaSchedulerNode node) { +- String askedNodeLabel = offswitchResourceRequest.getNodeLabelExpression(); +- if (null == askedNodeLabel) { +- askedNodeLabel = RMNodeLabelsManager.NO_LABEL; +- } +- return askedNodeLabel.equals(node.getPartition()); +- } + + @Override + public synchronized CSAssignment assignContainers(Resource clusterResource, +- FiCaSchedulerNode node, ResourceLimits currentResourceLimits) { ++ FiCaSchedulerNode node, ResourceLimits currentResourceLimits, ++ SchedulingMode schedulingMode) { + updateCurrentResourceLimits(currentResourceLimits, clusterResource); + + if(LOG.isDebugEnabled()) { +@@ -758,12 +730,6 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + + "" #applications="" + activeApplications.size()); + } + +- // if our queue cannot access this node, just return +- if (!SchedulerUtils.checkQueueAccessToNode(accessibleLabels, +- node.getLabels())) { +- return NULL_ASSIGNMENT; +- } +- + // Check for reserved resources + RMContainer reservedContainer = node.getReservedContainer(); + if (reservedContainer != null) { +@@ -771,8 +737,26 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + getApplication(reservedContainer.getApplicationAttemptId()); + synchronized (application) { + return assignReservedContainer(application, node, reservedContainer, +- clusterResource); ++ clusterResource, schedulingMode); ++ } ++ } ++ ++ // if our queue cannot access this node, just return ++ if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY ++ && !accessibleToPartition(node.getPartition())) { ++ return NULL_ASSIGNMENT; ++ } ++ ++ // Check if this queue need more resource, simply skip allocation if this ++ // queue doesn't need more resources. ++ if (!hasPendingResourceRequest(node.getPartition(), ++ clusterResource, schedulingMode)) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Skip this queue="" + getQueuePath() ++ + "", because it doesn't need more resource, schedulingMode="" ++ + schedulingMode.name() + "" node-partition="" + node.getPartition()); + } ++ return NULL_ASSIGNMENT; + } + + // Try to assign containers to applications in order +@@ -783,6 +767,17 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + + application.getApplicationId()); + application.showRequests(); + } ++ ++ // Check if application needs more resource, skip if it doesn't need more. ++ if (!application.hasPendingResourceRequest(resourceCalculator, ++ node.getPartition(), clusterResource, schedulingMode)) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Skip app_attempt="" + application.getApplicationAttemptId() ++ + "", because it doesn't need more resource, schedulingMode="" ++ + schedulingMode.name() + "" node-label="" + node.getPartition()); ++ } ++ continue; ++ } + + synchronized (application) { + // Check if this resource is on the blacklist +@@ -806,10 +801,27 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + continue; + } + ++ // AM container allocation doesn't support non-exclusive allocation to ++ // avoid painful of preempt an AM container ++ if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { ++ RMAppAttempt rmAppAttempt = ++ csContext.getRMContext().getRMApps() ++ .get(application.getApplicationId()).getCurrentAppAttempt(); ++ if (null == rmAppAttempt.getMasterContainer()) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Skip allocating AM container to app_attempt="" ++ + application.getApplicationAttemptId() ++ + "", don't allow to allocate AM container in non-exclusive mode""); ++ } ++ break; ++ } ++ } ++ + // Is the node-label-expression of this offswitch resource request + // matches the node's label? + // If not match, jump to next priority. +- if (!checkResourceRequestMatchingNodeLabel(anyRequest, node)) { ++ if (!SchedulerUtils.checkResourceRequestMatchingNodePartition( ++ anyRequest, node.getPartition(), schedulingMode)) { + continue; + } + +@@ -822,10 +834,6 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + } + } + +- Set requestedNodeLabels = +- getRequestLabelSetByExpression(anyRequest +- .getNodeLabelExpression()); +- + // Compute user-limit & set headroom + // Note: We compute both user-limit & headroom with the highest + // priority request as the target. +@@ -833,27 +841,61 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + // before all higher priority ones are serviced. + Resource userLimit = + computeUserLimitAndSetHeadroom(application, clusterResource, +- required, requestedNodeLabels); ++ required, node.getPartition(), schedulingMode); + + // Check queue max-capacity limit +- if (!super.canAssignToThisQueue(clusterResource, node.getLabels(), +- this.currentResourceLimits, required, application.getCurrentReservation())) { ++ if (!super.canAssignToThisQueue(clusterResource, node.getPartition(), ++ this.currentResourceLimits, required, ++ application.getCurrentReservation(), schedulingMode)) { + return NULL_ASSIGNMENT; + } + + // Check user limit + if (!canAssignToUser(clusterResource, application.getUser(), userLimit, +- application, true, requestedNodeLabels)) { ++ application, true, node.getPartition())) { + break; + } + + // Inform the application it is about to get a scheduling opportunity + application.addSchedulingOpportunity(priority); + ++ // Increase missed-non-partitioned-resource-request-opportunity. ++ // This is to make sure non-partitioned-resource-request will prefer ++ // to be allocated to non-partitioned nodes ++ int missedNonPartitionedRequestSchedulingOpportunity = 0; ++ if (anyRequest.getNodeLabelExpression().equals( ++ RMNodeLabelsManager.NO_LABEL)) { ++ missedNonPartitionedRequestSchedulingOpportunity = ++ application ++ .addMissedNonPartitionedRequestSchedulingOpportunity(priority); ++ } ++ ++ if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { ++ // Before doing allocation, we need to check scheduling opportunity to ++ // make sure : non-partitioned resource request should be scheduled to ++ // non-partitioned partition first. ++ if (missedNonPartitionedRequestSchedulingOpportunity < scheduler ++ .getNumClusterNodes()) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Skip app_attempt="" ++ + application.getApplicationAttemptId() ++ + "" priority="" ++ + priority ++ + "" because missed-non-partitioned-resource-request"" ++ + "" opportunity under requred:"" ++ + "" Now="" + missedNonPartitionedRequestSchedulingOpportunity ++ + "" required="" ++ + scheduler.getNumClusterNodes()); ++ } ++ ++ break; ++ } ++ } ++ + // Try to schedule + CSAssignment assignment = + assignContainersOnNode(clusterResource, node, application, priority, +- null); ++ null, schedulingMode); + + // Did the application skip this node? + if (assignment.getSkipped()) { +@@ -870,9 +912,9 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + // Book-keeping + // Note: Update headroom to account for current allocation too... + allocateResource(clusterResource, application, assigned, +- node.getLabels()); ++ node.getPartition()); + +- // Don't reset scheduling opportunities for non-local assignments ++ // Don't reset scheduling opportunities for offswitch assignments + // otherwise the app will be delayed for each non-local assignment. + // This helps apps with many off-cluster requests schedule faster. + if (assignment.getType() != NodeType.OFF_SWITCH) { +@@ -881,6 +923,10 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + } + application.resetSchedulingOpportunities(priority); + } ++ // Non-exclusive scheduling opportunity is different: we need reset ++ // it every time to make sure non-labeled resource request will be ++ // most likely allocated on non-labeled nodes first. ++ application.resetMissedNonPartitionedRequestSchedulingOpportunity(priority); + + // Done + return assignment; +@@ -904,7 +950,8 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + + private synchronized CSAssignment assignReservedContainer( + FiCaSchedulerApp application, FiCaSchedulerNode node, +- RMContainer rmContainer, Resource clusterResource) { ++ RMContainer rmContainer, Resource clusterResource, ++ SchedulingMode schedulingMode) { + // Do we still need this reservation? + Priority priority = rmContainer.getReservedPriority(); + if (application.getTotalRequiredResources(priority) == 0) { +@@ -915,7 +962,7 @@ private synchronized CSAssignment assignReservedContainer( + // Try to assign if we have sufficient resources + CSAssignment tmp = + assignContainersOnNode(clusterResource, node, application, priority, +- rmContainer); ++ rmContainer, schedulingMode); + + // Doesn't matter... since it's already charged for at time of reservation + // ""re-reservation"" is *free* +@@ -929,7 +976,8 @@ private synchronized CSAssignment assignReservedContainer( + protected Resource getHeadroom(User user, Resource queueCurrentLimit, + Resource clusterResource, FiCaSchedulerApp application, Resource required) { + return getHeadroom(user, queueCurrentLimit, clusterResource, +- computeUserLimit(application, clusterResource, required, user, null)); ++ computeUserLimit(application, clusterResource, required, user, ++ RMNodeLabelsManager.NO_LABEL, SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY)); + } + + private Resource getHeadroom(User user, Resource currentResourceLimit, +@@ -973,7 +1021,8 @@ private void setQueueResourceLimitsInfo( + + @Lock({LeafQueue.class, FiCaSchedulerApp.class}) + Resource computeUserLimitAndSetHeadroom(FiCaSchedulerApp application, +- Resource clusterResource, Resource required, Set requestedLabels) { ++ Resource clusterResource, Resource required, String nodePartition, ++ SchedulingMode schedulingMode) { + String user = application.getUser(); + User queueUser = getUser(user); + +@@ -981,7 +1030,7 @@ Resource computeUserLimitAndSetHeadroom(FiCaSchedulerApp application, + // TODO, need consider headroom respect labels also + Resource userLimit = + computeUserLimit(application, clusterResource, required, +- queueUser, requestedLabels); ++ queueUser, nodePartition, schedulingMode); + + setQueueResourceLimitsInfo(clusterResource); + +@@ -1010,34 +1059,18 @@ Resource computeUserLimitAndSetHeadroom(FiCaSchedulerApp application, + @Lock(NoLock.class) + private Resource computeUserLimit(FiCaSchedulerApp application, + Resource clusterResource, Resource required, User user, +- Set requestedLabels) { ++ String nodePartition, SchedulingMode schedulingMode) { + // What is our current capacity? + // * It is equal to the max(required, queue-capacity) if + // we're running below capacity. The 'max' ensures that jobs in queues + // with miniscule capacity (< 1 slot) make progress + // * If we're running over capacity, then its + // (usedResources + required) (which extra resources we are allocating) +- Resource queueCapacity = Resource.newInstance(0, 0); +- if (requestedLabels != null && !requestedLabels.isEmpty()) { +- // if we have multiple labels to request, we will choose to use the first +- // label +- String firstLabel = requestedLabels.iterator().next(); +- queueCapacity = +- Resources +- .max(resourceCalculator, clusterResource, queueCapacity, +- Resources.multiplyAndNormalizeUp(resourceCalculator, +- labelManager.getResourceByLabel(firstLabel, +- clusterResource), +- queueCapacities.getAbsoluteCapacity(firstLabel), +- minimumAllocation)); +- } else { +- // else there's no label on request, just to use absolute capacity as +- // capacity for nodes without label +- queueCapacity = +- Resources.multiplyAndNormalizeUp(resourceCalculator, labelManager +- .getResourceByLabel(CommonNodeLabelsManager.NO_LABEL, clusterResource), +- queueCapacities.getAbsoluteCapacity(), minimumAllocation); +- } ++ Resource queueCapacity = ++ Resources.multiplyAndNormalizeUp(resourceCalculator, ++ labelManager.getResourceByLabel(nodePartition, clusterResource), ++ queueCapacities.getAbsoluteCapacity(nodePartition), ++ minimumAllocation); + + // Allow progress for queues with miniscule capacity + queueCapacity = +@@ -1047,33 +1080,56 @@ private Resource computeUserLimit(FiCaSchedulerApp application, + required); + + Resource currentCapacity = +- Resources.lessThan(resourceCalculator, clusterResource, +- queueUsage.getUsed(), queueCapacity) ? +- queueCapacity : Resources.add(queueUsage.getUsed(), required); ++ Resources.lessThan(resourceCalculator, clusterResource, ++ queueUsage.getUsed(nodePartition), queueCapacity) ? queueCapacity ++ : Resources.add(queueUsage.getUsed(nodePartition), required); + + // Never allow a single user to take more than the + // queue's configured capacity * user-limit-factor. + // Also, the queue's configured capacity should be higher than + // queue-hard-limit * ulMin + +- final int activeUsers = activeUsersManager.getNumActiveUsers(); +- +- Resource limit = ++ final int activeUsers = activeUsersManager.getNumActiveUsers(); ++ ++ // User limit resource is determined by: ++ // max{currentCapacity / #activeUsers, currentCapacity * user-limit-percentage%) ++ Resource userLimitResource = Resources.max( ++ resourceCalculator, clusterResource, ++ Resources.divideAndCeil( ++ resourceCalculator, currentCapacity, activeUsers), ++ Resources.divideAndCeil( ++ resourceCalculator, ++ Resources.multiplyAndRoundDown( ++ currentCapacity, userLimit), ++ 100) ++ ); ++ ++ // User limit is capped by maxUserLimit ++ // - maxUserLimit = queueCapacity * user-limit-factor (RESPECT_PARTITION_EXCLUSIVITY) ++ // - maxUserLimit = total-partition-resource (IGNORE_PARTITION_EXCLUSIVITY) ++ // ++ // In IGNORE_PARTITION_EXCLUSIVITY mode, if a queue cannot access a ++ // partition, its guaranteed resource on that partition is 0. And ++ // user-limit-factor computation is based on queue's guaranteed capacity. So ++ // we will not cap user-limit as well as used resource when doing ++ // IGNORE_PARTITION_EXCLUSIVITY allocation. ++ Resource maxUserLimit = Resources.none(); ++ if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY) { ++ maxUserLimit = ++ Resources.multiplyAndRoundDown(queueCapacity, userLimitFactor); ++ } else if (schedulingMode == SchedulingMode.IGNORE_PARTITION_EXCLUSIVITY) { ++ maxUserLimit = ++ labelManager.getResourceByLabel(nodePartition, clusterResource); ++ } ++ ++ // Cap final user limit with maxUserLimit ++ userLimitResource = + Resources.roundUp( + resourceCalculator, + Resources.min( + resourceCalculator, clusterResource, +- Resources.max( +- resourceCalculator, clusterResource, +- Resources.divideAndCeil( +- resourceCalculator, currentCapacity, activeUsers), +- Resources.divideAndCeil( +- resourceCalculator, +- Resources.multiplyAndRoundDown( +- currentCapacity, userLimit), +- 100) +- ), +- Resources.multiplyAndRoundDown(queueCapacity, userLimitFactor) ++ userLimitResource, ++ maxUserLimit + ), + minimumAllocation); + +@@ -1081,11 +1137,11 @@ private Resource computeUserLimit(FiCaSchedulerApp application, + String userName = application.getUser(); + LOG.debug(""User limit computation for "" + userName + + "" in queue "" + getQueueName() + +- "" userLimit="" + userLimit + ++ "" userLimitPercent="" + userLimit + + "" userLimitFactor="" + userLimitFactor + + "" required: "" + required + + "" consumed: "" + user.getUsed() + +- "" limit: "" + limit + ++ "" user-limit-resource: "" + userLimitResource + + "" queueCapacity: "" + queueCapacity + + "" qconsumed: "" + queueUsage.getUsed() + + "" currentCapacity: "" + currentCapacity + +@@ -1093,31 +1149,26 @@ private Resource computeUserLimit(FiCaSchedulerApp application, + "" clusterCapacity: "" + clusterResource + ); + } +- user.setUserResourceLimit(limit); +- return limit; ++ user.setUserResourceLimit(userLimitResource); ++ return userLimitResource; + } + + @Private + protected synchronized boolean canAssignToUser(Resource clusterResource, + String userName, Resource limit, FiCaSchedulerApp application, +- boolean checkReservations, Set requestLabels) { ++ boolean checkReservations, String nodePartition) { + User user = getUser(userName); +- +- String label = CommonNodeLabelsManager.NO_LABEL; +- if (requestLabels != null && !requestLabels.isEmpty()) { +- label = requestLabels.iterator().next(); +- } + + // Note: We aren't considering the current request since there is a fixed + // overhead of the AM, but it's a > check, not a >= check, so... + if (Resources + .greaterThan(resourceCalculator, clusterResource, +- user.getUsed(label), ++ user.getUsed(nodePartition), + limit)) { + // if enabled, check to see if could we potentially use this node instead + // of a reserved node if the application has reserved containers + if (this.reservationsContinueLooking && checkReservations +- && label.equals(CommonNodeLabelsManager.NO_LABEL)) { ++ && nodePartition.equals(CommonNodeLabelsManager.NO_LABEL)) { + if (Resources.lessThanOrEqual( + resourceCalculator, + clusterResource, +@@ -1136,7 +1187,7 @@ protected synchronized boolean canAssignToUser(Resource clusterResource, + if (LOG.isDebugEnabled()) { + LOG.debug(""User "" + userName + "" in queue "" + getQueueName() + + "" will exceed limit - "" + "" consumed: "" +- + user.getUsed() + "" limit: "" + limit); ++ + user.getUsed(nodePartition) + "" limit: "" + limit); + } + return false; + } +@@ -1176,7 +1227,7 @@ resourceCalculator, required, getMaximumAllocation() + + private CSAssignment assignContainersOnNode(Resource clusterResource, + FiCaSchedulerNode node, FiCaSchedulerApp application, Priority priority, +- RMContainer reservedContainer) { ++ RMContainer reservedContainer, SchedulingMode schedulingMode) { + + CSAssignment assigned; + +@@ -1190,7 +1241,7 @@ private CSAssignment assignContainersOnNode(Resource clusterResource, + assigned = + assignNodeLocalContainers(clusterResource, nodeLocalResourceRequest, + node, application, priority, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + if (Resources.greaterThan(resourceCalculator, clusterResource, + assigned.getResource(), Resources.none())) { + +@@ -1219,7 +1270,7 @@ private CSAssignment assignContainersOnNode(Resource clusterResource, + assigned = + assignRackLocalContainers(clusterResource, rackLocalResourceRequest, + node, application, priority, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + if (Resources.greaterThan(resourceCalculator, clusterResource, + assigned.getResource(), Resources.none())) { + +@@ -1248,7 +1299,7 @@ private CSAssignment assignContainersOnNode(Resource clusterResource, + assigned = + assignOffSwitchContainers(clusterResource, offSwitchResourceRequest, + node, application, priority, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + + // update locality statistics + if (allocatedContainer.getValue() != null) { +@@ -1314,16 +1365,17 @@ protected boolean findNodeToUnreserve(Resource clusterResource, + + @Private + protected boolean checkLimitsToReserve(Resource clusterResource, +- FiCaSchedulerApp application, Resource capability) { ++ FiCaSchedulerApp application, Resource capability, String nodePartition, ++ SchedulingMode schedulingMode) { + // we can't reserve if we got here based on the limit + // checks assuming we could unreserve!!! + Resource userLimit = computeUserLimitAndSetHeadroom(application, +- clusterResource, capability, null); ++ clusterResource, capability, nodePartition, schedulingMode); + + // Check queue max-capacity limit, + // TODO: Consider reservation on labels +- if (!canAssignToThisQueue(clusterResource, null, +- this.currentResourceLimits, capability, Resources.none())) { ++ if (!canAssignToThisQueue(clusterResource, RMNodeLabelsManager.NO_LABEL, ++ this.currentResourceLimits, capability, Resources.none(), schedulingMode)) { + if (LOG.isDebugEnabled()) { + LOG.debug(""was going to reserve but hit queue limit""); + } +@@ -1332,7 +1384,7 @@ protected boolean checkLimitsToReserve(Resource clusterResource, + + // Check user limit + if (!canAssignToUser(clusterResource, application.getUser(), userLimit, +- application, false, null)) { ++ application, false, nodePartition)) { + if (LOG.isDebugEnabled()) { + LOG.debug(""was going to reserve but hit user limit""); + } +@@ -1345,12 +1397,13 @@ protected boolean checkLimitsToReserve(Resource clusterResource, + private CSAssignment assignNodeLocalContainers(Resource clusterResource, + ResourceRequest nodeLocalResourceRequest, FiCaSchedulerNode node, + FiCaSchedulerApp application, Priority priority, +- RMContainer reservedContainer, MutableObject allocatedContainer) { ++ RMContainer reservedContainer, MutableObject allocatedContainer, ++ SchedulingMode schedulingMode) { + if (canAssign(application, priority, node, NodeType.NODE_LOCAL, + reservedContainer)) { + return assignContainer(clusterResource, node, application, priority, + nodeLocalResourceRequest, NodeType.NODE_LOCAL, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + } + + return new CSAssignment(Resources.none(), NodeType.NODE_LOCAL); +@@ -1359,12 +1412,13 @@ private CSAssignment assignNodeLocalContainers(Resource clusterResource, + private CSAssignment assignRackLocalContainers(Resource clusterResource, + ResourceRequest rackLocalResourceRequest, FiCaSchedulerNode node, + FiCaSchedulerApp application, Priority priority, +- RMContainer reservedContainer, MutableObject allocatedContainer) { ++ RMContainer reservedContainer, MutableObject allocatedContainer, ++ SchedulingMode schedulingMode) { + if (canAssign(application, priority, node, NodeType.RACK_LOCAL, + reservedContainer)) { + return assignContainer(clusterResource, node, application, priority, + rackLocalResourceRequest, NodeType.RACK_LOCAL, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + } + + return new CSAssignment(Resources.none(), NodeType.RACK_LOCAL); +@@ -1373,16 +1427,21 @@ private CSAssignment assignRackLocalContainers(Resource clusterResource, + private CSAssignment assignOffSwitchContainers(Resource clusterResource, + ResourceRequest offSwitchResourceRequest, FiCaSchedulerNode node, + FiCaSchedulerApp application, Priority priority, +- RMContainer reservedContainer, MutableObject allocatedContainer) { ++ RMContainer reservedContainer, MutableObject allocatedContainer, ++ SchedulingMode schedulingMode) { + if (canAssign(application, priority, node, NodeType.OFF_SWITCH, + reservedContainer)) { + return assignContainer(clusterResource, node, application, priority, + offSwitchResourceRequest, NodeType.OFF_SWITCH, reservedContainer, +- allocatedContainer); ++ allocatedContainer, schedulingMode); + } + + return new CSAssignment(Resources.none(), NodeType.OFF_SWITCH); + } ++ ++ private int getActualNodeLocalityDelay() { ++ return Math.min(scheduler.getNumClusterNodes(), getNodeLocalityDelay()); ++ } + + boolean canAssign(FiCaSchedulerApp application, Priority priority, + FiCaSchedulerNode node, NodeType type, RMContainer reservedContainer) { +@@ -1417,10 +1476,7 @@ boolean canAssign(FiCaSchedulerApp application, Priority priority, + if (type == NodeType.RACK_LOCAL) { + // 'Delay' rack-local just a little bit... + long missedOpportunities = application.getSchedulingOpportunities(priority); +- return ( +- Math.min(scheduler.getNumClusterNodes(), getNodeLocalityDelay()) < +- missedOpportunities +- ); ++ return getActualNodeLocalityDelay() < missedOpportunities; + } + + // Check if we need containers on this host +@@ -1460,7 +1516,7 @@ Container createContainer(FiCaSchedulerApp application, FiCaSchedulerNode node, + private CSAssignment assignContainer(Resource clusterResource, FiCaSchedulerNode node, + FiCaSchedulerApp application, Priority priority, + ResourceRequest request, NodeType type, RMContainer rmContainer, +- MutableObject createdContainer) { ++ MutableObject createdContainer, SchedulingMode schedulingMode) { + if (LOG.isDebugEnabled()) { + LOG.debug(""assignContainers: node="" + node.getNodeName() + + "" application="" + application.getApplicationId() +@@ -1469,9 +1525,8 @@ private CSAssignment assignContainer(Resource clusterResource, FiCaSchedulerNode + } + + // check if the resource request can access the label +- if (!SchedulerUtils.checkNodeLabelExpression( +- node.getLabels(), +- request.getNodeLabelExpression())) { ++ if (!SchedulerUtils.checkResourceRequestMatchingNodePartition(request, ++ node.getPartition(), schedulingMode)) { + // this is a reserved container, but we cannot allocate it now according + // to label not match. This can be caused by node label changed + // We should un-reserve this container. +@@ -1576,8 +1631,8 @@ private CSAssignment assignContainer(Resource clusterResource, FiCaSchedulerNode + // If we're trying to reserve a container here, not container will be + // unreserved for reserving the new one. Check limits again before + // reserve the new container +- if (!checkLimitsToReserve(clusterResource, +- application, capability)) { ++ if (!checkLimitsToReserve(clusterResource, ++ application, capability, node.getPartition(), schedulingMode)) { + return new CSAssignment(Resources.none(), type); + } + } +@@ -1666,7 +1721,7 @@ public void completedContainer(Resource clusterResource, + // Book-keeping + if (removed) { + releaseResource(clusterResource, application, +- container.getResource(), node.getLabels()); ++ container.getResource(), node.getPartition()); + LOG.info(""completedContainer"" + + "" container="" + container + + "" queue="" + this + +@@ -1684,13 +1739,13 @@ public void completedContainer(Resource clusterResource, + + synchronized void allocateResource(Resource clusterResource, + SchedulerApplicationAttempt application, Resource resource, +- Set nodeLabels) { +- super.allocateResource(clusterResource, resource, nodeLabels); ++ String nodePartition) { ++ super.allocateResource(clusterResource, resource, nodePartition); + + // Update user metrics + String userName = application.getUser(); + User user = getUser(userName); +- user.assignContainer(resource, nodeLabels); ++ user.assignContainer(resource, nodePartition); + // Note this is a bit unconventional since it gets the object and modifies + // it here, rather then using set routine + Resources.subtractFrom(application.getHeadroom(), resource); // headroom +@@ -1707,13 +1762,13 @@ synchronized void allocateResource(Resource clusterResource, + } + + synchronized void releaseResource(Resource clusterResource, +- FiCaSchedulerApp application, Resource resource, Set nodeLabels) { +- super.releaseResource(clusterResource, resource, nodeLabels); ++ FiCaSchedulerApp application, Resource resource, String nodePartition) { ++ super.releaseResource(clusterResource, resource, nodePartition); + + // Update user metrics + String userName = application.getUser(); + User user = getUser(userName); +- user.releaseContainer(resource, nodeLabels); ++ user.releaseContainer(resource, nodePartition); + metrics.setAvailableResourcesToUser(userName, application.getHeadroom()); + + LOG.info(getQueueName() + +@@ -1723,7 +1778,8 @@ synchronized void releaseResource(Resource clusterResource, + + private void updateAbsoluteCapacityResource(Resource clusterResource) { + absoluteCapacityResource = +- Resources.multiplyAndNormalizeUp(resourceCalculator, clusterResource, ++ Resources.multiplyAndNormalizeUp(resourceCalculator, labelManager ++ .getResourceByLabel(RMNodeLabelsManager.NO_LABEL, clusterResource), + queueCapacities.getAbsoluteCapacity(), minimumAllocation); + } + +@@ -1769,8 +1825,9 @@ resourceCalculator, this, getParent(), clusterResource, + // Update application properties + for (FiCaSchedulerApp application : activeApplications) { + synchronized (application) { +- computeUserLimitAndSetHeadroom(application, clusterResource, +- Resources.none(), null); ++ computeUserLimitAndSetHeadroom(application, clusterResource, ++ Resources.none(), RMNodeLabelsManager.NO_LABEL, ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } + } + } +@@ -1828,25 +1885,12 @@ public synchronized void finishApplication(boolean wasActive) { + } + } + +- public void assignContainer(Resource resource, +- Set nodeLabels) { +- if (nodeLabels == null || nodeLabels.isEmpty()) { +- userResourceUsage.incUsed(resource); +- } else { +- for (String label : nodeLabels) { +- userResourceUsage.incUsed(label, resource); +- } +- } ++ public void assignContainer(Resource resource, String nodePartition) { ++ userResourceUsage.incUsed(nodePartition, resource); + } + +- public void releaseContainer(Resource resource, Set nodeLabels) { +- if (nodeLabels == null || nodeLabels.isEmpty()) { +- userResourceUsage.decUsed(resource); +- } else { +- for (String label : nodeLabels) { +- userResourceUsage.decUsed(label, resource); +- } +- } ++ public void releaseContainer(Resource resource, String nodePartition) { ++ userResourceUsage.decUsed(nodePartition, resource); + } + + public Resource getUserResourceLimit() { +@@ -1869,7 +1913,7 @@ public void recoverContainer(Resource clusterResource, + FiCaSchedulerNode node = + scheduler.getNode(rmContainer.getContainer().getNodeId()); + allocateResource(clusterResource, attempt, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + } + getParent().recoverContainer(clusterResource, attempt, rmContainer); + } +@@ -1909,7 +1953,7 @@ public void attachContainer(Resource clusterResource, + FiCaSchedulerNode node = + scheduler.getNode(rmContainer.getContainer().getNodeId()); + allocateResource(clusterResource, application, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + LOG.info(""movedContainer"" + "" container="" + rmContainer.getContainer() + + "" resource="" + rmContainer.getContainer().getResource() + + "" queueMoveIn="" + this + "" usedCapacity="" + getUsedCapacity() +@@ -1927,7 +1971,7 @@ public void detachContainer(Resource clusterResource, + FiCaSchedulerNode node = + scheduler.getNode(rmContainer.getContainer().getNodeId()); + releaseResource(clusterResource, application, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + LOG.info(""movedContainer"" + "" container="" + rmContainer.getContainer() + + "" resource="" + rmContainer.getContainer().getResource() + + "" queueMoveOut="" + this + "" usedCapacity="" + getUsedCapacity() +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java +index 882498a6808f2..eb64d4384f0a7 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.java +@@ -56,8 +56,6 @@ + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt; +-import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerUtils; +-import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.AssignmentInformation; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerNode; + import org.apache.hadoop.yarn.util.resource.Resources; +@@ -377,16 +375,29 @@ private synchronized void removeApplication(ApplicationId applicationId, + + @Override + public synchronized CSAssignment assignContainers(Resource clusterResource, +- FiCaSchedulerNode node, ResourceLimits resourceLimits) { +- CSAssignment assignment = +- new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); +- Set nodeLabels = node.getLabels(); +- ++ FiCaSchedulerNode node, ResourceLimits resourceLimits, ++ SchedulingMode schedulingMode) { + // if our queue cannot access this node, just return +- if (!SchedulerUtils.checkQueueAccessToNode(accessibleLabels, nodeLabels)) { +- return assignment; ++ if (schedulingMode == SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY ++ && !accessibleToPartition(node.getPartition())) { ++ return NULL_ASSIGNMENT; ++ } ++ ++ // Check if this queue need more resource, simply skip allocation if this ++ // queue doesn't need more resources. ++ if (!super.hasPendingResourceRequest(node.getPartition(), ++ clusterResource, schedulingMode)) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Skip this queue="" + getQueuePath() ++ + "", because it doesn't need more resource, schedulingMode="" ++ + schedulingMode.name() + "" node-partition="" + node.getPartition()); ++ } ++ return NULL_ASSIGNMENT; + } + ++ CSAssignment assignment = ++ new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); ++ + while (canAssign(clusterResource, node)) { + if (LOG.isDebugEnabled()) { + LOG.debug(""Trying to assign containers to child-queue of "" +@@ -396,15 +407,17 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + // Are we over maximum-capacity for this queue? + // This will also consider parent's limits and also continuous reservation + // looking +- if (!super.canAssignToThisQueue(clusterResource, nodeLabels, resourceLimits, +- minimumAllocation, Resources.createResource(getMetrics() +- .getReservedMB(), getMetrics().getReservedVirtualCores()))) { ++ if (!super.canAssignToThisQueue(clusterResource, node.getPartition(), ++ resourceLimits, minimumAllocation, Resources.createResource( ++ getMetrics().getReservedMB(), getMetrics() ++ .getReservedVirtualCores()), schedulingMode)) { + break; + } + + // Schedule +- CSAssignment assignedToChild = +- assignContainersToChildQueues(clusterResource, node, resourceLimits); ++ CSAssignment assignedToChild = ++ assignContainersToChildQueues(clusterResource, node, resourceLimits, ++ schedulingMode); + assignment.setType(assignedToChild.getType()); + + // Done if no child-queue assigned anything +@@ -413,7 +426,7 @@ public synchronized CSAssignment assignContainers(Resource clusterResource, + assignedToChild.getResource(), Resources.none())) { + // Track resource utilization for the parent-queue + super.allocateResource(clusterResource, assignedToChild.getResource(), +- nodeLabels); ++ node.getPartition()); + + // Track resource utilization in this pass of the scheduler + Resources +@@ -510,7 +523,8 @@ private ResourceLimits getResourceLimitsOfChild(CSQueue child, + } + + private synchronized CSAssignment assignContainersToChildQueues( +- Resource cluster, FiCaSchedulerNode node, ResourceLimits limits) { ++ Resource cluster, FiCaSchedulerNode node, ResourceLimits limits, ++ SchedulingMode schedulingMode) { + CSAssignment assignment = + new CSAssignment(Resources.createResource(0, 0), NodeType.NODE_LOCAL); + +@@ -523,12 +537,13 @@ private synchronized CSAssignment assignContainersToChildQueues( + LOG.debug(""Trying to assign to queue: "" + childQueue.getQueuePath() + + "" stats: "" + childQueue); + } +- ++ + // Get ResourceLimits of child queue before assign containers + ResourceLimits childLimits = + getResourceLimitsOfChild(childQueue, cluster, limits); + +- assignment = childQueue.assignContainers(cluster, node, childLimits); ++ assignment = childQueue.assignContainers(cluster, node, ++ childLimits, schedulingMode); + if(LOG.isDebugEnabled()) { + LOG.debug(""Assigned to queue: "" + childQueue.getQueuePath() + + "" stats: "" + childQueue + "" --> "" + +@@ -584,7 +599,7 @@ public void completedContainer(Resource clusterResource, + // Book keeping + synchronized (this) { + super.releaseResource(clusterResource, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + + LOG.info(""completedContainer"" + + "" queue="" + getQueueName() + +@@ -653,7 +668,7 @@ public void recoverContainer(Resource clusterResource, + FiCaSchedulerNode node = + scheduler.getNode(rmContainer.getContainer().getNodeId()); + super.allocateResource(clusterResource, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + } + if (parent != null) { + parent.recoverContainer(clusterResource, attempt, rmContainer); +@@ -681,7 +696,7 @@ public void attachContainer(Resource clusterResource, + FiCaSchedulerNode node = + scheduler.getNode(rmContainer.getContainer().getNodeId()); + super.allocateResource(clusterResource, rmContainer.getContainer() +- .getResource(), node.getLabels()); ++ .getResource(), node.getPartition()); + LOG.info(""movedContainer"" + "" queueMoveIn="" + getQueueName() + + "" usedCapacity="" + getUsedCapacity() + "" absoluteUsedCapacity="" + + getAbsoluteUsedCapacity() + "" used="" + queueUsage.getUsed() + "" cluster="" +@@ -701,7 +716,7 @@ public void detachContainer(Resource clusterResource, + scheduler.getNode(rmContainer.getContainer().getNodeId()); + super.releaseResource(clusterResource, + rmContainer.getContainer().getResource(), +- node.getLabels()); ++ node.getPartition()); + LOG.info(""movedContainer"" + "" queueMoveOut="" + getQueueName() + + "" usedCapacity="" + getUsedCapacity() + "" absoluteUsedCapacity="" + + getAbsoluteUsedCapacity() + "" used="" + queueUsage.getUsed() + "" cluster="" +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/SchedulingMode.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/SchedulingMode.java +new file mode 100644 +index 0000000000000..7e7dc37c9bea1 +--- /dev/null ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/SchedulingMode.java +@@ -0,0 +1,44 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; ++ ++/** ++ * Scheduling modes, see below for detailed explanations ++ */ ++public enum SchedulingMode { ++ /** ++ *

++ * When a node has partition (say partition=x), only application in the queue ++ * can access to partition=x AND requires for partition=x resource can get ++ * chance to allocate on the node. ++ *

++ * ++ *

++ * When a node has no partition, only application requires non-partitioned ++ * resource can get chance to allocate on the node. ++ *

++ */ ++ RESPECT_PARTITION_EXCLUSIVITY, ++ ++ /** ++ * Only used when a node has partition AND the partition isn't an exclusive ++ * partition AND application requires non-partitioned resource. ++ */ ++ IGNORE_PARTITION_EXCLUSIVITY ++} +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Application.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Application.java +index 76ede3940f825..9b7eb840dbecc 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Application.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/Application.java +@@ -54,6 +54,7 @@ + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; + import org.apache.hadoop.yarn.server.resourcemanager.Task.State; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; +@@ -277,6 +278,9 @@ private synchronized void addResourceRequest( + } else { + request.setNumContainers(request.getNumContainers() + 1); + } ++ if (request.getNodeLabelExpression() == null) { ++ request.setNodeLabelExpression(RMNodeLabelsManager.NO_LABEL); ++ } + + // Note this down for next interaction with ResourceManager + ask.remove(request); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.java +index f62fdb3dcee22..5c107aa38bfb1 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockAM.java +@@ -150,8 +150,14 @@ public AllocateResponse allocate( + public AllocateResponse allocate( + String host, int memory, int numContainers, + List releases, String labelExpression) throws Exception { ++ return allocate(host, memory, numContainers, 1, releases, labelExpression); ++ } ++ ++ public AllocateResponse allocate( ++ String host, int memory, int numContainers, int priority, ++ List releases, String labelExpression) throws Exception { + List reqs = +- createReq(new String[] { host }, memory, 1, numContainers, ++ createReq(new String[] { host }, memory, priority, numContainers, + labelExpression); + return allocate(reqs, releases); + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRM.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRM.java +index 06c6b3275e334..f2b1d8646de51 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRM.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/MockRM.java +@@ -21,6 +21,8 @@ + import java.io.IOException; + import java.nio.ByteBuffer; + import java.security.PrivilegedAction; ++import java.util.Arrays; ++import java.util.Collection; + import java.util.List; + import java.util.Map; + +@@ -200,10 +202,18 @@ public boolean waitForState(MockNM nm, ContainerId containerId, + + public boolean waitForState(MockNM nm, ContainerId containerId, + RMContainerState containerState, int timeoutMillisecs) throws Exception { ++ return waitForState(Arrays.asList(nm), containerId, containerState, ++ timeoutMillisecs); ++ } ++ ++ public boolean waitForState(Collection nms, ContainerId containerId, ++ RMContainerState containerState, int timeoutMillisecs) throws Exception { + RMContainer container = getResourceScheduler().getRMContainer(containerId); + int timeoutSecs = 0; + while(container == null && timeoutSecs++ < timeoutMillisecs / 100) { +- nm.nodeHeartbeat(true); ++ for (MockNM nm : nms) { ++ nm.nodeHeartbeat(true); ++ } + container = getResourceScheduler().getRMContainer(containerId); + System.out.println(""Waiting for container "" + containerId + "" to be allocated.""); + Thread.sleep(100); +@@ -217,9 +227,11 @@ public boolean waitForState(MockNM nm, ContainerId containerId, + && timeoutSecs++ < timeoutMillisecs / 100) { + System.out.println(""Container : "" + containerId + "" State is : "" + + container.getState() + "" Waiting for state : "" + containerState); +- nm.nodeHeartbeat(true); ++ for (MockNM nm : nms) { ++ nm.nodeHeartbeat(true); ++ } + Thread.sleep(100); +- ++ + if (timeoutMillisecs <= timeoutSecs * 100) { + return false; + } +@@ -650,11 +662,28 @@ public static void finishAMAndVerifyAppState(RMApp rmApp, MockRM rm, MockNM nm, + am.waitForState(RMAppAttemptState.FINISHED); + rm.waitForState(rmApp.getApplicationId(), RMAppState.FINISHED); + } ++ ++ @SuppressWarnings(""rawtypes"") ++ private static void waitForSchedulerAppAttemptAdded( ++ ApplicationAttemptId attemptId, MockRM rm) throws InterruptedException { ++ int tick = 0; ++ // Wait for at most 5 sec ++ while (null == ((AbstractYarnScheduler) rm.getResourceScheduler()) ++ .getApplicationAttempt(attemptId) && tick < 50) { ++ Thread.sleep(100); ++ if (tick % 10 == 0) { ++ System.out.println(""waiting for SchedulerApplicationAttempt="" ++ + attemptId + "" added.""); ++ } ++ tick++; ++ } ++ } + + public static MockAM launchAM(RMApp app, MockRM rm, MockNM nm) + throws Exception { + rm.waitForState(app.getApplicationId(), RMAppState.ACCEPTED); + RMAppAttempt attempt = app.getCurrentAppAttempt(); ++ waitForSchedulerAppAttemptAdded(attempt.getAppAttemptId(), rm); + System.out.println(""Launch AM "" + attempt.getAppAttemptId()); + nm.nodeHeartbeat(true); + MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId()); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationLimits.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationLimits.java +index 1ca5c97a411a5..46167ca68596b 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationLimits.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationLimits.java +@@ -612,7 +612,7 @@ public void testHeadroom() throws Exception { + + // Schedule to compute + queue.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + Resource expectedHeadroom = Resources.createResource(10*16*GB, 1); + assertEquals(expectedHeadroom, app_0_0.getHeadroom()); + +@@ -632,7 +632,7 @@ public void testHeadroom() throws Exception { + + // Schedule to compute + queue.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); // Schedule to compute ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); // Schedule to compute + assertEquals(expectedHeadroom, app_0_0.getHeadroom()); + assertEquals(expectedHeadroom, app_0_1.getHeadroom());// no change + +@@ -652,7 +652,7 @@ public void testHeadroom() throws Exception { + + // Schedule to compute + queue.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); // Schedule to compute ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); // Schedule to compute + expectedHeadroom = Resources.createResource(10*16*GB / 2, 1); // changes + assertEquals(expectedHeadroom, app_0_0.getHeadroom()); + assertEquals(expectedHeadroom, app_0_1.getHeadroom()); +@@ -661,7 +661,7 @@ public void testHeadroom() throws Exception { + // Now reduce cluster size and check for the smaller headroom + clusterResource = Resources.createResource(90*16*GB); + queue.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); // Schedule to compute ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); // Schedule to compute + expectedHeadroom = Resources.createResource(9*16*GB / 2, 1); // changes + assertEquals(expectedHeadroom, app_0_0.getHeadroom()); + assertEquals(expectedHeadroom, app_0_1.getHeadroom()); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestChildQueueOrder.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestChildQueueOrder.java +index 23b31faeb8f7d..970a98ad576f6 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestChildQueueOrder.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestChildQueueOrder.java +@@ -44,6 +44,7 @@ + import org.apache.hadoop.yarn.server.resourcemanager.RMContext; + import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; + import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType; +@@ -133,7 +134,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + final Resource allocatedResource = Resources.createResource(allocation); + if (queue instanceof ParentQueue) { + ((ParentQueue)queue).allocateResource(clusterResource, +- allocatedResource, null); ++ allocatedResource, RMNodeLabelsManager.NO_LABEL); + } else { + FiCaSchedulerApp app1 = getMockApplication(0, """"); + ((LeafQueue)queue).allocateResource(clusterResource, app1, +@@ -145,7 +146,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + doReturn(new CSAssignment(Resources.none(), type)). + when(queue) + .assignContainers(eq(clusterResource), eq(node), +- any(ResourceLimits.class)); ++ any(ResourceLimits.class), any(SchedulingMode.class)); + + // Mock the node's resource availability + Resource available = node.getAvailableResource(); +@@ -157,7 +158,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + } + }). + when(queue).assignContainers(eq(clusterResource), eq(node), +- any(ResourceLimits.class)); ++ any(ResourceLimits.class), any(SchedulingMode.class)); + doNothing().when(node).releaseContainer(any(Container.class)); + } + +@@ -241,6 +242,14 @@ public void testSortedQueues() throws Exception { + CSQueue b = queues.get(B); + CSQueue c = queues.get(C); + CSQueue d = queues.get(D); ++ ++ // Make a/b/c/d has >0 pending resource, so that allocation will continue. ++ queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() ++ .incPending(Resources.createResource(1 * GB)); ++ a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ c.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ d.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + + final String user_0 = ""user_0""; + +@@ -275,7 +284,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + for(int i=0; i < 2; i++) + { + stubQueueAllocation(a, clusterResource, node_0, 0*GB); +@@ -283,7 +292,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } + for(int i=0; i < 3; i++) + { +@@ -292,7 +301,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 1*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } + for(int i=0; i < 4; i++) + { +@@ -301,7 +310,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 1*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } + verifyQueueMetrics(a, 1*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); +@@ -335,7 +344,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); +@@ -363,7 +372,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 2*GB, clusterResource); + verifyQueueMetrics(b, 3*GB, clusterResource); + verifyQueueMetrics(c, 3*GB, clusterResource); +@@ -390,7 +399,7 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); + verifyQueueMetrics(c, 3*GB, clusterResource); +@@ -405,12 +414,14 @@ public void testSortedQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 0*GB); + stubQueueAllocation(d, clusterResource, node_0, 1*GB); + root.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + InOrder allocationOrder = inOrder(d,b); +- allocationOrder.verify(d).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), any(ResourceLimits.class)); +- allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), any(ResourceLimits.class)); ++ allocationOrder.verify(d).assignContainers(eq(clusterResource), ++ any(FiCaSchedulerNode.class), any(ResourceLimits.class), ++ any(SchedulingMode.class)); ++ allocationOrder.verify(b).assignContainers(eq(clusterResource), ++ any(FiCaSchedulerNode.class), any(ResourceLimits.class), ++ any(SchedulingMode.class)); + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); + verifyQueueMetrics(c, 3*GB, clusterResource); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestContainerAllocation.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestContainerAllocation.java +index 03b8f5c1fe195..54ba61724f95e 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestContainerAllocation.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestContainerAllocation.java +@@ -19,6 +19,8 @@ + package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; + + import java.util.ArrayList; ++import java.util.Arrays; ++import java.util.HashSet; + import java.util.List; + import java.util.Set; + +@@ -32,6 +34,7 @@ + import org.apache.hadoop.yarn.api.records.ContainerId; + import org.apache.hadoop.yarn.api.records.LogAggregationContext; + import org.apache.hadoop.yarn.api.records.NodeId; ++import org.apache.hadoop.yarn.api.records.NodeLabel; + import org.apache.hadoop.yarn.api.records.Priority; + import org.apache.hadoop.yarn.api.records.Resource; + import org.apache.hadoop.yarn.api.records.ResourceRequest; +@@ -51,9 +54,13 @@ + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; ++import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppReport; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; + import org.apache.hadoop.yarn.server.resourcemanager.security.RMContainerTokenSecretManager; + import org.apache.hadoop.yarn.server.utils.BuilderUtils; + import org.junit.Assert; +@@ -327,387 +334,4 @@ protected RMSecretManagerService createRMSecretManagerService() { + rm1.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.ALLOCATED); + MockRM.launchAndRegisterAM(app1, rm1, nm1); + } +- +- private Configuration getConfigurationWithQueueLabels(Configuration config) { +- CapacitySchedulerConfiguration conf = +- new CapacitySchedulerConfiguration(config); +- +- // Define top-level queues +- conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {""a"", ""b"", ""c""}); +- conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""x"", 100); +- conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""y"", 100); +- +- final String A = CapacitySchedulerConfiguration.ROOT + "".a""; +- conf.setCapacity(A, 10); +- conf.setMaximumCapacity(A, 15); +- conf.setAccessibleNodeLabels(A, toSet(""x"")); +- conf.setCapacityByLabel(A, ""x"", 100); +- +- final String B = CapacitySchedulerConfiguration.ROOT + "".b""; +- conf.setCapacity(B, 20); +- conf.setAccessibleNodeLabels(B, toSet(""y"")); +- conf.setCapacityByLabel(B, ""y"", 100); +- +- final String C = CapacitySchedulerConfiguration.ROOT + "".c""; +- conf.setCapacity(C, 70); +- conf.setMaximumCapacity(C, 70); +- conf.setAccessibleNodeLabels(C, RMNodeLabelsManager.EMPTY_STRING_SET); +- +- // Define 2nd-level queues +- final String A1 = A + "".a1""; +- conf.setQueues(A, new String[] {""a1""}); +- conf.setCapacity(A1, 100); +- conf.setMaximumCapacity(A1, 100); +- conf.setCapacityByLabel(A1, ""x"", 100); +- +- final String B1 = B + "".b1""; +- conf.setQueues(B, new String[] {""b1""}); +- conf.setCapacity(B1, 100); +- conf.setMaximumCapacity(B1, 100); +- conf.setCapacityByLabel(B1, ""y"", 100); +- +- final String C1 = C + "".c1""; +- conf.setQueues(C, new String[] {""c1""}); +- conf.setCapacity(C1, 100); +- conf.setMaximumCapacity(C1, 100); +- +- return conf; +- } +- +- private void checkTaskContainersHost(ApplicationAttemptId attemptId, +- ContainerId containerId, ResourceManager rm, String host) { +- YarnScheduler scheduler = rm.getRMContext().getScheduler(); +- SchedulerAppReport appReport = scheduler.getSchedulerAppInfo(attemptId); +- +- Assert.assertTrue(appReport.getLiveContainers().size() > 0); +- for (RMContainer c : appReport.getLiveContainers()) { +- if (c.getContainerId().equals(containerId)) { +- Assert.assertEquals(host, c.getAllocatedNode().getHost()); +- } +- } +- } +- +- @SuppressWarnings(""unchecked"") +- private Set toSet(E... elements) { +- Set set = Sets.newHashSet(elements); +- return set; +- } +- +- @Test (timeout = 300000) +- public void testContainerAllocationWithSingleUserLimits() throws Exception { +- final RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); +- mgr.init(conf); +- +- // set node -> label +- mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); +- mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), +- NodeId.newInstance(""h2"", 0), toSet(""y""))); +- +- // inject node label manager +- MockRM rm1 = new MockRM(TestUtils.getConfigurationWithDefaultQueueLabels(conf)) { +- @Override +- public RMNodeLabelsManager createNodeLabelManager() { +- return mgr; +- } +- }; +- +- rm1.getRMContext().setNodeLabelManager(mgr); +- rm1.start(); +- MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x +- rm1.registerNode(""h2:1234"", 8000); // label = y +- MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = +- +- // launch an app to queue a1 (label = x), and check all container will +- // be allocated in h1 +- RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); +- MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); +- +- // A has only 10% of x, so it can only allocate one container in label=empty +- ContainerId containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); +- am1.allocate(""*"", 1024, 1, new ArrayList(), """"); +- Assert.assertTrue(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- // Cannot allocate 2nd label=empty container +- containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), 3); +- am1.allocate(""*"", 1024, 1, new ArrayList(), """"); +- Assert.assertFalse(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- +- // A has default user limit = 100, so it can use all resource in label = x +- // We can allocate floor(8000 / 1024) = 7 containers +- for (int id = 3; id <= 8; id++) { +- containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), id); +- am1.allocate(""*"", 1024, 1, new ArrayList(), ""x""); +- Assert.assertTrue(rm1.waitForState(nm1, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- } +- rm1.close(); +- } +- +- @Test(timeout = 300000) +- public void testContainerAllocateWithComplexLabels() throws Exception { +- /* +- * Queue structure: +- * root (*) +- * ________________ +- * / \ +- * a x(100%), y(50%) b y(50%), z(100%) +- * ________________ ______________ +- * / / \ +- * a1 (x,y) b1(no) b2(y,z) +- * 100% y = 100%, z = 100% +- * +- * Node structure: +- * h1 : x +- * h2 : y +- * h3 : y +- * h4 : z +- * h5 : NO +- * +- * Total resource: +- * x: 4G +- * y: 6G +- * z: 2G +- * *: 2G +- * +- * Resource of +- * a1: x=4G, y=3G, NO=0.2G +- * b1: NO=0.9G (max=1G) +- * b2: y=3, z=2G, NO=0.9G (max=1G) +- * +- * Each node can only allocate two containers +- */ +- +- // set node -> label +- mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"", ""z"")); +- mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), +- toSet(""x""), NodeId.newInstance(""h2"", 0), toSet(""y""), +- NodeId.newInstance(""h3"", 0), toSet(""y""), NodeId.newInstance(""h4"", 0), +- toSet(""z""), NodeId.newInstance(""h5"", 0), +- RMNodeLabelsManager.EMPTY_STRING_SET)); +- +- // inject node label manager +- MockRM rm1 = new MockRM(TestUtils.getComplexConfigurationWithQueueLabels(conf)) { +- @Override +- public RMNodeLabelsManager createNodeLabelManager() { +- return mgr; +- } +- }; +- +- rm1.getRMContext().setNodeLabelManager(mgr); +- rm1.start(); +- MockNM nm1 = rm1.registerNode(""h1:1234"", 2048); +- MockNM nm2 = rm1.registerNode(""h2:1234"", 2048); +- MockNM nm3 = rm1.registerNode(""h3:1234"", 2048); +- MockNM nm4 = rm1.registerNode(""h4:1234"", 2048); +- MockNM nm5 = rm1.registerNode(""h5:1234"", 2048); +- +- ContainerId containerId; +- +- // launch an app to queue a1 (label = x), and check all container will +- // be allocated in h1 +- RMApp app1 = rm1.submitApp(1024, ""app"", ""user"", null, ""a1""); +- MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); +- +- // request a container (label = y). can be allocated on nm2 +- am1.allocate(""*"", 1024, 1, new ArrayList(), ""y""); +- containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), 2L); +- Assert.assertTrue(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, +- ""h2""); +- +- // launch an app to queue b1 (label = y), and check all container will +- // be allocated in h5 +- RMApp app2 = rm1.submitApp(1024, ""app"", ""user"", null, ""b1""); +- MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm5); +- +- // request a container for AM, will succeed +- // and now b1's queue capacity will be used, cannot allocate more containers +- // (Maximum capacity reached) +- am2.allocate(""*"", 1024, 1, new ArrayList()); +- containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm4, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertFalse(rm1.waitForState(nm5, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- +- // launch an app to queue b2 +- RMApp app3 = rm1.submitApp(1024, ""app"", ""user"", null, ""b2""); +- MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm5); +- +- // request a container. try to allocate on nm1 (label = x) and nm3 (label = +- // y,z). Will successfully allocate on nm3 +- am3.allocate(""*"", 1024, 1, new ArrayList(), ""y""); +- containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm1, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, +- ""h3""); +- +- // try to allocate container (request label = z) on nm4 (label = y,z). +- // Will successfully allocate on nm4 only. +- am3.allocate(""*"", 1024, 1, new ArrayList(), ""z""); +- containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 3L); +- Assert.assertTrue(rm1.waitForState(nm4, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, +- ""h4""); +- +- rm1.close(); +- } +- +- @Test (timeout = 120000) +- public void testContainerAllocateWithLabels() throws Exception { +- // set node -> label +- mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); +- mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), +- NodeId.newInstance(""h2"", 0), toSet(""y""))); +- +- // inject node label manager +- MockRM rm1 = new MockRM(getConfigurationWithQueueLabels(conf)) { +- @Override +- public RMNodeLabelsManager createNodeLabelManager() { +- return mgr; +- } +- }; +- +- rm1.getRMContext().setNodeLabelManager(mgr); +- rm1.start(); +- MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x +- MockNM nm2 = rm1.registerNode(""h2:1234"", 8000); // label = y +- MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = +- +- ContainerId containerId; +- +- // launch an app to queue a1 (label = x), and check all container will +- // be allocated in h1 +- RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); +- MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm3); +- +- // request a container. +- am1.allocate(""*"", 1024, 1, new ArrayList(), ""x""); +- containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm1, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, +- ""h1""); +- +- // launch an app to queue b1 (label = y), and check all container will +- // be allocated in h2 +- RMApp app2 = rm1.submitApp(200, ""app"", ""user"", null, ""b1""); +- MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm3); +- +- // request a container. +- am2.allocate(""*"", 1024, 1, new ArrayList(), ""y""); +- containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm1, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am2.getApplicationAttemptId(), containerId, rm1, +- ""h2""); +- +- // launch an app to queue c1 (label = """"), and check all container will +- // be allocated in h3 +- RMApp app3 = rm1.submitApp(200, ""app"", ""user"", null, ""c1""); +- MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm3); +- +- // request a container. +- am3.allocate(""*"", 1024, 1, new ArrayList()); +- containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, +- ""h3""); +- +- rm1.close(); +- } +- +- @Test (timeout = 120000) +- public void testContainerAllocateWithDefaultQueueLabels() throws Exception { +- // This test is pretty much similar to testContainerAllocateWithLabel. +- // Difference is, this test doesn't specify label expression in ResourceRequest, +- // instead, it uses default queue label expression +- +- // set node -> label +- mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); +- mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), +- NodeId.newInstance(""h2"", 0), toSet(""y""))); +- +- // inject node label manager +- MockRM rm1 = new MockRM(TestUtils.getConfigurationWithDefaultQueueLabels(conf)) { +- @Override +- public RMNodeLabelsManager createNodeLabelManager() { +- return mgr; +- } +- }; +- +- rm1.getRMContext().setNodeLabelManager(mgr); +- rm1.start(); +- MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x +- MockNM nm2 = rm1.registerNode(""h2:1234"", 8000); // label = y +- MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = +- +- ContainerId containerId; +- +- // launch an app to queue a1 (label = x), and check all container will +- // be allocated in h1 +- RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); +- MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); +- +- // request a container. +- am1.allocate(""*"", 1024, 1, new ArrayList()); +- containerId = +- ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm1, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, +- ""h1""); +- +- // launch an app to queue b1 (label = y), and check all container will +- // be allocated in h2 +- RMApp app2 = rm1.submitApp(200, ""app"", ""user"", null, ""b1""); +- MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); +- +- // request a container. +- am2.allocate(""*"", 1024, 1, new ArrayList()); +- containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am2.getApplicationAttemptId(), containerId, rm1, +- ""h2""); +- +- // launch an app to queue c1 (label = """"), and check all container will +- // be allocated in h3 +- RMApp app3 = rm1.submitApp(200, ""app"", ""user"", null, ""c1""); +- MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm3); +- +- // request a container. +- am3.allocate(""*"", 1024, 1, new ArrayList()); +- containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); +- Assert.assertFalse(rm1.waitForState(nm2, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- Assert.assertTrue(rm1.waitForState(nm3, containerId, +- RMContainerState.ALLOCATED, 10 * 1000)); +- checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, +- ""h3""); +- +- rm1.close(); +- } + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java +index 972cabbf2cc2c..0b5250b4fae87 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.java +@@ -351,7 +351,7 @@ public void testSingleQueueOneUserMetrics() throws Exception { + + // Only 1 container + a.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals( + (int)(node_0.getTotalResource().getMemory() * a.getCapacity()) - (1*GB), + a.getMetrics().getAvailableMB()); +@@ -487,7 +487,7 @@ public void testSingleQueueWithOneUser() throws Exception { + + // Only 1 container + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -498,7 +498,7 @@ public void testSingleQueueWithOneUser() throws Exception { + // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also + // you can get one container more than user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -507,7 +507,7 @@ public void testSingleQueueWithOneUser() throws Exception { + + // Can't allocate 3rd due to user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -517,7 +517,7 @@ public void testSingleQueueWithOneUser() throws Exception { + // Bump up user-limit-factor, now allocate should work + a.setUserLimitFactor(10); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(3*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -526,7 +526,7 @@ public void testSingleQueueWithOneUser() throws Exception { + + // One more should work, for app_1, due to user-limit-factor + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(4*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); +@@ -537,7 +537,7 @@ public void testSingleQueueWithOneUser() throws Exception { + // Now - no more allocs since we are at max-cap + a.setMaxCapacity(0.5f); + a.assignContainers(clusterResource, node_0, new ResourceLimits( +- clusterResource)); ++ clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(4*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); +@@ -653,21 +653,21 @@ public void testUserLimits() throws Exception { + + // 1 container to user_0 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); + + // Again one to user_0 since he hasn't exceeded user limit yet + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(3*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); + + // One more to user_0 since he is the only active user + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(4*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(2*GB, app_1.getCurrentConsumption().getMemory()); +@@ -719,10 +719,10 @@ public void testComputeUserLimitAndSetHeadroom(){ + 1, qb.getActiveUsersManager().getNumActiveUsers()); + //get headroom + qb.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.computeUserLimitAndSetHeadroom(app_0, clusterResource, app_0 + .getResourceRequest(u0Priority, ResourceRequest.ANY).getCapability(), +- null); ++ """", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + + //maxqueue 16G, userlimit 13G, - 4G used = 9G + assertEquals(9*GB,app_0.getHeadroom().getMemory()); +@@ -739,10 +739,10 @@ public void testComputeUserLimitAndSetHeadroom(){ + u1Priority, recordFactory))); + qb.submitApplicationAttempt(app_2, user_1); + qb.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.computeUserLimitAndSetHeadroom(app_0, clusterResource, app_0 + .getResourceRequest(u0Priority, ResourceRequest.ANY).getCapability(), +- null); ++ """", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + + assertEquals(8*GB, qb.getUsedResources().getMemory()); + assertEquals(4*GB, app_0.getCurrentConsumption().getMemory()); +@@ -782,12 +782,12 @@ public void testComputeUserLimitAndSetHeadroom(){ + qb.submitApplicationAttempt(app_1, user_0); + qb.submitApplicationAttempt(app_3, user_1); + qb.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.computeUserLimitAndSetHeadroom(app_3, clusterResource, app_3 + .getResourceRequest(u1Priority, ResourceRequest.ANY).getCapability(), +- null); ++ """", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(4*GB, qb.getUsedResources().getMemory()); + //maxqueue 16G, userlimit 7G, used (by each user) 2G, headroom 5G (both) + assertEquals(5*GB, app_3.getHeadroom().getMemory()); +@@ -803,13 +803,13 @@ public void testComputeUserLimitAndSetHeadroom(){ + TestUtils.createResourceRequest(ResourceRequest.ANY, 6*GB, 1, true, + u0Priority, recordFactory))); + qb.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.computeUserLimitAndSetHeadroom(app_4, clusterResource, app_4 + .getResourceRequest(u0Priority, ResourceRequest.ANY).getCapability(), +- null); ++ """", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + qb.computeUserLimitAndSetHeadroom(app_3, clusterResource, app_3 + .getResourceRequest(u1Priority, ResourceRequest.ANY).getCapability(), +- null); ++ """", SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + + + //app3 is user1, active from last test case +@@ -876,7 +876,7 @@ public void testUserHeadroomMultiApp() throws Exception { + priority, recordFactory))); + + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -893,7 +893,7 @@ public void testUserHeadroomMultiApp() throws Exception { + priority, recordFactory))); + + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); +@@ -982,7 +982,7 @@ public void testHeadroomWithMaxCap() throws Exception { + + // 1 container to user_0 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -993,7 +993,7 @@ public void testHeadroomWithMaxCap() throws Exception { + + // Again one to user_0 since he hasn't exceeded user limit yet + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(3*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1010,7 +1010,7 @@ public void testHeadroomWithMaxCap() throws Exception { + // No more to user_0 since he is already over user-limit + // and no more containers to queue since it's already at max-cap + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(3*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(1*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1024,7 +1024,7 @@ public void testHeadroomWithMaxCap() throws Exception { + priority, recordFactory))); + assertEquals(1, a.getActiveUsersManager().getNumActiveUsers()); + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(0*GB, app_2.getHeadroom().getMemory()); // hit queue max-cap + } + +@@ -1095,7 +1095,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + + // Only 1 container + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1103,7 +1103,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also + // you can get one container more than user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1111,7 +1111,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + // Can't allocate 3rd due to user-limit + a.setUserLimit(25); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1130,7 +1130,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + // user_0 is at limit inspite of high user-limit-factor + a.setUserLimitFactor(10); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1140,7 +1140,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + // Now allocations should goto app_0 since + // user_0 is at user-limit not above it + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(6*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1151,7 +1151,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + // Now - no more allocs since we are at max-cap + a.setMaxCapacity(0.5f); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(6*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1163,7 +1163,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + a.setMaxCapacity(1.0f); + a.setUserLimitFactor(1); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(7*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1172,7 +1172,7 @@ public void testSingleQueueWithMultipleUsers() throws Exception { + + // Now we should assign to app_3 again since user_2 is under user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8*GB, a.getUsedResources().getMemory()); + assertEquals(3*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1272,7 +1272,7 @@ public void testReservation() throws Exception { + + // Only 1 container + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1283,7 +1283,7 @@ public void testReservation() throws Exception { + // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also + // you can get one container more than user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1292,7 +1292,7 @@ public void testReservation() throws Exception { + + // Now, reservation should kick in for app_1 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(6*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1309,7 +1309,7 @@ public void testReservation() throws Exception { + ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), + RMContainerEventType.KILL, null, true); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1326,7 +1326,7 @@ public void testReservation() throws Exception { + ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), + RMContainerEventType.KILL, null, true); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(4*GB, a.getUsedResources().getMemory()); + assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1394,7 +1394,7 @@ public void testStolenReservedContainer() throws Exception { + // Start testing... + + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1404,7 +1404,7 @@ public void testStolenReservedContainer() throws Exception { + + // Now, reservation should kick in for app_1 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(6*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1418,7 +1418,7 @@ public void testStolenReservedContainer() throws Exception { + doReturn(-1).when(a).getNodeLocalityDelay(); + + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(10*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1435,7 +1435,7 @@ public void testStolenReservedContainer() throws Exception { + ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), + RMContainerEventType.KILL, null, true); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8*GB, a.getUsedResources().getMemory()); + assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(8*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1504,7 +1504,7 @@ public void testReservationExchange() throws Exception { + + // Only 1 container + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1512,14 +1512,14 @@ public void testReservationExchange() throws Exception { + // Also 2nd -> minCapacity = 1024 since (.1 * 8G) < minAlloc, also + // you can get one container more than user-limit + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); + + // Now, reservation should kick in for app_1 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(6*GB, a.getUsedResources().getMemory()); + assertEquals(2*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1534,7 +1534,7 @@ public void testReservationExchange() throws Exception { + ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), + RMContainerEventType.KILL, null, true); + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1544,7 +1544,7 @@ public void testReservationExchange() throws Exception { + + // Re-reserve + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1554,7 +1554,7 @@ public void testReservationExchange() throws Exception { + + // Try to schedule on node_1 now, should *move* the reservation + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(9*GB, a.getUsedResources().getMemory()); + assertEquals(1*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1572,7 +1572,7 @@ public void testReservationExchange() throws Exception { + ContainerExitStatus.KILLED_BY_RESOURCEMANAGER), + RMContainerEventType.KILL, null, true); + CSAssignment assignment = a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8*GB, a.getUsedResources().getMemory()); + assertEquals(0*GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(4*GB, app_1.getCurrentConsumption().getMemory()); +@@ -1644,7 +1644,7 @@ public void testLocalityScheduling() throws Exception { + + // Start with off switch, shouldn't allocate due to delay scheduling + assignment = a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_2), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(1, app_0.getSchedulingOpportunities(priority)); +@@ -1653,7 +1653,7 @@ public void testLocalityScheduling() throws Exception { + + // Another off switch, shouldn't allocate due to delay scheduling + assignment = a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_2), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(2, app_0.getSchedulingOpportunities(priority)); +@@ -1662,7 +1662,7 @@ public void testLocalityScheduling() throws Exception { + + // Another off switch, shouldn't allocate due to delay scheduling + assignment = a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_2), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(3, app_0.getSchedulingOpportunities(priority)); +@@ -1672,7 +1672,7 @@ public void testLocalityScheduling() throws Exception { + // Another off switch, now we should allocate + // since missedOpportunities=3 and reqdContainers=3 + assignment = a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.OFF_SWITCH), eq(node_2), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(4, app_0.getSchedulingOpportunities(priority)); // should NOT reset +@@ -1681,7 +1681,7 @@ public void testLocalityScheduling() throws Exception { + + // NODE_LOCAL - node_0 + assignment = a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset +@@ -1690,7 +1690,7 @@ public void testLocalityScheduling() throws Exception { + + // NODE_LOCAL - node_1 + assignment = a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset +@@ -1719,14 +1719,14 @@ public void testLocalityScheduling() throws Exception { + + // Shouldn't assign RACK_LOCAL yet + assignment = a.assignContainers(clusterResource, node_3, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(1, app_0.getSchedulingOpportunities(priority)); + assertEquals(2, app_0.getTotalRequiredResources(priority)); + assertEquals(NodeType.NODE_LOCAL, assignment.getType()); // None->NODE_LOCAL + + // Should assign RACK_LOCAL now + assignment = a.assignContainers(clusterResource, node_3, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.RACK_LOCAL), eq(node_3), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset +@@ -1808,7 +1808,7 @@ public void testApplicationPriorityScheduling() throws Exception { + // Start with off switch, shouldn't allocate P1 due to delay scheduling + // thus, no P2 either! + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_2), + eq(priority_1), any(ResourceRequest.class), any(Container.class)); + assertEquals(1, app_0.getSchedulingOpportunities(priority_1)); +@@ -1821,7 +1821,7 @@ public void testApplicationPriorityScheduling() throws Exception { + // Another off-switch, shouldn't allocate P1 due to delay scheduling + // thus, no P2 either! + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_2), + eq(priority_1), any(ResourceRequest.class), any(Container.class)); + assertEquals(2, app_0.getSchedulingOpportunities(priority_1)); +@@ -1833,7 +1833,7 @@ public void testApplicationPriorityScheduling() throws Exception { + + // Another off-switch, shouldn't allocate OFF_SWITCH P1 + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.OFF_SWITCH), eq(node_2), + eq(priority_1), any(ResourceRequest.class), any(Container.class)); + assertEquals(3, app_0.getSchedulingOpportunities(priority_1)); +@@ -1845,7 +1845,7 @@ public void testApplicationPriorityScheduling() throws Exception { + + // Now, DATA_LOCAL for P1 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_0), + eq(priority_1), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority_1)); +@@ -1857,7 +1857,7 @@ public void testApplicationPriorityScheduling() throws Exception { + + // Now, OFF_SWITCH for P2 + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_1), + eq(priority_1), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority_1)); +@@ -1934,7 +1934,7 @@ public void testSchedulingConstraints() throws Exception { + + // NODE_LOCAL - node_0_1 + a.assignContainers(clusterResource, node_0_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_0_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset +@@ -1943,7 +1943,7 @@ public void testSchedulingConstraints() throws Exception { + // No allocation on node_1_0 even though it's node/rack local since + // required(ANY) == 0 + a.assignContainers(clusterResource, node_1_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_1_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // Still zero +@@ -1960,7 +1960,7 @@ public void testSchedulingConstraints() throws Exception { + // No allocation on node_0_1 even though it's node/rack local since + // required(rack_1) == 0 + a.assignContainers(clusterResource, node_0_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_1_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(1, app_0.getSchedulingOpportunities(priority)); +@@ -1968,7 +1968,7 @@ public void testSchedulingConstraints() throws Exception { + + // NODE_LOCAL - node_1 + a.assignContainers(clusterResource, node_1_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_1_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should reset +@@ -2221,7 +2221,7 @@ public void testLocalityConstraints() throws Exception { + // node_0_1 + // Shouldn't allocate since RR(rack_0) = null && RR(ANY) = relax: false + a.assignContainers(clusterResource, node_0_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_0_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 +@@ -2244,7 +2244,7 @@ public void testLocalityConstraints() throws Exception { + // node_1_1 + // Shouldn't allocate since RR(rack_1) = relax: false + a.assignContainers(clusterResource, node_1_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_0_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 +@@ -2275,7 +2275,7 @@ public void testLocalityConstraints() throws Exception { + // node_1_1 + // Shouldn't allocate since node_1_1 is blacklisted + a.assignContainers(clusterResource, node_1_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_1_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 +@@ -2304,7 +2304,7 @@ public void testLocalityConstraints() throws Exception { + // node_1_1 + // Shouldn't allocate since rack_1 is blacklisted + a.assignContainers(clusterResource, node_1_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0, never()).allocate(any(NodeType.class), eq(node_1_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); // should be 0 +@@ -2331,7 +2331,7 @@ public void testLocalityConstraints() throws Exception { + + // Now, should allocate since RR(rack_1) = relax: true + a.assignContainers(clusterResource, node_1_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0,never()).allocate(eq(NodeType.RACK_LOCAL), eq(node_1_1), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); +@@ -2362,7 +2362,7 @@ public void testLocalityConstraints() throws Exception { + // host_1_1: 7G + + a.assignContainers(clusterResource, node_1_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verify(app_0).allocate(eq(NodeType.NODE_LOCAL), eq(node_1_0), + any(Priority.class), any(ResourceRequest.class), any(Container.class)); + assertEquals(0, app_0.getSchedulingOpportunities(priority)); +@@ -2445,7 +2445,7 @@ public void testAllocateContainerOnNodeWithoutOffSwitchSpecified() + + try { + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + } catch (NullPointerException e) { + Assert.fail(""NPE when allocating container on node but "" + + ""forget to set off-switch request should be handled""); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestNodeLabelContainerAllocation.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestNodeLabelContainerAllocation.java +new file mode 100644 +index 0000000000000..cf1b26f37e9cf +--- /dev/null ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestNodeLabelContainerAllocation.java +@@ -0,0 +1,1027 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity; ++ ++import java.util.ArrayList; ++import java.util.Arrays; ++import java.util.HashSet; ++import java.util.Set; ++ ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; ++import org.apache.hadoop.yarn.api.records.ContainerId; ++import org.apache.hadoop.yarn.api.records.NodeId; ++import org.apache.hadoop.yarn.api.records.NodeLabel; ++import org.apache.hadoop.yarn.api.records.Priority; ++import org.apache.hadoop.yarn.api.records.ResourceRequest; ++import org.apache.hadoop.yarn.conf.YarnConfiguration; ++import org.apache.hadoop.yarn.server.resourcemanager.MockAM; ++import org.apache.hadoop.yarn.server.resourcemanager.MockNM; ++import org.apache.hadoop.yarn.server.resourcemanager.MockRM; ++import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.NullRMNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; ++import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; ++import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; ++import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState; ++import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerAppReport; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; ++import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; ++import org.junit.Assert; ++import org.junit.Before; ++import org.junit.Test; ++ ++import com.google.common.collect.ImmutableMap; ++import com.google.common.collect.ImmutableSet; ++import com.google.common.collect.Sets; ++ ++public class TestNodeLabelContainerAllocation { ++ private final int GB = 1024; ++ ++ private YarnConfiguration conf; ++ ++ RMNodeLabelsManager mgr; ++ ++ @Before ++ public void setUp() throws Exception { ++ conf = new YarnConfiguration(); ++ conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ++ ResourceScheduler.class); ++ mgr = new NullRMNodeLabelsManager(); ++ mgr.init(conf); ++ } ++ ++ private Configuration getConfigurationWithQueueLabels(Configuration config) { ++ CapacitySchedulerConfiguration conf = ++ new CapacitySchedulerConfiguration(config); ++ ++ // Define top-level queues ++ conf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {""a"", ""b"", ""c""}); ++ conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""x"", 100); ++ conf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""y"", 100); ++ ++ final String A = CapacitySchedulerConfiguration.ROOT + "".a""; ++ conf.setCapacity(A, 10); ++ conf.setMaximumCapacity(A, 15); ++ conf.setAccessibleNodeLabels(A, toSet(""x"")); ++ conf.setCapacityByLabel(A, ""x"", 100); ++ ++ final String B = CapacitySchedulerConfiguration.ROOT + "".b""; ++ conf.setCapacity(B, 20); ++ conf.setAccessibleNodeLabels(B, toSet(""y"")); ++ conf.setCapacityByLabel(B, ""y"", 100); ++ ++ final String C = CapacitySchedulerConfiguration.ROOT + "".c""; ++ conf.setCapacity(C, 70); ++ conf.setMaximumCapacity(C, 70); ++ conf.setAccessibleNodeLabels(C, RMNodeLabelsManager.EMPTY_STRING_SET); ++ ++ // Define 2nd-level queues ++ final String A1 = A + "".a1""; ++ conf.setQueues(A, new String[] {""a1""}); ++ conf.setCapacity(A1, 100); ++ conf.setMaximumCapacity(A1, 100); ++ conf.setCapacityByLabel(A1, ""x"", 100); ++ ++ final String B1 = B + "".b1""; ++ conf.setQueues(B, new String[] {""b1""}); ++ conf.setCapacity(B1, 100); ++ conf.setMaximumCapacity(B1, 100); ++ conf.setCapacityByLabel(B1, ""y"", 100); ++ ++ final String C1 = C + "".c1""; ++ conf.setQueues(C, new String[] {""c1""}); ++ conf.setCapacity(C1, 100); ++ conf.setMaximumCapacity(C1, 100); ++ ++ return conf; ++ } ++ ++ private void checkTaskContainersHost(ApplicationAttemptId attemptId, ++ ContainerId containerId, ResourceManager rm, String host) { ++ YarnScheduler scheduler = rm.getRMContext().getScheduler(); ++ SchedulerAppReport appReport = scheduler.getSchedulerAppInfo(attemptId); ++ ++ Assert.assertTrue(appReport.getLiveContainers().size() > 0); ++ for (RMContainer c : appReport.getLiveContainers()) { ++ if (c.getContainerId().equals(containerId)) { ++ Assert.assertEquals(host, c.getAllocatedNode().getHost()); ++ } ++ } ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ private Set toSet(E... elements) { ++ Set set = Sets.newHashSet(elements); ++ return set; ++ } ++ ++ ++ @Test (timeout = 300000) ++ public void testContainerAllocationWithSingleUserLimits() throws Exception { ++ final RMNodeLabelsManager mgr = new NullRMNodeLabelsManager(); ++ mgr.init(conf); ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), ++ NodeId.newInstance(""h2"", 0), toSet(""y""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithDefaultQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x ++ rm1.registerNode(""h2:1234"", 8000); // label = y ++ MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = ++ ++ // launch an app to queue a1 (label = x), and check all container will ++ // be allocated in h1 ++ RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); ++ ++ // A has only 10% of x, so it can only allocate one container in label=empty ++ ContainerId containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); ++ am1.allocate(""*"", 1024, 1, new ArrayList(), """"); ++ Assert.assertTrue(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ // Cannot allocate 2nd label=empty container ++ containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 3); ++ am1.allocate(""*"", 1024, 1, new ArrayList(), """"); ++ Assert.assertFalse(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ ++ // A has default user limit = 100, so it can use all resource in label = x ++ // We can allocate floor(8000 / 1024) = 7 containers ++ for (int id = 3; id <= 8; id++) { ++ containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), id); ++ am1.allocate(""*"", 1024, 1, new ArrayList(), ""x""); ++ Assert.assertTrue(rm1.waitForState(nm1, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ } ++ rm1.close(); ++ } ++ ++ @Test(timeout = 300000) ++ public void testContainerAllocateWithComplexLabels() throws Exception { ++ /* ++ * Queue structure: ++ * root (*) ++ * ________________ ++ * / \ ++ * a x(100%), y(50%) b y(50%), z(100%) ++ * ________________ ______________ ++ * / / \ ++ * a1 (x,y) b1(no) b2(y,z) ++ * 100% y = 100%, z = 100% ++ * ++ * Node structure: ++ * h1 : x ++ * h2 : y ++ * h3 : y ++ * h4 : z ++ * h5 : NO ++ * ++ * Total resource: ++ * x: 4G ++ * y: 6G ++ * z: 2G ++ * *: 2G ++ * ++ * Resource of ++ * a1: x=4G, y=3G, NO=0.2G ++ * b1: NO=0.9G (max=1G) ++ * b2: y=3, z=2G, NO=0.9G (max=1G) ++ * ++ * Each node can only allocate two containers ++ */ ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"", ""z"")); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), ++ toSet(""x""), NodeId.newInstance(""h2"", 0), toSet(""y""), ++ NodeId.newInstance(""h3"", 0), toSet(""y""), NodeId.newInstance(""h4"", 0), ++ toSet(""z""), NodeId.newInstance(""h5"", 0), ++ RMNodeLabelsManager.EMPTY_STRING_SET)); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getComplexConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 2048); ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 2048); ++ MockNM nm3 = rm1.registerNode(""h3:1234"", 2048); ++ MockNM nm4 = rm1.registerNode(""h4:1234"", 2048); ++ MockNM nm5 = rm1.registerNode(""h5:1234"", 2048); ++ ++ ContainerId containerId; ++ ++ // launch an app to queue a1 (label = x), and check all container will ++ // be allocated in h1 ++ RMApp app1 = rm1.submitApp(1024, ""app"", ""user"", null, ""a1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); ++ ++ // request a container (label = y). can be allocated on nm2 ++ am1.allocate(""*"", 1024, 1, new ArrayList(), ""y""); ++ containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 2L); ++ Assert.assertTrue(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, ++ ""h2""); ++ ++ // launch an app to queue b1 (label = y), and check all container will ++ // be allocated in h5 ++ RMApp app2 = rm1.submitApp(1024, ""app"", ""user"", null, ""b1""); ++ MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm5); ++ ++ // request a container for AM, will succeed ++ // and now b1's queue capacity will be used, cannot allocate more containers ++ // (Maximum capacity reached) ++ am2.allocate(""*"", 1024, 1, new ArrayList()); ++ containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm4, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertFalse(rm1.waitForState(nm5, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ ++ // launch an app to queue b2 ++ RMApp app3 = rm1.submitApp(1024, ""app"", ""user"", null, ""b2""); ++ MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm5); ++ ++ // request a container. try to allocate on nm1 (label = x) and nm3 (label = ++ // y,z). Will successfully allocate on nm3 ++ am3.allocate(""*"", 1024, 1, new ArrayList(), ""y""); ++ containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm1, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, ++ ""h3""); ++ ++ // try to allocate container (request label = z) on nm4 (label = y,z). ++ // Will successfully allocate on nm4 only. ++ am3.allocate(""*"", 1024, 1, new ArrayList(), ""z""); ++ containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 3L); ++ Assert.assertTrue(rm1.waitForState(nm4, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, ++ ""h4""); ++ ++ rm1.close(); ++ } ++ ++ @Test (timeout = 120000) ++ public void testContainerAllocateWithLabels() throws Exception { ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), ++ NodeId.newInstance(""h2"", 0), toSet(""y""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(getConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 8000); // label = y ++ MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = ++ ++ ContainerId containerId; ++ ++ // launch an app to queue a1 (label = x), and check all container will ++ // be allocated in h1 ++ RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm3); ++ ++ // request a container. ++ am1.allocate(""*"", 1024, 1, new ArrayList(), ""x""); ++ containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm1, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, ++ ""h1""); ++ ++ // launch an app to queue b1 (label = y), and check all container will ++ // be allocated in h2 ++ RMApp app2 = rm1.submitApp(200, ""app"", ""user"", null, ""b1""); ++ MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm3); ++ ++ // request a container. ++ am2.allocate(""*"", 1024, 1, new ArrayList(), ""y""); ++ containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm1, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am2.getApplicationAttemptId(), containerId, rm1, ++ ""h2""); ++ ++ // launch an app to queue c1 (label = """"), and check all container will ++ // be allocated in h3 ++ RMApp app3 = rm1.submitApp(200, ""app"", ""user"", null, ""c1""); ++ MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm3); ++ ++ // request a container. ++ am3.allocate(""*"", 1024, 1, new ArrayList()); ++ containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, ++ ""h3""); ++ ++ rm1.close(); ++ } ++ ++ @Test (timeout = 120000) ++ public void testContainerAllocateWithDefaultQueueLabels() throws Exception { ++ // This test is pretty much similar to testContainerAllocateWithLabel. ++ // Difference is, this test doesn't specify label expression in ResourceRequest, ++ // instead, it uses default queue label expression ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""), ++ NodeId.newInstance(""h2"", 0), toSet(""y""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithDefaultQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8000); // label = x ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 8000); // label = y ++ MockNM nm3 = rm1.registerNode(""h3:1234"", 8000); // label = ++ ++ ContainerId containerId; ++ ++ // launch an app to queue a1 (label = x), and check all container will ++ // be allocated in h1 ++ RMApp app1 = rm1.submitApp(200, ""app"", ""user"", null, ""a1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); ++ ++ // request a container. ++ am1.allocate(""*"", 1024, 1, new ArrayList()); ++ containerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm1, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am1.getApplicationAttemptId(), containerId, rm1, ++ ""h1""); ++ ++ // launch an app to queue b1 (label = y), and check all container will ++ // be allocated in h2 ++ RMApp app2 = rm1.submitApp(200, ""app"", ""user"", null, ""b1""); ++ MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); ++ ++ // request a container. ++ am2.allocate(""*"", 1024, 1, new ArrayList()); ++ containerId = ContainerId.newContainerId(am2.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am2.getApplicationAttemptId(), containerId, rm1, ++ ""h2""); ++ ++ // launch an app to queue c1 (label = """"), and check all container will ++ // be allocated in h3 ++ RMApp app3 = rm1.submitApp(200, ""app"", ""user"", null, ""c1""); ++ MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm3); ++ ++ // request a container. ++ am3.allocate(""*"", 1024, 1, new ArrayList()); ++ containerId = ContainerId.newContainerId(am3.getApplicationAttemptId(), 2); ++ Assert.assertFalse(rm1.waitForState(nm2, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ Assert.assertTrue(rm1.waitForState(nm3, containerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ checkTaskContainersHost(am3.getApplicationAttemptId(), containerId, rm1, ++ ""h3""); ++ ++ rm1.close(); ++ } ++ ++ private void checkPendingResource(MockRM rm, int priority, ++ ApplicationAttemptId attemptId, int memory) { ++ CapacityScheduler cs = (CapacityScheduler) rm.getRMContext().getScheduler(); ++ FiCaSchedulerApp app = cs.getApplicationAttempt(attemptId); ++ ResourceRequest rr = ++ app.getAppSchedulingInfo().getResourceRequest( ++ Priority.newInstance(priority), ""*""); ++ Assert.assertEquals(memory, ++ rr.getCapability().getMemory() * rr.getNumContainers()); ++ } ++ ++ private void checkLaunchedContainerNumOnNode(MockRM rm, NodeId nodeId, ++ int numContainers) { ++ CapacityScheduler cs = (CapacityScheduler) rm.getRMContext().getScheduler(); ++ SchedulerNode node = cs.getSchedulerNode(nodeId); ++ Assert.assertEquals(numContainers, node.getNumContainers()); ++ } ++ ++ @Test ++ public void testPreferenceOfNeedyAppsTowardsNodePartitions() throws Exception { ++ /** ++ * Test case: Submit two application to a queue (app1 first then app2), app1 ++ * asked for no-label, app2 asked for label=x, when node1 has label=x ++ * doing heart beat, app2 will get allocation first, even if app2 submits later ++ * than app1 ++ */ ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ // Makes y to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""y"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""y""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8 * GB); // label = y ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 100 * GB); // label = ++ ++ // launch an app to queue b1 (label = y), AM container should be launched in nm2 ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm2); ++ ++ // launch another app to queue b1 (label = y), AM container should be launched in nm2 ++ RMApp app2 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); ++ ++ // request container and nm1 do heartbeat (nm2 has label=y), note that app1 ++ // request non-labeled container, and app2 request labeled container, app2 ++ // will get allocated first even if app1 submitted first. ++ am1.allocate(""*"", 1 * GB, 8, new ArrayList()); ++ am2.allocate(""*"", 1 * GB, 8, new ArrayList(), ""y""); ++ ++ CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); ++ RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); ++ RMNode rmNode2 = rm1.getRMContext().getRMNodes().get(nm2.getNodeId()); ++ ++ // Do node heartbeats many times ++ for (int i = 0; i < 50; i++) { ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode2)); ++ } ++ ++ // App2 will get preference to be allocated on node1, and node1 will be all ++ // used by App2. ++ FiCaSchedulerApp schedulerApp1 = cs.getApplicationAttempt(am1.getApplicationAttemptId()); ++ FiCaSchedulerApp schedulerApp2 = cs.getApplicationAttempt(am2.getApplicationAttemptId()); ++ // app1 get nothing in nm1 (partition=y) ++ checkNumOfContainersInAnAppOnGivenNode(0, nm1.getNodeId(), schedulerApp1); ++ checkNumOfContainersInAnAppOnGivenNode(9, nm2.getNodeId(), schedulerApp1); ++ // app2 get all resource in nm1 (partition=y) ++ checkNumOfContainersInAnAppOnGivenNode(8, nm1.getNodeId(), schedulerApp2); ++ checkNumOfContainersInAnAppOnGivenNode(1, nm2.getNodeId(), schedulerApp2); ++ ++ rm1.close(); ++ } ++ ++ private void checkNumOfContainersInAnAppOnGivenNode(int expectedNum, ++ NodeId nodeId, FiCaSchedulerApp app) { ++ int num = 0; ++ for (RMContainer container : app.getLiveContainers()) { ++ if (container.getAllocatedNode().equals(nodeId)) { ++ num++; ++ } ++ } ++ Assert.assertEquals(expectedNum, num); ++ } ++ ++ @Test ++ public void ++ testPreferenceOfNeedyPrioritiesUnderSameAppTowardsNodePartitions() ++ throws Exception { ++ /** ++ * Test case: Submit one application, it asks label="""" in priority=1 and ++ * label=""x"" in priority=2, when a node with label=x heartbeat, priority=2 ++ * will get allocation first even if there're pending resource in priority=1 ++ */ ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ // Makes y to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""y"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""y""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8 * GB); // label = y ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 100 * GB); // label = ++ ++ ContainerId nextContainerId; ++ ++ // launch an app to queue b1 (label = y), AM container should be launched in nm3 ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm2); ++ ++ // request containers from am2, priority=1 asks for """" and priority=2 asks ++ // for ""y"", ""y"" container should be allocated first ++ nextContainerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), 2); ++ am1.allocate(""*"", 1 * GB, 1, 1, new ArrayList(), """"); ++ am1.allocate(""*"", 1 * GB, 1, 2, new ArrayList(), ""y""); ++ Assert.assertTrue(rm1.waitForState(nm1, nextContainerId, ++ RMContainerState.ALLOCATED, 10 * 1000)); ++ ++ // Check pending resource for am2, priority=1 doesn't get allocated before ++ // priority=2 allocated ++ checkPendingResource(rm1, 1, am1.getApplicationAttemptId(), 1 * GB); ++ checkPendingResource(rm1, 2, am1.getApplicationAttemptId(), 0 * GB); ++ ++ rm1.close(); ++ } ++ ++ @Test ++ public void testNonLabeledResourceRequestGetPreferrenceToNonLabeledNode() ++ throws Exception { ++ /** ++ * Test case: Submit one application, it asks 6 label="""" containers, NM1 ++ * with label=y and NM2 has no label, NM1/NM2 doing heartbeat together. Even ++ * if NM1 has idle resource, containers are all allocated to NM2 since ++ * non-labeled request should get allocation on non-labeled nodes first. ++ */ ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ // Makes x to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""x"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8 * GB); // label = y ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 100 * GB); // label = ++ ++ ContainerId nextContainerId; ++ ++ // launch an app to queue b1 (label = y), AM container should be launched in nm3 ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm2); ++ ++ // request containers from am2, priority=1 asks for """" * 6 (id from 4 to 9), ++ // nm2/nm3 do ++ // heartbeat at the same time, check containers are always allocated to nm3. ++ // This is to verify when there's resource available in non-labeled ++ // partition, non-labeled resource should allocate to non-labeled partition ++ // first. ++ am1.allocate(""*"", 1 * GB, 6, 1, new ArrayList(), """"); ++ for (int i = 2; i < 2 + 6; i++) { ++ nextContainerId = ++ ContainerId.newContainerId(am1.getApplicationAttemptId(), i); ++ Assert.assertTrue(rm1.waitForState(Arrays.asList(nm1, nm2), ++ nextContainerId, RMContainerState.ALLOCATED, 10 * 1000)); ++ } ++ // no more container allocated on nm1 ++ checkLaunchedContainerNumOnNode(rm1, nm1.getNodeId(), 0); ++ // all 7 (1 AM container + 6 task container) containers allocated on nm2 ++ checkLaunchedContainerNumOnNode(rm1, nm2.getNodeId(), 7); ++ ++ rm1.close(); ++ } ++ ++ @Test ++ public void testPreferenceOfQueuesTowardsNodePartitions() ++ throws Exception { ++ /** ++ * Test case: have a following queue structure: ++ * ++ *
++     *            root
++     *         /   |   \
++     *        a     b    c
++     *       / \   / \  /  \
++     *      a1 a2 b1 b2 c1 c2
++     *     (x)    (x)   (x)
++     * 
++ * ++ * Only a1, b1, c1 can access label=x, and their default label=x Each each ++ * has one application, asks for 5 containers. NM1 has label=x ++ * ++ * NM1/NM2 doing heartbeat for 15 times, it should allocate all 15 ++ * containers with label=x ++ */ ++ ++ CapacitySchedulerConfiguration csConf = ++ new CapacitySchedulerConfiguration(this.conf); ++ ++ // Define top-level queues ++ csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {""a"", ""b"", ""c""}); ++ csConf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""x"", 100); ++ ++ final String A = CapacitySchedulerConfiguration.ROOT + "".a""; ++ csConf.setCapacity(A, 33); ++ csConf.setAccessibleNodeLabels(A, toSet(""x"")); ++ csConf.setCapacityByLabel(A, ""x"", 33); ++ csConf.setQueues(A, new String[] {""a1"", ""a2""}); ++ ++ final String B = CapacitySchedulerConfiguration.ROOT + "".b""; ++ csConf.setCapacity(B, 33); ++ csConf.setAccessibleNodeLabels(B, toSet(""x"")); ++ csConf.setCapacityByLabel(B, ""x"", 33); ++ csConf.setQueues(B, new String[] {""b1"", ""b2""}); ++ ++ final String C = CapacitySchedulerConfiguration.ROOT + "".c""; ++ csConf.setCapacity(C, 34); ++ csConf.setAccessibleNodeLabels(C, toSet(""x"")); ++ csConf.setCapacityByLabel(C, ""x"", 34); ++ csConf.setQueues(C, new String[] {""c1"", ""c2""}); ++ ++ // Define 2nd-level queues ++ final String A1 = A + "".a1""; ++ csConf.setCapacity(A1, 50); ++ csConf.setCapacityByLabel(A1, ""x"", 100); ++ csConf.setDefaultNodeLabelExpression(A1, ""x""); ++ ++ final String A2 = A + "".a2""; ++ csConf.setCapacity(A2, 50); ++ csConf.setCapacityByLabel(A2, ""x"", 0); ++ ++ final String B1 = B + "".b1""; ++ csConf.setCapacity(B1, 50); ++ csConf.setCapacityByLabel(B1, ""x"", 100); ++ csConf.setDefaultNodeLabelExpression(B1, ""x""); ++ ++ final String B2 = B + "".b2""; ++ csConf.setCapacity(B2, 50); ++ csConf.setCapacityByLabel(B2, ""x"", 0); ++ ++ final String C1 = C + "".c1""; ++ csConf.setCapacity(C1, 50); ++ csConf.setCapacityByLabel(C1, ""x"", 100); ++ csConf.setDefaultNodeLabelExpression(C1, ""x""); ++ ++ final String C2 = C + "".c2""; ++ csConf.setCapacity(C2, 50); ++ csConf.setCapacityByLabel(C2, ""x"", 0); ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ // Makes x to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""x"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(csConf) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 20 * GB); // label = x ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 100 * GB); // label = ++ ++ // app1 -> a1 ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""a1""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm1); ++ ++ // app2 -> a2 ++ RMApp app2 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""a2""); ++ MockAM am2 = MockRM.launchAndRegisterAM(app2, rm1, nm2); ++ ++ // app3 -> b1 ++ RMApp app3 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ MockAM am3 = MockRM.launchAndRegisterAM(app3, rm1, nm1); ++ ++ // app4 -> b2 ++ RMApp app4 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b2""); ++ MockAM am4 = MockRM.launchAndRegisterAM(app4, rm1, nm2); ++ ++ // app5 -> c1 ++ RMApp app5 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""c1""); ++ MockAM am5 = MockRM.launchAndRegisterAM(app5, rm1, nm1); ++ ++ // app6 -> b2 ++ RMApp app6 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""c2""); ++ MockAM am6 = MockRM.launchAndRegisterAM(app6, rm1, nm2); ++ ++ // Each application request 5 * 1GB container ++ am1.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ am2.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ am3.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ am4.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ am5.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ am6.allocate(""*"", 1 * GB, 5, new ArrayList()); ++ ++ // NM1 do 15 heartbeats ++ CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); ++ RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); ++ for (int i = 0; i < 15; i++) { ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); ++ } ++ ++ // NM1 get 15 new containers (total is 18, 15 task containers and 3 AM ++ // containers) ++ checkLaunchedContainerNumOnNode(rm1, nm1.getNodeId(), 18); ++ ++ // Check pending resource each application ++ // APP1/APP3/APP5 get satisfied, and APP2/APP2/APP3 get nothing. ++ checkPendingResource(rm1, 1, am1.getApplicationAttemptId(), 0 * GB); ++ checkPendingResource(rm1, 1, am2.getApplicationAttemptId(), 5 * GB); ++ checkPendingResource(rm1, 1, am3.getApplicationAttemptId(), 0 * GB); ++ checkPendingResource(rm1, 1, am4.getApplicationAttemptId(), 5 * GB); ++ checkPendingResource(rm1, 1, am5.getApplicationAttemptId(), 0 * GB); ++ checkPendingResource(rm1, 1, am6.getApplicationAttemptId(), 5 * GB); ++ ++ rm1.close(); ++ } ++ ++ @Test ++ public void testQueuesWithoutAccessUsingPartitionedNodes() throws Exception { ++ /** ++ * Test case: have a following queue structure: ++ * ++ *
++     *            root
++     *         /      \
++     *        a        b
++     *        (x)
++     * 
++ * ++ * Only a can access label=x, two nodes in the cluster, n1 has x and n2 has ++ * no-label. ++ * ++ * When user-limit-factor=5, submit one application in queue b and request ++ * for infinite containers should be able to use up all cluster resources. ++ */ ++ ++ CapacitySchedulerConfiguration csConf = ++ new CapacitySchedulerConfiguration(this.conf); ++ ++ // Define top-level queues ++ csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] {""a"", ""b""}); ++ csConf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""x"", 100); ++ ++ final String A = CapacitySchedulerConfiguration.ROOT + "".a""; ++ csConf.setCapacity(A, 50); ++ csConf.setAccessibleNodeLabels(A, toSet(""x"")); ++ csConf.setCapacityByLabel(A, ""x"", 100); ++ ++ final String B = CapacitySchedulerConfiguration.ROOT + "".b""; ++ csConf.setCapacity(B, 50); ++ csConf.setAccessibleNodeLabels(B, new HashSet()); ++ csConf.setUserLimitFactor(B, 5); ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"")); ++ // Makes x to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""x"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(csConf) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 10 * GB); // label = x ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 10 * GB); // label = ++ ++ // app1 -> b ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm2); ++ ++ // Each application request 5 * 1GB container ++ am1.allocate(""*"", 1 * GB, 50, new ArrayList()); ++ ++ // NM1 do 50 heartbeats ++ CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); ++ RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); ++ RMNode rmNode2 = rm1.getRMContext().getRMNodes().get(nm2.getNodeId()); ++ ++ SchedulerNode schedulerNode1 = cs.getSchedulerNode(nm1.getNodeId()); ++ ++ // How much cycles we waited to be allocated when available resource only on ++ // partitioned node ++ int cycleWaited = 0; ++ for (int i = 0; i < 50; i++) { ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode2)); ++ if (schedulerNode1.getNumContainers() == 0) { ++ cycleWaited++; ++ } ++ } ++ // We will will 10 cycles before get allocated on partitioned node ++ // NM2 can allocate 10 containers totally, exclude already allocated AM ++ // container, we will wait 9 to fulfill non-partitioned node, and need wait ++ // one more cycle before allocating to non-partitioned node ++ Assert.assertEquals(10, cycleWaited); ++ ++ // Both NM1/NM2 launched 10 containers, cluster resource is exhausted ++ checkLaunchedContainerNumOnNode(rm1, nm1.getNodeId(), 10); ++ checkLaunchedContainerNumOnNode(rm1, nm2.getNodeId(), 10); ++ ++ rm1.close(); ++ } ++ ++ @Test ++ public void testAMContainerAllocationWillAlwaysBeExclusive() ++ throws Exception { ++ /** ++ * Test case: Submit one application without partition, trying to allocate a ++ * node has partition=x, it should fail to allocate since AM container will ++ * always respect exclusivity for partitions ++ */ ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"", ""y"")); ++ // Makes x to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""x"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(TestUtils.getConfigurationWithQueueLabels(conf)) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 8 * GB); // label = x ++ ++ // launch an app to queue b1 (label = y), AM container should be launched in nm3 ++ rm1.submitApp(1 * GB, ""app"", ""user"", null, ""b1""); ++ ++ CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); ++ RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); ++ ++ // Heartbeat for many times, app1 should get nothing ++ for (int i = 0; i < 50; i++) { ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); ++ } ++ ++ Assert.assertEquals(0, cs.getSchedulerNode(nm1.getNodeId()) ++ .getNumContainers()); ++ ++ rm1.close(); ++ } ++ ++ @Test ++ public void ++ testQueueMaxCapacitiesWillNotBeHonoredWhenNotRespectingExclusivity() ++ throws Exception { ++ /** ++ * Test case: have a following queue structure: ++ * ++ *
++     *            root
++     *         /      \
++     *        a        b
++     *        (x)     (x)
++     * 
++ * ++ * a/b can access x, both of them has max-capacity-on-x = 50 ++ * ++ * When doing non-exclusive allocation, app in a (or b) can use 100% of x ++ * resource. ++ */ ++ ++ CapacitySchedulerConfiguration csConf = ++ new CapacitySchedulerConfiguration(this.conf); ++ ++ // Define top-level queues ++ csConf.setQueues(CapacitySchedulerConfiguration.ROOT, new String[] { ""a"", ++ ""b"" }); ++ csConf.setCapacityByLabel(CapacitySchedulerConfiguration.ROOT, ""x"", 100); ++ ++ final String A = CapacitySchedulerConfiguration.ROOT + "".a""; ++ csConf.setCapacity(A, 50); ++ csConf.setAccessibleNodeLabels(A, toSet(""x"")); ++ csConf.setCapacityByLabel(A, ""x"", 50); ++ csConf.setMaximumCapacityByLabel(A, ""x"", 50); ++ ++ final String B = CapacitySchedulerConfiguration.ROOT + "".b""; ++ csConf.setCapacity(B, 50); ++ csConf.setAccessibleNodeLabels(B, toSet(""x"")); ++ csConf.setCapacityByLabel(B, ""x"", 50); ++ csConf.setMaximumCapacityByLabel(B, ""x"", 50); ++ ++ // set node -> label ++ mgr.addToCluserNodeLabels(ImmutableSet.of(""x"")); ++ // Makes x to be non-exclusive node labels ++ mgr.updateNodeLabels(Arrays.asList(NodeLabel.newInstance(""x"", false))); ++ mgr.addLabelsToNode(ImmutableMap.of(NodeId.newInstance(""h1"", 0), toSet(""x""))); ++ ++ // inject node label manager ++ MockRM rm1 = new MockRM(csConf) { ++ @Override ++ public RMNodeLabelsManager createNodeLabelManager() { ++ return mgr; ++ } ++ }; ++ ++ rm1.getRMContext().setNodeLabelManager(mgr); ++ rm1.start(); ++ MockNM nm1 = rm1.registerNode(""h1:1234"", 10 * GB); // label = x ++ MockNM nm2 = rm1.registerNode(""h2:1234"", 10 * GB); // label = ++ ++ // app1 -> a ++ RMApp app1 = rm1.submitApp(1 * GB, ""app"", ""user"", null, ""a""); ++ MockAM am1 = MockRM.launchAndRegisterAM(app1, rm1, nm2); ++ ++ // app1 asks for 10 partition= containers ++ am1.allocate(""*"", 1 * GB, 10, new ArrayList()); ++ ++ // NM1 do 50 heartbeats ++ CapacityScheduler cs = (CapacityScheduler) rm1.getResourceScheduler(); ++ RMNode rmNode1 = rm1.getRMContext().getRMNodes().get(nm1.getNodeId()); ++ ++ SchedulerNode schedulerNode1 = cs.getSchedulerNode(nm1.getNodeId()); ++ ++ for (int i = 0; i < 50; i++) { ++ cs.handle(new NodeUpdateSchedulerEvent(rmNode1)); ++ } ++ ++ // app1 gets all resource in partition=x ++ Assert.assertEquals(10, schedulerNode1.getNumContainers()); ++ ++ rm1.close(); ++ } ++} +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java +index 7da1c97fec0ef..52d0bc1241bed 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.java +@@ -23,7 +23,6 @@ + import static org.junit.Assert.assertTrue; + import static org.junit.Assert.fail; + import static org.mockito.Matchers.any; +-import static org.mockito.Matchers.anyBoolean; + import static org.mockito.Matchers.eq; + import static org.mockito.Mockito.doAnswer; + import static org.mockito.Mockito.doReturn; +@@ -45,6 +44,7 @@ + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.security.YarnAuthorizationProvider; + import org.apache.hadoop.yarn.server.resourcemanager.RMContext; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.NodeType; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceLimits; + import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; +@@ -146,7 +146,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + final Resource allocatedResource = Resources.createResource(allocation); + if (queue instanceof ParentQueue) { + ((ParentQueue)queue).allocateResource(clusterResource, +- allocatedResource, null); ++ allocatedResource, RMNodeLabelsManager.NO_LABEL); + } else { + FiCaSchedulerApp app1 = getMockApplication(0, """"); + ((LeafQueue)queue).allocateResource(clusterResource, app1, +@@ -157,7 +157,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + if (allocation > 0) { + doReturn(new CSAssignment(Resources.none(), type)).when(queue) + .assignContainers(eq(clusterResource), eq(node), +- any(ResourceLimits.class)); ++ any(ResourceLimits.class), any(SchedulingMode.class)); + + // Mock the node's resource availability + Resource available = node.getAvailableResource(); +@@ -168,7 +168,7 @@ public CSAssignment answer(InvocationOnMock invocation) throws Throwable { + return new CSAssignment(allocatedResource, type); + } + }).when(queue).assignContainers(eq(clusterResource), eq(node), +- any(ResourceLimits.class)); ++ any(ResourceLimits.class), any(SchedulingMode.class)); + } + + private float computeQueueAbsoluteUsedCapacity(CSQueue queue, +@@ -228,11 +228,16 @@ public void testSingleLevelQueues() throws Exception { + LeafQueue a = (LeafQueue)queues.get(A); + LeafQueue b = (LeafQueue)queues.get(B); + ++ a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() ++ .incPending(Resources.createResource(1 * GB)); ++ + // Simulate B returning a container on node_0 + stubQueueAllocation(a, clusterResource, node_0, 0*GB); + stubQueueAllocation(b, clusterResource, node_0, 1*GB); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 0*GB, clusterResource); + verifyQueueMetrics(b, 1*GB, clusterResource); + +@@ -240,12 +245,12 @@ public void testSingleLevelQueues() throws Exception { + stubQueueAllocation(a, clusterResource, node_1, 2*GB); + stubQueueAllocation(b, clusterResource, node_1, 1*GB); + root.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + InOrder allocationOrder = inOrder(a, b); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 2*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); + +@@ -254,12 +259,12 @@ public void testSingleLevelQueues() throws Exception { + stubQueueAllocation(a, clusterResource, node_0, 1*GB); + stubQueueAllocation(b, clusterResource, node_0, 2*GB); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(b, a); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 4*GB, clusterResource); + +@@ -268,12 +273,12 @@ public void testSingleLevelQueues() throws Exception { + stubQueueAllocation(a, clusterResource, node_0, 0*GB); + stubQueueAllocation(b, clusterResource, node_0, 4*GB); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(b, a); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 8*GB, clusterResource); + +@@ -282,12 +287,12 @@ public void testSingleLevelQueues() throws Exception { + stubQueueAllocation(a, clusterResource, node_1, 1*GB); + stubQueueAllocation(b, clusterResource, node_1, 1*GB); + root.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(a, b); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 4*GB, clusterResource); + verifyQueueMetrics(b, 9*GB, clusterResource); + } +@@ -448,16 +453,27 @@ public void testMultiLevelQueues() throws Exception { + + // Start testing + CSQueue a = queues.get(A); ++ a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue b = queues.get(B); ++ b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue c = queues.get(C); ++ c.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue d = queues.get(D); ++ d.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + + CSQueue a1 = queues.get(A1); ++ a1.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue a2 = queues.get(A2); ++ a2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + + CSQueue b1 = queues.get(B1); ++ b1.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue b2 = queues.get(B2); ++ b2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + CSQueue b3 = queues.get(B3); ++ b3.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() ++ .incPending(Resources.createResource(1 * GB)); + + // Simulate C returning a container on node_0 + stubQueueAllocation(a, clusterResource, node_0, 0*GB); +@@ -465,7 +481,7 @@ public void testMultiLevelQueues() throws Exception { + stubQueueAllocation(c, clusterResource, node_0, 1*GB); + stubQueueAllocation(d, clusterResource, node_0, 0*GB); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 0*GB, clusterResource); + verifyQueueMetrics(b, 0*GB, clusterResource); + verifyQueueMetrics(c, 1*GB, clusterResource); +@@ -478,7 +494,7 @@ public void testMultiLevelQueues() throws Exception { + stubQueueAllocation(b2, clusterResource, node_1, 4*GB); + stubQueueAllocation(c, clusterResource, node_1, 0*GB); + root.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 0*GB, clusterResource); + verifyQueueMetrics(b, 4*GB, clusterResource); + verifyQueueMetrics(c, 1*GB, clusterResource); +@@ -490,14 +506,14 @@ public void testMultiLevelQueues() throws Exception { + stubQueueAllocation(b3, clusterResource, node_0, 2*GB); + stubQueueAllocation(c, clusterResource, node_0, 2*GB); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + InOrder allocationOrder = inOrder(a, c, b); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(c).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 1*GB, clusterResource); + verifyQueueMetrics(b, 6*GB, clusterResource); + verifyQueueMetrics(c, 3*GB, clusterResource); +@@ -517,16 +533,16 @@ public void testMultiLevelQueues() throws Exception { + stubQueueAllocation(b1, clusterResource, node_2, 1*GB); + stubQueueAllocation(c, clusterResource, node_2, 1*GB); + root.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(a, a2, a1, b, c); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(a2).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(c).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 3*GB, clusterResource); + verifyQueueMetrics(b, 8*GB, clusterResource); + verifyQueueMetrics(c, 4*GB, clusterResource); +@@ -622,12 +638,16 @@ public void testOffSwitchScheduling() throws Exception { + // Start testing + LeafQueue a = (LeafQueue)queues.get(A); + LeafQueue b = (LeafQueue)queues.get(B); ++ a.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() ++ .incPending(Resources.createResource(1 * GB)); + + // Simulate B returning a container on node_0 + stubQueueAllocation(a, clusterResource, node_0, 0*GB, NodeType.OFF_SWITCH); + stubQueueAllocation(b, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(a, 0*GB, clusterResource); + verifyQueueMetrics(b, 1*GB, clusterResource); + +@@ -636,12 +656,12 @@ public void testOffSwitchScheduling() throws Exception { + stubQueueAllocation(a, clusterResource, node_1, 2*GB, NodeType.RACK_LOCAL); + stubQueueAllocation(b, clusterResource, node_1, 1*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + InOrder allocationOrder = inOrder(a, b); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 2*GB, clusterResource); + verifyQueueMetrics(b, 2*GB, clusterResource); + +@@ -651,12 +671,12 @@ public void testOffSwitchScheduling() throws Exception { + stubQueueAllocation(a, clusterResource, node_0, 1*GB, NodeType.NODE_LOCAL); + stubQueueAllocation(b, clusterResource, node_0, 2*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(b, a); + allocationOrder.verify(b).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(a).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(a, 2*GB, clusterResource); + verifyQueueMetrics(b, 4*GB, clusterResource); + +@@ -691,12 +711,19 @@ public void testOffSwitchSchedulingMultiLevelQueues() throws Exception { + // Start testing + LeafQueue b3 = (LeafQueue)queues.get(B3); + LeafQueue b2 = (LeafQueue)queues.get(B2); ++ b2.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ b3.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); ++ queues.get(CapacitySchedulerConfiguration.ROOT).getQueueResourceUsage() ++ .incPending(Resources.createResource(1 * GB)); ++ ++ CSQueue b = queues.get(B); ++ b.getQueueResourceUsage().incPending(Resources.createResource(1 * GB)); + + // Simulate B3 returning a container on node_0 + stubQueueAllocation(b2, clusterResource, node_0, 0*GB, NodeType.OFF_SWITCH); + stubQueueAllocation(b3, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + verifyQueueMetrics(b2, 0*GB, clusterResource); + verifyQueueMetrics(b3, 1*GB, clusterResource); + +@@ -705,12 +732,12 @@ public void testOffSwitchSchedulingMultiLevelQueues() throws Exception { + stubQueueAllocation(b2, clusterResource, node_1, 1*GB, NodeType.RACK_LOCAL); + stubQueueAllocation(b3, clusterResource, node_1, 1*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + InOrder allocationOrder = inOrder(b2, b3); + allocationOrder.verify(b2).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b3).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(b2, 1*GB, clusterResource); + verifyQueueMetrics(b3, 2*GB, clusterResource); + +@@ -720,12 +747,12 @@ public void testOffSwitchSchedulingMultiLevelQueues() throws Exception { + stubQueueAllocation(b2, clusterResource, node_0, 1*GB, NodeType.NODE_LOCAL); + stubQueueAllocation(b3, clusterResource, node_0, 1*GB, NodeType.OFF_SWITCH); + root.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + allocationOrder = inOrder(b3, b2); + allocationOrder.verify(b3).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + allocationOrder.verify(b2).assignContainers(eq(clusterResource), +- any(FiCaSchedulerNode.class), anyResourceLimits()); ++ any(FiCaSchedulerNode.class), anyResourceLimits(), any(SchedulingMode.class)); + verifyQueueMetrics(b2, 1*GB, clusterResource); + verifyQueueMetrics(b3, 3*GB, clusterResource); + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservations.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservations.java +index e8a8243203365..47be61809881f 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservations.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestReservations.java +@@ -48,10 +48,10 @@ + import org.apache.hadoop.yarn.event.DrainDispatcher; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.RMContext; + import org.apache.hadoop.yarn.server.resourcemanager.ahs.RMApplicationHistoryWriter; + import org.apache.hadoop.yarn.server.resourcemanager.metrics.SystemMetricsPublisher; ++import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.ContainerAllocationExpirer; + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; +@@ -266,7 +266,7 @@ public void testReservation() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -278,7 +278,7 @@ public void testReservation() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -290,7 +290,7 @@ public void testReservation() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -305,7 +305,7 @@ public void testReservation() throws Exception { + + // try to assign reducer (5G on node 0 and should reserve) + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -321,7 +321,7 @@ public void testReservation() throws Exception { + + // assign reducer to node 2 + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(18 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -338,7 +338,7 @@ public void testReservation() throws Exception { + // node_1 heartbeat and unreserves from node_0 in order to allocate + // on node_1 + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(18 * GB, a.getUsedResources().getMemory()); + assertEquals(18 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -422,7 +422,7 @@ public void testReservationNoContinueLook() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -434,7 +434,7 @@ public void testReservationNoContinueLook() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -446,7 +446,7 @@ public void testReservationNoContinueLook() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -461,7 +461,7 @@ public void testReservationNoContinueLook() throws Exception { + + // try to assign reducer (5G on node 0 and should reserve) + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -477,7 +477,7 @@ public void testReservationNoContinueLook() throws Exception { + + // assign reducer to node 2 + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(18 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -494,7 +494,7 @@ public void testReservationNoContinueLook() throws Exception { + // node_1 heartbeat and won't unreserve from node_0, potentially stuck + // if AM doesn't handle + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(18 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -570,7 +570,7 @@ public void testAssignContainersNeedToUnreserve() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -581,7 +581,7 @@ public void testAssignContainersNeedToUnreserve() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -592,7 +592,7 @@ public void testAssignContainersNeedToUnreserve() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -606,7 +606,7 @@ public void testAssignContainersNeedToUnreserve() throws Exception { + + // try to assign reducer (5G on node 0 and should reserve) + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -621,7 +621,7 @@ public void testAssignContainersNeedToUnreserve() throws Exception { + + // could allocate but told need to unreserve first + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -823,7 +823,7 @@ public void testAssignToQueue() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -834,7 +834,7 @@ public void testAssignToQueue() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -845,7 +845,7 @@ public void testAssignToQueue() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -860,15 +860,16 @@ public void testAssignToQueue() throws Exception { + Resource capability = Resources.createResource(32 * GB, 0); + boolean res = + a.canAssignToThisQueue(clusterResource, +- CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( +- clusterResource), capability, Resources.none()); ++ RMNodeLabelsManager.NO_LABEL, new ResourceLimits( ++ clusterResource), capability, Resources.none(), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertFalse(res); + + // now add in reservations and make sure it continues if config set + // allocate to queue so that the potential new capacity is greater then + // absoluteMaxCapacity + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, a.getMetrics().getReservedMB()); +@@ -881,16 +882,17 @@ CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( + capability = Resources.createResource(5 * GB, 0); + res = + a.canAssignToThisQueue(clusterResource, +- CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( +- clusterResource), capability, Resources +- .createResource(5 * GB)); ++ RMNodeLabelsManager.NO_LABEL, new ResourceLimits( ++ clusterResource), capability, Resources.createResource(5 * GB), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertTrue(res); + + // tell to not check reservations + res = + a.canAssignToThisQueue(clusterResource, +- CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( +- clusterResource), capability, Resources.none()); ++ RMNodeLabelsManager.NO_LABEL, new ResourceLimits( ++ clusterResource), capability, Resources.none(), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertFalse(res); + + refreshQueuesTurnOffReservationsContLook(a, csConf); +@@ -899,15 +901,16 @@ CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( + // in since feature is off + res = + a.canAssignToThisQueue(clusterResource, +- CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( +- clusterResource), capability, Resources.none()); ++ RMNodeLabelsManager.NO_LABEL, new ResourceLimits( ++ clusterResource), capability, Resources.none(), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertFalse(res); + + res = + a.canAssignToThisQueue(clusterResource, +- CommonNodeLabelsManager.EMPTY_STRING_SET, new ResourceLimits( +- clusterResource), capability, Resources +- .createResource(5 * GB)); ++ RMNodeLabelsManager.NO_LABEL, new ResourceLimits( ++ clusterResource), capability, Resources.createResource(5 * GB), ++ SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertFalse(res); + } + +@@ -1008,7 +1011,7 @@ public void testAssignToUser() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1019,7 +1022,7 @@ public void testAssignToUser() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1030,7 +1033,7 @@ public void testAssignToUser() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1044,7 +1047,7 @@ public void testAssignToUser() throws Exception { + // allocate to queue so that the potential new capacity is greater then + // absoluteMaxCapacity + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(5 * GB, app_0.getCurrentReservation().getMemory()); +@@ -1059,18 +1062,18 @@ public void testAssignToUser() throws Exception { + // set limit so subtrace reservations it can continue + Resource limit = Resources.createResource(12 * GB, 0); + boolean res = a.canAssignToUser(clusterResource, user_0, limit, app_0, +- true, null); ++ true, """"); + assertTrue(res); + + // tell it not to check for reservations and should fail as already over + // limit +- res = a.canAssignToUser(clusterResource, user_0, limit, app_0, false, null); ++ res = a.canAssignToUser(clusterResource, user_0, limit, app_0, false, """"); + assertFalse(res); + + refreshQueuesTurnOffReservationsContLook(a, csConf); + + // should now return false since feature off +- res = a.canAssignToUser(clusterResource, user_0, limit, app_0, true, null); ++ res = a.canAssignToUser(clusterResource, user_0, limit, app_0, true, """"); + assertFalse(res); + } + +@@ -1143,7 +1146,7 @@ public void testReservationsNoneAvailable() throws Exception { + // Start testing... + // Only AM + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(2 * GB, a.getUsedResources().getMemory()); + assertEquals(2 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1155,7 +1158,7 @@ public void testReservationsNoneAvailable() throws Exception { + + // Only 1 map - simulating reduce + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(5 * GB, a.getUsedResources().getMemory()); + assertEquals(5 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1167,7 +1170,7 @@ public void testReservationsNoneAvailable() throws Exception { + + // Only 1 map to other node - simulating reduce + a.assignContainers(clusterResource, node_1, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1183,7 +1186,7 @@ public void testReservationsNoneAvailable() throws Exception { + // some resource. Even with continous reservation looking, we don't allow + // unreserve resource to reserve container. + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(Resources.createResource(10 * GB))); ++ new ResourceLimits(Resources.createResource(10 * GB)), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1199,7 +1202,7 @@ public void testReservationsNoneAvailable() throws Exception { + // used (8G) + required (5G). It will not reserved since it has to unreserve + // some resource. Unfortunately, there's nothing to unreserve. + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(Resources.createResource(10 * GB))); ++ new ResourceLimits(Resources.createResource(10 * GB)), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(8 * GB, a.getUsedResources().getMemory()); + assertEquals(8 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1213,7 +1216,7 @@ public void testReservationsNoneAvailable() throws Exception { + + // let it assign 5G to node_2 + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(13 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(0 * GB, a.getMetrics().getReservedMB()); +@@ -1226,7 +1229,7 @@ public void testReservationsNoneAvailable() throws Exception { + + // reserve 8G node_0 + a.assignContainers(clusterResource, node_0, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(21 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(8 * GB, a.getMetrics().getReservedMB()); +@@ -1241,7 +1244,7 @@ public void testReservationsNoneAvailable() throws Exception { + // continued to try due to having reservation above, + // but hits queue limits so can't reserve anymore. + a.assignContainers(clusterResource, node_2, +- new ResourceLimits(clusterResource)); ++ new ResourceLimits(clusterResource), SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY); + assertEquals(21 * GB, a.getUsedResources().getMemory()); + assertEquals(13 * GB, app_0.getCurrentConsumption().getMemory()); + assertEquals(8 * GB, a.getMetrics().getReservedMB()); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestUtils.java +index 62135b91df4d7..84abf4e5445bf 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestUtils.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestUtils.java +@@ -160,6 +160,7 @@ public static ResourceRequest createResourceRequest( + request.setCapability(capability); + request.setRelaxLocality(relaxLocality); + request.setPriority(priority); ++ request.setNodeLabelExpression(RMNodeLabelsManager.NO_LABEL); + return request; + } + +@@ -273,6 +274,7 @@ public static Configuration getConfigurationWithQueueLabels(Configuration config + conf.setCapacity(B1, 100); + conf.setMaximumCapacity(B1, 100); + conf.setCapacityByLabel(B1, ""y"", 100); ++ conf.setMaximumApplicationMasterResourcePerQueuePercent(B1, 1f); + + final String C1 = C + "".c1""; + conf.setQueues(C, new String[] {""c1""});" +4916128227c75b9ead023d37ba86a2685aebf62c,Delta Spike,"DELTASPIKE-289 enable WindowContext via Extension +",c,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DeltaSpikeContextExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DeltaSpikeContextExtension.java +new file mode 100644 +index 000000000..9f03783b2 +--- /dev/null ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/DeltaSpikeContextExtension.java +@@ -0,0 +1,38 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.core.impl.scope.window; ++ ++import javax.enterprise.event.Observes; ++import javax.enterprise.inject.spi.AfterBeanDiscovery; ++import javax.enterprise.inject.spi.BeanManager; ++ ++/** ++ * Handle all DeltaSpike WindowContext and ConversationContext ++ * related features. ++ */ ++public class DeltaSpikeContextExtension ++{ ++ private DefaultWindowContext windowContext; ++ ++ public void registerDeltaSpikeContexts(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) ++ { ++ windowContext = new DefaultWindowContext(beanManager); ++ afterBeanDiscovery.addContext(windowContext); ++ } ++}" +887139648d2e693bb50f286810231150bf1fba9f,drools,BZ-986000 - DRL-to-RuleModel marshalling- improvements--,p,https://github.com/kiegroup/drools,"diff --git a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceImpl.java b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceImpl.java +index 069fea6cbb3..bfb2af28075 100644 +--- a/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceImpl.java ++++ b/drools-workbench-models/drools-workbench-models-commons/src/main/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceImpl.java +@@ -740,8 +740,10 @@ public void generateSeparator( FieldConstraint constr, + if ( !gctx.isHasOutput() ) { + return; + } +- if ( gctx.getDepth() == 0 ) { +- buf.append( "", "" ); ++ if ( gctx.getDepth() == 0 ) { ++ if (buf.length() > 2 && !(buf.charAt(buf.length() - 2) == ',')) { ++ buf.append("", ""); ++ } + } else { + CompositeFieldConstraint cconstr = (CompositeFieldConstraint) gctx.getParent().getFieldConstraint(); + buf.append( cconstr.getCompositeJunctionType() + "" "" ); +@@ -800,18 +802,18 @@ private void generateSingleFieldConstraint( final SingleFieldConstraint constr, + assertConstraintValue( constr ); + + if ( isConstraintComplete( constr ) ) { +- SingleFieldConstraint parent = (SingleFieldConstraint) constr.getParent(); +- StringBuilder parentBuf = new StringBuilder(); +- while ( parent != null ) { +- String fieldName = parent.getFieldName(); +- parentBuf.insert( 0, +- fieldName + ""."" ); +- parent = (SingleFieldConstraint) parent.getParent(); +- } +- buf.append( parentBuf ); + if ( constr instanceof SingleFieldConstraintEBLeftSide ) { + buf.append( ( (SingleFieldConstraintEBLeftSide) constr ).getExpressionLeftSide().getText() ); + } else { ++ SingleFieldConstraint parent = (SingleFieldConstraint) constr.getParent(); ++ StringBuilder parentBuf = new StringBuilder(); ++ while ( parent != null ) { ++ String fieldName = parent.getFieldName(); ++ parentBuf.insert( 0, ++ fieldName + ""."" ); ++ parent = (SingleFieldConstraint) parent.getParent(); ++ } ++ buf.append( parentBuf ); + String fieldName = constr.getFieldName(); + buf.append( fieldName ); + } +diff --git a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceTest.java b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceTest.java +index a2b7bfaa608..71e2ede3d3f 100644 +--- a/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceTest.java ++++ b/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceTest.java +@@ -275,7 +275,6 @@ public void testSumAsGivenValue() { + } + + @Test +- @Ignore + public void testNotNull() { + String expected = """" + + ""rule \""my rule\"" \n"" + +@@ -284,6 +283,37 @@ public void testNotNull() { + "" Customer( contact != null , contact.tel1 > 15 )\n"" + + "" then\n"" + + ""end\n""; ++ ++ PackageDataModelOracle dmo = mock(PackageDataModelOracle.class); ++ when( ++ dmo.getProjectModelFields() ++ ).thenReturn( ++ new HashMap() {{ ++ put(""Customer"", ++ new ModelField[]{ ++ new ModelField( ++ ""contact"", ++ ""Contact"", ++ ModelField.FIELD_CLASS_TYPE.TYPE_DECLARATION_CLASS, ++ ModelField.FIELD_ORIGIN.DECLARED, ++ FieldAccessorsAndMutators.BOTH, ++ ""Contact"" ++ ) ++ }); ++ put(""Contact"", ++ new ModelField[]{ ++ new ModelField( ++ ""tel1"", ++ ""Integer"", ++ ModelField.FIELD_CLASS_TYPE.TYPE_DECLARATION_CLASS, ++ ModelField.FIELD_ORIGIN.DECLARED, ++ FieldAccessorsAndMutators.BOTH, ++ ""Integer"" ++ ) ++ }); ++ }} ++ ); ++ + final RuleModel m = new RuleModel(); + + FactPattern factPattern = new FactPattern(); +@@ -304,7 +334,7 @@ public void testNotNull() { + + m.name = ""my rule""; + +- checkMarshallUnmarshall(expected, m); ++ checkMarshallUnmarshall(expected, m, dmo); + } + + @Test" +f6d8ce0ddb06773f1b9a269bdb94ac8840673d82,tapiji,"Prepares maven pom files for building tapiji translator (RCP) +",a,https://github.com/tapiji/tapiji,"diff --git a/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF +index ac6e3ae8..c1fcc5b9 100644 +--- a/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF ++++ b/org.eclipselabs.tapiji.translator.swt.compat/META-INF/MANIFEST.MF +@@ -2,7 +2,7 @@ Manifest-Version: 1.0 + Bundle-ManifestVersion: 2 + Bundle-Name: RCP Compatibiltiy for TapiJI Translator + Bundle-SymbolicName: org.eclipselabs.tapiji.translator.swt.compat +-Bundle-Version: 0.0.2.qualifier ++Bundle-Version: 0.9.0.B1 + Bundle-Activator: org.eclipselabs.tapiji.translator.compat.Activator + Bundle-ActivationPolicy: lazy + Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +diff --git a/org.eclipselabs.tapiji.translator.swt.compat/pom.xml b/org.eclipselabs.tapiji.translator.swt.compat/pom.xml +new file mode 100644 +index 00000000..dc9aaae2 +--- /dev/null ++++ b/org.eclipselabs.tapiji.translator.swt.compat/pom.xml +@@ -0,0 +1,29 @@ ++ ++ ++ ++ ++ ++ 4.0.0 ++ org.eclipselabs.tapiji.translator.swt.compat ++ eclipse-plugin ++ ++ ++ org.eclipselabs.tapiji ++ org.eclipselabs.tapiji.translator.parent ++ 0.9.0.B1 ++ .. ++ ++ ++ 0.9.0.B1 ++ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/.classpath b/org.eclipselabs.tapiji.translator.swt.product/.classpath +new file mode 100644 +index 00000000..ad32c83a +--- /dev/null ++++ b/org.eclipselabs.tapiji.translator.swt.product/.classpath +@@ -0,0 +1,7 @@ ++ ++ ++ ++ ++ ++ ++ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/.project b/org.eclipselabs.tapiji.translator.swt.product/.project +new file mode 100644 +index 00000000..650df245 +--- /dev/null ++++ b/org.eclipselabs.tapiji.translator.swt.product/.project +@@ -0,0 +1,7 @@ ++ ++ ++ org.eclipselabs.tapiji.translator.swt.parent ++ ++ ++ ++ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png +new file mode 100644 +index 00000000..98514e0e +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_128.png differ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png +new file mode 100644 +index 00000000..73b82c2f +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_16.png differ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png +new file mode 100644 +index 00000000..3984eba6 +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_32.png differ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png +new file mode 100644 +index 00000000..190a92e4 +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_48.png differ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png +new file mode 100644 +index 00000000..89988073 +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/icons/TapiJI_64.png differ +diff --git a/org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product +similarity index 94% +rename from org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product +rename to org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product +index ff6c0744..6b53d02a 100644 +--- a/org.eclipselabs.tapiji.translator.swt/org.eclipselabs.tapiji.translator.product ++++ b/org.eclipselabs.tapiji.translator.swt.product/org.eclipselabs.tapiji.translator.swt.product.product +@@ -1,7 +1,7 @@ + + + +- ++ + + + +@@ -239,9 +239,7 @@ litigation. + + + +- +- +- ++ + + + +@@ -252,7 +250,6 @@ litigation. + + + +- + + + +@@ -288,11 +285,6 @@ litigation. + + + +- +- +- +- +- + + + +@@ -300,10 +292,7 @@ litigation. + + + +- +- + +- + + + +@@ -317,8 +306,7 @@ litigation. + + + +- +- ++ + + + +diff --git a/org.eclipselabs.tapiji.translator.swt.product/pom.xml b/org.eclipselabs.tapiji.translator.swt.product/pom.xml +new file mode 100644 +index 00000000..67d70438 +--- /dev/null ++++ b/org.eclipselabs.tapiji.translator.swt.product/pom.xml +@@ -0,0 +1,44 @@ ++ ++ ++ ++ ++ ++ 4.0.0 ++ org.eclipselabs.tapiji.translator.swt.product ++ eclipse-application ++ ++ ++ org.eclipselabs.tapiji ++ org.eclipselabs.tapiji.translator.parent ++ 0.9.0.B1 ++ .. ++ ++ ++ ++ +diff --git a/org.eclipselabs.tapiji.translator.swt.product/splash.bmp b/org.eclipselabs.tapiji.translator.swt.product/splash.bmp +new file mode 100644 +index 00000000..9283331e +Binary files /dev/null and b/org.eclipselabs.tapiji.translator.swt.product/splash.bmp differ +diff --git a/org.eclipselabs.tapiji.translator.swt/fragment.xml b/org.eclipselabs.tapiji.translator.swt/fragment.xml +index c5df4ff8..d7f1d28d 100644 +--- a/org.eclipselabs.tapiji.translator.swt/fragment.xml ++++ b/org.eclipselabs.tapiji.translator.swt/fragment.xml +@@ -6,11 +6,11 @@ + id=""product"" + point=""org.eclipse.core.runtime.products""> + + ++ value=""platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_16.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_32.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_48.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_64.png,platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png""> + + + ++ value=""platform:/plugin/org.eclipselabs.tapiji.translator/icons/TapiJI_128.png""> + + ++ ++ ++ ++ ++ 4.0.0 ++ org.eclipselabs.tapiji.translator.swt ++ eclipse-plugin ++ ++ ++ org.eclipselabs.tapiji ++ org.eclipselabs.tapiji.translator.parent ++ 0.9.0.B1 ++ .. ++ ++ ++ +diff --git a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF +index 2eeeb311..8432e599 100644 +--- a/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF ++++ b/org.eclipselabs.tapiji.translator/META-INF/MANIFEST.MF +@@ -2,7 +2,7 @@ Manifest-Version: 1.0 + Bundle-ManifestVersion: 2 + Bundle-Name: TapiJI Translator + Bundle-SymbolicName: org.eclipselabs.tapiji.translator;singleton:=true +-Bundle-Version: 0.0.2.qualifier ++Bundle-Version: 0.9.0.B1 + Bundle-Activator: org.eclipselabs.tapiji.translator.Activator + Require-Bundle: org.eclipse.ui;resolution:=optional, + org.eclipse.core.runtime;bundle-version=""[3.5.0,4.0.0)"", +diff --git a/org.eclipselabs.tapiji.translator/plugin.xml b/org.eclipselabs.tapiji.translator/plugin.xml +index 4e251edb..077db6a4 100644 +--- a/org.eclipselabs.tapiji.translator/plugin.xml ++++ b/org.eclipselabs.tapiji.translator/plugin.xml +@@ -80,4 +80,48 @@ + + + ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ + +diff --git a/org.eclipselabs.tapiji.translator/pom.xml b/org.eclipselabs.tapiji.translator/pom.xml +new file mode 100644 +index 00000000..84cbce9f +--- /dev/null ++++ b/org.eclipselabs.tapiji.translator/pom.xml +@@ -0,0 +1,22 @@ ++ ++ ++ ++ ++ ++ 4.0.0 ++ org.eclipselabs.tapiji.translator ++ eclipse-plugin ++ ++ ++ org.eclipselabs.tapiji ++ org.eclipselabs.tapiji.translator.parent ++ 0.9.0.B1 ++ .. ++ ++ ++ +diff --git a/pom.xml b/pom.xml +index dfa7fd1a..d4ce706f 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -1,129 +1,194 @@ + + +- ++ + + +- 4.0.0 +- org.eclipse.babel.plugins +- org.eclipse.babel.tapiji.tools.parent +- 0.0.2-SNAPSHOT +- pom ++ xsi:schemaLocation=""http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"" ++ xmlns=""http://maven.apache.org/POM/4.0.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> ++ 4.0.0 ++ org.eclipselabs.tapiji ++ org.eclipselabs.tapiji.translator.parent ++ 0.9.0.B1 ++ pom + +- +- +- 3.0 +- ++ ++ org.eclipselabs.tapiji.translator.swt.compat ++ org.eclipselabs.tapiji.translator ++ org.eclipselabs.tapiji.translator.swt.product ++ + +- +- 0.16.0 +- +- +- +- +- indigo +- p2 +- http://download.eclipse.org/releases/indigo +- +- ++ ++ 0.16.0 ++ http://download.eclipse.org/eclipse/updates/3.6 ++ http://build.eclipse.org/technology/babel/tools-updates-nightly ++ + +- +- +- maven.eclipse.org +- http://maven.eclipse.org/nexus/content/repositories/milestone-indigo/ +- +- ++ ++ ++ indigo rcp ++ ++ http://download.eclipse.org/releases/indigo ++ http://build.eclipse.org/technology/babel/tools-updates-nightly ++ ++ ++ true ++ ++ maven.profile ++ swt-editor ++ ++ ++ ++ ++ ++ org.eclipse.tycho ++ target-platform-configuration ++ ${tycho-version} ++ ++ ++ ++ ignore ++ ++ ++ eclipse-plugin ++ org.eclipselabs.tapiji.translator.swt.compat ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.babel.editor.swt.compat ++ 0.9.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.jface.text ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui.editors ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui.ide ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui.workbench.texteditor ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui.forms ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ltk.core.refactoring ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ltk.ui.refactoring ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.junit ++ 0.0.0 ++ ++ ++ eclipse-plugin ++ org.eclipse.ui.forms ++ 3.5.101 ++ ++ ++ ++ ++ ++ ++ ++ ++ + +- +- +- +- +- org.eclipse.tycho +- tycho-maven-plugin +- ${tycho-version} +- true +- ++ ++ ++ eclipse-repository ++ ${eclipse-repository-url} ++ p2 ++ ++ ++ babel-extension-plugins ++ ${babel-plugins-url} ++ p2 ++ ++ + +- +- +- org.eclipse.tycho +- tycho-source-plugin +- ${tycho-version} +- +- +- plugin-source +- +- plugin-source +- +- +- +- ++ ++ ++ ++ org.eclipse.tycho ++ tycho-maven-plugin ++ ${tycho-version} ++ true ++ ++ ++ org.eclipse.tycho ++ target-platform-configuration ++ ${tycho-version} ++ ++ ++ ++ linux ++ gtk ++ x86_64 ++ ++ ++ linux ++ gtk ++ x86 ++ ++ ++ macosx ++ carbon ++ x86 ++ ++ ++ macosx ++ cocoa ++ x86 ++ ++ ++ macosx ++ cocoa ++ x86_64 ++ ++ ++ win32 ++ win32 ++ x86 ++ ++ ++ win32 ++ win32 ++ x86_64 ++ ++ ++ ++ ++ ++ + +- +- org.eclipse.tycho +- target-platform-configuration +- ${tycho-version} +- +- +- +- org.eclipse.babel.plugins +- org.eclipse.babel.tapiji.tools.target +- 0.0.2-SNAPSHOT +- +- +- +- +- +- linux +- gtk +- x86_64 +- +- +- win32 +- win32 +- x86_64 +- +- +- +- +- +- +- +- +- +- org.eclipse.dash.maven +- eclipse-signing-maven-plugin +- 1.0.5 +- +- +- +- +- +- org.eclipse.babel.core +- org.eclipse.babel.editor +- org.eclipse.babel.tapiji.tools.core +- org.eclipse.babel.tapiji.tools.core.ui +- org.eclipse.babel.tapiji.tools.java +- org.eclipse.babel.tapiji.tools.java.feature +- org.eclipse.babel.tapiji.tools.java.ui +- org.eclipse.babel.tapiji.tools.rbmanager +- org.eclipse.babel.editor.nls +- org.eclipse.babel.tapiji.tools.target +- org.eclipse.babel.core.pdeutils +- org.eclipse.babel.repository +- + " +1c31074ed8a27a91cc794c5ebf26c64fcb0fda75,Vala,"libsoup-2.4: update to 2.30.0 + +Fixes bug 615047. +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +ce5970c5bf7bf7925b0830054da067c1c89e7b0f,Vala,"vapigen: fix a crash if type_name is used for pointer arguments + +Fixes bug 614348. +",c,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +614faccf1d353c3b4835e6df0e6902839d54b5f6,hadoop,YARN-1910. Fixed a race condition in TestAMRMTokens- that causes the test to fail more often on Windows. Contributed by Xuan Gong.- svn merge --ignore-ancestry -c 1586192 ../../trunk/--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1586193 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 2abb35dfa9b02..188a80035ac85 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -79,6 +79,9 @@ Release 2.4.1 - UNRELEASED + YARN-1908. Fixed DistributedShell to not fail in secure clusters. (Vinod + Kumar Vavilapalli and Jian He via vinodkv) + ++ YARN-1910. Fixed a race condition in TestAMRMTokens that causes the test to ++ fail more often on Windows. (Xuan Gong via vinodkv) ++ + Release 2.4.0 - 2014-04-07 + + INCOMPATIBLE CHANGES +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java +index aa894c5f6a920..64602bd888e27 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestAMRMTokens.java +@@ -48,6 +48,7 @@ + import org.apache.hadoop.yarn.server.resourcemanager.TestAMAuthorization.MyContainerManager; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; ++import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptContainerFinishedEvent; + import org.apache.hadoop.yarn.server.utils.BuilderUtils; + import org.apache.hadoop.yarn.util.Records; +@@ -63,6 +64,7 @@ public class TestAMRMTokens { + private static final Log LOG = LogFactory.getLog(TestAMRMTokens.class); + + private final Configuration conf; ++ private static final int maxWaitAttempts = 50; + + @Parameters + public static Collection configs() { +@@ -153,6 +155,16 @@ public void testTokenExpiry() throws Exception { + new RMAppAttemptContainerFinishedEvent(applicationAttemptId, + containerStatus)); + ++ // Make sure the RMAppAttempt is at Finished State. ++ // Both AMRMToken and ClientToAMToken have been removed. ++ int count = 0; ++ while (attempt.getState() != RMAppAttemptState.FINISHED ++ && count < maxWaitAttempts) { ++ Thread.sleep(100); ++ count++; ++ } ++ Assert.assertTrue(attempt.getState() == RMAppAttemptState.FINISHED); ++ + // Now simulate trying to allocate. RPC call itself should throw auth + // exception. + rpc.stopProxy(rmClient, conf); // To avoid using cached client" +f16e39ecb1dcb4d5964235ef94d84ab4d70ac314,hadoop,Merge -c 1529538 from trunk to branch-2 to fix- YARN-1090. Fixed CS UI to better reflect applications as non-schedulable and- not as pending. Contributed by Jian He.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1529539 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 6a997b42ecf8d..4babceb873418 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -166,6 +166,9 @@ Release 2.1.2 - UNRELEASED + + YARN-1032. Fixed NPE in RackResolver. (Lohit Vijayarenu via acmurthy) + ++ YARN-1090. Fixed CS UI to better reflect applications as non-schedulable ++ and not as pending. (Jian He via acmurthy) ++ + Release 2.1.1-beta - 2013-09-23 + + INCOMPATIBLE CHANGES +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/QueueMetrics.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/QueueMetrics.java +index 9d2c739e480cf..8a030952504fb 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/QueueMetrics.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/QueueMetrics.java +@@ -73,7 +73,7 @@ public class QueueMetrics implements MetricsSource { + @Metric(""Reserved CPU in virtual cores"") MutableGaugeInt reservedVCores; + @Metric(""# of reserved containers"") MutableGaugeInt reservedContainers; + @Metric(""# of active users"") MutableGaugeInt activeUsers; +- @Metric(""# of active users"") MutableGaugeInt activeApplications; ++ @Metric(""# of active applications"") MutableGaugeInt activeApplications; + private final MutableGaugeInt[] runningTime; + private TimeBucketMetrics runBuckets; + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/CapacitySchedulerPage.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/CapacitySchedulerPage.java +index 0bf851722e218..900c1a62ddade 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/CapacitySchedulerPage.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/CapacitySchedulerPage.java +@@ -98,24 +98,25 @@ protected void render(Block html) { + for (UserInfo entry: users) { + activeUserList.append(entry.getUsername()).append("" <"") + .append(getPercentage(entry.getResourcesUsed(), usedResources)) +- .append("", Active Apps: "" + entry.getNumActiveApplications()) +- .append("", Pending Apps: "" + entry.getNumPendingApplications()) ++ .append("", Schedulable Apps: "" + entry.getNumActiveApplications()) ++ .append("", Non-Schedulable Apps: "" + entry.getNumPendingApplications()) + .append("">
""); //Force line break + } + + ResponseInfo ri = info(""\'"" + lqinfo.getQueuePath().substring(5) + ""\' Queue Status""). + _(""Queue State:"", lqinfo.getQueueState()). + _(""Used Capacity:"", percent(lqinfo.getUsedCapacity() / 100)). ++ _(""Absolute Used Capacity:"", percent(lqinfo.getAbsoluteUsedCapacity() / 100)). + _(""Absolute Capacity:"", percent(lqinfo.getAbsoluteCapacity() / 100)). + _(""Absolute Max Capacity:"", percent(lqinfo.getAbsoluteMaxCapacity() / 100)). + _(""Used Resources:"", StringEscapeUtils.escapeHtml(lqinfo.getUsedResources().toString())). +- _(""Num Active Applications:"", Integer.toString(lqinfo.getNumActiveApplications())). +- _(""Num Pending Applications:"", Integer.toString(lqinfo.getNumPendingApplications())). ++ _(""Num Schedulable Applications:"", Integer.toString(lqinfo.getNumActiveApplications())). ++ _(""Num Non-Schedulable Applications:"", Integer.toString(lqinfo.getNumPendingApplications())). + _(""Num Containers:"", Integer.toString(lqinfo.getNumContainers())). + _(""Max Applications:"", Integer.toString(lqinfo.getMaxApplications())). + _(""Max Applications Per User:"", Integer.toString(lqinfo.getMaxApplicationsPerUser())). +- _(""Max Active Applications:"", Integer.toString(lqinfo.getMaxActiveApplications())). +- _(""Max Active Applications Per User:"", Integer.toString(lqinfo.getMaxActiveApplicationsPerUser())). ++ _(""Max Schedulable Applications:"", Integer.toString(lqinfo.getMaxActiveApplications())). ++ _(""Max Schedulable Applications Per User:"", Integer.toString(lqinfo.getMaxActiveApplicationsPerUser())). + _(""Configured Capacity:"", percent(lqinfo.getCapacity() / 100)). + _(""Configured Max Capacity:"", percent(lqinfo.getMaxCapacity() / 100)). + _(""Configured Minimum User Limit Percent:"", Integer.toString(lqinfo.getUserLimit()) + ""%"")." +e56f26140787fbe76b3c155c0248558287370e2c,Delta Spike,"DELTASPIKE-208 explicitely enable global alternatives + +This now works on Weld, OWB with BDA enabled, etc +",c,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java +index 88a59724e..22dd33cb1 100644 +--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/exclude/extension/ExcludeExtension.java +@@ -44,8 +44,10 @@ + import java.net.URL; + import java.util.ArrayList; + import java.util.Arrays; ++import java.util.HashMap; + import java.util.HashSet; + import java.util.List; ++import java.util.Map; + import java.util.Set; + import java.util.jar.Attributes; + import java.util.jar.Manifest; +@@ -60,27 +62,56 @@ + */ + public class ExcludeExtension implements Extension, Deactivatable + { +- private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName()); ++ private static final String GLOBAL_ALTERNATIVES = ""globalAlternatives.""; + +- private static Boolean isWeld1Detected = false; ++ private static final Logger LOG = Logger.getLogger(ExcludeExtension.class.getName()); + + private boolean isActivated = true; + private boolean isGlobalAlternativeActivated = true; + private boolean isCustomProjectStageBeanFilterActivated = true; + ++ /** ++ * Contains the globalAlternatives which should get used ++ * KEY=Interface class name ++ * VALUE=Implementation class name ++ */ ++ private Map globalAlternatives = new HashMap(); ++ ++ + @SuppressWarnings(""UnusedDeclaration"") + protected void init(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) + { + isActivated = + ClassDeactivationUtils.isActivated(getClass()); + +- isGlobalAlternativeActivated = +- ClassDeactivationUtils.isActivated(GlobalAlternative.class); +- + isCustomProjectStageBeanFilterActivated = + ClassDeactivationUtils.isActivated(CustomProjectStageBeanFilter.class); + +- isWeld1Detected = isWeld1(beanManager); ++ isGlobalAlternativeActivated = ++ ClassDeactivationUtils.isActivated(GlobalAlternative.class); ++ if (isGlobalAlternativeActivated) ++ { ++ Map allProperties = ConfigResolver.getAllProperties(); ++ for (Map.Entry property : allProperties.entrySet()) ++ { ++ if (property.getKey().startsWith(GLOBAL_ALTERNATIVES)) ++ { ++ String interfaceName = property.getKey().substring(GLOBAL_ALTERNATIVES.length()); ++ String implementation = property.getValue(); ++ if (LOG.isLoggable(Level.FINE)) ++ { ++ LOG.fine(""Enabling global alternative for interface "" + interfaceName + "": "" + implementation); ++ } ++ ++ globalAlternatives.put(interfaceName, implementation); ++ } ++ } ++ ++ if (globalAlternatives.isEmpty()) ++ { ++ isGlobalAlternativeActivated = false; ++ } ++ } + } + + /** +@@ -101,9 +132,9 @@ protected void initProjectStage(@Observes AfterDeploymentValidation afterDeploym + protected void vetoBeans(@Observes ProcessAnnotatedType processAnnotatedType, BeanManager beanManager) + { + //we need to do it before the exclude logic to keep the @Exclude support for global alternatives +- if (isGlobalAlternativeActivated && isWeld1Detected) ++ if (isGlobalAlternativeActivated) + { +- activateGlobalAlternativesWeld1(processAnnotatedType, beanManager); ++ activateGlobalAlternatives(processAnnotatedType, beanManager); + } + + if (isCustomProjectStageBeanFilterActivated) +@@ -158,8 +189,8 @@ protected void vetoCustomProjectStageBeans(ProcessAnnotatedType processAnnotated + + + +- private void activateGlobalAlternativesWeld1(ProcessAnnotatedType processAnnotatedType, +- BeanManager beanManager) ++ private void activateGlobalAlternatives(ProcessAnnotatedType processAnnotatedType, ++ BeanManager beanManager) + { + Class currentBean = processAnnotatedType.getAnnotatedType().getJavaClass(); + +@@ -184,7 +215,7 @@ private void activateGlobalAlternativesWeld1(ProcessAnnotatedType processAnnotat + { + alternativeBeanAnnotations = new HashSet(); + +- configuredBeanName = ConfigResolver.getPropertyValue(currentType.getName()); ++ configuredBeanName = globalAlternatives.get(currentType.getName()); + if (configuredBeanName != null && configuredBeanName.length() > 0) + { + alternativeBeanClass = ClassUtils.tryToLoadClassForName(configuredBeanName); +@@ -442,26 +473,6 @@ private void veto(ProcessAnnotatedType processAnnotatedType, String vetoType) + processAnnotatedType.getAnnotatedType().getJavaClass()); + } + +- private boolean isWeld1(BeanManager beanManager) +- { +- if (beanManager.getClass().getName().startsWith(""org.apache"")) +- { +- return false; +- } +- +- if (beanManager.getClass().getName().startsWith(""org.jboss.weld"")) +- { +- String version = getJarVersion(beanManager.getClass()); +- +- if (version != null && version.startsWith(""1."")) +- { +- return true; +- } +- } +- +- return false; +- } +- + private static String getJarVersion(Class targetClass) + { + String manifestFileLocation = getManifestFileLocationOfClass(targetClass); +diff --git a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties +index b935ffcb8..ba2908684 100644 +--- a/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties ++++ b/deltaspike/core/impl/src/test/resources/META-INF/apache-deltaspike.properties +@@ -20,10 +20,10 @@ org.apache.deltaspike.core.spi.activation.ClassDeactivator=org.apache.deltaspike + testProperty02=test_value_02 + db=prodDB + +-org.apache.deltaspike.test.core.api.alternative.global.BaseBean1=org.apache.deltaspike.test.core.api.alternative.global.SubBaseBean2 +-org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1=org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1AlternativeImplementation ++globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.BaseBean1=org.apache.deltaspike.test.core.api.alternative.global.SubBaseBean2 ++globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1=org.apache.deltaspike.test.core.api.alternative.global.BaseInterface1AlternativeImplementation + +-org.apache.deltaspike.test.core.api.alternative.global.qualifier.BaseInterface=org.apache.deltaspike.test.core.api.alternative.global.qualifier.AlternativeBaseBeanB ++globalAlternatives.org.apache.deltaspike.test.core.api.alternative.global.qualifier.BaseInterface=org.apache.deltaspike.test.core.api.alternative.global.qualifier.AlternativeBaseBeanB + + configProperty1=14 + configProperty2=7" +72d780f2cab2892259331c8d6f2d5b33d291d416,drools,"JBRULES-3200 Support for dynamic typing (aka- ""traits"")--",a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java b/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java +index dbfb8b253b6..bfb18418e9f 100644 +--- a/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java ++++ b/drools-compiler/src/main/java/org/drools/lang/descr/TypeDeclarationDescr.java +@@ -102,6 +102,18 @@ public void setType( String name, String namespace ) { + type = new QualifiedName( name, namespace ); + } + ++ public String getSuperTypeName() { ++ return superTypes == null ? null : superTypes.get(0).getName(); ++ } ++ ++ public String getSuperTypeNamespace() { ++ return superTypes == null ? null : superTypes.get(0).getNamespace(); ++ } ++ ++ public String getSupertTypeFullName() { ++ return superTypes == null ? null : superTypes.get(0).getFullName(); ++ } ++ + + /** + * @return the fields" +9b07112e30871a4a4f8253c8418e93417dcdad97,drools,JBRULES-1906: NPE when LiteralRestriction value is- set to null--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@24509 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-verifier/src/main/java/org/drools/verifier/components/Field.java b/drools-verifier/src/main/java/org/drools/verifier/components/Field.java +index 4e4b6463cc8..453f1b59d12 100644 +--- a/drools-verifier/src/main/java/org/drools/verifier/components/Field.java ++++ b/drools-verifier/src/main/java/org/drools/verifier/components/Field.java +@@ -18,6 +18,7 @@ public static class FieldType { + public static final FieldType VARIABLE = new FieldType(""Variable""); + public static final FieldType OBJECT = new FieldType(""Object""); + public static final FieldType ENUM = new FieldType(""Enum""); ++ public static final FieldType UNKNOWN = new FieldType(""Unknown""); + + private final String string; + +diff --git a/drools-verifier/src/main/java/org/drools/verifier/components/LiteralRestriction.java b/drools-verifier/src/main/java/org/drools/verifier/components/LiteralRestriction.java +index 73133feb2db..756d31dac0d 100644 +--- a/drools-verifier/src/main/java/org/drools/verifier/components/LiteralRestriction.java ++++ b/drools-verifier/src/main/java/org/drools/verifier/components/LiteralRestriction.java +@@ -8,7 +8,7 @@ + import org.drools.verifier.report.components.Cause; + + /** +- * ++ * + * @author Toni Rikkola + */ + public class LiteralRestriction extends Restriction implements Cause { +@@ -31,7 +31,7 @@ public RestrictionType getRestrictionType() { + + /** + * Compares two LiteralRestrictions by value. +- * ++ * + * @param restriction + * Restriction that this object is compared to. + * @return a negative integer, zero, or a positive integer as this object is +@@ -68,6 +68,8 @@ public int compareValues(LiteralRestriction restriction) + } + } else if (valueType == Field.FieldType.STRING) { + return stringValue.compareTo(restriction.getValueAsString()); ++ } else if (valueType == Field.FieldType.UNKNOWN) { ++ return 0; + } + + throw new DataFormatException(""Value types did not match. Value type "" +@@ -109,6 +111,15 @@ public Date getDateValue() { + + public void setValue(String value) { + ++ if (value == null) { ++ stringValue = null; ++ valueType = Field.FieldType.UNKNOWN; ++ return; ++ } ++ ++ stringValue = value; ++ valueType = Field.FieldType.STRING; ++ + if (""true"".equals(value) || ""false"".equals(value)) { + booleanValue = value.equals(""true""); + valueType = Field.FieldType.BOOLEAN; +@@ -147,11 +158,9 @@ public void setValue(String value) { + // Not a date. + } + +- stringValue = value; +- valueType = Field.FieldType.STRING; + } + +- public boolean isBooleanValue() { ++ public boolean getBooleanValue() { + return booleanValue; + } + +diff --git a/drools-verifier/src/test/java/org/drools/verifier/components/LiteralRestrictionTest.java b/drools-verifier/src/test/java/org/drools/verifier/components/LiteralRestrictionTest.java +new file mode 100644 +index 00000000000..668e9bed5c7 +--- /dev/null ++++ b/drools-verifier/src/test/java/org/drools/verifier/components/LiteralRestrictionTest.java +@@ -0,0 +1,44 @@ ++package org.drools.verifier.components; ++ ++import junit.framework.TestCase; ++ ++public class LiteralRestrictionTest extends TestCase { ++ ++ public void testSetValue() { ++ LiteralRestriction booleanRestriction = new LiteralRestriction(); ++ booleanRestriction.setValue(""true""); ++ ++ assertEquals(Field.FieldType.BOOLEAN, booleanRestriction.getValueType()); ++ assertEquals(true, booleanRestriction.getBooleanValue()); ++ ++ LiteralRestriction intRestriction = new LiteralRestriction(); ++ intRestriction.setValue(""1""); ++ ++ assertEquals(Field.FieldType.INT, intRestriction.getValueType()); ++ assertEquals(1, intRestriction.getIntValue()); ++ ++ LiteralRestriction doubleRestriction = new LiteralRestriction(); ++ doubleRestriction.setValue(""1.0""); ++ ++ assertEquals(Field.FieldType.DOUBLE, doubleRestriction.getValueType()); ++ assertEquals(1.0, doubleRestriction.getDoubleValue()); ++ ++ LiteralRestriction dateRestriction = new LiteralRestriction(); ++ dateRestriction.setValue(""11-jan-2008""); ++ ++ assertEquals(Field.FieldType.DATE, dateRestriction.getValueType()); ++ ++ LiteralRestriction stringRestriction = new LiteralRestriction(); ++ stringRestriction.setValue(""test test""); ++ ++ assertEquals(Field.FieldType.STRING, stringRestriction.getValueType()); ++ assertEquals(""test test"", stringRestriction.getValueAsString()); ++ ++ LiteralRestriction nullRestriction = new LiteralRestriction(); ++ nullRestriction.setValue(null); ++ ++ assertEquals(Field.FieldType.UNKNOWN, nullRestriction.getValueType()); ++ assertEquals(null, nullRestriction.getValueAsString()); ++ assertEquals(null, nullRestriction.getValueAsObject()); ++ } ++}" +5fee1b116bcd427168f1fafc7948c2e44520cc5c,intellij-community,PY-16335 Preserve formatting of converted- collection literals--,c,https://github.com/JetBrains/intellij-community,"diff --git a/python/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java b/python/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java +index 0ac0409edf1f4..daa669af001e3 100644 +--- a/python/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java ++++ b/python/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java +@@ -98,16 +98,17 @@ public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws + replacedElement = literal; + } + ++ final String innerText = stripLiteralBraces(replacedElement); + final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); + final PyExpression newLiteral = elementGenerator.createExpressionFromText(LanguageLevel.forElement(file), +- myLeftBrace + stripLiteralBraces(literal) + myRightBrace); ++ myLeftBrace + innerText + myRightBrace); + replacedElement.replace(newLiteral); + } + + @NotNull +- private static String stripLiteralBraces(@NotNull PySequenceExpression literal) { ++ private static String stripLiteralBraces(@NotNull PsiElement literal) { + if (literal instanceof PyTupleExpression) { +- return literal.getText().trim(); ++ return literal.getText(); + } + + final PsiElement firstChild = literal.getFirstChild(); +@@ -130,7 +131,7 @@ private static String stripLiteralBraces(@NotNull PySequenceExpression literal) + contentEndOffset = replacedText.length(); + } + +- return literal.getText().substring(contentStartOffset, contentEndOffset).trim(); ++ return literal.getText().substring(contentStartOffset, contentEndOffset); + } + + @Nullable +diff --git a/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments.py b/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments.py +new file mode 100644 +index 0000000000000..0c688956c9b78 +--- /dev/null ++++ b/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments.py +@@ -0,0 +1,4 @@ ++xs = ( ++ 1, 2, # comment 1 ++ 3 # comment 2 ++) +\ No newline at end of file +diff --git a/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments_after.py b/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments_after.py +new file mode 100644 +index 0000000000000..adccc398ae06a +--- /dev/null ++++ b/python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertLiteralPreservesFormattingAndComments_after.py +@@ -0,0 +1,4 @@ ++xs = [ ++ 1, 2, # comment 1 ++ 3 # comment 2 ++] +\ No newline at end of file +diff --git a/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java b/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java +index 0e50c05e8d1f3..7b10e2bd57cf1 100644 +--- a/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java ++++ b/python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java +@@ -103,4 +103,9 @@ public void testConvertSetWithoutClosingBraceToTuple() { + public void testConvertSetToList() { + doIntentionTest(CONVERT_SET_TO_LIST); + } ++ ++ // PY-16335 ++ public void testConvertLiteralPreservesFormattingAndComments() { ++ doIntentionTest(CONVERT_TUPLE_TO_LIST); ++ } + }" +5dabaf626e0a3493889eadcbd5ebf73d4e145912,camel,CAMEL-1091 - Fix compilation issue on Java 1.5--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@718279 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/camel,"diff --git a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/InterfacesTest.java b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/InterfacesTest.java +index b36e2faef83de..337ac66092c4a 100644 +--- a/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/InterfacesTest.java ++++ b/components/camel-jetty/src/test/java/org/apache/camel/component/jetty/InterfacesTest.java +@@ -15,25 +15,27 @@ public class InterfacesTest extends ContextTestSupport { + + private String remoteInterfaceAddress; + +- public InterfacesTest() throws SocketException { +- // retirieve an address of some remote network interface ++ public InterfacesTest() throws IOException { ++ // Retrieve an address of some remote network interface + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) { + NetworkInterface interfaze = interfaces.nextElement(); +- if (!interfaze.isUp() || interfaze.isLoopback()) { +- continue; +- } + Enumeration addresses = interfaze.getInetAddresses(); +- if(addresses.hasMoreElements()) { +- remoteInterfaceAddress = addresses.nextElement().getHostAddress(); ++ if(addresses.hasMoreElements()) { ++ InetAddress nextAddress = addresses.nextElement(); ++ if (nextAddress.isLoopbackAddress() || nextAddress.isReachable(2000)) { ++ break; ++ } ++ remoteInterfaceAddress = nextAddress.getHostAddress(); + } + }; + + } + + public void testLocalInterfaceHandled() throws IOException, InterruptedException { +- getMockEndpoint(""mock:endpoint"").expectedMessageCount(3); ++ int expectedMessages = (remoteInterfaceAddress != null) ? 3 : 2; ++ getMockEndpoint(""mock:endpoint"").expectedMessageCount(expectedMessages); + + URL localUrl = new URL(""http://localhost:4567/testRoute""); + String localResponse = IOUtils.toString(localUrl.openStream()); +@@ -44,9 +46,11 @@ public void testLocalInterfaceHandled() throws IOException, InterruptedException + localResponse = IOUtils.toString(localUrl.openStream()); + assertEquals(""local-differentPort"", localResponse); + +- URL url = new URL(""http://"" + remoteInterfaceAddress + "":4567/testRoute""); +- String remoteResponse = IOUtils.toString(url.openStream()); +- assertEquals(""remote"", remoteResponse); ++ if (remoteInterfaceAddress != null) { ++ URL url = new URL(""http://"" + remoteInterfaceAddress + "":4567/testRoute""); ++ String remoteResponse = IOUtils.toString(url.openStream()); ++ assertEquals(""remote"", remoteResponse); ++ } + + assertMockEndpointsSatisfied(); + } +@@ -65,9 +69,11 @@ public void configure() throws Exception { + .setBody().constant(""local-differentPort"") + .to(""mock:endpoint""); + +- from(""jetty:http://"" + remoteInterfaceAddress + "":4567/testRoute"") +- .setBody().constant(""remote"") +- .to(""mock:endpoint""); ++ if (remoteInterfaceAddress != null) { ++ from(""jetty:http://"" + remoteInterfaceAddress + "":4567/testRoute"") ++ .setBody().constant(""remote"") ++ .to(""mock:endpoint""); ++ } + } + }; + }" +35c49ea2db324c527a45be9a219cc05f2a718950,Mylyn Reviews,"ANTLR based dsl implementation + +removed existing xtext based dsl and replaced with antlr impl. +",c,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java +index aad5c57d..75b03c6e 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewTaskMapper.java +@@ -23,104 +23,153 @@ + import org.eclipse.mylyn.reviews.tasks.core.PatchScopeItem; + import org.eclipse.mylyn.reviews.tasks.core.Rating; + import org.eclipse.mylyn.reviews.tasks.core.ResourceScopeItem; ++import org.eclipse.mylyn.reviews.tasks.core.ReviewResult; + import org.eclipse.mylyn.reviews.tasks.core.ReviewScope; + import org.eclipse.mylyn.reviews.tasks.core.TaskComment; +-import org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.ReviewDslParser; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.AttachmentSource; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ChangedReviewScope; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ChangesetDef; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.PatchDef; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResourceDef; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ResultEnum; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewDslFactory; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem; +-import org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.Source; +-import org.eclipse.xtext.parser.IParseResult; +-import org.eclipse.xtext.parsetree.reconstr.Serializer; ++import org.eclipse.mylyn.reviews.tasks.dsl.IReviewDslMapper; ++import org.eclipse.mylyn.reviews.tasks.dsl.IReviewDslSerializer; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslAttachmentScopeItem; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslAttachmentScopeItem.Type; ++import org.eclipse.mylyn.reviews.tasks.dsl.ParseException; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslChangesetScopeItem; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScope; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScopeItem; + + /** + * @author mattk + * + */ + public class ReviewTaskMapper implements IReviewMapper { +- private ReviewDslParser parser; +- private Serializer serializer; ++ private IReviewDslMapper parser; ++ private IReviewDslSerializer serializer; + +- public ReviewTaskMapper(ReviewDslParser parser, Serializer serializer) { ++ public ReviewTaskMapper(IReviewDslMapper parser, ++ IReviewDslSerializer serializer) { + this.parser = parser; + this.serializer = serializer; + } + +- private org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapResult( +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult parsed, +- TaskComment comment) { +- if (parsed == null) +- return null; ++ @Override ++ public ReviewScope mapTaskToScope(ITaskProperties properties) ++ throws CoreException { ++ Assert.isNotNull(properties); ++ try { ++ ReviewDslScope parsedReviewScope = parser ++ .parseReviewScope(properties.getDescription()); ++ ReviewScope originalScope = mapReviewScope(properties, ++ parsedReviewScope); ++ // FIXME changed review scope ++ // for (TaskComment comment : properties.getComments()) { ++ // if (properties.getReporter().equals(comment.getAuthor())) { ++ // ChangedReviewScope changedScope = ++ // parser.parseChangedReviewScope(comment.getText()); ++ // applyChangedScope(properties, originalScope, changedScope); ++ // } ++ // } ++ // } ++ return originalScope; ++ } catch (ParseException ex) { ++ // ignore ++ } ++ return null; + +- org.eclipse.mylyn.reviews.tasks.core.ReviewResult result = new org.eclipse.mylyn.reviews.tasks.core.ReviewResult(); +- result.setReviewer(comment.getAuthor()); +- result.setDate(comment.getDate()); +- result.setRating(mapRating(parsed.getResult())); +- result.setComment(parsed.getComment()); +- return result; + } + +- private Rating mapRating(ResultEnum result) { +- switch (result) { ++ @Override ++ public void mapScopeToTask(ReviewScope scope, ITaskProperties taskProperties) { ++ ReviewDslScope scope2 = mapScope(scope); ++ ++ taskProperties.setDescription(serializer.serialize(scope2)); ++ } ++ ++ @Override ++ public void mapResultToTask( ++ org.eclipse.mylyn.reviews.tasks.core.ReviewResult res, ++ ITaskProperties taskProperties) { ++ ReviewDslResult result = new ReviewDslResult(); ++ ReviewDslResult.Rating rating = ReviewDslResult.Rating.WARNING; ++ switch (res.getRating()) { ++ case FAIL: ++ rating = ReviewDslResult.Rating.FAILED; ++ break; + case PASSED: +- return Rating.PASSED; +- case FAILED: +- return Rating.FAIL; +- case WARNING: +- return Rating.WARNING; ++ rating = ReviewDslResult.Rating.PASSED; ++ break; + case TODO: +- return Rating.TODO; ++ rating = ReviewDslResult.Rating.TODO; ++ break; ++ case WARNING: ++ rating = ReviewDslResult.Rating.WARNING; ++ break; + } +- throw new IllegalArgumentException(); ++ result.setRating(rating); ++ result.setComment(res.getComment()); ++ ++ String resultAsText = serializer.serialize(result); ++ taskProperties.setNewCommentText(resultAsText); + } + + @Override +- public ReviewScope mapTaskToScope(ITaskProperties properties) +- throws CoreException { +- Assert.isNotNull(properties); +- IParseResult parsed = parser.doParse(properties.getDescription()); ++ public org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapCurrentReviewResult( ++ ITaskProperties taskProperties) { ++ Assert.isNotNull(taskProperties); ++ if (taskProperties.getNewCommentText() == null) ++ return null; ++ ReviewResult result = null; ++ try { ++ ReviewDslResult res = parser.parseReviewResult(taskProperties ++ .getNewCommentText()); ++ result = new ReviewResult(); ++ if (res == null) ++ return null; ++ result.setComment(res.getComment()); ++ result.setRating(mapRating(res.getRating())); ++ // FIXME filecomment, linecomment ++ // FIXME author is current ++ // result.setReviewer() ++ // result.setDate() ++ } catch (ParseException ex) { ++ /* ignore */ ++ } ++ return result; ++ } + +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope = (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope) parsed +- .getRootASTElement(); +- ReviewScope originalScope = mapReviewScope(properties, scope); +- for (TaskComment comment : properties.getComments()) { +- if (properties.getReporter().equals(comment.getAuthor())) { +- parsed = parser.doParse(comment.getText()); +- if (parsed.getRootASTElement() instanceof ChangedReviewScope) { +- ChangedReviewScope changedScope = (ChangedReviewScope) parsed +- .getRootASTElement(); +- applyChangedScope(properties, originalScope, changedScope); ++ @Override ++ public List mapTaskToResults(ITaskProperties taskProperties) { ++ List results = new ArrayList(); ++ for (TaskComment comment : taskProperties.getComments()) { ++ try { ++ ReviewDslResult parsed = parser.parseReviewResult(comment ++ .getText()); ++ if (parsed != null) { ++ results.add(mapResult(parsed, comment)); + } ++ } catch (ParseException ex) { ++ // ignore + } + } +- return originalScope; ++ return results; + } + +- private void applyChangedScope(ITaskProperties properties, +- ReviewScope originalScope, ChangedReviewScope changedScope) +- throws CoreException { +- for (ReviewScopeItem scope : changedScope.getScope()) { +- IReviewScopeItem item = mapReviewScopeItem(properties, scope); +- originalScope.addScope(item); +- } +- } ++ // FIXME Changed Review scope ++ // private void applyChangedScope(ITaskProperties properties, ++ // ReviewScope originalScope, ChangedReviewScope changedScope) ++ // throws CoreException { ++ // for (ReviewScopeItem scope : changedScope.getScope()) { ++ // IReviewScopeItem item = mapReviewScopeItem(properties, scope); ++ // originalScope.addScope(item); ++ // } ++ // } + + private ReviewScope mapReviewScope(ITaskProperties properties, +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope) +- throws CoreException { ++ ReviewDslScope scope) throws CoreException { + if (scope == null) + return null; + + ReviewScope mappedScope = new ReviewScope(); + mappedScope.setCreator(properties.getReporter()); +- for (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem s : scope +- .getScope()) { ++ for (ReviewDslScopeItem s : scope.getItems()) { + IReviewScopeItem item = mapReviewScopeItem(properties, s); + if (item != null) { + mappedScope.addScope(item); +@@ -130,174 +179,93 @@ private ReviewScope mapReviewScope(ITaskProperties properties, + } + + private IReviewScopeItem mapReviewScopeItem(ITaskProperties properties, +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem s) +- throws CoreException { ++ ReviewDslScopeItem s) throws CoreException { + IReviewScopeItem item = null; +- if (s instanceof PatchDef) { +- item = mapPatchDef(properties, (PatchDef) s); +- } else if (s instanceof ResourceDef) { +- ResourceDef res = (ResourceDef) s; +- item = mapResourceDef(properties, res); +- } else if (s instanceof ChangesetDef) { +- ChangesetDef res = (ChangesetDef) s; +- item = mapChangesetDef(properties, res); ++ if (s instanceof ReviewDslAttachmentScopeItem) { ++ item = mapPatchDef(properties, (ReviewDslAttachmentScopeItem) s); ++ } else if (s instanceof ReviewDslChangesetScopeItem) { ++ item = mapChangesetDef(properties, (ReviewDslChangesetScopeItem) s); + } + return item; + } + + private ChangesetScopeItem mapChangesetDef(ITaskProperties properties, +- ChangesetDef cs) throws CoreException { +- return new ChangesetScopeItem(cs.getRevision(), cs.getUrl()); ++ ReviewDslChangesetScopeItem cs) throws CoreException { ++ return new ChangesetScopeItem(cs.getRevision(), cs.getRepoUrl()); + } + +- private ResourceScopeItem mapResourceDef(ITaskProperties properties, +- ResourceDef res) throws CoreException { +- Source source = res.getSource(); +- Attachment att = null; +- if (source instanceof AttachmentSource) { +- att = parseAttachmenSource(properties, source); +- } +- return new ResourceScopeItem(att); +- } ++ private IReviewScopeItem mapPatchDef(ITaskProperties properties, ++ ReviewDslAttachmentScopeItem scopeItem) throws CoreException { + +- private PatchScopeItem mapPatchDef(ITaskProperties properties, +- PatchDef patch) throws CoreException { +- Source source = patch.getSource(); +- Attachment att = null; +- if (source instanceof AttachmentSource) { +- att = parseAttachmenSource(properties, source); ++ Attachment att = ReviewsUtil.findAttachment(scopeItem.getFileName(), ++ scopeItem.getAuthor(), scopeItem.getCreatedDate(), ++ properties.loadFor(scopeItem.getTaskId())); ++ if (scopeItem.getType() == Type.PATCH) { ++ return new PatchScopeItem(att); ++ } else { ++ return new ResourceScopeItem(att); + } +- return new PatchScopeItem(att); + } + +- private Attachment parseAttachmenSource(ITaskProperties properties, +- Source source) throws CoreException { +- AttachmentSource attachment = (AttachmentSource) source; ++ private ReviewResult mapResult(ReviewDslResult parsed, TaskComment comment) { ++ if (parsed == null) ++ return null; + +- Attachment att = ReviewsUtil.findAttachment(attachment.getFilename(), +- attachment.getAuthor(), attachment.getCreatedDate(), +- properties.loadFor(attachment.getTaskId())); +- return att; ++ ReviewResult result = new ReviewResult(); ++ result.setReviewer(comment.getAuthor()); ++ result.setDate(comment.getDate()); ++ result.setRating(mapRating(parsed.getRating())); ++ result.setComment(parsed.getComment()); ++ return result; + } + +- @Override +- public void mapScopeToTask(ReviewScope scope, ITaskProperties taskProperties) { +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope2 = mapScope(scope); +- +- taskProperties.setDescription(serializer.serialize(scope2)); ++ private Rating mapRating(ReviewDslResult.Rating result) { ++ switch (result) { ++ case PASSED: ++ return Rating.PASSED; ++ case FAILED: ++ return Rating.FAIL; ++ case WARNING: ++ return Rating.WARNING; ++ case TODO: ++ return Rating.TODO; ++ } ++ throw new IllegalArgumentException(); + } + +- private org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope mapScope( +- ReviewScope scope) { +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScope scope2 = ReviewDslFactory.eINSTANCE +- .createReviewScope(); ++ private ReviewDslScope mapScope(ReviewScope scope) { ++ ReviewDslScope scope2 = new ReviewDslScope(); ++ + for (IReviewScopeItem item : scope.getItems()) { +- scope2.getScope().add(mapScopeItem(item)); ++ scope2.getItems().add(mapScopeItem(item)); + } + return scope2; + } + +- private org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewScopeItem mapScopeItem( +- IReviewScopeItem item) { ++ private ReviewDslScopeItem mapScopeItem(IReviewScopeItem item) { + if (item instanceof PatchScopeItem) { + PatchScopeItem patchItem = (PatchScopeItem) item; +- PatchDef patch = ReviewDslFactory.eINSTANCE.createPatchDef(); +- Attachment attachment = patchItem.getAttachment(); +- AttachmentSource source = mapAttachment(attachment); +- patch.setSource(source); +- +- return patch; ++ return createAttachmentScopeItem(Type.PATCH, ++ patchItem.getAttachment()); + } else if (item instanceof ResourceScopeItem) { + ResourceScopeItem resourceItem = (ResourceScopeItem) item; +- ResourceDef resource = ReviewDslFactory.eINSTANCE +- .createResourceDef(); +- Attachment attachment = resourceItem.getAttachment(); +- AttachmentSource source = mapAttachment(attachment); +- resource.setSource(source); +- return resource; ++ return createAttachmentScopeItem(Type.RESOURCE, ++ resourceItem.getAttachment()); + } else if (item instanceof ChangesetScopeItem) { + ChangesetScopeItem changesetItem = (ChangesetScopeItem) item; +- ChangesetDef changeset = ReviewDslFactory.eINSTANCE +- .createChangesetDef(); ++ ReviewDslChangesetScopeItem changeset = new ReviewDslChangesetScopeItem(); + changeset.setRevision(changesetItem.getRevisionId()); +- changeset.setUrl(changesetItem.getRepositoryUrl()); ++ changeset.setRepoUrl(changesetItem.getRepositoryUrl()); + return changeset; + } + return null; + } + +- private AttachmentSource mapAttachment(Attachment attachment) { +- AttachmentSource source = ReviewDslFactory.eINSTANCE +- .createAttachmentSource(); +- source.setAuthor(attachment.getAuthor()); +- source.setCreatedDate(attachment.getDate()); +- source.setFilename(attachment.getFileName()); +- source.setTaskId(attachment.getTask().getTaskId()); +- return source; +- } +- +- @Override +- public void mapResultToTask( +- org.eclipse.mylyn.reviews.tasks.core.ReviewResult res, +- ITaskProperties taskProperties) { +- ReviewResult result = ReviewDslFactory.eINSTANCE.createReviewResult(); +- ResultEnum rating = ResultEnum.WARNING; +- switch (res.getRating()) { +- case FAIL: +- rating = ResultEnum.FAILED; +- break; +- case PASSED: +- rating = ResultEnum.PASSED; +- break; +- case TODO: +- rating = ResultEnum.TODO; +- break; +- case WARNING: +- rating = ResultEnum.WARNING; +- break; +- } +- result.setResult(rating); +- result.setComment(res.getComment()); +- +- String resultAsText = serializer.serialize(result); +- taskProperties.setNewCommentText(resultAsText); +- } +- +- @Override +- public org.eclipse.mylyn.reviews.tasks.core.ReviewResult mapCurrentReviewResult( +- ITaskProperties taskProperties) { +- Assert.isNotNull(taskProperties); +- if (taskProperties.getNewCommentText() == null) +- return null; +- IParseResult parsed = parser +- .doParse(taskProperties.getNewCommentText()); +- +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult res = (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult) parsed +- .getRootASTElement(); +- org.eclipse.mylyn.reviews.tasks.core.ReviewResult result = new org.eclipse.mylyn.reviews.tasks.core.ReviewResult(); +- if (res == null) +- return null; +- result.setComment(res.getComment()); +- result.setRating(mapRating(res.getResult())); +- // FIXME author is current +- // result.setReviewer() +- // result.setDate() +- return result; +- } +- +- @Override +- public List mapTaskToResults( +- ITaskProperties taskProperties) { +- List results = new ArrayList(); +- for (TaskComment comment : taskProperties.getComments()) { +- IParseResult parsed = parser.doParse(comment.getText()); +- if (parsed.getRootASTElement() != null) { +- results.add(mapResult( +- (org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.ReviewResult) parsed +- .getRootASTElement(), comment)); +- } +- } +- return results; ++ private ReviewDslAttachmentScopeItem createAttachmentScopeItem(Type type, ++ Attachment attachment) { ++ return new ReviewDslAttachmentScopeItem(type, attachment.getFileName(), ++ attachment.getAuthor(), attachment.getDate(), attachment ++ .getTask().getTaskId()); + } + + } +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java +index 5907e378..1cb3bcc8 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.core/src/org/eclipse/mylyn/reviews/tasks/core/internal/ReviewsUtil.java +@@ -23,14 +23,11 @@ + import org.eclipse.mylyn.reviews.tasks.core.patch.GitPatchPathFindingStrategy; + import org.eclipse.mylyn.reviews.tasks.core.patch.ITargetPathStrategy; + import org.eclipse.mylyn.reviews.tasks.core.patch.SimplePathFindingStrategy; +-import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslStandaloneSetup; +-import org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.ReviewDslParser; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslMapper; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslSerializer; + import org.eclipse.mylyn.tasks.core.ITask; + import org.eclipse.mylyn.tasks.core.ITaskContainer; + import org.eclipse.mylyn.tasks.core.data.ITaskDataManager; +-import org.eclipse.xtext.parsetree.reconstr.Serializer; +- +-import com.google.inject.Injector; + + /** + * @author Kilian Matt +@@ -91,14 +88,9 @@ public static Attachment findAttachment(String filename, String author, + return null; + } + +- public static ReviewTaskMapper createMapper() { +- Injector createInjectorAndDoEMFRegistration = new ReviewDslStandaloneSetup() +- .createInjectorAndDoEMFRegistration(); +- ReviewDslParser parser = createInjectorAndDoEMFRegistration +- .getInstance(ReviewDslParser.class); +- Serializer serializer = createInjectorAndDoEMFRegistration +- .getInstance(Serializer.class); +- return new ReviewTaskMapper(parser, serializer); ++ public static IReviewMapper createMapper() { ++ return new ReviewTaskMapper(new ReviewDslMapper(), ++ new ReviewDslSerializer()); + } + + } +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath +index 7e8449de..304e8618 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/.classpath +@@ -1,7 +1,6 @@ + + + +- + + + +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF +index de4ab427..e28d532f 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/META-INF/MANIFEST.MF +@@ -5,27 +5,9 @@ Bundle-Vendor: Eclipse Mylyn + Bundle-Version: 0.7.0.qualifier + Bundle-SymbolicName: org.eclipse.mylyn.reviews.tasks.dsl;singleton:=true + Bundle-ActivationPolicy: lazy +-Require-Bundle: org.eclipse.xtext, +- org.eclipse.xtext.generator;resolution:=optional, +- org.apache.commons.logging;resolution:=optional, +- org.eclipse.emf.codegen.ecore;resolution:=optional, +- org.eclipse.emf.mwe.utils;resolution:=optional, +- org.eclipse.emf.mwe2.launch;resolution:=optional, +- com.ibm.icu;resolution:=optional, +- org.eclipse.xtext.xtend;resolution:=optional, +- org.eclipse.xtext.util, +- org.eclipse.emf.ecore, +- org.eclipse.emf.common, +- org.antlr.runtime ++Require-Bundle: org.antlr.runtime;bundle-version=""3.0.0"" + Import-Package: org.apache.log4j + Bundle-RequiredExecutionEnvironment: J2SE-1.5 + Export-Package: org.eclipse.mylyn.reviews.tasks.dsl, +- org.eclipse.mylyn.reviews.tasks.dsl.parseTreeConstruction, +- org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr, +- org.eclipse.mylyn.reviews.tasks.dsl.parser.antlr.internal, +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl, +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.impl, +- org.eclipse.mylyn.reviews.tasks.dsl.reviewDsl.util, +- org.eclipse.mylyn.reviews.tasks.dsl.services, +- org.eclipse.mylyn.reviews.tasks.dsl.validation ++ org.eclipse.mylyn.reviews.tasks.dsl.internal + +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml +index 8881d7bf..20bb679e 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml +@@ -3,13 +3,6 @@ + + + +- +- +- +- + + + +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen +deleted file mode 100644 +index 8881d7bf..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/plugin.xml_gen ++++ /dev/null +@@ -1,18 +0,0 @@ +- +- +- +- +- +- +- +- +- +- +- +- +- +- +- +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml +index 0eaa057b..a652c89f 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/pom.xml +@@ -17,14 +17,6 @@ + target/classes + + +- +- org.fornax.toolsupport +- fornax-oaw-m2-plugin +- +- mwe2 +- ${project.basedir}/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2 +- +- + + org.sonatype.tycho + maven-osgi-source-plugin +@@ -38,41 +30,5 @@ + maven-pmd-plugin + + +- +- +- +- org.fornax.toolsupport +- fornax-oaw-m2-plugin +- 3.2.0-SNAPSHOT +- +- mwe2 +- +- +- +- generate-sources +- +- run-workflow +- +- +- +- +- +- + +- +- +- fornax-snapshots +- http://fornax.itemis.de/nexus/content/repositories/snapshots +- +- false +- +- +- true +- +- +- +- fornax-releases +- http://fornax.itemis.de/nexus/content/repositories/releases/ +- +- + +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2 b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2 +deleted file mode 100644 +index 06d08ac7..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/GenerateReviewDsl.mwe2 ++++ /dev/null +@@ -1,100 +0,0 @@ +-module org.eclipse.mylyn.reviews.tasks.dsl.ReviewDsl +- +-import org.eclipse.emf.mwe.utils.* +-import org.eclipse.xtext.generator.* +-import org.eclipse.xtext.ui.generator.* +- +-var grammarURI = ""classpath:/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext"" +-var file.extensions = ""review-dsl"" +-var projectName = ""org.eclipse.mylyn.reviews.tasks.dsl"" +-var runtimeProject = ""../${projectName}"" +- +-Workflow { +- bean = StandaloneSetup { +- platformUri = ""${runtimeProject}/.."" +- } +- +- component = DirectoryCleaner { +- directory = ""${runtimeProject}/src-gen"" +- } +- +- component = DirectoryCleaner { +- directory = ""${runtimeProject}.ui/src-gen"" +- } +- +- component = Generator { +- pathRtProject = runtimeProject +- pathUiProject = ""${runtimeProject}.ui"" +- projectNameRt = projectName +- projectNameUi = ""${projectName}.ui"" +- language = { +- uri = grammarURI +- fileExtensions = file.extensions +- +- // Java API to access grammar elements (required by several other fragments) +- fragment = grammarAccess.GrammarAccessFragment {} +- +- // generates Java API for the generated EPackages +- fragment = ecore.EcoreGeneratorFragment { +- // referencedGenModels = ""uri to genmodel, uri to next genmodel"" +- } +- +- // the serialization component +- fragment = parseTreeConstructor.ParseTreeConstructorFragment {} +- +- // a custom ResourceFactory for use with EMF +- fragment = resourceFactory.ResourceFactoryFragment { +- fileExtensions = file.extensions +- } +- +- // The antlr parser generator fragment. +- fragment = parser.antlr.XtextAntlrGeneratorFragment { +- // options = { +- // backtrack = true +- // } +- } +- +- // java-based API for validation +- fragment = validation.JavaValidatorFragment { +- composedCheck = ""org.eclipse.xtext.validation.ImportUriValidator"" +- composedCheck = ""org.eclipse.xtext.validation.NamesAreUniqueValidator"" +- // registerForImportedPackages = true +- } +- +- // scoping and exporting API +- // fragment = scoping.ImportURIScopingFragment {} +- // fragment = exporting.SimpleNamesFragment {} +- +- // scoping and exporting API +- fragment = scoping.ImportNamespacesScopingFragment {} +- fragment = exporting.QualifiedNamesFragment {} +- fragment = builder.BuilderIntegrationFragment {} +- +- // formatter API +- fragment = formatting.FormatterFragment {} +- +- // labeling API +- fragment = labeling.LabelProviderFragment {} +- +- // outline API +- fragment = outline.TransformerFragment {} +- fragment = outline.OutlineNodeAdapterFactoryFragment {} +- fragment = outline.QuickOutlineFragment {} +- +- // quickfix API +- fragment = quickfix.QuickfixProviderFragment {} +- +- // content assist API +- fragment = contentAssist.JavaBasedContentAssistFragment {} +- +- // generates a more lightweight Antlr parser and lexer tailored for content assist +- fragment = parser.antlr.XtextAntlrUiGeneratorFragment {} +- +- // project wizard (optional) +- // fragment = projectWizard.SimpleProjectWizardFragment { +- // generatorProjectName = ""${projectName}.generator"" +- // modelFileExtension = file.extensions +- // } +- } +- } +-} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslMapper.java +new file mode 100644 +index 00000000..6d2de436 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslMapper.java +@@ -0,0 +1,29 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public interface IReviewDslMapper { ++ ++ public abstract ReviewDslResult parseReviewResult(String text) ++ throws ParseException; ++ ++ public abstract ReviewDslScope parseReviewScope(String text) ++ throws ParseException; ++ ++ public abstract ReviewDslResult parseChangedReviewScope(String text); ++ ++} +\ No newline at end of file +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslSerializer.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslSerializer.java +new file mode 100644 +index 00000000..a014d272 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/IReviewDslSerializer.java +@@ -0,0 +1,25 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public interface IReviewDslSerializer { ++ ++ public abstract String serialize(ReviewDslScope scope); ++ ++ public abstract String serialize(ReviewDslResult result); ++ ++} +\ No newline at end of file +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ParseException.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ParseException.java +new file mode 100644 +index 00000000..5dc74dea +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ParseException.java +@@ -0,0 +1,27 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ParseException extends Exception { ++ ++ private static final long serialVersionUID = -7998527695103083639L; ++ ++ public ParseException(String message) { ++ super(message); ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext +deleted file mode 100644 +index ea536461..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDsl.xtext ++++ /dev/null +@@ -1,55 +0,0 @@ +-grammar org.eclipse.mylyn.reviews.tasks.dsl.ReviewDsl with org.eclipse.xtext.common.Terminals +- +-generate reviewDsl ""http://www.eclipse.org/mylyn/reviews/tasks/dsl/ReviewDsl"" +- +-Model: +- ReviewResult | ReviewScope | ChangedReviewScope; +- +-ReviewResult: +- ""Review result:"" result=ResultEnum +- (""Comment:"" comment=STRING)? (filecomments+=FileComment)*; +- +-enum ResultEnum: +- passed=""PASSED"" | failed=""FAILED"" +- | todo=""TODO"" | warning=""WARNING""; +- +-FileComment: +- ""File"" path=STRING "":"" comment=STRING? +- linecomments+=LineComment*; +- +-LineComment: +- ""Line"" start=INT (""-"" end=INT)? "":"" comment=STRING; +- +-ReviewScope: +- {ReviewScope} ""Review scope:"" +- (scope+=ReviewScopeItem)*; +- +-ChangedReviewScope: +- ""Updated review scope:"" +- //(refines"" (refineOriginal?=""original scope""| (""scope from comment #"" refineComment=INT)) "":"" +- (scope+=ReviewScopeItem)+; +- +-ChangesetDef: +- (""Changeset"" revision=STRING ""from"" url=STRING); +- +-ReviewScopeItem: +- ResourceDef | PatchDef | ChangesetDef; +- +-ResourceDef: +- (""Resource"" source=Source); +- +-PatchDef: +- (""Patch"" source=Source); +- +-Source: +- AttachmentSource; +- +-AttachmentSource: +- ""from Attachment"" filename=STRING +- ""by"" author=STRING +- ""on"" createdDate=STRING +- ""of task"" taskId=TASK_ID; +- +-terminal TASK_ID: +- ('a'..'z' | 'A'..'Z' | '_' | '-' | '0'..'9')*; +- +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslAttachmentScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslAttachmentScopeItem.java +new file mode 100644 +index 00000000..044f346c +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslAttachmentScopeItem.java +@@ -0,0 +1,74 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslAttachmentScopeItem extends ReviewDslScopeItem { ++ ++ public enum Type { ++ PATCH, RESOURCE ++ } ++ ++ private Type type; ++ private String fileName; ++ private String author; ++ private String createdDate; ++ private String taskId; ++ ++ public ReviewDslAttachmentScopeItem(Type type, String fileName, ++ String author, String createdDate, String taskId) { ++ super(); ++ this.type = type; ++ this.fileName = fileName; ++ this.author = author; ++ this.createdDate = createdDate; ++ this.taskId = taskId; ++ } ++ ++ public Type getType() { ++ return type; ++ } ++ ++ public String getFileName() { ++ return fileName; ++ } ++ ++ public String getAuthor() { ++ return author; ++ } ++ ++ public String getCreatedDate() { ++ return createdDate; ++ } ++ ++ public String getTaskId() { ++ return taskId; ++ } ++ ++ @Override ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(type == Type.PATCH ? ""Patch"" : ""Resource""); ++ sb.append(""from Attachment \""""); ++ sb.append(fileName); ++ sb.append(""\"" by \""""); ++ sb.append(author); ++ sb.append(""\"" on \""""); ++ sb.append(createdDate); ++ sb.append(""\"" of task ""); ++ sb.append(taskId); ++ return sb; ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslChangesetScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslChangesetScopeItem.java +new file mode 100644 +index 00000000..bfb5ff27 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslChangesetScopeItem.java +@@ -0,0 +1,50 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslChangesetScopeItem extends ReviewDslScopeItem { ++ ++ private String revision; ++ private String repoUrl; ++ ++ public String getRevision() { ++ return revision; ++ } ++ ++ public void setRevision(String revision) { ++ this.revision = revision; ++ } ++ ++ public String getRepoUrl() { ++ return repoUrl; ++ } ++ ++ public void setRepoUrl(String repoUrl) { ++ this.repoUrl = repoUrl; ++ } ++ ++ @Override ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(""Changeset \""""); ++ sb.append(revision); ++ sb.append(""\"" from \""""); ++ sb.append(repoUrl); ++ sb.append(""\""""); ++ return sb; ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslResult.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslResult.java +new file mode 100644 +index 00000000..ee0063d8 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslResult.java +@@ -0,0 +1,153 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++import java.util.ArrayList; ++import java.util.List; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslResult { ++ public enum Rating { ++ PASSED, FAILED, WARNING, TODO ++ } ++ ++ public static class FileComment { ++ ++ private String fileName; ++ private String comment; ++ private List lineComments = new ArrayList(); ++ ++ public String getFileName() { ++ return fileName; ++ } ++ ++ public String getComment() { ++ return comment; ++ } ++ ++ public void setFileName(String path) { ++ this.fileName = path; ++ } ++ ++ public void setComment(String comment) { ++ this.comment = comment; ++ } ++ ++ public List getLineComments() { ++ return lineComments; ++ } ++ ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(""File \""""); ++ sb.append(fileName); ++ sb.append(""\""""); ++ if (comment != null) { ++ sb.append("" \""""); ++ sb.append(comment); ++ sb.append(""\""""); ++ } ++ for (LineComment c : lineComments) { ++ sb.append(""\n""); ++ c.serialize(sb); ++ } ++ return sb; ++ } ++ ++ } ++ ++ public static class LineComment { ++ private int begin; ++ private int end; ++ private String comment; ++ ++ public int getBegin() { ++ return begin; ++ } ++ ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(""Line ""); ++ sb.append(begin); ++ if (begin != end) { ++ sb.append("" - ""); ++ sb.append(end); ++ } ++ sb.append("": \""""); ++ sb.append(comment); ++ sb.append(""\""""); ++ return sb; ++ } ++ ++ public void setBegin(int begin) { ++ this.begin = begin; ++ } ++ ++ public int getEnd() { ++ return end; ++ } ++ ++ public void setEnd(int end) { ++ this.end = end; ++ } ++ ++ public String getComment() { ++ return comment; ++ } ++ ++ public void setComment(String comment) { ++ this.comment = comment; ++ } ++ ++ } ++ ++ private Rating rating; ++ private String comment; ++ private List fileComments = new ArrayList(); ++ ++ public Rating getRating() { ++ return rating; ++ } ++ ++ public String getComment() { ++ return comment; ++ } ++ ++ public void setRating(Rating rating) { ++ this.rating = rating; ++ } ++ ++ public void setComment(String comment) { ++ this.comment = comment; ++ } ++ ++ public List getFileComments() { ++ return fileComments; ++ } ++ ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(""Review result: ""); ++ sb.append(rating.toString()); ++ if (comment != null) { ++ sb.append("" \""""); ++ sb.append(comment); ++ sb.append(""\""""); ++ } ++ for (FileComment c : fileComments) { ++ sb.append(""\n""); ++ c.serialize(sb); ++ } ++ return sb; ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java +deleted file mode 100644 +index 7bf5ed9f..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslRuntimeModule.java ++++ /dev/null +@@ -1,12 +0,0 @@ +-/* +- * generated by Xtext +- */ +-package org.eclipse.mylyn.reviews.tasks.dsl; +- +- +-/** +- * Use this class to register components to be used at runtime / without the Equinox extension registry. +- */ +-public class ReviewDslRuntimeModule extends org.eclipse.mylyn.reviews.tasks.dsl.AbstractReviewDslRuntimeModule { +- +-} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScope.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScope.java +new file mode 100644 +index 00000000..90b9859c +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScope.java +@@ -0,0 +1,40 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++import java.util.ArrayList; ++import java.util.Collections; ++import java.util.List; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslScope { ++ List items = new ArrayList(); ++ public void addItem(ReviewDslScopeItem item) { ++ items.add(item); ++ } ++ ++ public List getItems() { ++ return Collections.unmodifiableList(items); ++ } ++ ++ public StringBuilder serialize(StringBuilder sb) { ++ sb.append(""Review scope:""); ++ for(ReviewDslScopeItem item : items) { ++ item.serialize(sb); ++ sb.append(""\n""); ++ } ++ return sb; ++ } ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScopeItem.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScopeItem.java +new file mode 100644 +index 00000000..fc1952b8 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslScopeItem.java +@@ -0,0 +1,22 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.dsl; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public abstract class ReviewDslScopeItem { ++ ++ public abstract StringBuilder serialize(StringBuilder sb) ; ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java +deleted file mode 100644 +index e5caf580..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/ReviewDslStandaloneSetup.java ++++ /dev/null +@@ -1,16 +0,0 @@ +- +-package org.eclipse.mylyn.reviews.tasks.dsl; +- +-import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslStandaloneSetupGenerated; +- +-/** +- * Initialization support for running Xtext languages +- * without equinox extension registry +- */ +-public class ReviewDslStandaloneSetup extends ReviewDslStandaloneSetupGenerated{ +- +- public static void doSetup() { +- new ReviewDslStandaloneSetup().createInjectorAndDoEMFRegistration(); +- } +-} +- +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java +deleted file mode 100644 +index 35f59b67..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/formatting/ReviewDslFormatter.java ++++ /dev/null +@@ -1,33 +0,0 @@ +-/* +- * generated by Xtext +- */ +-package org.eclipse.mylyn.reviews.tasks.dsl.formatting; +- +-import org.eclipse.mylyn.reviews.tasks.dsl.services.ReviewDslGrammarAccess; +-import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter; +-import org.eclipse.xtext.formatting.impl.FormattingConfig; +- +-/** +- * This class contains custom formatting description. +- * +- * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting +- * on how and when to use it +- * +- * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an +- * example +- */ +-public class ReviewDslFormatter extends AbstractDeclarativeFormatter { +- +- @Override +- protected void configureFormatting(FormattingConfig c) { +- ReviewDslGrammarAccess grammar = (ReviewDslGrammarAccess) getGrammarAccess(); +- c.setLinewrap().after(grammar.getModelRule()); +- c.setIndentationIncrement().before(grammar.getReviewScopeItemRule()); +- c.setIndentationDecrement().after(grammar.getReviewScopeItemRule()); +- c.setLinewrap().after(grammar.getReviewScopeItemRule()); +- c.setLinewrap().before( +- grammar.getReviewResultAccess().getCommentKeyword_2_0()); +- c.setLinewrap().after( +- grammar.getReviewResultAccess().getCommentAssignment_2_1()); +- } +-} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslLexer.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslLexer.java +new file mode 100644 +index 00000000..69cf5513 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslLexer.java +@@ -0,0 +1,2399 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.dsl.internal; ++ ++// $ANTLR 3.0 ReviewDsl.g 2011-03-06 18:30:25 ++ ++import org.antlr.runtime.CharStream; ++import org.antlr.runtime.EarlyExitException; ++import org.antlr.runtime.Lexer; ++import org.antlr.runtime.MismatchedSetException; ++import org.antlr.runtime.NoViableAltException; ++import org.antlr.runtime.RecognitionException; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslLexer extends Lexer { ++ public static final int TASK_ID=6; ++ public static final int UNICODE_ESC=8; ++ public static final int OCTAL_ESC=9; ++ public static final int HEX_DIGIT=10; ++ public static final int T29=29; ++ public static final int INT=5; ++ public static final int T28=28; ++ public static final int T27=27; ++ public static final int T26=26; ++ public static final int T25=25; ++ public static final int Tokens=33; ++ public static final int T24=24; ++ public static final int EOF=-1; ++ public static final int T23=23; ++ public static final int T22=22; ++ public static final int T21=21; ++ public static final int T20=20; ++ public static final int ESC_SEQ=7; ++ public static final int WS=11; ++ public static final int T12=12; ++ public static final int T13=13; ++ public static final int T14=14; ++ public static final int T15=15; ++ public static final int T16=16; ++ public static final int T17=17; ++ public static final int T18=18; ++ public static final int T30=30; ++ public static final int T19=19; ++ public static final int T32=32; ++ public static final int STRING=4; ++ public static final int T31=31; ++ public ReviewDslLexer() {;} ++ public ReviewDslLexer(CharStream input) { ++ super(input); ++ } ++ public String getGrammarFileName() { return ""ReviewDsl.g""; } ++ ++ // $ANTLR start T12 ++ public final void mT12() throws RecognitionException { ++ try { ++ int _type = T12; ++ // ReviewDsl.g:3:7: ( 'Review' ) ++ // ReviewDsl.g:3:7: 'Review' ++ { ++ match(""Review""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T12 ++ ++ // $ANTLR start T13 ++ public final void mT13() throws RecognitionException { ++ try { ++ int _type = T13; ++ // ReviewDsl.g:4:7: ( 'result:' ) ++ // ReviewDsl.g:4:7: 'result:' ++ { ++ match(""result:""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T13 ++ ++ // $ANTLR start T14 ++ public final void mT14() throws RecognitionException { ++ try { ++ int _type = T14; ++ // ReviewDsl.g:5:7: ( 'Comment:' ) ++ // ReviewDsl.g:5:7: 'Comment:' ++ { ++ match(""Comment:""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T14 ++ ++ // $ANTLR start T15 ++ public final void mT15() throws RecognitionException { ++ try { ++ int _type = T15; ++ // ReviewDsl.g:6:7: ( 'PASSED' ) ++ // ReviewDsl.g:6:7: 'PASSED' ++ { ++ match(""PASSED""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T15 ++ ++ // $ANTLR start T16 ++ public final void mT16() throws RecognitionException { ++ try { ++ int _type = T16; ++ // ReviewDsl.g:7:7: ( 'WARNING' ) ++ // ReviewDsl.g:7:7: 'WARNING' ++ { ++ match(""WARNING""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T16 ++ ++ // $ANTLR start T17 ++ public final void mT17() throws RecognitionException { ++ try { ++ int _type = T17; ++ // ReviewDsl.g:8:7: ( 'FAILED' ) ++ // ReviewDsl.g:8:7: 'FAILED' ++ { ++ match(""FAILED""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T17 ++ ++ // $ANTLR start T18 ++ public final void mT18() throws RecognitionException { ++ try { ++ int _type = T18; ++ // ReviewDsl.g:9:7: ( 'TODO' ) ++ // ReviewDsl.g:9:7: 'TODO' ++ { ++ match(""TODO""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T18 ++ ++ // $ANTLR start T19 ++ public final void mT19() throws RecognitionException { ++ try { ++ int _type = T19; ++ // ReviewDsl.g:10:7: ( 'File' ) ++ // ReviewDsl.g:10:7: 'File' ++ { ++ match(""File""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T19 ++ ++ // $ANTLR start T20 ++ public final void mT20() throws RecognitionException { ++ try { ++ int _type = T20; ++ // ReviewDsl.g:11:7: ( ':' ) ++ // ReviewDsl.g:11:7: ':' ++ { ++ match(':'); ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T20 ++ ++ // $ANTLR start T21 ++ public final void mT21() throws RecognitionException { ++ try { ++ int _type = T21; ++ // ReviewDsl.g:12:7: ( 'Line' ) ++ // ReviewDsl.g:12:7: 'Line' ++ { ++ match(""Line""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T21 ++ ++ // $ANTLR start T22 ++ public final void mT22() throws RecognitionException { ++ try { ++ int _type = T22; ++ // ReviewDsl.g:13:7: ( '-' ) ++ // ReviewDsl.g:13:7: '-' ++ { ++ match('-'); ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T22 ++ ++ // $ANTLR start T23 ++ public final void mT23() throws RecognitionException { ++ try { ++ int _type = T23; ++ // ReviewDsl.g:14:7: ( 'scope:' ) ++ // ReviewDsl.g:14:7: 'scope:' ++ { ++ match(""scope:""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T23 ++ ++ // $ANTLR start T24 ++ public final void mT24() throws RecognitionException { ++ try { ++ int _type = T24; ++ // ReviewDsl.g:15:7: ( 'Resource' ) ++ // ReviewDsl.g:15:7: 'Resource' ++ { ++ match(""Resource""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T24 ++ ++ // $ANTLR start T25 ++ public final void mT25() throws RecognitionException { ++ try { ++ int _type = T25; ++ // ReviewDsl.g:16:7: ( 'Changeset' ) ++ // ReviewDsl.g:16:7: 'Changeset' ++ { ++ match(""Changeset""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T25 ++ ++ // $ANTLR start T26 ++ public final void mT26() throws RecognitionException { ++ try { ++ int _type = T26; ++ // ReviewDsl.g:17:7: ( 'from' ) ++ // ReviewDsl.g:17:7: 'from' ++ { ++ match(""from""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T26 ++ ++ // $ANTLR start T27 ++ public final void mT27() throws RecognitionException { ++ try { ++ int _type = T27; ++ // ReviewDsl.g:18:7: ( 'Patch' ) ++ // ReviewDsl.g:18:7: 'Patch' ++ { ++ match(""Patch""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T27 ++ ++ // $ANTLR start T28 ++ public final void mT28() throws RecognitionException { ++ try { ++ int _type = T28; ++ // ReviewDsl.g:19:7: ( 'Attachment' ) ++ // ReviewDsl.g:19:7: 'Attachment' ++ { ++ match(""Attachment""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T28 ++ ++ // $ANTLR start T29 ++ public final void mT29() throws RecognitionException { ++ try { ++ int _type = T29; ++ // ReviewDsl.g:20:7: ( 'by' ) ++ // ReviewDsl.g:20:7: 'by' ++ { ++ match(""by""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T29 ++ ++ // $ANTLR start T30 ++ public final void mT30() throws RecognitionException { ++ try { ++ int _type = T30; ++ // ReviewDsl.g:21:7: ( 'on' ) ++ // ReviewDsl.g:21:7: 'on' ++ { ++ match(""on""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T30 ++ ++ // $ANTLR start T31 ++ public final void mT31() throws RecognitionException { ++ try { ++ int _type = T31; ++ // ReviewDsl.g:22:7: ( 'of' ) ++ // ReviewDsl.g:22:7: 'of' ++ { ++ match(""of""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T31 ++ ++ // $ANTLR start T32 ++ public final void mT32() throws RecognitionException { ++ try { ++ int _type = T32; ++ // ReviewDsl.g:23:7: ( 'task' ) ++ // ReviewDsl.g:23:7: 'task' ++ { ++ match(""task""); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end T32 ++ ++ // $ANTLR start TASK_ID ++ public final void mTASK_ID() throws RecognitionException { ++ try { ++ int _type = TASK_ID; ++ // ReviewDsl.g:72:2: ( ( 'a' .. 'z' | 'A' .. 'Z' )+ ( '_' | '-' )? ( 'a' .. 'z' | 'A' .. 'Z' | INT )+ ) ++ // ReviewDsl.g:72:2: ( 'a' .. 'z' | 'A' .. 'Z' )+ ( '_' | '-' )? ( 'a' .. 'z' | 'A' .. 'Z' | INT )+ ++ { ++ // ReviewDsl.g:72:2: ( 'a' .. 'z' | 'A' .. 'Z' )+ ++ int cnt1=0; ++ loop1: ++ do { ++ int alt1=2; ++ int LA1_0 = input.LA(1); ++ ++ if ( ((LA1_0>='a' && LA1_0<='z')) ) { ++ alt1=1; ++ } ++ else if ( ((LA1_0>='A' && LA1_0<='Z')) ) { ++ alt1=1; ++ } ++ ++ ++ switch (alt1) { ++ case 1 : ++ // ReviewDsl.g: ++ { ++ if ( (input.LA(1)>='A' && input.LA(1)<='Z')||(input.LA(1)>='a' && input.LA(1)<='z') ) { ++ input.consume(); ++ ++ } ++ else { ++ MismatchedSetException mse = ++ new MismatchedSetException(null,input); ++ recover(mse); throw mse; ++ } ++ ++ ++ } ++ break; ++ ++ default : ++ if ( cnt1 >= 1 ) break loop1; ++ EarlyExitException eee = ++ new EarlyExitException(1, input); ++ throw eee; ++ } ++ cnt1++; ++ } while (true); ++ ++ // ReviewDsl.g:72:25: ( '_' | '-' )? ++ int alt2=2; ++ int LA2_0 = input.LA(1); ++ ++ if ( (LA2_0=='-'||LA2_0=='_') ) { ++ alt2=1; ++ } ++ switch (alt2) { ++ case 1 : ++ // ReviewDsl.g: ++ { ++ if ( input.LA(1)=='-'||input.LA(1)=='_' ) { ++ input.consume(); ++ ++ } ++ else { ++ MismatchedSetException mse = ++ new MismatchedSetException(null,input); ++ recover(mse); throw mse; ++ } ++ ++ ++ } ++ break; ++ ++ } ++ ++ // ReviewDsl.g:72:38: ( 'a' .. 'z' | 'A' .. 'Z' | INT )+ ++ int cnt3=0; ++ loop3: ++ do { ++ int alt3=4; ++ switch ( input.LA(1) ) { ++ case 'a': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'f': ++ case 'g': ++ case 'h': ++ case 'i': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'n': ++ case 'o': ++ case 'p': ++ case 'q': ++ case 'r': ++ case 's': ++ case 't': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt3=1; ++ } ++ break; ++ case 'A': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'L': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'P': ++ case 'Q': ++ case 'R': ++ case 'S': ++ case 'T': ++ case 'U': ++ case 'V': ++ case 'W': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ { ++ alt3=2; ++ } ++ break; ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ { ++ alt3=3; ++ } ++ break; ++ ++ } ++ ++ switch (alt3) { ++ case 1 : ++ // ReviewDsl.g:72:39: 'a' .. 'z' ++ { ++ matchRange('a','z'); ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:72:50: 'A' .. 'Z' ++ { ++ matchRange('A','Z'); ++ ++ } ++ break; ++ case 3 : ++ // ReviewDsl.g:72:61: INT ++ { ++ mINT(); ++ ++ } ++ break; ++ ++ default : ++ if ( cnt3 >= 1 ) break loop3; ++ EarlyExitException eee = ++ new EarlyExitException(3, input); ++ throw eee; ++ } ++ cnt3++; ++ } while (true); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end TASK_ID ++ ++ // $ANTLR start INT ++ public final void mINT() throws RecognitionException { ++ try { ++ int _type = INT; ++ // ReviewDsl.g:75:2: ( ( '0' .. '9' )+ ) ++ // ReviewDsl.g:75:2: ( '0' .. '9' )+ ++ { ++ // ReviewDsl.g:75:2: ( '0' .. '9' )+ ++ int cnt4=0; ++ loop4: ++ do { ++ int alt4=2; ++ int LA4_0 = input.LA(1); ++ ++ if ( ((LA4_0>='0' && LA4_0<='9')) ) { ++ alt4=1; ++ } ++ ++ ++ switch (alt4) { ++ case 1 : ++ // ReviewDsl.g:75:2: '0' .. '9' ++ { ++ matchRange('0','9'); ++ ++ } ++ break; ++ ++ default : ++ if ( cnt4 >= 1 ) break loop4; ++ EarlyExitException eee = ++ new EarlyExitException(4, input); ++ throw eee; ++ } ++ cnt4++; ++ } while (true); ++ ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end INT ++ ++ // $ANTLR start STRING ++ public final void mSTRING() throws RecognitionException { ++ try { ++ int _type = STRING; ++ // ReviewDsl.g:79:8: ( '\""' ( ESC_SEQ | ~ ( '\\\\' | '\""' ) )* '\""' ) ++ // ReviewDsl.g:79:8: '\""' ( ESC_SEQ | ~ ( '\\\\' | '\""' ) )* '\""' ++ { ++ match('\""'); ++ // ReviewDsl.g:79:12: ( ESC_SEQ | ~ ( '\\\\' | '\""' ) )* ++ loop5: ++ do { ++ int alt5=3; ++ int LA5_0 = input.LA(1); ++ ++ if ( (LA5_0=='\\') ) { ++ alt5=1; ++ } ++ else if ( ((LA5_0>='\u0000' && LA5_0<='!')||(LA5_0>='#' && LA5_0<='[')||(LA5_0>=']' && LA5_0<='\uFFFE')) ) { ++ alt5=2; ++ } ++ ++ ++ switch (alt5) { ++ case 1 : ++ // ReviewDsl.g:79:14: ESC_SEQ ++ { ++ mESC_SEQ(); ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:79:24: ~ ( '\\\\' | '\""' ) ++ { ++ if ( (input.LA(1)>='\u0000' && input.LA(1)<='!')||(input.LA(1)>='#' && input.LA(1)<='[')||(input.LA(1)>=']' && input.LA(1)<='\uFFFE') ) { ++ input.consume(); ++ ++ } ++ else { ++ MismatchedSetException mse = ++ new MismatchedSetException(null,input); ++ recover(mse); throw mse; ++ } ++ ++ ++ } ++ break; ++ ++ default : ++ break loop5; ++ } ++ } while (true); ++ ++ match('\""'); ++ ++ } ++ ++ this.type = _type; ++ } ++ finally { ++ } ++ } ++ // $ANTLR end STRING ++ ++ // $ANTLR start ESC_SEQ ++ public final void mESC_SEQ() throws RecognitionException { ++ try { ++ // ReviewDsl.g:83:9: ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\""' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC ) ++ int alt6=3; ++ int LA6_0 = input.LA(1); ++ ++ if ( (LA6_0=='\\') ) { ++ switch ( input.LA(2) ) { ++ case 'u': ++ { ++ alt6=2; ++ } ++ break; ++ case '\""': ++ case '\'': ++ case '\\': ++ case 'b': ++ case 'f': ++ case 'n': ++ case 'r': ++ case 't': ++ { ++ alt6=1; ++ } ++ break; ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ { ++ alt6=3; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""81:1: fragment ESC_SEQ : ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\""' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC );"", 6, 1, input); ++ ++ throw nvae; ++ } ++ ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""81:1: fragment ESC_SEQ : ( '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\""' | '\\'' | '\\\\' ) | UNICODE_ESC | OCTAL_ESC );"", 6, 0, input); ++ ++ throw nvae; ++ } ++ switch (alt6) { ++ case 1 : ++ // ReviewDsl.g:83:9: '\\\\' ( 'b' | 't' | 'n' | 'f' | 'r' | '\\\""' | '\\'' | '\\\\' ) ++ { ++ match('\\'); ++ if ( input.LA(1)=='\""'||input.LA(1)=='\''||input.LA(1)=='\\'||input.LA(1)=='b'||input.LA(1)=='f'||input.LA(1)=='n'||input.LA(1)=='r'||input.LA(1)=='t' ) { ++ input.consume(); ++ ++ } ++ else { ++ MismatchedSetException mse = ++ new MismatchedSetException(null,input); ++ recover(mse); throw mse; ++ } ++ ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:84:9: UNICODE_ESC ++ { ++ mUNICODE_ESC(); ++ ++ } ++ break; ++ case 3 : ++ // ReviewDsl.g:85:9: OCTAL_ESC ++ { ++ mOCTAL_ESC(); ++ ++ } ++ break; ++ ++ } ++ } ++ finally { ++ } ++ } ++ // $ANTLR end ESC_SEQ ++ ++ // $ANTLR start OCTAL_ESC ++ public final void mOCTAL_ESC() throws RecognitionException { ++ try { ++ // ReviewDsl.g:89:9: ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ) ++ int alt7=3; ++ int LA7_0 = input.LA(1); ++ ++ if ( (LA7_0=='\\') ) { ++ int LA7_1 = input.LA(2); ++ ++ if ( ((LA7_1>='0' && LA7_1<='3')) ) { ++ int LA7_2 = input.LA(3); ++ ++ if ( ((LA7_2>='0' && LA7_2<='7')) ) { ++ int LA7_5 = input.LA(4); ++ ++ if ( ((LA7_5>='0' && LA7_5<='7')) ) { ++ alt7=1; ++ } ++ else { ++ alt7=2;} ++ } ++ else { ++ alt7=3;} ++ } ++ else if ( ((LA7_1>='4' && LA7_1<='7')) ) { ++ int LA7_3 = input.LA(3); ++ ++ if ( ((LA7_3>='0' && LA7_3<='7')) ) { ++ alt7=2; ++ } ++ else { ++ alt7=3;} ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""87:1: fragment OCTAL_ESC : ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) );"", 7, 1, input); ++ ++ throw nvae; ++ } ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""87:1: fragment OCTAL_ESC : ( '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) | '\\\\' ( '0' .. '7' ) );"", 7, 0, input); ++ ++ throw nvae; ++ } ++ switch (alt7) { ++ case 1 : ++ // ReviewDsl.g:89:9: '\\\\' ( '0' .. '3' ) ( '0' .. '7' ) ( '0' .. '7' ) ++ { ++ match('\\'); ++ // ReviewDsl.g:89:14: ( '0' .. '3' ) ++ // ReviewDsl.g:89:15: '0' .. '3' ++ { ++ matchRange('0','3'); ++ ++ } ++ ++ // ReviewDsl.g:89:25: ( '0' .. '7' ) ++ // ReviewDsl.g:89:26: '0' .. '7' ++ { ++ matchRange('0','7'); ++ ++ } ++ ++ // ReviewDsl.g:89:36: ( '0' .. '7' ) ++ // ReviewDsl.g:89:37: '0' .. '7' ++ { ++ matchRange('0','7'); ++ ++ } ++ ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:90:9: '\\\\' ( '0' .. '7' ) ( '0' .. '7' ) ++ { ++ match('\\'); ++ // ReviewDsl.g:90:14: ( '0' .. '7' ) ++ // ReviewDsl.g:90:15: '0' .. '7' ++ { ++ matchRange('0','7'); ++ ++ } ++ ++ // ReviewDsl.g:90:25: ( '0' .. '7' ) ++ // ReviewDsl.g:90:26: '0' .. '7' ++ { ++ matchRange('0','7'); ++ ++ } ++ ++ ++ } ++ break; ++ case 3 : ++ // ReviewDsl.g:91:9: '\\\\' ( '0' .. '7' ) ++ { ++ match('\\'); ++ // ReviewDsl.g:91:14: ( '0' .. '7' ) ++ // ReviewDsl.g:91:15: '0' .. '7' ++ { ++ matchRange('0','7'); ++ ++ } ++ ++ ++ } ++ break; ++ ++ } ++ } ++ finally { ++ } ++ } ++ // $ANTLR end OCTAL_ESC ++ ++ // $ANTLR start UNICODE_ESC ++ public final void mUNICODE_ESC() throws RecognitionException { ++ try { ++ // ReviewDsl.g:95:9: ( '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ) ++ // ReviewDsl.g:95:9: '\\\\' 'u' HEX_DIGIT HEX_DIGIT HEX_DIGIT HEX_DIGIT ++ { ++ match('\\'); ++ match('u'); ++ mHEX_DIGIT(); ++ mHEX_DIGIT(); ++ mHEX_DIGIT(); ++ mHEX_DIGIT(); ++ ++ } ++ ++ } ++ finally { ++ } ++ } ++ // $ANTLR end UNICODE_ESC ++ ++ // $ANTLR start HEX_DIGIT ++ public final void mHEX_DIGIT() throws RecognitionException { ++ try { ++ // ReviewDsl.g:99:13: ( ( INT | 'a' .. 'f' | 'A' .. 'F' ) ) ++ // ReviewDsl.g:99:13: ( INT | 'a' .. 'f' | 'A' .. 'F' ) ++ { ++ // ReviewDsl.g:99:13: ( INT | 'a' .. 'f' | 'A' .. 'F' ) ++ int alt8=3; ++ switch ( input.LA(1) ) { ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ { ++ alt8=1; ++ } ++ break; ++ case 'a': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'f': ++ { ++ alt8=2; ++ } ++ break; ++ case 'A': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ { ++ alt8=3; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""99:13: ( INT | 'a' .. 'f' | 'A' .. 'F' )"", 8, 0, input); ++ ++ throw nvae; ++ } ++ ++ switch (alt8) { ++ case 1 : ++ // ReviewDsl.g:99:14: INT ++ { ++ mINT(); ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:99:18: 'a' .. 'f' ++ { ++ matchRange('a','f'); ++ ++ } ++ break; ++ case 3 : ++ // ReviewDsl.g:99:27: 'A' .. 'F' ++ { ++ matchRange('A','F'); ++ ++ } ++ break; ++ ++ } ++ ++ ++ } ++ ++ } ++ finally { ++ } ++ } ++ // $ANTLR end HEX_DIGIT ++ ++ // $ANTLR start WS ++ public final void mWS() throws RecognitionException { ++ try { ++ // ReviewDsl.g:102:9: ( ( ' ' | '\\t' | '\\r' | '\\n' ) ) ++ // ReviewDsl.g:102:9: ( ' ' | '\\t' | '\\r' | '\\n' ) ++ { ++ if ( (input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ' ) { ++ input.consume(); ++ ++ } ++ else { ++ MismatchedSetException mse = ++ new MismatchedSetException(null,input); ++ recover(mse); throw mse; ++ } ++ ++ channel=HIDDEN; ++ ++ } ++ ++ } ++ finally { ++ } ++ } ++ // $ANTLR end WS ++ ++ public void mTokens() throws RecognitionException { ++ // ReviewDsl.g:1:10: ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING ) ++ int alt9=24; ++ switch ( input.LA(1) ) { ++ case 'R': ++ { ++ int LA9_1 = input.LA(2); ++ ++ if ( (LA9_1=='e') ) { ++ switch ( input.LA(3) ) { ++ case 'v': ++ { ++ int LA9_38 = input.LA(4); ++ ++ if ( (LA9_38=='i') ) { ++ int LA9_57 = input.LA(5); ++ ++ if ( (LA9_57=='e') ) { ++ int LA9_73 = input.LA(6); ++ ++ if ( (LA9_73=='w') ) { ++ int LA9_89 = input.LA(7); ++ ++ if ( (LA9_89=='-'||(LA9_89>='0' && LA9_89<='9')||(LA9_89>='A' && LA9_89<='Z')||LA9_89=='_'||(LA9_89>='a' && LA9_89<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=1;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case 's': ++ { ++ int LA9_39 = input.LA(4); ++ ++ if ( (LA9_39=='o') ) { ++ int LA9_58 = input.LA(5); ++ ++ if ( (LA9_58=='u') ) { ++ int LA9_74 = input.LA(6); ++ ++ if ( (LA9_74=='r') ) { ++ int LA9_90 = input.LA(7); ++ ++ if ( (LA9_90=='c') ) { ++ int LA9_101 = input.LA(8); ++ ++ if ( (LA9_101=='e') ) { ++ int LA9_109 = input.LA(9); ++ ++ if ( (LA9_109=='-'||(LA9_109>='0' && LA9_109<='9')||(LA9_109>='A' && LA9_109<='Z')||LA9_109=='_'||(LA9_109>='a' && LA9_109<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=13;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ default: ++ alt9=22;} ++ ++ } ++ else if ( (LA9_1=='-'||(LA9_1>='0' && LA9_1<='9')||(LA9_1>='A' && LA9_1<='Z')||LA9_1=='_'||(LA9_1>='a' && LA9_1<='d')||(LA9_1>='f' && LA9_1<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 1, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'r': ++ { ++ int LA9_2 = input.LA(2); ++ ++ if ( (LA9_2=='e') ) { ++ int LA9_21 = input.LA(3); ++ ++ if ( (LA9_21=='s') ) { ++ int LA9_40 = input.LA(4); ++ ++ if ( (LA9_40=='u') ) { ++ int LA9_59 = input.LA(5); ++ ++ if ( (LA9_59=='l') ) { ++ int LA9_75 = input.LA(6); ++ ++ if ( (LA9_75=='t') ) { ++ int LA9_91 = input.LA(7); ++ ++ if ( (LA9_91==':') ) { ++ alt9=2; ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_2=='-'||(LA9_2>='0' && LA9_2<='9')||(LA9_2>='A' && LA9_2<='Z')||LA9_2=='_'||(LA9_2>='a' && LA9_2<='d')||(LA9_2>='f' && LA9_2<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 2, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'C': ++ { ++ switch ( input.LA(2) ) { ++ case 'h': ++ { ++ int LA9_22 = input.LA(3); ++ ++ if ( (LA9_22=='a') ) { ++ int LA9_41 = input.LA(4); ++ ++ if ( (LA9_41=='n') ) { ++ int LA9_60 = input.LA(5); ++ ++ if ( (LA9_60=='g') ) { ++ int LA9_76 = input.LA(6); ++ ++ if ( (LA9_76=='e') ) { ++ int LA9_92 = input.LA(7); ++ ++ if ( (LA9_92=='s') ) { ++ int LA9_103 = input.LA(8); ++ ++ if ( (LA9_103=='e') ) { ++ int LA9_110 = input.LA(9); ++ ++ if ( (LA9_110=='t') ) { ++ int LA9_115 = input.LA(10); ++ ++ if ( (LA9_115=='-'||(LA9_115>='0' && LA9_115<='9')||(LA9_115>='A' && LA9_115<='Z')||LA9_115=='_'||(LA9_115>='a' && LA9_115<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=14;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case 'o': ++ { ++ int LA9_23 = input.LA(3); ++ ++ if ( (LA9_23=='m') ) { ++ int LA9_42 = input.LA(4); ++ ++ if ( (LA9_42=='m') ) { ++ int LA9_61 = input.LA(5); ++ ++ if ( (LA9_61=='e') ) { ++ int LA9_77 = input.LA(6); ++ ++ if ( (LA9_77=='n') ) { ++ int LA9_93 = input.LA(7); ++ ++ if ( (LA9_93=='t') ) { ++ int LA9_104 = input.LA(8); ++ ++ if ( (LA9_104==':') ) { ++ alt9=3; ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case '-': ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ case 'A': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'L': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'P': ++ case 'Q': ++ case 'R': ++ case 'S': ++ case 'T': ++ case 'U': ++ case 'V': ++ case 'W': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ case '_': ++ case 'a': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'f': ++ case 'g': ++ case 'i': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'n': ++ case 'p': ++ case 'q': ++ case 'r': ++ case 's': ++ case 't': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt9=22; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 3, input); ++ ++ throw nvae; ++ } ++ ++ } ++ break; ++ case 'P': ++ { ++ switch ( input.LA(2) ) { ++ case 'a': ++ { ++ int LA9_24 = input.LA(3); ++ ++ if ( (LA9_24=='t') ) { ++ int LA9_43 = input.LA(4); ++ ++ if ( (LA9_43=='c') ) { ++ int LA9_62 = input.LA(5); ++ ++ if ( (LA9_62=='h') ) { ++ int LA9_78 = input.LA(6); ++ ++ if ( (LA9_78=='-'||(LA9_78>='0' && LA9_78<='9')||(LA9_78>='A' && LA9_78<='Z')||LA9_78=='_'||(LA9_78>='a' && LA9_78<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=16;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case 'A': ++ { ++ int LA9_25 = input.LA(3); ++ ++ if ( (LA9_25=='S') ) { ++ int LA9_44 = input.LA(4); ++ ++ if ( (LA9_44=='S') ) { ++ int LA9_63 = input.LA(5); ++ ++ if ( (LA9_63=='E') ) { ++ int LA9_79 = input.LA(6); ++ ++ if ( (LA9_79=='D') ) { ++ int LA9_95 = input.LA(7); ++ ++ if ( (LA9_95=='-'||(LA9_95>='0' && LA9_95<='9')||(LA9_95>='A' && LA9_95<='Z')||LA9_95=='_'||(LA9_95>='a' && LA9_95<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=4;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case '-': ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'L': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'P': ++ case 'Q': ++ case 'R': ++ case 'S': ++ case 'T': ++ case 'U': ++ case 'V': ++ case 'W': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ case '_': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'f': ++ case 'g': ++ case 'h': ++ case 'i': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'n': ++ case 'o': ++ case 'p': ++ case 'q': ++ case 'r': ++ case 's': ++ case 't': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt9=22; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 4, input); ++ ++ throw nvae; ++ } ++ ++ } ++ break; ++ case 'W': ++ { ++ int LA9_5 = input.LA(2); ++ ++ if ( (LA9_5=='A') ) { ++ int LA9_26 = input.LA(3); ++ ++ if ( (LA9_26=='R') ) { ++ int LA9_45 = input.LA(4); ++ ++ if ( (LA9_45=='N') ) { ++ int LA9_64 = input.LA(5); ++ ++ if ( (LA9_64=='I') ) { ++ int LA9_80 = input.LA(6); ++ ++ if ( (LA9_80=='N') ) { ++ int LA9_96 = input.LA(7); ++ ++ if ( (LA9_96=='G') ) { ++ int LA9_106 = input.LA(8); ++ ++ if ( (LA9_106=='-'||(LA9_106>='0' && LA9_106<='9')||(LA9_106>='A' && LA9_106<='Z')||LA9_106=='_'||(LA9_106>='a' && LA9_106<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=5;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_5=='-'||(LA9_5>='0' && LA9_5<='9')||(LA9_5>='B' && LA9_5<='Z')||LA9_5=='_'||(LA9_5>='a' && LA9_5<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 5, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'F': ++ { ++ switch ( input.LA(2) ) { ++ case 'A': ++ { ++ int LA9_27 = input.LA(3); ++ ++ if ( (LA9_27=='I') ) { ++ int LA9_46 = input.LA(4); ++ ++ if ( (LA9_46=='L') ) { ++ int LA9_65 = input.LA(5); ++ ++ if ( (LA9_65=='E') ) { ++ int LA9_81 = input.LA(6); ++ ++ if ( (LA9_81=='D') ) { ++ int LA9_97 = input.LA(7); ++ ++ if ( (LA9_97=='-'||(LA9_97>='0' && LA9_97<='9')||(LA9_97>='A' && LA9_97<='Z')||LA9_97=='_'||(LA9_97>='a' && LA9_97<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=6;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case 'i': ++ { ++ int LA9_28 = input.LA(3); ++ ++ if ( (LA9_28=='l') ) { ++ int LA9_47 = input.LA(4); ++ ++ if ( (LA9_47=='e') ) { ++ int LA9_66 = input.LA(5); ++ ++ if ( (LA9_66=='-'||(LA9_66>='0' && LA9_66<='9')||(LA9_66>='A' && LA9_66<='Z')||LA9_66=='_'||(LA9_66>='a' && LA9_66<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=8;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ break; ++ case '-': ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'L': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'P': ++ case 'Q': ++ case 'R': ++ case 'S': ++ case 'T': ++ case 'U': ++ case 'V': ++ case 'W': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ case '_': ++ case 'a': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'f': ++ case 'g': ++ case 'h': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'n': ++ case 'o': ++ case 'p': ++ case 'q': ++ case 'r': ++ case 's': ++ case 't': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt9=22; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 6, input); ++ ++ throw nvae; ++ } ++ ++ } ++ break; ++ case 'T': ++ { ++ int LA9_7 = input.LA(2); ++ ++ if ( (LA9_7=='O') ) { ++ int LA9_29 = input.LA(3); ++ ++ if ( (LA9_29=='D') ) { ++ int LA9_48 = input.LA(4); ++ ++ if ( (LA9_48=='O') ) { ++ int LA9_67 = input.LA(5); ++ ++ if ( (LA9_67=='-'||(LA9_67>='0' && LA9_67<='9')||(LA9_67>='A' && LA9_67<='Z')||LA9_67=='_'||(LA9_67>='a' && LA9_67<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=7;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_7=='-'||(LA9_7>='0' && LA9_7<='9')||(LA9_7>='A' && LA9_7<='N')||(LA9_7>='P' && LA9_7<='Z')||LA9_7=='_'||(LA9_7>='a' && LA9_7<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 7, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case ':': ++ { ++ alt9=9; ++ } ++ break; ++ case 'L': ++ { ++ int LA9_9 = input.LA(2); ++ ++ if ( (LA9_9=='i') ) { ++ int LA9_30 = input.LA(3); ++ ++ if ( (LA9_30=='n') ) { ++ int LA9_49 = input.LA(4); ++ ++ if ( (LA9_49=='e') ) { ++ int LA9_68 = input.LA(5); ++ ++ if ( (LA9_68=='-'||(LA9_68>='0' && LA9_68<='9')||(LA9_68>='A' && LA9_68<='Z')||LA9_68=='_'||(LA9_68>='a' && LA9_68<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=10;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_9=='-'||(LA9_9>='0' && LA9_9<='9')||(LA9_9>='A' && LA9_9<='Z')||LA9_9=='_'||(LA9_9>='a' && LA9_9<='h')||(LA9_9>='j' && LA9_9<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 9, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case '-': ++ { ++ alt9=11; ++ } ++ break; ++ case 's': ++ { ++ int LA9_11 = input.LA(2); ++ ++ if ( (LA9_11=='c') ) { ++ int LA9_31 = input.LA(3); ++ ++ if ( (LA9_31=='o') ) { ++ int LA9_50 = input.LA(4); ++ ++ if ( (LA9_50=='p') ) { ++ int LA9_69 = input.LA(5); ++ ++ if ( (LA9_69=='e') ) { ++ int LA9_85 = input.LA(6); ++ ++ if ( (LA9_85==':') ) { ++ alt9=12; ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_11=='-'||(LA9_11>='0' && LA9_11<='9')||(LA9_11>='A' && LA9_11<='Z')||LA9_11=='_'||(LA9_11>='a' && LA9_11<='b')||(LA9_11>='d' && LA9_11<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 11, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'f': ++ { ++ int LA9_12 = input.LA(2); ++ ++ if ( (LA9_12=='r') ) { ++ int LA9_32 = input.LA(3); ++ ++ if ( (LA9_32=='o') ) { ++ int LA9_51 = input.LA(4); ++ ++ if ( (LA9_51=='m') ) { ++ int LA9_70 = input.LA(5); ++ ++ if ( (LA9_70=='-'||(LA9_70>='0' && LA9_70<='9')||(LA9_70>='A' && LA9_70<='Z')||LA9_70=='_'||(LA9_70>='a' && LA9_70<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=15;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_12=='-'||(LA9_12>='0' && LA9_12<='9')||(LA9_12>='A' && LA9_12<='Z')||LA9_12=='_'||(LA9_12>='a' && LA9_12<='q')||(LA9_12>='s' && LA9_12<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 12, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'A': ++ { ++ int LA9_13 = input.LA(2); ++ ++ if ( (LA9_13=='t') ) { ++ int LA9_33 = input.LA(3); ++ ++ if ( (LA9_33=='t') ) { ++ int LA9_52 = input.LA(4); ++ ++ if ( (LA9_52=='a') ) { ++ int LA9_71 = input.LA(5); ++ ++ if ( (LA9_71=='c') ) { ++ int LA9_87 = input.LA(6); ++ ++ if ( (LA9_87=='h') ) { ++ int LA9_99 = input.LA(7); ++ ++ if ( (LA9_99=='m') ) { ++ int LA9_108 = input.LA(8); ++ ++ if ( (LA9_108=='e') ) { ++ int LA9_113 = input.LA(9); ++ ++ if ( (LA9_113=='n') ) { ++ int LA9_116 = input.LA(10); ++ ++ if ( (LA9_116=='t') ) { ++ int LA9_118 = input.LA(11); ++ ++ if ( (LA9_118=='-'||(LA9_118>='0' && LA9_118<='9')||(LA9_118>='A' && LA9_118<='Z')||LA9_118=='_'||(LA9_118>='a' && LA9_118<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=17;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_13=='-'||(LA9_13>='0' && LA9_13<='9')||(LA9_13>='A' && LA9_13<='Z')||LA9_13=='_'||(LA9_13>='a' && LA9_13<='s')||(LA9_13>='u' && LA9_13<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 13, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'b': ++ { ++ int LA9_14 = input.LA(2); ++ ++ if ( (LA9_14=='y') ) { ++ int LA9_34 = input.LA(3); ++ ++ if ( (LA9_34=='-'||(LA9_34>='0' && LA9_34<='9')||(LA9_34>='A' && LA9_34<='Z')||LA9_34=='_'||(LA9_34>='a' && LA9_34<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=18;} ++ } ++ else if ( (LA9_14=='-'||(LA9_14>='0' && LA9_14<='9')||(LA9_14>='A' && LA9_14<='Z')||LA9_14=='_'||(LA9_14>='a' && LA9_14<='x')||LA9_14=='z') ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 14, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'o': ++ { ++ switch ( input.LA(2) ) { ++ case 'n': ++ { ++ int LA9_35 = input.LA(3); ++ ++ if ( (LA9_35=='-'||(LA9_35>='0' && LA9_35<='9')||(LA9_35>='A' && LA9_35<='Z')||LA9_35=='_'||(LA9_35>='a' && LA9_35<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=19;} ++ } ++ break; ++ case 'f': ++ { ++ int LA9_36 = input.LA(3); ++ ++ if ( (LA9_36=='-'||(LA9_36>='0' && LA9_36<='9')||(LA9_36>='A' && LA9_36<='Z')||LA9_36=='_'||(LA9_36>='a' && LA9_36<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=20;} ++ } ++ break; ++ case '-': ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ case 'A': ++ case 'B': ++ case 'C': ++ case 'D': ++ case 'E': ++ case 'F': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'L': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'P': ++ case 'Q': ++ case 'R': ++ case 'S': ++ case 'T': ++ case 'U': ++ case 'V': ++ case 'W': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ case '_': ++ case 'a': ++ case 'b': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'g': ++ case 'h': ++ case 'i': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'o': ++ case 'p': ++ case 'q': ++ case 'r': ++ case 's': ++ case 't': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt9=22; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 15, input); ++ ++ throw nvae; ++ } ++ ++ } ++ break; ++ case 't': ++ { ++ int LA9_16 = input.LA(2); ++ ++ if ( (LA9_16=='a') ) { ++ int LA9_37 = input.LA(3); ++ ++ if ( (LA9_37=='s') ) { ++ int LA9_56 = input.LA(4); ++ ++ if ( (LA9_56=='k') ) { ++ int LA9_72 = input.LA(5); ++ ++ if ( (LA9_72=='-'||(LA9_72>='0' && LA9_72<='9')||(LA9_72>='A' && LA9_72<='Z')||LA9_72=='_'||(LA9_72>='a' && LA9_72<='z')) ) { ++ alt9=22; ++ } ++ else { ++ alt9=21;} ++ } ++ else { ++ alt9=22;} ++ } ++ else { ++ alt9=22;} ++ } ++ else if ( (LA9_16=='-'||(LA9_16>='0' && LA9_16<='9')||(LA9_16>='A' && LA9_16<='Z')||LA9_16=='_'||(LA9_16>='b' && LA9_16<='z')) ) { ++ alt9=22; ++ } ++ else { ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 16, input); ++ ++ throw nvae; ++ } ++ } ++ break; ++ case 'B': ++ case 'D': ++ case 'E': ++ case 'G': ++ case 'H': ++ case 'I': ++ case 'J': ++ case 'K': ++ case 'M': ++ case 'N': ++ case 'O': ++ case 'Q': ++ case 'S': ++ case 'U': ++ case 'V': ++ case 'X': ++ case 'Y': ++ case 'Z': ++ case 'a': ++ case 'c': ++ case 'd': ++ case 'e': ++ case 'g': ++ case 'h': ++ case 'i': ++ case 'j': ++ case 'k': ++ case 'l': ++ case 'm': ++ case 'n': ++ case 'p': ++ case 'q': ++ case 'u': ++ case 'v': ++ case 'w': ++ case 'x': ++ case 'y': ++ case 'z': ++ { ++ alt9=22; ++ } ++ break; ++ case '0': ++ case '1': ++ case '2': ++ case '3': ++ case '4': ++ case '5': ++ case '6': ++ case '7': ++ case '8': ++ case '9': ++ { ++ alt9=23; ++ } ++ break; ++ case '\""': ++ { ++ alt9=24; ++ } ++ break; ++ default: ++ NoViableAltException nvae = ++ new NoViableAltException(""1:1: Tokens : ( T12 | T13 | T14 | T15 | T16 | T17 | T18 | T19 | T20 | T21 | T22 | T23 | T24 | T25 | T26 | T27 | T28 | T29 | T30 | T31 | T32 | TASK_ID | INT | STRING );"", 9, 0, input); ++ ++ throw nvae; ++ } ++ ++ switch (alt9) { ++ case 1 : ++ // ReviewDsl.g:1:10: T12 ++ { ++ mT12(); ++ ++ } ++ break; ++ case 2 : ++ // ReviewDsl.g:1:14: T13 ++ { ++ mT13(); ++ ++ } ++ break; ++ case 3 : ++ // ReviewDsl.g:1:18: T14 ++ { ++ mT14(); ++ ++ } ++ break; ++ case 4 : ++ // ReviewDsl.g:1:22: T15 ++ { ++ mT15(); ++ ++ } ++ break; ++ case 5 : ++ // ReviewDsl.g:1:26: T16 ++ { ++ mT16(); ++ ++ } ++ break; ++ case 6 : ++ // ReviewDsl.g:1:30: T17 ++ { ++ mT17(); ++ ++ } ++ break; ++ case 7 : ++ // ReviewDsl.g:1:34: T18 ++ { ++ mT18(); ++ ++ } ++ break; ++ case 8 : ++ // ReviewDsl.g:1:38: T19 ++ { ++ mT19(); ++ ++ } ++ break; ++ case 9 : ++ // ReviewDsl.g:1:42: T20 ++ { ++ mT20(); ++ ++ } ++ break; ++ case 10 : ++ // ReviewDsl.g:1:46: T21 ++ { ++ mT21(); ++ ++ } ++ break; ++ case 11 : ++ // ReviewDsl.g:1:50: T22 ++ { ++ mT22(); ++ ++ } ++ break; ++ case 12 : ++ // ReviewDsl.g:1:54: T23 ++ { ++ mT23(); ++ ++ } ++ break; ++ case 13 : ++ // ReviewDsl.g:1:58: T24 ++ { ++ mT24(); ++ ++ } ++ break; ++ case 14 : ++ // ReviewDsl.g:1:62: T25 ++ { ++ mT25(); ++ ++ } ++ break; ++ case 15 : ++ // ReviewDsl.g:1:66: T26 ++ { ++ mT26(); ++ ++ } ++ break; ++ case 16 : ++ // ReviewDsl.g:1:70: T27 ++ { ++ mT27(); ++ ++ } ++ break; ++ case 17 : ++ // ReviewDsl.g:1:74: T28 ++ { ++ mT28(); ++ ++ } ++ break; ++ case 18 : ++ // ReviewDsl.g:1:78: T29 ++ { ++ mT29(); ++ ++ } ++ break; ++ case 19 : ++ // ReviewDsl.g:1:82: T30 ++ { ++ mT30(); ++ ++ } ++ break; ++ case 20 : ++ // ReviewDsl.g:1:86: T31 ++ { ++ mT31(); ++ ++ } ++ break; ++ case 21 : ++ // ReviewDsl.g:1:90: T32 ++ { ++ mT32(); ++ ++ } ++ break; ++ case 22 : ++ // ReviewDsl.g:1:94: TASK_ID ++ { ++ mTASK_ID(); ++ ++ } ++ break; ++ case 23 : ++ // ReviewDsl.g:1:102: INT ++ { ++ mINT(); ++ ++ } ++ break; ++ case 24 : ++ // ReviewDsl.g:1:106: STRING ++ { ++ mSTRING(); ++ ++ } ++ break; ++ ++ } ++ ++ } ++ ++ ++ ++ ++} +\ No newline at end of file +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslMapper.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslMapper.java +new file mode 100644 +index 00000000..93fed735 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslMapper.java +@@ -0,0 +1,215 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl.internal; ++ ++import org.antlr.runtime.ANTLRStringStream; ++import org.antlr.runtime.CommonTokenStream; ++import org.antlr.runtime.RecognitionException; ++import org.antlr.runtime.TokenStream; ++import org.antlr.runtime.tree.TreeAdaptor; ++import org.eclipse.mylyn.reviews.tasks.dsl.IReviewDslMapper; ++import org.eclipse.mylyn.reviews.tasks.dsl.ParseException; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslAttachmentScopeItem; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslChangesetScopeItem; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslAttachmentScopeItem.Type; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult.FileComment; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult.LineComment; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult.Rating; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScope; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScopeItem; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.attachmentSource_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.changesetDef_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.fileComment_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.lineComment_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.patchDef_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.resourceDef_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.reviewResult_return; ++import org.eclipse.mylyn.reviews.tasks.dsl.internal.ReviewDslParser.reviewScope_return; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslMapper implements IReviewDslMapper { ++ ++ /* (non-Javadoc) ++ * @see org.eclipse.mylyn.reviews.tasks.dsl.internal.IReviewDslMapper#parseReviewResult(java.lang.String) ++ */ ++ @Override ++ public ReviewDslResult parseReviewResult(String text) throws ParseException { ++ ReviewDslLexer lexer = new ReviewDslLexer(new ANTLRStringStream(text)); ++ TokenStream input = new CommonTokenStream(lexer); ++ ReviewDslParser parser = new ReviewDslParser(input); ++ try { ++ return mapResult(parser.reviewResult(), parser.getTreeAdaptor()); ++ } catch (RecognitionException e) { ++ throw new ParseException(e.getMessage()); ++ } ++ ++ } ++ ++ private ReviewDslResult mapResult(reviewResult_return reviewResult, ++ TreeAdaptor treeAdaptor) { ++ ReviewDslResult result = new ReviewDslResult(); ++ ++ result.setRating(Rating.valueOf(reviewResult.result)); ++ result.setComment(convertStr(reviewResult.comment)); ++ if (reviewResult.fileComments != null) { ++ for (int i = 0; i < reviewResult.fileComments.size(); i++) { ++ fileComment_return fc = (fileComment_return) reviewResult.fileComments ++ .get(i); ++ result.getFileComments().add(map(fc)); ++ } ++ } ++ return result; ++ } ++ ++ private FileComment map(fileComment_return fc) { ++ FileComment fileComment = new FileComment(); ++ fileComment.setFileName(convertStr(fc.path)); ++ fileComment.setComment(convertStr(fc.comment)); ++ if (fc.lineComments != null) { ++ for (int i = 0; i < fc.lineComments.size(); i++) { ++ lineComment_return lc = (lineComment_return) fc.lineComments ++ .get(i); ++ fileComment.getLineComments().add(map(lc)); ++ } ++ } ++ return fileComment; ++ } ++ ++ private LineComment map(lineComment_return lc) { ++ LineComment lineComment = new LineComment(); ++ lineComment.setBegin(lc.begin); ++ if (lc.end != null) { ++ lineComment.setEnd(Integer.parseInt(lc.end)); ++ } else { ++ lineComment.setEnd(lineComment.getBegin()); ++ } ++ lineComment.setComment(convertStr(lc.comment)); ++ ++ return lineComment; ++ } ++ ++ private String convertStr(String string) { ++ if (string == null) ++ return string; ++ int startIdx = 0; ++ int endIdx = string.length(); ++ if (string.startsWith(""\"""")) ++ startIdx = 1; ++ if (string.endsWith(""\"""")) ++ endIdx--; ++ return string.substring(startIdx, endIdx); ++ } ++ ++ /* (non-Javadoc) ++ * @see org.eclipse.mylyn.reviews.tasks.dsl.internal.IReviewDslMapper#parseReviewScope(java.lang.String) ++ */ ++ @Override ++ public ReviewDslScope parseReviewScope(String text) throws ParseException { ++ ReviewDslLexer lexer = new ReviewDslLexer(new ANTLRStringStream(text)); ++ TokenStream input = new CommonTokenStream(lexer); ++ ReviewDslParser parser = new ReviewDslParser(input); ++ try { ++ return mapScope(parser.reviewScope(), parser.getTreeAdaptor()); ++ } catch (RecognitionException e) { ++ throw new ParseException(e.getMessage()); ++ } ++ } ++ ++ private ReviewDslScope mapScope(reviewScope_return reviewScope, ++ TreeAdaptor treeAdaptor) { ++ if (reviewScope == null) ++ return null; ++ ReviewDslScope scope = new ReviewDslScope(); ++ ++ if (reviewScope.scopeItems != null) { ++ for (int i = 0; i < reviewScope.scopeItems.size(); i++) { ++ Object child = reviewScope.scopeItems.get(i); ++ if (patchDef_return.class.equals(child.getClass())) { ++ scope.addItem(parsePatch((patchDef_return) child, ++ treeAdaptor)); ++ } else if (resourceDef_return.class.equals(child.getClass())) { ++ scope.addItem(parseResource((resourceDef_return) child, ++ treeAdaptor)); ++ } else if (changesetDef_return.class.equals(child.getClass())) { ++ scope.addItem(parseChangeSet((changesetDef_return) child)); ++ } ++ } ++ } ++ return scope; ++ } ++ ++ private ReviewDslChangesetScopeItem parseChangeSet(changesetDef_return child) { ++ ReviewDslChangesetScopeItem item = new ReviewDslChangesetScopeItem(); ++ item.setRevision(convertStr(child.revision)); ++ item.setRepoUrl(convertStr(child.repoUrl)); ++ return item; ++ } ++ ++ private ReviewDslAttachmentScopeItem parseResource( ++ resourceDef_return child, TreeAdaptor treeAdaptor) { ++ AttachmentSource source = parseAttachmentSource( ++ (attachmentSource_return) child.source); ++ return new ReviewDslAttachmentScopeItem(Type.RESOURCE, source.fileName, ++ source.author, source.createdDate, source.taskId); ++ } ++ ++ private ReviewDslAttachmentScopeItem parsePatch(patchDef_return child, ++ TreeAdaptor treeAdaptor) { ++ ++ AttachmentSource source = parseAttachmentSource( ++ (attachmentSource_return) child.source); ++ return new ReviewDslAttachmentScopeItem(Type.PATCH, source.fileName, ++ source.author, source.createdDate, source.taskId); ++ } ++ ++ private AttachmentSource parseAttachmentSource( ++ attachmentSource_return child) { ++ AttachmentSource source = new AttachmentSource(); ++ source.fileName = convertStr(child.filename); ++ source.author = convertStr(child.author); ++ source.createdDate =convertStr(child.createdDate); ++ source.taskId = convertStr(child.taskId); ++ return source; ++ } ++ ++ private static class AttachmentSource { ++ public String fileName; ++ public String author; ++ public String createdDate; ++ public String taskId; ++ } ++ ++ public static void main(String[] args) throws Exception { ++ // String text = ""Review result: TODO Comment: \""test\""""; ++ String text = ""Review scope: Patch from Attachment \""0001-Extension-point-for-scm-connector-defined-jaxb-model.patch\"" by \""Jane@inso.tuwien.ac.at\"" on \""2010-06-25 17:42:00\"" of task 85""; ++ IReviewDslMapper reviewDslMapper = new ReviewDslMapper(); ++ ReviewDslScope parseReviewScope = reviewDslMapper ++ .parseReviewScope(text); ++ ++ if (parseReviewScope != null) { ++ for (ReviewDslScopeItem item : parseReviewScope.getItems()) { ++ System.err.println(item); ++ } ++ } ++ } ++ ++ @Override ++ public ReviewDslResult parseChangedReviewScope(String text) { ++ // TODO Auto-generated method stub ++ return null; ++ } ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java +new file mode 100644 +index 00000000..5291ed39 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslParser.java +@@ -0,0 +1,1154 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++// $ANTLR 3.0 ReviewDsl.g 2011-03-06 18:30:25 ++ ++package org.eclipse.mylyn.reviews.tasks.dsl.internal; ++ ++import java.util.ArrayList; ++import java.util.List; ++ ++import org.antlr.runtime.BitSet; ++import org.antlr.runtime.EarlyExitException; ++import org.antlr.runtime.MismatchedSetException; ++import org.antlr.runtime.NoViableAltException; ++import org.antlr.runtime.Parser; ++import org.antlr.runtime.ParserRuleReturnScope; ++import org.antlr.runtime.RecognitionException; ++import org.antlr.runtime.RuleReturnScope; ++import org.antlr.runtime.Token; ++import org.antlr.runtime.TokenStream; ++import org.antlr.runtime.tree.CommonTree; ++import org.antlr.runtime.tree.CommonTreeAdaptor; ++import org.antlr.runtime.tree.TreeAdaptor; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslParser extends Parser { ++ public static final String[] tokenNames = new String[] { """", ++ """", """", """", ""STRING"", ""INT"", ""TASK_ID"", ""ESC_SEQ"", ++ ""UNICODE_ESC"", ""OCTAL_ESC"", ""HEX_DIGIT"", ""WS"", ""'Review'"", ++ ""'result:'"", ""'Comment:'"", ""'PASSED'"", ""'WARNING'"", ""'FAILED'"", ++ ""'TODO'"", ""'File'"", ""':'"", ""'Line'"", ""'-'"", ""'scope:'"", ++ ""'Resource'"", ""'Changeset'"", ""'from'"", ""'Patch'"", ""'Attachment'"", ++ ""'by'"", ""'on'"", ""'of'"", ""'task'"" }; ++ public static final int WS = 11; ++ public static final int ESC_SEQ = 7; ++ public static final int TASK_ID = 6; ++ public static final int UNICODE_ESC = 8; ++ public static final int OCTAL_ESC = 9; ++ public static final int HEX_DIGIT = 10; ++ public static final int INT = 5; ++ public static final int EOF = -1; ++ public static final int STRING = 4; ++ ++ public ReviewDslParser(TokenStream input) { ++ super(input); ++ } ++ ++ protected TreeAdaptor adaptor = new CommonTreeAdaptor(); ++ ++ public void setTreeAdaptor(TreeAdaptor adaptor) { ++ this.adaptor = adaptor; ++ } ++ ++ public TreeAdaptor getTreeAdaptor() { ++ return adaptor; ++ } ++ ++ public String[] getTokenNames() { ++ return tokenNames; ++ } ++ ++ public String getGrammarFileName() { ++ return ""ReviewDsl.g""; ++ } ++ ++ public static class reviewResult_return extends ParserRuleReturnScope { ++ public String result; ++ public String comment; ++ public List fileComments; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start reviewResult ++ // ReviewDsl.g:14:1: reviewResult returns [String result, String comment, ++ // List fileComments] : 'Review' 'result:' res= resultEnum ( 'Comment:' c= ++ // STRING )? ( (fc+= fileComment )+ )? ; ++ public final reviewResult_return reviewResult() throws RecognitionException { ++ reviewResult_return retval = new reviewResult_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token c = null; ++ Token string_literal1 = null; ++ Token string_literal2 = null; ++ Token string_literal3 = null; ++ List list_fc = null; ++ resultEnum_return res = null; ++ ++ RuleReturnScope fc = null; ++ CommonTree c_tree = null; ++ CommonTree string_literal1_tree = null; ++ CommonTree string_literal2_tree = null; ++ CommonTree string_literal3_tree = null; ++ ++ try { ++ // ReviewDsl.g:15:3: ( 'Review' 'result:' res= resultEnum ( ++ // 'Comment:' c= STRING )? ( (fc+= fileComment )+ )? ) ++ // ReviewDsl.g:15:3: 'Review' 'result:' res= resultEnum ( 'Comment:' ++ // c= STRING )? ( (fc+= fileComment )+ )? ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal1 = (Token) input.LT(1); ++ match(input, 12, FOLLOW_12_in_reviewResult39); ++ string_literal1_tree = (CommonTree) adaptor ++ .create(string_literal1); ++ adaptor.addChild(root_0, string_literal1_tree); ++ ++ string_literal2 = (Token) input.LT(1); ++ match(input, 13, FOLLOW_13_in_reviewResult41); ++ string_literal2_tree = (CommonTree) adaptor ++ .create(string_literal2); ++ adaptor.addChild(root_0, string_literal2_tree); ++ ++ pushFollow(FOLLOW_resultEnum_in_reviewResult46); ++ res = resultEnum(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, res.getTree()); ++ // ReviewDsl.g:16:3: ( 'Comment:' c= STRING )? ++ int alt1 = 2; ++ int LA1_0 = input.LA(1); ++ ++ if ((LA1_0 == 14)) { ++ alt1 = 1; ++ } ++ switch (alt1) { ++ case 1: ++ // ReviewDsl.g:16:4: 'Comment:' c= STRING ++ { ++ string_literal3 = (Token) input.LT(1); ++ match(input, 14, FOLLOW_14_in_reviewResult52); ++ string_literal3_tree = (CommonTree) adaptor ++ .create(string_literal3); ++ adaptor.addChild(root_0, string_literal3_tree); ++ ++ c = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_reviewResult56); ++ c_tree = (CommonTree) adaptor.create(c); ++ adaptor.addChild(root_0, c_tree); ++ ++ } ++ break; ++ ++ } ++ ++ // ReviewDsl.g:17:2: ( (fc+= fileComment )+ )? ++ int alt3 = 2; ++ int LA3_0 = input.LA(1); ++ ++ if ((LA3_0 == 19)) { ++ alt3 = 1; ++ } ++ switch (alt3) { ++ case 1: ++ // ReviewDsl.g:17:3: (fc+= fileComment )+ ++ { ++ // ReviewDsl.g:17:5: (fc+= fileComment )+ ++ int cnt2 = 0; ++ loop2: do { ++ int alt2 = 2; ++ int LA2_0 = input.LA(1); ++ ++ if ((LA2_0 == 19)) { ++ alt2 = 1; ++ } ++ ++ switch (alt2) { ++ case 1: ++ // ReviewDsl.g:17:5: fc+= fileComment ++ { ++ pushFollow(FOLLOW_fileComment_in_reviewResult64); ++ fc = fileComment(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, fc.getTree()); ++ if (list_fc == null) ++ list_fc = new ArrayList(); ++ list_fc.add(fc); ++ ++ } ++ break; ++ ++ default: ++ if (cnt2 >= 1) ++ break loop2; ++ EarlyExitException eee = new EarlyExitException(2, ++ input); ++ throw eee; ++ } ++ cnt2++; ++ } while (true); ++ ++ } ++ break; ++ ++ } ++ ++ retval.result = input.toString(res.start, res.stop); ++ retval.comment = c != null ? c.getText() : null; ++ retval.fileComments = list_fc; ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end reviewResult ++ ++ public static class resultEnum_return extends ParserRuleReturnScope { ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start resultEnum ++ // ReviewDsl.g:21:1: resultEnum : ( 'PASSED' | 'WARNING' | 'FAILED' | 'TODO' ++ // ); ++ public final resultEnum_return resultEnum() throws RecognitionException { ++ resultEnum_return retval = new resultEnum_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token set4 = null; ++ ++ CommonTree set4_tree = null; ++ ++ try { ++ // ReviewDsl.g:22:3: ( 'PASSED' | 'WARNING' | 'FAILED' | 'TODO' ) ++ // ReviewDsl.g: ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ set4 = (Token) input.LT(1); ++ if ((input.LA(1) >= 15 && input.LA(1) <= 18)) { ++ input.consume(); ++ adaptor.addChild(root_0, adaptor.create(set4)); ++ errorRecovery = false; ++ } else { ++ MismatchedSetException mse = new MismatchedSetException( ++ null, input); ++ recoverFromMismatchedSet(input, mse, ++ FOLLOW_set_in_resultEnum0); ++ throw mse; ++ } ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end resultEnum ++ ++ public static class fileComment_return extends ParserRuleReturnScope { ++ public String path; ++ public String comment; ++ public List lineComments; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start fileComment ++ // ReviewDsl.g:24:1: fileComment returns [String path, String comment, List ++ // lineComments] : 'File' p= STRING ':' (c= STRING )? (lc+= lineComment )* ; ++ public final fileComment_return fileComment() throws RecognitionException { ++ fileComment_return retval = new fileComment_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token p = null; ++ Token c = null; ++ Token string_literal5 = null; ++ Token char_literal6 = null; ++ List list_lc = null; ++ RuleReturnScope lc = null; ++ CommonTree p_tree = null; ++ CommonTree c_tree = null; ++ CommonTree string_literal5_tree = null; ++ CommonTree char_literal6_tree = null; ++ ++ try { ++ // ReviewDsl.g:25:2: ( 'File' p= STRING ':' (c= STRING )? (lc+= ++ // lineComment )* ) ++ // ReviewDsl.g:25:2: 'File' p= STRING ':' (c= STRING )? (lc+= ++ // lineComment )* ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal5 = (Token) input.LT(1); ++ match(input, 19, FOLLOW_19_in_fileComment98); ++ string_literal5_tree = (CommonTree) adaptor ++ .create(string_literal5); ++ adaptor.addChild(root_0, string_literal5_tree); ++ ++ p = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_fileComment102); ++ p_tree = (CommonTree) adaptor.create(p); ++ adaptor.addChild(root_0, p_tree); ++ ++ char_literal6 = (Token) input.LT(1); ++ match(input, 20, FOLLOW_20_in_fileComment104); ++ char_literal6_tree = (CommonTree) adaptor.create(char_literal6); ++ adaptor.addChild(root_0, char_literal6_tree); ++ ++ // ReviewDsl.g:25:22: (c= STRING )? ++ int alt4 = 2; ++ int LA4_0 = input.LA(1); ++ ++ if ((LA4_0 == STRING)) { ++ alt4 = 1; ++ } ++ switch (alt4) { ++ case 1: ++ // ReviewDsl.g:25:23: c= STRING ++ { ++ c = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_fileComment109); ++ c_tree = (CommonTree) adaptor.create(c); ++ adaptor.addChild(root_0, c_tree); ++ ++ } ++ break; ++ ++ } ++ ++ // ReviewDsl.g:26:3: (lc+= lineComment )* ++ loop5: do { ++ int alt5 = 2; ++ int LA5_0 = input.LA(1); ++ ++ if ((LA5_0 == 21)) { ++ alt5 = 1; ++ } ++ ++ switch (alt5) { ++ case 1: ++ // ReviewDsl.g:26:3: lc+= lineComment ++ { ++ pushFollow(FOLLOW_lineComment_in_fileComment115); ++ lc = lineComment(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, lc.getTree()); ++ if (list_lc == null) ++ list_lc = new ArrayList(); ++ list_lc.add(lc); ++ ++ } ++ break; ++ ++ default: ++ break loop5; ++ } ++ } while (true); ++ ++ retval.path = p.getText(); ++ retval.comment = c.getText(); ++ retval.lineComments = list_lc; ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end fileComment ++ ++ public static class lineComment_return extends ParserRuleReturnScope { ++ public int begin; ++ public String end; ++ public String comment; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start lineComment ++ // ReviewDsl.g:29:1: lineComment returns [int begin, String end, String ++ // comment] : 'Line' s= INT ( '-' e= INT )? ':' c= STRING ; ++ public final lineComment_return lineComment() throws RecognitionException { ++ lineComment_return retval = new lineComment_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token s = null; ++ Token e = null; ++ Token c = null; ++ Token string_literal7 = null; ++ Token char_literal8 = null; ++ Token char_literal9 = null; ++ ++ CommonTree s_tree = null; ++ CommonTree e_tree = null; ++ CommonTree c_tree = null; ++ CommonTree string_literal7_tree = null; ++ CommonTree char_literal8_tree = null; ++ CommonTree char_literal9_tree = null; ++ ++ try { ++ // ReviewDsl.g:30:3: ( 'Line' s= INT ( '-' e= INT )? ':' c= STRING ) ++ // ReviewDsl.g:30:3: 'Line' s= INT ( '-' e= INT )? ':' c= STRING ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal7 = (Token) input.LT(1); ++ match(input, 21, FOLLOW_21_in_lineComment130); ++ string_literal7_tree = (CommonTree) adaptor ++ .create(string_literal7); ++ adaptor.addChild(root_0, string_literal7_tree); ++ ++ s = (Token) input.LT(1); ++ match(input, INT, FOLLOW_INT_in_lineComment134); ++ s_tree = (CommonTree) adaptor.create(s); ++ adaptor.addChild(root_0, s_tree); ++ ++ // ReviewDsl.g:30:16: ( '-' e= INT )? ++ int alt6 = 2; ++ int LA6_0 = input.LA(1); ++ ++ if ((LA6_0 == 22)) { ++ alt6 = 1; ++ } ++ switch (alt6) { ++ case 1: ++ // ReviewDsl.g:30:17: '-' e= INT ++ { ++ char_literal8 = (Token) input.LT(1); ++ match(input, 22, FOLLOW_22_in_lineComment137); ++ char_literal8_tree = (CommonTree) adaptor ++ .create(char_literal8); ++ adaptor.addChild(root_0, char_literal8_tree); ++ ++ e = (Token) input.LT(1); ++ match(input, INT, FOLLOW_INT_in_lineComment141); ++ e_tree = (CommonTree) adaptor.create(e); ++ adaptor.addChild(root_0, e_tree); ++ ++ } ++ break; ++ ++ } ++ ++ char_literal9 = (Token) input.LT(1); ++ match(input, 20, FOLLOW_20_in_lineComment145); ++ char_literal9_tree = (CommonTree) adaptor.create(char_literal9); ++ adaptor.addChild(root_0, char_literal9_tree); ++ ++ c = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_lineComment150); ++ c_tree = (CommonTree) adaptor.create(c); ++ adaptor.addChild(root_0, c_tree); ++ ++ retval.begin = Integer.parseInt(s.getText()); ++ retval.end = e != null ? e.getText() : null; ++ retval.comment = c.getText(); ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end lineComment ++ ++ public static class reviewScope_return extends ParserRuleReturnScope { ++ public List scopeItems; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start reviewScope ++ // ReviewDsl.g:35:1: reviewScope returns [List scopeItems] : 'Review' ++ // 'scope:' (s+= ( resourceDef | patchDef | changesetDef ) )* ; ++ public final reviewScope_return reviewScope() throws RecognitionException { ++ reviewScope_return retval = new reviewScope_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token string_literal10 = null; ++ Token string_literal11 = null; ++ Token s = null; ++ List list_s = new ArrayList(); ++ resourceDef_return resourceDef12 = null; ++ ++ patchDef_return patchDef13 = null; ++ ++ changesetDef_return changesetDef14 = null; ++ ++ CommonTree string_literal10_tree = null; ++ CommonTree string_literal11_tree = null; ++ CommonTree s_tree = null; ++ ++ try { ++ // ReviewDsl.g:36:4: ( 'Review' 'scope:' (s+= ( resourceDef | ++ // patchDef | changesetDef ) )* ) ++ // ReviewDsl.g:36:4: 'Review' 'scope:' (s+= ( resourceDef | patchDef ++ // | changesetDef ) )* ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal10 = (Token) input.LT(1); ++ match(input, 12, FOLLOW_12_in_reviewScope167); ++ string_literal10_tree = (CommonTree) adaptor ++ .create(string_literal10); ++ adaptor.addChild(root_0, string_literal10_tree); ++ ++ string_literal11 = (Token) input.LT(1); ++ match(input, 23, FOLLOW_23_in_reviewScope169); ++ string_literal11_tree = (CommonTree) adaptor ++ .create(string_literal11); ++ adaptor.addChild(root_0, string_literal11_tree); ++ ++ // ReviewDsl.g:36:22: (s+= ( resourceDef | patchDef | ++ // changesetDef ) )* ++ loop8: do { ++ int alt8 = 2; ++ int LA8_0 = input.LA(1); ++ ++ if (((LA8_0 >= 24 && LA8_0 <= 25) || LA8_0 == 27)) { ++ alt8 = 1; ++ } ++ ++ switch (alt8) { ++ case 1: ++ // ReviewDsl.g:36:23: s+= ( resourceDef | patchDef | ++ // changesetDef ) ++ { ++ // ReviewDsl.g:36:26: ( resourceDef | patchDef | ++ // changesetDef ) ++ int alt7 = 3; ++ switch (input.LA(1)) { ++ case 24: { ++ alt7 = 1; ++ } ++ break; ++ case 27: { ++ alt7 = 2; ++ } ++ break; ++ case 25: { ++ alt7 = 3; ++ } ++ break; ++ default: ++ NoViableAltException nvae = new NoViableAltException( ++ ""36:26: ( resourceDef | patchDef | changesetDef )"", ++ 7, 0, input); ++ ++ throw nvae; ++ } ++ ++ switch (alt7) { ++ case 1: ++ // ReviewDsl.g:36:27: resourceDef ++ { ++ pushFollow(FOLLOW_resourceDef_in_reviewScope175); ++ resourceDef12 = resourceDef(); ++ list_s.add(resourceDef12); ++ _fsp--; ++ ++ adaptor.addChild(root_0, resourceDef12.getTree()); ++ ++ } ++ break; ++ case 2: ++ // ReviewDsl.g:36:40: patchDef ++ { ++ pushFollow(FOLLOW_patchDef_in_reviewScope178); ++ patchDef13 = patchDef(); ++ list_s.add(patchDef13); ++ _fsp--; ++ ++ adaptor.addChild(root_0, patchDef13.getTree()); ++ ++ } ++ break; ++ case 3: ++ // ReviewDsl.g:36:52: changesetDef ++ { ++ pushFollow(FOLLOW_changesetDef_in_reviewScope183); ++ changesetDef14 = changesetDef(); ++ list_s.add(changesetDef14); ++ _fsp--; ++ ++ adaptor.addChild(root_0, changesetDef14.getTree()); ++ ++ } ++ break; ++ ++ } ++ ++ } ++ break; ++ ++ default: ++ break loop8; ++ } ++ } while (true); ++ ++ retval.scopeItems = list_s; ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end reviewScope ++ ++ public static class resourceDef_return extends ParserRuleReturnScope { ++ public Object source; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start resourceDef ++ // ReviewDsl.g:40:1: resourceDef returns [Object source] : 'Resource' s= ++ // attachmentSource ; ++ public final resourceDef_return resourceDef() throws RecognitionException { ++ resourceDef_return retval = new resourceDef_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token string_literal15 = null; ++ attachmentSource_return s = null; ++ ++ CommonTree string_literal15_tree = null; ++ ++ try { ++ // ReviewDsl.g:41:4: ( 'Resource' s= attachmentSource ) ++ // ReviewDsl.g:41:4: 'Resource' s= attachmentSource ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal15 = (Token) input.LT(1); ++ match(input, 24, FOLLOW_24_in_resourceDef205); ++ string_literal15_tree = (CommonTree) adaptor ++ .create(string_literal15); ++ adaptor.addChild(root_0, string_literal15_tree); ++ ++ pushFollow(FOLLOW_attachmentSource_in_resourceDef210); ++ s = attachmentSource(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, s.getTree()); ++ retval.source = s; ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end resourceDef ++ ++ public static class changesetDef_return extends ParserRuleReturnScope { ++ public String revision; ++ public String repoUrl; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start changesetDef ++ // ReviewDsl.g:44:1: changesetDef returns [String revision, String repoUrl] ++ // : 'Changeset' rev= STRING 'from' url= STRING ; ++ public final changesetDef_return changesetDef() throws RecognitionException { ++ changesetDef_return retval = new changesetDef_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token rev = null; ++ Token url = null; ++ Token string_literal16 = null; ++ Token string_literal17 = null; ++ ++ CommonTree rev_tree = null; ++ CommonTree url_tree = null; ++ CommonTree string_literal16_tree = null; ++ CommonTree string_literal17_tree = null; ++ ++ try { ++ // ReviewDsl.g:45:4: ( 'Changeset' rev= STRING 'from' url= STRING ) ++ // ReviewDsl.g:45:4: 'Changeset' rev= STRING 'from' url= STRING ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal16 = (Token) input.LT(1); ++ match(input, 25, FOLLOW_25_in_changesetDef226); ++ string_literal16_tree = (CommonTree) adaptor ++ .create(string_literal16); ++ adaptor.addChild(root_0, string_literal16_tree); ++ ++ rev = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_changesetDef230); ++ rev_tree = (CommonTree) adaptor.create(rev); ++ adaptor.addChild(root_0, rev_tree); ++ ++ string_literal17 = (Token) input.LT(1); ++ match(input, 26, FOLLOW_26_in_changesetDef233); ++ string_literal17_tree = (CommonTree) adaptor ++ .create(string_literal17); ++ adaptor.addChild(root_0, string_literal17_tree); ++ ++ url = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_changesetDef237); ++ url_tree = (CommonTree) adaptor.create(url); ++ adaptor.addChild(root_0, url_tree); ++ ++ retval.revision = rev.getText(); ++ retval.repoUrl = url.getText(); ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end changesetDef ++ ++ public static class patchDef_return extends ParserRuleReturnScope { ++ public Object source; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start patchDef ++ // ReviewDsl.g:48:1: patchDef returns [Object source] : 'Patch' s= ++ // attachmentSource ; ++ public final patchDef_return patchDef() throws RecognitionException { ++ patchDef_return retval = new patchDef_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token string_literal18 = null; ++ attachmentSource_return s = null; ++ ++ CommonTree string_literal18_tree = null; ++ ++ try { ++ // ReviewDsl.g:49:2: ( 'Patch' s= attachmentSource ) ++ // ReviewDsl.g:49:2: 'Patch' s= attachmentSource ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal18 = (Token) input.LT(1); ++ match(input, 27, FOLLOW_27_in_patchDef252); ++ string_literal18_tree = (CommonTree) adaptor ++ .create(string_literal18); ++ adaptor.addChild(root_0, string_literal18_tree); ++ ++ pushFollow(FOLLOW_attachmentSource_in_patchDef256); ++ s = attachmentSource(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, s.getTree()); ++ retval.source = s; ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end patchDef ++ ++ public static class attachmentSource_return extends ParserRuleReturnScope { ++ public String filename; ++ public String author; ++ String createdDate; ++ public String taskId; ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start attachmentSource ++ // ReviewDsl.g:52:1: attachmentSource returns [String filename, String ++ // author; String createdDate, String taskId] : 'from' 'Attachment' fn= ++ // STRING 'by' a= STRING 'on' d= STRING 'of' 'task' t= taskIdDef ; ++ public final attachmentSource_return attachmentSource() ++ throws RecognitionException { ++ attachmentSource_return retval = new attachmentSource_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token fn = null; ++ Token a = null; ++ Token d = null; ++ Token string_literal19 = null; ++ Token string_literal20 = null; ++ Token string_literal21 = null; ++ Token string_literal22 = null; ++ Token string_literal23 = null; ++ Token string_literal24 = null; ++ taskIdDef_return t = null; ++ ++ CommonTree fn_tree = null; ++ CommonTree a_tree = null; ++ CommonTree d_tree = null; ++ CommonTree string_literal19_tree = null; ++ CommonTree string_literal20_tree = null; ++ CommonTree string_literal21_tree = null; ++ CommonTree string_literal22_tree = null; ++ CommonTree string_literal23_tree = null; ++ CommonTree string_literal24_tree = null; ++ ++ try { ++ // ReviewDsl.g:53:2: ( 'from' 'Attachment' fn= STRING 'by' a= STRING ++ // 'on' d= STRING 'of' 'task' t= taskIdDef ) ++ // ReviewDsl.g:53:2: 'from' 'Attachment' fn= STRING 'by' a= STRING ++ // 'on' d= STRING 'of' 'task' t= taskIdDef ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ string_literal19 = (Token) input.LT(1); ++ match(input, 26, FOLLOW_26_in_attachmentSource274); ++ string_literal19_tree = (CommonTree) adaptor ++ .create(string_literal19); ++ adaptor.addChild(root_0, string_literal19_tree); ++ ++ string_literal20 = (Token) input.LT(1); ++ match(input, 28, FOLLOW_28_in_attachmentSource276); ++ string_literal20_tree = (CommonTree) adaptor ++ .create(string_literal20); ++ adaptor.addChild(root_0, string_literal20_tree); ++ ++ fn = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_attachmentSource280); ++ fn_tree = (CommonTree) adaptor.create(fn); ++ adaptor.addChild(root_0, fn_tree); ++ ++ string_literal21 = (Token) input.LT(1); ++ match(input, 29, FOLLOW_29_in_attachmentSource284); ++ string_literal21_tree = (CommonTree) adaptor ++ .create(string_literal21); ++ adaptor.addChild(root_0, string_literal21_tree); ++ ++ a = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_attachmentSource288); ++ a_tree = (CommonTree) adaptor.create(a); ++ adaptor.addChild(root_0, a_tree); ++ ++ string_literal22 = (Token) input.LT(1); ++ match(input, 30, FOLLOW_30_in_attachmentSource292); ++ string_literal22_tree = (CommonTree) adaptor ++ .create(string_literal22); ++ adaptor.addChild(root_0, string_literal22_tree); ++ ++ d = (Token) input.LT(1); ++ match(input, STRING, FOLLOW_STRING_in_attachmentSource296); ++ d_tree = (CommonTree) adaptor.create(d); ++ adaptor.addChild(root_0, d_tree); ++ ++ string_literal23 = (Token) input.LT(1); ++ match(input, 31, FOLLOW_31_in_attachmentSource300); ++ string_literal23_tree = (CommonTree) adaptor ++ .create(string_literal23); ++ adaptor.addChild(root_0, string_literal23_tree); ++ ++ string_literal24 = (Token) input.LT(1); ++ match(input, 32, FOLLOW_32_in_attachmentSource302); ++ string_literal24_tree = (CommonTree) adaptor ++ .create(string_literal24); ++ adaptor.addChild(root_0, string_literal24_tree); ++ ++ pushFollow(FOLLOW_taskIdDef_in_attachmentSource306); ++ t = taskIdDef(); ++ _fsp--; ++ ++ adaptor.addChild(root_0, t.getTree()); ++ retval.filename = fn.getText(); ++ retval.author = a.getText(); ++ retval.createdDate = d.getText(); ++ retval.taskId = input.toString(t.start, t.stop); ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end attachmentSource ++ ++ public static class taskIdDef_return extends ParserRuleReturnScope { ++ CommonTree tree; ++ ++ public Object getTree() { ++ return tree; ++ } ++ }; ++ ++ // $ANTLR start taskIdDef ++ // ReviewDsl.g:60:1: taskIdDef : ( TASK_ID | INT ); ++ public final taskIdDef_return taskIdDef() throws RecognitionException { ++ taskIdDef_return retval = new taskIdDef_return(); ++ retval.start = input.LT(1); ++ ++ CommonTree root_0 = null; ++ ++ Token set25 = null; ++ ++ CommonTree set25_tree = null; ++ ++ try { ++ // ReviewDsl.g:61:4: ( TASK_ID | INT ) ++ // ReviewDsl.g: ++ { ++ root_0 = (CommonTree) adaptor.nil(); ++ ++ set25 = (Token) input.LT(1); ++ if ((input.LA(1) >= INT && input.LA(1) <= TASK_ID)) { ++ input.consume(); ++ adaptor.addChild(root_0, adaptor.create(set25)); ++ errorRecovery = false; ++ } else { ++ MismatchedSetException mse = new MismatchedSetException( ++ null, input); ++ recoverFromMismatchedSet(input, mse, ++ FOLLOW_set_in_taskIdDef0); ++ throw mse; ++ } ++ ++ } ++ ++ retval.stop = input.LT(-1); ++ ++ retval.tree = (CommonTree) adaptor.rulePostProcessing(root_0); ++ adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); ++ ++ } catch (RecognitionException re) { ++ reportError(re); ++ recover(input, re); ++ } finally { ++ } ++ return retval; ++ } ++ ++ // $ANTLR end taskIdDef ++ ++ public static final BitSet FOLLOW_12_in_reviewResult39 = new BitSet( ++ new long[] { 0x0000000000002000L }); ++ public static final BitSet FOLLOW_13_in_reviewResult41 = new BitSet( ++ new long[] { 0x0000000000078000L }); ++ public static final BitSet FOLLOW_resultEnum_in_reviewResult46 = new BitSet( ++ new long[] { 0x0000000000084002L }); ++ public static final BitSet FOLLOW_14_in_reviewResult52 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_reviewResult56 = new BitSet( ++ new long[] { 0x0000000000080002L }); ++ public static final BitSet FOLLOW_fileComment_in_reviewResult64 = new BitSet( ++ new long[] { 0x0000000000080002L }); ++ public static final BitSet FOLLOW_set_in_resultEnum0 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_19_in_fileComment98 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_fileComment102 = new BitSet( ++ new long[] { 0x0000000000100000L }); ++ public static final BitSet FOLLOW_20_in_fileComment104 = new BitSet( ++ new long[] { 0x0000000000200012L }); ++ public static final BitSet FOLLOW_STRING_in_fileComment109 = new BitSet( ++ new long[] { 0x0000000000200002L }); ++ public static final BitSet FOLLOW_lineComment_in_fileComment115 = new BitSet( ++ new long[] { 0x0000000000200002L }); ++ public static final BitSet FOLLOW_21_in_lineComment130 = new BitSet( ++ new long[] { 0x0000000000000020L }); ++ public static final BitSet FOLLOW_INT_in_lineComment134 = new BitSet( ++ new long[] { 0x0000000000500000L }); ++ public static final BitSet FOLLOW_22_in_lineComment137 = new BitSet( ++ new long[] { 0x0000000000000020L }); ++ public static final BitSet FOLLOW_INT_in_lineComment141 = new BitSet( ++ new long[] { 0x0000000000100000L }); ++ public static final BitSet FOLLOW_20_in_lineComment145 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_lineComment150 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_12_in_reviewScope167 = new BitSet( ++ new long[] { 0x0000000000800000L }); ++ public static final BitSet FOLLOW_23_in_reviewScope169 = new BitSet( ++ new long[] { 0x000000000B000002L }); ++ public static final BitSet FOLLOW_resourceDef_in_reviewScope175 = new BitSet( ++ new long[] { 0x000000000B000002L }); ++ public static final BitSet FOLLOW_patchDef_in_reviewScope178 = new BitSet( ++ new long[] { 0x000000000B000002L }); ++ public static final BitSet FOLLOW_changesetDef_in_reviewScope183 = new BitSet( ++ new long[] { 0x000000000B000002L }); ++ public static final BitSet FOLLOW_24_in_resourceDef205 = new BitSet( ++ new long[] { 0x0000000004000000L }); ++ public static final BitSet FOLLOW_attachmentSource_in_resourceDef210 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_25_in_changesetDef226 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_changesetDef230 = new BitSet( ++ new long[] { 0x0000000004000000L }); ++ public static final BitSet FOLLOW_26_in_changesetDef233 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_changesetDef237 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_27_in_patchDef252 = new BitSet( ++ new long[] { 0x0000000004000000L }); ++ public static final BitSet FOLLOW_attachmentSource_in_patchDef256 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_26_in_attachmentSource274 = new BitSet( ++ new long[] { 0x0000000010000000L }); ++ public static final BitSet FOLLOW_28_in_attachmentSource276 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_attachmentSource280 = new BitSet( ++ new long[] { 0x0000000020000000L }); ++ public static final BitSet FOLLOW_29_in_attachmentSource284 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_attachmentSource288 = new BitSet( ++ new long[] { 0x0000000040000000L }); ++ public static final BitSet FOLLOW_30_in_attachmentSource292 = new BitSet( ++ new long[] { 0x0000000000000010L }); ++ public static final BitSet FOLLOW_STRING_in_attachmentSource296 = new BitSet( ++ new long[] { 0x0000000080000000L }); ++ public static final BitSet FOLLOW_31_in_attachmentSource300 = new BitSet( ++ new long[] { 0x0000000100000000L }); ++ public static final BitSet FOLLOW_32_in_attachmentSource302 = new BitSet( ++ new long[] { 0x0000000000000060L }); ++ public static final BitSet FOLLOW_taskIdDef_in_attachmentSource306 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ public static final BitSet FOLLOW_set_in_taskIdDef0 = new BitSet( ++ new long[] { 0x0000000000000002L }); ++ ++} +\ No newline at end of file +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslSerializer.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslSerializer.java +new file mode 100644 +index 00000000..567758f3 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/internal/ReviewDslSerializer.java +@@ -0,0 +1,39 @@ ++/******************************************************************************* ++ * Copyright (c) 2011 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ ++ ++package org.eclipse.mylyn.reviews.tasks.dsl.internal; ++ ++import org.eclipse.mylyn.reviews.tasks.dsl.IReviewDslSerializer; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult; ++import org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScope; ++ ++/** ++ * ++ * @author mattk ++ * ++ */ ++public class ReviewDslSerializer implements IReviewDslSerializer { ++ ++ /* (non-Javadoc) ++ * @see org.eclipse.mylyn.reviews.tasks.dsl.internal.IReviewDslSerializer#serialize(org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslScope) ++ */ ++ @Override ++ public String serialize(ReviewDslScope scope) { ++ return scope.serialize(new StringBuilder()).toString(); ++ } ++ /* (non-Javadoc) ++ * @see org.eclipse.mylyn.reviews.tasks.dsl.internal.IReviewDslSerializer#serialize(org.eclipse.mylyn.reviews.tasks.dsl.ReviewDslResult) ++ */ ++ @Override ++ public String serialize(ReviewDslResult result) { ++ return result.serialize(new StringBuilder()).toString(); ++ } ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java +deleted file mode 100644 +index b763d9b4..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/scoping/ReviewDslScopeProvider.java ++++ /dev/null +@@ -1,17 +0,0 @@ +-/* +- * generated by Xtext +- */ +-package org.eclipse.mylyn.reviews.tasks.dsl.scoping; +- +-import org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider; +- +-/** +- * This class contains custom scoping description. +- * +- * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#scoping +- * on how and when to use it +- * +- */ +-public class ReviewDslScopeProvider extends AbstractDeclarativeScopeProvider { +- +-} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java +deleted file mode 100644 +index 1ebad0a8..00000000 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/src/org/eclipse/mylyn/reviews/tasks/dsl/validation/ReviewDslJavaValidator.java ++++ /dev/null +@@ -1,13 +0,0 @@ +-package org.eclipse.mylyn.reviews.tasks.dsl.validation; +- +- +-public class ReviewDslJavaValidator extends AbstractReviewDslJavaValidator { +- +-// @Check +-// public void checkGreetingStartsWithCapital(Greeting greeting) { +-// if (!Character.isUpperCase(greeting.getName().charAt(0))) { +-// warning(""Name should start with a capital"", MyDslPackage.GREETING__NAME); +-// } +-// } +- +-} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java +index 1d0602c9..a54bb134 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/ReviewsUiPlugin.java +@@ -29,7 +29,7 @@ public class ReviewsUiPlugin extends AbstractUIPlugin { + // The shared instance + private static ReviewsUiPlugin plugin; + +- private static ReviewTaskMapper mapper; ++ private static IReviewMapper mapper; + + /** + * The constructor" +8de9caa985fa3e79348c1c88b9313a4bce4d92e6,Valadoc,"libvaladoc: Add support for SourceCode attributes +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +08dbf2ed3696c16a8c2f67e436ace7f6a7622386,cloudname$cloudname,"Brave new world +Rewrite into a core library with simple methods and an abstraction layer on +top of the backend system. +The following backends are implemented +* Memory (for testing; only works within a single JVM) +* ZooKeeper (proof-of-concept implementation of the backend) +The following libraries are created: +* Service discovery library +This brings the overall functionality on par with 2.x with a few exceptions: +* Locking isn't implemented. That did not work for the old library so +there's no real change in functionality +* It isn't possible to query *everything* from a client. This will be +addressed in another commit (or just ignored completely since the +backends offers this in some shape or form) +* It isn't possible to resolve coordinates partially, f.e. finding +""logserver"" when your own coordinate is ""service.tag.region""; +""logserver"" should resolve to ""logserver.tag.region"". This will +be solved in a later commit by making a separate resolver class that +creates service coordinates based on existing coordinates. +",p,https://github.com/cloudname/cloudname,"diff --git a/README.md b/README.md +index 4a1fbe9b..90ef64d5 100644 +--- a/README.md ++++ b/README.md +@@ -1,3 +1,31 @@ + # Brave new world: Cloudname 3.0 + +-Forget everything we said earlier. This is going to be even greater. ++## cn-core ++The core Cloudname library for resource management ++ ++## cn-service ++Service discovery built on top of the core library. ++ ++--- ++# The yet-to-be-updated section ++ ++## a3 -- Authentication, Authorization and Access library ++Mostly the first, some of the second. Still unchanged from 2.x ++ ++## Idgen - Generating IDs ++Generate bucketloads of unique IDs spread across multiple hosts, services and ++regions. ++ ++## Flags - Command line Flags ++Simple command line flag handling via annotations on properties and accessors. ++ ++## Log - Core logging library ++Core entities for logging. ++ ++## Timber - A log server and client ++A networked high-performance log server that uses protobuf entities. Server and ++client code. ++ ++## Testtools - Testing tools and utilities ++ ++Mostly for internal use by the various modules. +diff --git a/cn-core/README.md b/cn-core/README.md +new file mode 100644 +index 00000000..9df86e77 +--- /dev/null ++++ b/cn-core/README.md +@@ -0,0 +1,30 @@ ++# Cloudname Core ++ ++The core libraries are mostly for internal use and are the basic building block for the other libraries. Clients won't use or access this library directly but through the libraries build on the core library. ++ ++The core library supports various backends. The build-in backend is memory-based and is *not* something you want to use in a production service. Its sole purpose is to provide a fast single-JVM backend used when testing other modules built on top of the core library. ++ ++## Key concepts ++### Leases ++The backends expose **leases** to clients. Each lease is represented by a **path**. Clients belong to a **region**. A region is typically a cluster of servers that are coordinate through a single backend. ++ ++ ++ ++#### Client leases ++Ordinary leases exists only as long as the client is running and is connected to the backend. When the client terminates the connection the lease expires and anyone listening on changes will be notified. ++ ++#### Permanent leases ++Permanent leases persist between client connections. If a client connects to the backend, creates a permanent lease and then disconnects the lease will still be in place. The permanent leases does not expire and will only be removed if done so explicitly by the clients. ++ ++### Paths ++A **path** is nothing more than an ordered set of strings that represents a (real or virtual) tree structure. The backend itself does not need to use a hierarchical storage mechanism since the paths can be used directly as identifiers. ++ ++Elements in the paths follows the DNS naming conventions in RFC 952 and RFC 1123: Strings between 1-63 characters long, a-z characters (case insensitive) and hyphens. A string cannot start or end with a hyphen. ++ ++ ++## Backend requirements ++* Paths are guaranteed unique for all clients in the same cluster. There is no guarantee that a lease will be unique for other regions. ++* The backend ensures there are no duplicate leases for the current region. ++* The backend will create notifications in the same order as they occur. ++* Past leases given to disconnected clients are not guaranteed to be unique ++* The backend is responsible for cleanups of leases; if all clients disconnect the only leases that should be left is the permanent leases. +diff --git a/cn-core/pom.xml b/cn-core/pom.xml +new file mode 100644 +index 00000000..1c8fe5f9 +--- /dev/null ++++ b/cn-core/pom.xml +@@ -0,0 +1,46 @@ ++ ++ 4.0.0 ++ ++ ++ org.cloudname ++ cloudname-parent ++ 3.0-SNAPSHOT ++ ++ ++ cn-core ++ jar ++ ++ Cloudname Library ++ Managing distributed resources ++ https://github.com/Cloudname/cloudname ++ ++ ++ ++ junit ++ junit ++ test ++ ++ ++ ++ org.hamcrest ++ hamcrest-all ++ 1.3 ++ ++ ++ ++ ++ ++ ++ ++ org.apache.maven.plugins ++ maven-surefire-plugin ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ++ ++ ++ ++ +diff --git a/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java b/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java +new file mode 100644 +index 00000000..ed7f2270 +--- /dev/null ++++ b/cn-core/src/main/java/org/cloudname/core/CloudnameBackend.java +@@ -0,0 +1,133 @@ ++package org.cloudname.core; ++ ++/** ++ * Backends implement this interface. Clients won't use this interface; the logic is handled by the ++ * libaries built on top of the backend. Each backend provides a few basic primitives that must be ++ * implemented. One caveat: The backend is responsible for cleaning up unused paths. The clients won't ++ * remote unused elements. ++ * ++ * There are two kinds of leases - permanent and temporary. The permanent leases persist in the ++ * backend and aren't removed when clients disconnect, even if *all* clients disconnects. ++ * The temporary leases are removed by the backend when the client closes. Note that clients might ++ * not be well-behaved and may terminate without calling close(). The backend should remove ++ * these leases automatically. ++ * ++ * Clients listen on both kinds of leases and get notifications through listeners whenever something ++ * is changed. Notifications to the clients are sent in the same order they are received. ++ * ++ * Each lease have a data string attached to the lease and clients may update this freely. ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface CloudnameBackend extends AutoCloseable { ++ /** ++ * Create a temporary lease. The temporary lease is limited by the client's connection and will ++ * be available for as long as the client is connected to the backend. Once the client ++ * disconnects (either through the LeaseHandle instance that is returned or just vanishing ++ * from the face of the earth) the lease is removed by the backend. The backend should support ++ * an unlimited number of leases (FSVO ""unlimited"") ++ * ++ * @param path Path to temporary lease. This value cannot be null. The path supplied by the ++ * client is just the stem of the full lease, i.e. if a client supplies foo:bar the backend ++ * will return an unique path to the client which represent the lease (for ""foo:bar"" the ++ * backend might return ""foo:bar:uniqueid0"", ""foo:bar:uniqueid1""... to clients acquiring ++ * the lease. ++ * ++ * @param data Temporary lease data. This is an arbitrary string supplied by the client. It ++ * carries no particular semantics for the backend and the backend only have to return the ++ * same string to the client. This value cannot be null. ++ * ++ * @return A LeaseHandle instance that the client can use to manipulate its data or release ++ * the lease (ie closing it). ++ */ ++ LeaseHandle createTemporaryLease(final CloudnamePath path, final String data); ++ ++ /** ++ * Update a client's lease. Normally this is something the client does itself but libraries ++ * built on top of the backends might use it to set additional properties. ++ * @param path Path to the temporary lease. ++ * @param data The updated lease data. ++ * @return True if successful, false otherwise ++ */ ++ boolean writeTemporaryLeaseData(final CloudnamePath path, final String data); ++ ++ /** ++ * Read temporary lease data. Clients won't use this in regular use but rather monitor changes ++ * through the listeners but libraries built on top of the backend might read the data. ++ * ++ * @param path Path to the client lease. ++ * @return The data stored in the client lease. ++ */ ++ String readTemporaryLeaseData(final CloudnamePath path); ++ ++ /** ++ * Add a listener to a set of temporary leases identified by a path. The temporary leases ++ * doesn't have to exist but as soon as someone creates a lease matching the given path a ++ * notification must be sent by the backend implementation. ++ * ++ * @param pathToObserve The path to observe for changes. ++ * @param listener Client's listener. Callbacks on this listener will be invoked by the backend. ++ */ ++ void addTemporaryLeaseListener(final CloudnamePath pathToObserve, final LeaseListener listener); ++ ++ /** ++ * Remove a previously attached listener. The backend will ignore leases that doesn't exist. ++ * ++ * @param listener The listener to remove ++ */ ++ void removeTemporaryLeaseListener(final LeaseListener listener); ++ ++ /** ++ * Create a permanent lease. A permanent lease persists even if the client that created it ++ * terminates or closes the connection. Other clients will still see the lease. Permanent leases ++ * must persist until they are explicitly removed. ++ * ++ * All permanent leases must be unique. Duplicate permanent leases yields an error. ++ * ++ * @param path Path to the permanent lease. ++ * @param data Data to store in the permanent lease when it is created. ++ * @return true if successful ++ */ ++ boolean createPermanantLease(final CloudnamePath path, final String data); ++ ++ /** ++ * Remove a permanent lease. The lease will be removed and clients listening on the lease ++ * will be notified. ++ * ++ * @param path The path to the lease ++ * @return true if lease is removed. ++ */ ++ boolean removePermanentLease(final CloudnamePath path); ++ ++ /** ++ * Update data on permanent lease. ++ * ++ * @param path path to the permanent lease ++ * @param data data to write to the lease ++ * @return true if successful ++ */ ++ boolean writePermanentLeaseData(final CloudnamePath path, final String data); ++ ++ /** ++ * Read data from permanent lease. ++ * ++ * @param path path to permanent lease ++ * @return data stored in lease or null if the lease doesn't exist ++ */ ++ String readPermanentLeaseData(final CloudnamePath path); ++ ++ /** ++ * Add a listener to a permanent lease. The listener is attached to just one lease, as opposed ++ * to the termporary lease listener. ++ * ++ * @param pathToObserver Path to lease ++ * @param listener Listener. Callbacks on this listener is invoked by the backend. ++ */ ++ void addPermanentLeaseListener(final CloudnamePath pathToObserver, final LeaseListener listener); ++ ++ /** ++ * Remove listener on permanent lease. Unknown listeners are ignored by the backend. ++ * @param listener The listener to remove ++ */ ++ void removePermanentLeaseListener(final LeaseListener listener); ++} +diff --git a/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java b/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java +new file mode 100644 +index 00000000..269d57cd +--- /dev/null ++++ b/cn-core/src/main/java/org/cloudname/core/CloudnamePath.java +@@ -0,0 +1,195 @@ ++package org.cloudname.core; ++ ++import java.util.Arrays; ++import java.util.regex.Matcher; ++import java.util.regex.Pattern; ++ ++/** ++ * A generic representation of a path. A ""path"" might be a bit of a misnomer in the actual ++ * backend implementation but it can be represented as an uniquely identifying string for the ++ * leases handed out. A path can be split into elements which can be accessed individually. ++ * ++ * Paths are an ordered set of strings consisting of the characters according to RFC 952 and ++ * RFC 1123, ie [a-z,0-9,-]. The names cannot start or end with an hyphen and can be between ++ * 1 and 63 characters long. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class CloudnamePath { ++ private final String[] pathElements; ++ private static final Pattern NAME_PATTERN = Pattern.compile(""[a-z0-9-]*""); ++ ++ /** ++ * Check if path element is a valid name according to RFC 953/RCC 1123 ++ * ++ * @param name The element to check ++ * @return true if element is a valid stirng ++ */ ++ public static boolean isValidPathElementName(final String name) { ++ if (name == null || name.isEmpty()) { ++ return false; ++ } ++ ++ final Matcher matcher = NAME_PATTERN.matcher(name); ++ if (!matcher.matches()) { ++ return false; ++ } ++ if (name.length() > 64) { ++ return false; ++ } ++ if (name.charAt(0) == '-' || name.charAt(name.length() - 1) == '-') { ++ return false; ++ } ++ return true; ++ } ++ ++ /** ++ * @param pathElements the string array to create the path from. Order is preserved so ++ * pathElements[0] corresponds to the first element in the path. ++ * @throws AssertionError if the pathElements parameter is null. ++ */ ++ public CloudnamePath(final String[] pathElements) { ++ if (pathElements == null) { ++ throw new IllegalArgumentException(""Path elements can not be null""); ++ } ++ this.pathElements = new String[pathElements.length]; ++ for (int i = 0; i < pathElements.length; i++) { ++ if (pathElements[i] == null) { ++ throw new IllegalArgumentException(""Path element at index "" + i + "" is null""); ++ } ++ final String element = pathElements[i].toLowerCase(); ++ if (!isValidPathElementName(element)) { ++ throw new IllegalArgumentException(""Name element "" + element + "" isn't a valid name""); ++ } ++ this.pathElements[i] = element; ++ } ++ } ++ ++ /** ++ * Create a new path based on an existing one by appending a new element ++ * ++ * @param path The original CloudnamePath instance ++ * @param additionalElement Element to append to the end of the original path ++ * @throws AssertionError if one or more of the parameters are null ++ */ ++ public CloudnamePath(final CloudnamePath path, final String additionalElement) { ++ if (path == null) { ++ throw new IllegalArgumentException(""Path can not be null""); ++ } ++ if (additionalElement == null) { ++ throw new IllegalArgumentException(""additionalElement can not be null""); ++ } ++ ++ if (!isValidPathElementName(additionalElement)) { ++ throw new IllegalArgumentException(additionalElement + "" isn't a valid path name""); ++ } ++ this.pathElements = Arrays.copyOf(path.pathElements, path.pathElements.length + 1); ++ this.pathElements[this.pathElements.length - 1] = additionalElement; ++ ++ } ++ ++ /** ++ * @return the number of elements in the path ++ */ ++ public int length() { ++ return pathElements.length; ++ } ++ ++ /** ++ * Join the path elements into a string, f.e. join ""foo"", ""bar"" into ""foo:bar"" ++ * ++ * @param separator separator character between elements ++ * @return joined elements ++ */ ++ public String join(final char separator) { ++ final StringBuilder sb = new StringBuilder(); ++ boolean first = true; ++ for (final String element : pathElements) { ++ if (!first) { ++ sb.append(separator); ++ } ++ sb.append(element); ++ first = false; ++ } ++ return sb.toString(); ++ } ++ ++ /** ++ * @param index index of element ++ * @return element at index ++ * @throws IndexOutOfBoundsException if the index is out of range ++ */ ++ public String get(final int index) { ++ return pathElements[index]; ++ } ++ ++ /** ++ * Check if this path is a subpath. A path is a subpath whenever it starts with the ++ * same elements as the other path (""foo/bar/baz"" would be a subpath of ""foo/bar/baz/baz"" ++ * but not of ""bar/foo"") ++ * ++ * @param other Path to check ++ * @return true if this path is a subpath of the specified path ++ */ ++ public boolean isSubpathOf(final CloudnamePath other) { ++ if (other == null) { ++ return false; ++ } ++ if (this.pathElements.length > other.pathElements.length) { ++ return false; ++ } ++ ++ if (this.pathElements.length == 0) { ++ // This is an empty path. It is the subpath of any other path. ++ return true; ++ } ++ ++ for (int i = 0; i < this.pathElements.length; i++) { ++ if (!other.pathElements[i].equals(this.pathElements[i])) { ++ return false; ++ } ++ } ++ ++ return true; ++ } ++ ++ /** ++ * @return parent path of current. If this is the root path (ie it is empty), return the ++ * current path ++ */ ++ public CloudnamePath getParent() { ++ if (this.pathElements.length == 0) { ++ return this; ++ } ++ return new CloudnamePath(Arrays.copyOf(pathElements, this.pathElements.length - 1)); ++ } ++ ++ @Override ++ public boolean equals(final Object other) { ++ if (other == null || !(other instanceof CloudnamePath)) { ++ return false; ++ } ++ final CloudnamePath otherPath = (CloudnamePath) other; ++ if (otherPath.pathElements.length != pathElements.length) { ++ return false; ++ } ++ for (int i = 0; i < pathElements.length; i++) { ++ if (!pathElements[i].equals(otherPath.pathElements[i])) { ++ return false; ++ } ++ } ++ return true; ++ } ++ ++ @Override ++ public int hashCode() { ++ return Arrays.hashCode(pathElements); ++ } ++ ++ @Override ++ public String toString() { ++ return ""[ CloudnamePath ("" + Arrays.toString(pathElements) + "") ]""; ++ } ++ ++ ++} +diff --git a/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java b/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java +new file mode 100644 +index 00000000..45b79740 +--- /dev/null ++++ b/cn-core/src/main/java/org/cloudname/core/LeaseHandle.java +@@ -0,0 +1,21 @@ ++package org.cloudname.core; ++ ++/** ++ * Handle returned by the backend when a temporary lease is created. ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface LeaseHandle extends AutoCloseable { ++ /** ++ * Write data to the lease. ++ * ++ * @param data data to write. Cannot be null. ++ * @return true if data is written ++ */ ++ boolean writeLeaseData(final String data); ++ ++ /** ++ * @return The full path of the lease ++ */ ++ CloudnamePath getLeasePath(); ++} +\ No newline at end of file +diff --git a/cn-core/src/main/java/org/cloudname/core/LeaseListener.java b/cn-core/src/main/java/org/cloudname/core/LeaseListener.java +new file mode 100644 +index 00000000..1586b100 +--- /dev/null ++++ b/cn-core/src/main/java/org/cloudname/core/LeaseListener.java +@@ -0,0 +1,31 @@ ++package org.cloudname.core; ++ ++/** ++ * Lease notifications to clients. ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface LeaseListener { ++ /** ++ * A new lease is created. The lease is created at this point in time. ++ * ++ * @param path The full path of the lease ++ * @param data The data stored on the lease ++ */ ++ void leaseCreated(final CloudnamePath path, final String data); ++ ++ /** ++ * A lease is removed. The lease might not exist anymore at this point in time. ++ * ++ * @param path The path of the lease. ++ */ ++ void leaseRemoved(final CloudnamePath path); ++ ++ /** ++ * Lease data have changed in one of the leases the client is listening on. ++ * ++ * @param path Full path to the lease that have changed ++ * @param data The new data element stored in the lease ++ */ ++ void dataChanged(final CloudnamePath path, final String data); ++} +diff --git a/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java b/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java +new file mode 100644 +index 00000000..0e6bff9b +--- /dev/null ++++ b/cn-core/src/test/java/org/cloudname/core/CloudnamePathTest.java +@@ -0,0 +1,204 @@ ++package org.cloudname.core; ++ ++import org.junit.Test; ++ ++import static org.hamcrest.CoreMatchers.equalTo; ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.notNullValue; ++import static org.junit.Assert.assertThat; ++import static org.junit.Assert.assertTrue; ++import static org.junit.Assert.fail; ++ ++/** ++ * Test the CloudnamePath class. ++ */ ++public class CloudnamePathTest { ++ private final String[] emptyElements = new String[] {}; ++ private final String[] oneElement = new String[] { ""foo"" }; ++ private final String[] twoElements = new String[] { ""foo"", ""bar"" }; ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void elementsCantBeNull() { ++ new CloudnamePath(null); ++ fail(""No exception, no pass for you!""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void pathCantBeNull() { ++ new CloudnamePath(null, ""foof""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void additionalElementCantBeNull() { ++ new CloudnamePath(new CloudnamePath(new String[] { ""foo"" }), null); ++ } ++ ++ @Test ++ public void appendPath() { ++ final CloudnamePath singleElement = new CloudnamePath(new String[] { ""one"" }); ++ final CloudnamePath twoElements = new CloudnamePath(new String[] { ""one"", ""two"" }); ++ assertThat(""Elements aren't equal"", singleElement.equals(twoElements), is(false)); ++ final CloudnamePath appendedElement = new CloudnamePath(singleElement, ""two""); ++ assertThat(""Appended are equal"", appendedElement.equals(twoElements), is(true)); ++ } ++ ++ @Test ++ public void elementAccess() { ++ final CloudnamePath path = new CloudnamePath(twoElements); ++ assertThat(path.get(0), is(twoElements[0])); ++ assertThat(path.get(1), is(twoElements[1])); ++ } ++ ++ @Test (expected = IndexOutOfBoundsException.class) ++ public void elementAccessMustBeWithinBounds() { ++ final CloudnamePath path = new CloudnamePath(twoElements); ++ path.get(2); ++ } ++ ++ @Test ++ public void joinPaths() { ++ final CloudnamePath empty = new CloudnamePath(emptyElements); ++ assertThat(""The empty path is length = 0"", empty.length(), is(0)); ++ assertThat(""String representation of emmpty path is empty string"", empty.join('.'), is("""")); ++ ++ final CloudnamePath one = new CloudnamePath(oneElement); ++ assertThat(""A single element path has length 1"", one.length(), is(1)); ++ assertThat(""String representation of a single element path is the element"", ++ one.join('.'), is(oneElement[0])); ++ ++ final CloudnamePath two = new CloudnamePath(twoElements); ++ assertThat(""Two element paths have length 2"", two.length(), is(2)); ++ assertThat(""String representation of two element paths includes both elements"", ++ two.join('.'), is(twoElements[0] + '.' + twoElements[1])); ++ } ++ ++ @Test ++ public void equalsTest() { ++ final CloudnamePath twoA = new CloudnamePath(twoElements); ++ final CloudnamePath twoB = new CloudnamePath(twoElements); ++ final CloudnamePath none = new CloudnamePath(emptyElements); ++ final CloudnamePath entirelyDifferent = new CloudnamePath(new String[] { ""foo"", ""2"" }); ++ ++ assertThat(""Identical paths are equal"", twoA.equals(twoB), is(true)); ++ assertThat(""Hash codes for equal objects are the same"", ++ twoA.hashCode(), is(twoB.hashCode())); ++ assertThat(""Identical paths are equal, ignore order"", twoB.equals(twoA), is(true)); ++ assertThat(""Paths aren't equal to strings"", twoA.equals(""""), is(false)); ++ assertThat(""Empty path does not equal actual path"", twoA.equals(none), is(false)); ++ assertThat(""Null elements aren't equal"", twoA.equals(null), is(false)); ++ assertThat(""Differen is just different"", twoA.equals(entirelyDifferent), is(false)); ++ } ++ ++ @Test ++ public void subpaths() { ++ final String[] e1 = new String[] { ""1"", ""2"", ""3"", ""4"" }; ++ final String[] e2 = new String[] { ""1"", ""2"" }; ++ ++ final CloudnamePath first = new CloudnamePath(e1); ++ final CloudnamePath second = new CloudnamePath(e2); ++ final CloudnamePath last = new CloudnamePath(twoElements); ++ ++ ++ assertThat(""More specific paths can't be subpaths"", first.isSubpathOf(second), is(false)); ++ assertThat(""More generic paths are subpaths"", second.isSubpathOf(first), is(true)); ++ assertThat(""A path can be subpath of itself"", first.isSubpathOf(first), is(true)); ++ ++ assertThat(""Paths must match at root levels"", last.isSubpathOf(second), is(false)); ++ ++ assertThat(""Null paths are not subpaths of anything"", first.isSubpathOf(null), is(false)); ++ ++ final CloudnamePath empty = new CloudnamePath(emptyElements); ++ assertThat(""An empty path is a subpath of everything"", empty.isSubpathOf(first), is(true)); ++ assertThat(""Empty paths can't have subpaths"", first.isSubpathOf(empty), is(false)); ++ } ++ ++ @Test ++ public void parentPaths() { ++ final CloudnamePath originalPath = new CloudnamePath(new String[] { ""foo"", ""bar"", ""baz"" }); ++ ++ assertTrue(originalPath.getParent().isSubpathOf(originalPath)); ++ ++ assertThat(originalPath.getParent(), is(equalTo( ++ new CloudnamePath(new String[] { ""foo"", ""bar"" })))); ++ ++ assertThat(originalPath.getParent().getParent(), ++ is(equalTo(new CloudnamePath(new String[] { ""foo"" })))); ++ ++ final CloudnamePath emptyPath = new CloudnamePath(new String[] { }); ++ ++ assertThat(originalPath.getParent().getParent().getParent(), ++ is(equalTo(emptyPath))); ++ ++ assertThat(originalPath.getParent().getParent().getParent().getParent(), ++ is(equalTo(emptyPath))); ++ ++ assertThat(emptyPath.getParent(), is(equalTo(emptyPath))); ++ } ++ @Test ++ public void testToString() { ++ final CloudnamePath one = new CloudnamePath(oneElement); ++ final CloudnamePath two = new CloudnamePath(twoElements); ++ final CloudnamePath three = new CloudnamePath(emptyElements); ++ ++ assertThat(one.toString(), is(notNullValue())); ++ assertThat(two.toString(), is(notNullValue())); ++ assertThat(three.toString(), is(notNullValue())); ++ } ++ ++ @Test ++ public void invalidPathNameWithHyphenFirst() { ++ assertThat(CloudnamePath.isValidPathElementName(""-invalid""), is(false)); ++ } ++ ++ @Test ++ public void invalidPathNameIsNull() { ++ assertThat(CloudnamePath.isValidPathElementName(null), is(false)); ++ } ++ @Test ++ public void invalidPathNameWithHyphenLast() { ++ assertThat(CloudnamePath.isValidPathElementName(""invalid-""), is(false)); ++ } ++ ++ @Test ++ public void invalidPathNameWithEmptyString() { ++ assertThat(CloudnamePath.isValidPathElementName(""""), is(false)); ++ } ++ ++ @Test ++ public void invalidPathNameWithIllegalChars() { ++ assertThat(CloudnamePath.isValidPathElementName(""__""), is(false)); ++ } ++ ++ @Test ++ public void invalidPathNameWithTooLongLabel() { ++ assertThat(CloudnamePath.isValidPathElementName( ++ ""rindfleischetikettierungsueberwachungsaufgabenuebertragungsgesetz""), is(false)); ++ } ++ ++ @Test ++ public void labelNamesAreCaseInsensitive() { ++ final CloudnamePath one = new CloudnamePath(new String[] { ""FirstSecond"" }); ++ final CloudnamePath two = new CloudnamePath(new String[] { ""fIRSTsECOND"" }); ++ assertTrue(""Label names aren't case sensitive"", one.equals(two)); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void pathCanNotBeNull() { ++ new CloudnamePath(null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void pathElementsCanNotBeNull() { ++ new CloudnamePath(new String[] { null, null }); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void pathElementNamesCanNotBeInvalid() { ++ new CloudnamePath(new String[] { ""__"", ""foo"", ""bar""}); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void additionalElementsMustBeValid() { ++ new CloudnamePath(new CloudnamePath(new String[] { ""foo"" }), ""__""); ++ } ++} +diff --git a/cn-memory/README.md b/cn-memory/README.md +new file mode 100644 +index 00000000..bea9e848 +--- /dev/null ++++ b/cn-memory/README.md +@@ -0,0 +1,4 @@ ++# Memory-based backend ++ ++This backend is only suitable for testing. It will only work in a single ++VM. +diff --git a/cn-memory/pom.xml b/cn-memory/pom.xml +new file mode 100644 +index 00000000..ea56d0c7 +--- /dev/null ++++ b/cn-memory/pom.xml +@@ -0,0 +1,57 @@ ++ ++ 4.0.0 ++ ++ ++ org.cloudname ++ cloudname-parent ++ 3.0-SNAPSHOT ++ ++ ++ cn-memory ++ jar ++ ++ Cloudname Memory backend ++ Memory backend for Cloudname ++ https://github.com/Cloudname/cloudname ++ ++ ++ ++ org.cloudname ++ cn-core ++ ++ ++ ++ junit ++ junit ++ test ++ ++ ++ ++ org.hamcrest ++ hamcrest-all ++ 1.3 ++ ++ ++ ++ org.cloudname ++ testtools ++ test ++ ++ ++ ++ ++ ++ ++ ++ org.apache.maven.plugins ++ maven-surefire-plugin ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ++ ++ ++ ++ +diff --git a/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java +new file mode 100644 +index 00000000..0a869de6 +--- /dev/null ++++ b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryBackend.java +@@ -0,0 +1,270 @@ ++package org.cloudname.backends.memory; ++ ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++import org.cloudname.core.LeaseListener; ++ ++import java.util.HashMap; ++import java.util.HashSet; ++import java.util.Map; ++import java.util.Random; ++import java.util.Set; ++ ++/** ++ * Memory backend. This is the canonical implementation. The synchronization is probably not ++ * optimal but for testing this is OK. It defines the correct behaviour for backends, including ++ * calling listeners, return values and uniqueness. The actual timing of the various backends ++ * will of course vary. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class MemoryBackend implements CloudnameBackend { ++ private enum LeaseEvent { ++ CREATED, ++ REMOVED, ++ DATA ++ } ++ ++ private final Map temporaryLeases = new HashMap<>(); ++ private final Map permanentLeases = new HashMap<>(); ++ private final Map> observedTemporaryPaths = new HashMap<>(); ++ private final Map> observedPermanentPaths = new HashMap<>(); ++ private final Object syncObject = new Object(); ++ ++ /* package-private */ void removeTemporaryLease(final CloudnamePath leasePath) { ++ synchronized (syncObject) { ++ if (temporaryLeases.containsKey(leasePath)) { ++ temporaryLeases.remove(leasePath); ++ notifyTemporaryObservers(leasePath, LeaseEvent.REMOVED, null); ++ } ++ } ++ } ++ private final Random random = new Random(); ++ ++ private String createRandomInstanceName() { ++ return Long.toHexString(random.nextLong()); ++ } ++ ++ /** ++ * @param path The path that has changed ++ * @param event The event ++ * @param data The data ++ */ ++ private void notifyTemporaryObservers( ++ final CloudnamePath path, final LeaseEvent event, final String data) { ++ for (final CloudnamePath observedPath : observedTemporaryPaths.keySet()) { ++ if (observedPath.isSubpathOf(path)) { ++ for (final LeaseListener listener : observedTemporaryPaths.get(observedPath)) { ++ switch (event) { ++ case CREATED: ++ listener.leaseCreated(path, data); ++ break; ++ case REMOVED: ++ listener.leaseRemoved(path); ++ break; ++ case DATA: ++ listener.dataChanged(path, data); ++ break; ++ default: ++ throw new RuntimeException(""Don't know how to handle "" + event); ++ } ++ } ++ } ++ } ++ } ++ ++ /** ++ * Notify observers of changes ++ */ ++ private void notifyPermanentObservers( ++ final CloudnamePath path, final LeaseEvent event, final String data) { ++ for (final CloudnamePath observedPath : observedPermanentPaths.keySet()) { ++ if (observedPath.isSubpathOf(path)) { ++ for (final LeaseListener listener : observedPermanentPaths.get(observedPath)) { ++ switch (event) { ++ case CREATED: ++ listener.leaseCreated(path, data); ++ break; ++ case REMOVED: ++ listener.leaseRemoved(path); ++ break; ++ case DATA: ++ listener.dataChanged(path, data); ++ break; ++ default: ++ throw new RuntimeException(""Don't know how to handle "" + event); ++ } ++ } ++ } ++ } ++ } ++ ++ @Override ++ public boolean createPermanantLease(final CloudnamePath path, final String data) { ++ assert path != null : ""Path to lease must be set!""; ++ assert data != null : ""Lease data is required""; ++ synchronized (syncObject) { ++ if (permanentLeases.containsKey(path)) { ++ return false; ++ } ++ permanentLeases.put(path, data); ++ notifyPermanentObservers(path, LeaseEvent.CREATED, data); ++ } ++ return true; ++ } ++ ++ @Override ++ public boolean removePermanentLease(final CloudnamePath path) { ++ synchronized (syncObject) { ++ if (!permanentLeases.containsKey(path)) { ++ return false; ++ } ++ permanentLeases.remove(path); ++ notifyPermanentObservers(path, LeaseEvent.REMOVED, null); ++ } ++ return true; ++ } ++ ++ @Override ++ public boolean writePermanentLeaseData(final CloudnamePath path, String data) { ++ synchronized (syncObject) { ++ if (!permanentLeases.containsKey(path)) { ++ return false; ++ } ++ permanentLeases.put(path, data); ++ notifyPermanentObservers(path, LeaseEvent.DATA, data); ++ } ++ return true; ++ } ++ ++ @Override ++ public String readPermanentLeaseData(final CloudnamePath path) { ++ synchronized (syncObject) { ++ if (!permanentLeases.containsKey(path)) { ++ return null; ++ } ++ return permanentLeases.get(path); ++ } ++ } ++ ++ @Override ++ public boolean writeTemporaryLeaseData(final CloudnamePath path, String data) { ++ synchronized (syncObject) { ++ if (!temporaryLeases.containsKey(path)) { ++ return false; ++ } ++ temporaryLeases.put(path, data); ++ notifyTemporaryObservers(path, LeaseEvent.DATA, data); ++ } ++ return true; ++ } ++ ++ @Override ++ public String readTemporaryLeaseData(final CloudnamePath path) { ++ synchronized (syncObject) { ++ if (!temporaryLeases.containsKey(path)) { ++ return null; ++ } ++ return temporaryLeases.get(path); ++ } ++ } ++ ++ @Override ++ public LeaseHandle createTemporaryLease(final CloudnamePath path, final String data) { ++ synchronized (syncObject) { ++ final String instanceName = createRandomInstanceName(); ++ CloudnamePath instancePath = new CloudnamePath(path, instanceName); ++ while (temporaryLeases.containsKey(instancePath)) { ++ instancePath = new CloudnamePath(path, instanceName); ++ } ++ temporaryLeases.put(instancePath, data); ++ notifyTemporaryObservers(instancePath, LeaseEvent.CREATED, data); ++ return new MemoryLeaseHandle(this, instancePath); ++ } ++ } ++ ++ /** ++ * Generate created events for temporary leases for newly attached listeners. ++ */ ++ private void regenerateEventsForTemporaryListener( ++ final CloudnamePath path, final LeaseListener listener) { ++ for (final CloudnamePath temporaryPath : temporaryLeases.keySet()) { ++ if (path.isSubpathOf(temporaryPath)) { ++ listener.leaseCreated(temporaryPath, temporaryLeases.get(temporaryPath)); ++ } ++ } ++ } ++ ++ /** ++ * Generate created events on permanent leases for newly attached listeners. ++ */ ++ private void regenerateEventsForPermanentListener( ++ final CloudnamePath path, final LeaseListener listener) { ++ for (final CloudnamePath permanentPath : permanentLeases.keySet()) { ++ if (path.isSubpathOf(permanentPath)) { ++ listener.leaseCreated(permanentPath, permanentLeases.get(permanentPath)); ++ } ++ } ++ } ++ ++ @Override ++ public void addTemporaryLeaseListener( ++ final CloudnamePath pathToObserve, final LeaseListener listener) { ++ synchronized (syncObject) { ++ Set listeners = observedTemporaryPaths.get(pathToObserve); ++ if (listeners == null) { ++ listeners = new HashSet<>(); ++ } ++ listeners.add(listener); ++ observedTemporaryPaths.put(pathToObserve, listeners); ++ regenerateEventsForTemporaryListener(pathToObserve, listener); ++ } ++ } ++ ++ @Override ++ public void removeTemporaryLeaseListener(final LeaseListener listener) { ++ synchronized (syncObject) { ++ for (final Set listeners : observedTemporaryPaths.values()) { ++ if (listeners.contains(listener)) { ++ listeners.remove(listener); ++ return; ++ } ++ } ++ } ++ } ++ ++ @Override ++ public void addPermanentLeaseListener( ++ final CloudnamePath pathToObserve, final LeaseListener listener) { ++ synchronized (syncObject) { ++ Set listeners = observedPermanentPaths.get(pathToObserve); ++ if (listeners == null) { ++ listeners = new HashSet<>(); ++ } ++ listeners.add(listener); ++ observedPermanentPaths.put(pathToObserve, listeners); ++ regenerateEventsForPermanentListener(pathToObserve, listener); ++ } ++ } ++ ++ @Override ++ public void removePermanentLeaseListener(final LeaseListener listener) { ++ synchronized (syncObject) { ++ for (final Set listeners : observedPermanentPaths.values()) { ++ if (listeners.contains(listener)) { ++ listeners.remove(listener); ++ return; ++ } ++ } ++ } ++ } ++ ++ @Override ++ public void close() { ++ synchronized (syncObject) { ++ observedTemporaryPaths.clear(); ++ observedPermanentPaths.clear(); ++ } ++ } ++} +diff --git a/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java +new file mode 100644 +index 00000000..53b1e277 +--- /dev/null ++++ b/cn-memory/src/main/java/org/cloudname/backends/memory/MemoryLeaseHandle.java +@@ -0,0 +1,47 @@ ++package org.cloudname.backends.memory; ++ ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++ ++import java.io.IOException; ++import java.util.concurrent.atomic.AtomicBoolean; ++ ++/** ++ * A handle returned to clients acquiring temporary leases. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class MemoryLeaseHandle implements LeaseHandle { ++ private final MemoryBackend backend; ++ private final CloudnamePath clientLeasePath; ++ private AtomicBoolean expired = new AtomicBoolean(false); ++ ++ /** ++ * @param backend The backend issuing the lease ++ * @param clientLeasePath The path to the lease ++ */ ++ public MemoryLeaseHandle(final MemoryBackend backend, final CloudnamePath clientLeasePath) { ++ this.backend = backend; ++ this.clientLeasePath = clientLeasePath; ++ expired.set(false); ++ } ++ ++ @Override ++ public boolean writeLeaseData(String data) { ++ return backend.writeTemporaryLeaseData(clientLeasePath, data); ++ } ++ ++ @Override ++ public CloudnamePath getLeasePath() { ++ if (expired.get()) { ++ return null; ++ } ++ return clientLeasePath; ++ } ++ ++ @Override ++ public void close() throws IOException { ++ backend.removeTemporaryLease(clientLeasePath); ++ expired.set(true); ++ } ++} +diff --git a/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java b/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java +new file mode 100644 +index 00000000..acc1ad8e +--- /dev/null ++++ b/cn-memory/src/test/java/org/cloudname/backends/memory/MemoryBackendTest.java +@@ -0,0 +1,18 @@ ++package org.cloudname.backends.memory; ++ ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.testtools.backend.CoreBackendTest; ++ ++/** ++ * Test the memory backend. Since the memory backend is the reference implementation this test ++ * shouldn't fail. Ever. ++ */ ++public class MemoryBackendTest extends CoreBackendTest { ++ private static final CloudnameBackend BACKEND = new MemoryBackend(); ++ ++ @Override ++ protected CloudnameBackend getBackend() { ++ return BACKEND; ++ } ++ ++} +diff --git a/cn-service/README.md b/cn-service/README.md +new file mode 100644 +index 00000000..8cf7df15 +--- /dev/null ++++ b/cn-service/README.md +@@ -0,0 +1,107 @@ ++# Cloudname service discovery ++ ++## Coordinates ++Each service that runs is represented by a **coordinate**. There are two kinds of coordinates: ++* **Service coordinates** which are generic coordinates that points to one or more services ++* **Instance coordinates** which points to a particular service ++ ++Coordinates are specified through **regions** and **tags**. A **region** is a separate (logical) cluster of services. One region is usually not connected to another region. The simplest comparison is either a *data center* or an AWS *region* or *availability zone* (like eu-west-1, us-east-1 and so on). ++ ++The **tag** is just that - a tag that you can assign to a cluster of different services. The tag doesn't contain any particular semantics. ++ ++A **service coordinate** looks like `..`, f.e. `geolocation.rel1501.dc1` or (if you are running in AWS and have decided that you'll assume regions are availability zones) `geolocation.rel1501.eu-west-1a`. ++ ++Instance coordinates points to a particular service instance and looks like this: `...`. For the examples above the instance coordinates might look like `ff08f0ah.geolocation.rel1501.dc1` or `ab08bed5.geolocation.rel1501.eu-west-1a`. ++ ++The instance identifier is an unique identifier for that instance. Note that the instance identifier isn't unique across all services, isn't sequential and does not carry any semantic information. ++ ++## Register a service ++A service is registered through the `CloudnameService` class: ++```java ++// Create the service class. Note that getBackend() returns a Cloudname backend ++// instance. There ar multiple types available. ++try (CloudnameService cloudnameService = new CloudnameService(getBackend())) { ++ // Create the coordinate and endpoint ++ ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(""myservice.demo.local""); ++ Endpoint httpEndpoint = new Endpoint(""http"", ""127.0.0.1"", 80); ++ ++ ServiceData serviceData = new ServiceData(Arrays.asList(httpEndpoint)); ++ ++ // This will register the service. The returned handle will expose the registration ++ // to other clients until it is closed. ++ try (ServiceHandle handle = cloudnameService.registerService(serviceCoordinate, serviceData)) { ++ ++ // ...Run your service here ++ ++ } ++} ++``` ++ ++## Looking up services ++Services can be located without registering a service; supply a listener to the CloudnameService instance to get notified of new services: ++```java ++CloudnameService cloudnameService = new CloudnameService(getBackend()); ++ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(""myservice.demo.local""); ++cloudnameService.addServiceListener(ServiceCoordinate, new ServiceListener() { ++ @Override ++ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) { ++ // A new instance is launched. Retrieve the endpoints via the data parameter. ++ // Note that this method is also called when the listener is set so you'll ++ // get notifications on already existing services as well. ++ } ++ ++ @Override ++ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) { ++ // There's a change in endpoints for the given instance. The updated endpoints ++ // are supplied in the data parameter ++ } ++ ++ @Override ++ public void onServiceRemoved(final InstanceCoordinate coordinate) { ++ // One of the instances is stopped. It might become unavailable shortly ++ // (or it might have terminated) ++ } ++}); ++``` ++ ++## Permanent services ++Some resources might not be suitable for service discovery, either because they are not under your control, they are pet services or not designed for cloud-like behavior (aka ""pet servers""). You can still use those in service discovery; just add them as *permanent services*. Permanent services behave a bit differently from ordinary services; they stay alive for long periods of time and on some rare occasions they change their endpoint. Registering permanent services are similar to ordinary services. The following snippet registers a permanent service, then terminates. The service registration will still be available to other clients when this client has terminated: ++ ++```java ++try (CloudnameService cloudnameService = new CloudnameService(getBackend())) { ++ ServiceCoordinate coordinate = ServiceCoordinate.parse(""mydb.demo.local""); ++ Endpoint endpoint = new Endpoint(""db"", ""127.0.0.1"", 5678); ++ ++ if (!cloudnameService.createPermanentService(coordinate, endpoint)) { ++ System.out.println(""Couldn't register permanent service!""); ++ } ++} ++``` ++Note that permanent services can not have more than one endpoint registered at any time. A permanent service registration applies only to *one* service at a time. ++ ++Looking up permanent service registrations is similar to ordinary services: ++ ++```java ++try (CloudnameService cloudnameService = new CloudnameService(getBackend())) { ++ ServiceCoordinate coordinate = ServiceCoordinate.parse(""mydb.demo.local""); ++ cloudnameService.addPermanentServiceListener(coordinate, ++ new PermanentServiceListener() { ++ @Override ++ public void onServiceCreated(Endpoint endpoint) { ++ // Service is created. Note that this is also called when the ++ // listener is set so you'll get notifications on already ++ // existing services as well. ++ } ++ ++ @Override ++ public void onServiceChanged(Endpoint endpoint) { ++ // The endpoint is updated ++ } ++ ++ @Override ++ public void onServiceRemoved() { ++ // The service has been removed ++ } ++ }); ++} ++``` +diff --git a/cn-service/pom.xml b/cn-service/pom.xml +new file mode 100644 +index 00000000..f3788ed2 +--- /dev/null ++++ b/cn-service/pom.xml +@@ -0,0 +1,63 @@ ++ ++ 4.0.0 ++ ++ ++ org.cloudname ++ cloudname-parent ++ 3.0-SNAPSHOT ++ ++ ++ cn-service ++ jar ++ ++ Cloudname Service Discovery ++ Simple library for service discovery (and notifications) ++ https://github.com/Cloudname/cloudname ++ ++ ++ ++ org.cloudname ++ cn-core ++ ++ ++ ++ junit ++ junit ++ test ++ ++ ++ ++ org.hamcrest ++ hamcrest-all ++ 1.3 ++ ++ ++ ++ org.json ++ json ++ 20140107 ++ ++ ++ ++ org.cloudname ++ cn-memory ++ test ++ ++ ++ ++ ++ ++ ++ ++ org.apache.maven.plugins ++ maven-surefire-plugin ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ++ ++ ++ ++ +diff --git a/cn-service/src/main/java/org/cloudname/service/CloudnameService.java b/cn-service/src/main/java/org/cloudname/service/CloudnameService.java +new file mode 100644 +index 00000000..9c4747f4 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/CloudnameService.java +@@ -0,0 +1,237 @@ ++package org.cloudname.service; ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++import org.cloudname.core.LeaseListener; ++ ++import java.util.ArrayList; ++import java.util.List; ++import java.util.Set; ++import java.util.concurrent.CopyOnWriteArraySet; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++ ++/** ++ * Service discovery implementation. Use registerService() and addServiceListener() to register ++ * and locate services. ++ * ++ * TODO: Enable lookups based on partial coordinates. Create builder for service coordinates, ++ * use own coordinate to resolve complete coordinate. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class CloudnameService implements AutoCloseable { ++ private final Logger LOG = Logger.getLogger(CloudnameService.class.getName()); ++ ++ private final CloudnameBackend backend; ++ private final List handles = new ArrayList<>(); ++ private final List temporaryListeners = new ArrayList<>(); ++ private final List permanentListeners = new ArrayList<>(); ++ private final Set permanentUpdatesInProgress = new CopyOnWriteArraySet<>(); ++ private final Object syncObject = new Object(); ++ ++ /** ++ * @oaram backend backend implementation to use ++ * @throws IllegalArgumentException if parameter is invalid ++ */ ++ public CloudnameService(final CloudnameBackend backend) { ++ if (backend == null) { ++ throw new IllegalArgumentException(""Backend can not be null""); ++ } ++ this.backend = backend; ++ } ++ ++ /** ++ * Register an instance with the given service coordinate. The service will get its own ++ * instance coordinate under the given service coordinate. ++ * ++ * @param serviceCoordinate The service coordinate that the service (instance) will attach to ++ * @param serviceData Service data for the instance ++ * @return ServiceHandle a handle the client can use to manage the endpoints for the service. ++ * The most typical use case is to register all endpoints ++ * @throws IllegalArgumentException if the parameters are invalid ++ */ ++ public ServiceHandle registerService( ++ final ServiceCoordinate serviceCoordinate, final ServiceData serviceData) { ++ ++ if (serviceCoordinate == null) { ++ throw new IllegalArgumentException(""Coordinate cannot be null""); ++ } ++ if (serviceData == null) { ++ throw new IllegalArgumentException(""Service Data cannot be null""); ++ } ++ final LeaseHandle leaseHandle = backend.createTemporaryLease( ++ serviceCoordinate.toCloudnamePath(), serviceData.toJsonString()); ++ ++ final ServiceHandle serviceHandle = new ServiceHandle( ++ new InstanceCoordinate(leaseHandle.getLeasePath()), serviceData, leaseHandle); ++ ++ synchronized (syncObject) { ++ handles.add(serviceHandle); ++ } ++ return serviceHandle; ++ } ++ ++ /** ++ * Add listener for service events. This only applies to ordinary services. ++ * ++ * @param coordinate The coordinate to monitor. ++ * @param listener Listener getting notifications on changes. ++ * @throws IllegalArgumentException if parameters are invalid ++ */ ++ public void addServiceListener( ++ final ServiceCoordinate coordinate, final ServiceListener listener) { ++ if (coordinate == null) { ++ throw new IllegalArgumentException(""Coordinate can not be null""); ++ } ++ if (listener == null) { ++ throw new IllegalArgumentException(""Listener can not be null""); ++ } ++ // Just create the corresponding listener on the backend and translate the parameters ++ // from the listener. ++ final LeaseListener leaseListener = new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path); ++ final ServiceData serviceData = ServiceData.fromJsonString(data); ++ listener.onServiceCreated(instanceCoordinate, serviceData); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path); ++ listener.onServiceRemoved(instanceCoordinate); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ final InstanceCoordinate instanceCoordinate = new InstanceCoordinate(path); ++ final ServiceData serviceData = ServiceData.fromJsonString(data); ++ listener.onServiceDataChanged(instanceCoordinate, serviceData); ++ } ++ }; ++ synchronized (syncObject) { ++ temporaryListeners.add(leaseListener); ++ } ++ backend.addTemporaryLeaseListener(coordinate.toCloudnamePath(), leaseListener); ++ } ++ ++ /** ++ * Create a permanent service. The service registration will be kept when the client exits. The ++ * service will have a single endpoint. ++ */ ++ public boolean createPermanentService( ++ final ServiceCoordinate coordinate, final Endpoint endpoint) { ++ if (coordinate == null) { ++ throw new IllegalArgumentException(""Service coordinate can't be null""); ++ } ++ if (endpoint == null) { ++ throw new IllegalArgumentException(""Endpoint can't be null""); ++ } ++ ++ return backend.createPermanantLease(coordinate.toCloudnamePath(), endpoint.toJsonString()); ++ } ++ ++ /** ++ * Update permanent service coordinate. Note that this is a non-atomic operation with multiple ++ * trips to the backend system. The update is done in two operations; one delete and one ++ * create. If the delete operation fail and the create operation succeeds it might end up ++ * removing the permanent service coordinate. Clients will not be notified of the removal. ++ */ ++ public boolean updatePermanentService( ++ final ServiceCoordinate coordinate, final Endpoint endpoint) { ++ if (coordinate == null) { ++ throw new IllegalArgumentException(""Coordinate can't be null""); ++ } ++ if (endpoint == null) { ++ throw new IllegalArgumentException(""Endpoint can't be null""); ++ } ++ ++ if (permanentUpdatesInProgress.contains(coordinate)) { ++ LOG.log(Level.WARNING, ""Attempt to update a permanent service which is already"" ++ + "" updating. (coordinate: "" + coordinate + "", endpoint: "" + endpoint); ++ return false; ++ } ++ // Check if the endpoint name still matches. ++ final String data = backend.readPermanentLeaseData(coordinate.toCloudnamePath()); ++ if (data == null) { ++ return false; ++ } ++ final Endpoint oldEndpoint = Endpoint.fromJson(data); ++ if (!oldEndpoint.getName().equals(endpoint.getName())) { ++ LOG.log(Level.INFO, ""Rejecting attempt to update permanent service with a new endpoint"" ++ + "" that has a different name. Old name: "" + oldEndpoint + "" new: "" + endpoint); ++ return false; ++ } ++ permanentUpdatesInProgress.add(coordinate); ++ try { ++ return backend.writePermanentLeaseData( ++ coordinate.toCloudnamePath(), endpoint.toJsonString()); ++ } catch (final RuntimeException ex) { ++ LOG.log(Level.WARNING, ""Got exception updating permanent lease. The system might be in"" ++ + "" an indeterminate state"", ex); ++ return false; ++ } finally { ++ permanentUpdatesInProgress.remove(coordinate); ++ } ++ } ++ ++ /** ++ * Remove a perviously registered permanent service. Needless to say: Use with caution. ++ */ ++ public boolean removePermanentService(final ServiceCoordinate coordinate) { ++ if (coordinate == null) { ++ throw new IllegalArgumentException(""Coordinate can not be null""); ++ } ++ return backend.removePermanentLease(coordinate.toCloudnamePath()); ++ } ++ ++ /** ++ * Listen for changes in permanent services. The changes are usually of the earth-shattering ++ * variety so as a client you'd be interested in knowing about these as soon as possible. ++ */ ++ public void addPermanentServiceListener( ++ final ServiceCoordinate coordinate, final PermanentServiceListener listener) { ++ if (coordinate == null) { ++ throw new IllegalArgumentException(""Coordinate can not be null""); ++ } ++ if (listener == null) { ++ throw new IllegalArgumentException(""Listener can not be null""); ++ } ++ final LeaseListener leaseListener = new LeaseListener() { ++ @Override ++ public void leaseCreated(CloudnamePath path, String data) { ++ listener.onServiceCreated(Endpoint.fromJson(data)); ++ } ++ ++ @Override ++ public void leaseRemoved(CloudnamePath path) { ++ listener.onServiceRemoved(); ++ } ++ ++ @Override ++ public void dataChanged(CloudnamePath path, String data) { ++ listener.onServiceChanged(Endpoint.fromJson(data)); ++ } ++ }; ++ synchronized (syncObject) { ++ permanentListeners.add(leaseListener); ++ } ++ backend.addPermanentLeaseListener(coordinate.toCloudnamePath(), leaseListener); ++ } ++ ++ @Override ++ public void close() { ++ synchronized (syncObject) { ++ for (final ServiceHandle handle : handles) { ++ handle.close(); ++ } ++ for (final LeaseListener listener : temporaryListeners) { ++ backend.removeTemporaryLeaseListener(listener); ++ } ++ for (final LeaseListener listener : permanentListeners) { ++ backend.removePermanentLeaseListener(listener); ++ } ++ } ++ } ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/Endpoint.java b/cn-service/src/main/java/org/cloudname/service/Endpoint.java +new file mode 100644 +index 00000000..d20371fd +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/Endpoint.java +@@ -0,0 +1,114 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++import org.json.JSONObject; ++ ++/** ++ * Endpoints exposed by services. Endpoints contains host address and port number. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class Endpoint { ++ private final String name; ++ private final String host; ++ private final int port; ++ ++ /** ++ * @param name Name of endpoint. Must conform to RFC 952 and RFC 1123, ++ * ie [a-z,0-9,-] ++ * @param host Host name or IP address ++ * @param port Port number (1- max port number) ++ * @throws IllegalArgumentException if one of the parameters are null (name/host) or zero (port) ++ */ ++ public Endpoint(final String name, final String host, final int port) { ++ if (name == null || name.isEmpty()) { ++ throw new IllegalArgumentException(""Name can not be null or empty""); ++ } ++ if (host == null || host.isEmpty()) { ++ throw new IllegalArgumentException(""Host can not be null or empty""); ++ } ++ if (port < 1) { ++ throw new IllegalArgumentException(""Port can not be < 1""); ++ } ++ if (!CloudnamePath.isValidPathElementName(name)) { ++ throw new IllegalArgumentException(""Name is not a valid identifier""); ++ } ++ ++ this.name = name; ++ this.host = host; ++ this.port = port; ++ } ++ ++ /** ++ * @return The endpoint's name ++ */ ++ public String getName() { ++ return name; ++ } ++ ++ /** ++ * @return The endpoint's host name or IP address ++ */ ++ public String getHost() { ++ return host; ++ } ++ ++ /** ++ * @return The endpoint's port number ++ */ ++ public int getPort() { ++ return port; ++ } ++ ++ /** ++ * @return JSON representation of isntance ++ */ ++ /* package-private */ String toJsonString() { ++ return new JSONObject() ++ .put(""name"", name) ++ .put(""host"", host) ++ .put(""port"", port) ++ .toString(); ++ } ++ ++ /** ++ * @param jsonString String with JSON representation of instance ++ * @return Endpoint instance ++ * @throws org.json.JSONException if the string is malformed. ++ */ ++ /* package-private */ static Endpoint fromJson(final String jsonString) { ++ final JSONObject json = new JSONObject(jsonString); ++ return new Endpoint( ++ json.getString(""name""), ++ json.getString(""host""), ++ json.getInt(""port"")); ++ } ++ ++ @Override ++ public boolean equals(final Object o) { ++ if (o == null || !(o instanceof Endpoint)) { ++ return false; ++ } ++ final Endpoint other = (Endpoint) o; ++ ++ if (!this.name.equals(other.name) ++ || !this.host.equals(other.host) ++ || this.port != other.port) { ++ return false; ++ } ++ return true; ++ } ++ ++ @Override ++ public int hashCode() { ++ return this.toString().hashCode(); ++ } ++ ++ @Override ++ public String toString() { ++ return ""[ name = "" + name ++ + "", host = "" + host ++ + "", port = "" + port ++ + ""]""; ++ } ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java b/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java +new file mode 100644 +index 00000000..7d219357 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/InstanceCoordinate.java +@@ -0,0 +1,146 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++import org.json.JSONObject; ++ ++import java.util.regex.Matcher; ++import java.util.regex.Pattern; ++ ++/** ++ * A coordinate representing a running service. The coordinate consists of four parts; instance id, ++ * service name, tag and region. ++ * ++ * Note that the order of elements in the string representation is opposite of the CloudnamePath ++ * class; you can't create a canonical representation of the instance coordinate by calling join() ++ * on the CloudnamePath instance. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class InstanceCoordinate { ++ private static final Pattern COORDINATE_PATTERN = Pattern.compile(""(.*)\\.(.*)\\.(.*)\\.(.*)""); ++ private static final String REGION_NAME = ""region""; ++ private static final String TAG_NAME = ""tag""; ++ private static final String SERVICE_NAME = ""service""; ++ private static final String INSTANCE_NAME = ""instance""; ++ ++ ++ private final String region; ++ private final String tag; ++ private final String service; ++ private final String instance; ++ ++ /** ++ * @param path CloudnamePath instance to use as source ++ * @throws IllegalArgumentException if parameters are invalid ++ */ ++ /* package-private */ InstanceCoordinate(final CloudnamePath path) { ++ if (path == null) { ++ throw new IllegalArgumentException(""Path can not be null""); ++ } ++ if (path.length() != 4) { ++ throw new IllegalArgumentException(""Path must contain 4 elements""); ++ } ++ this.region = path.get(0); ++ this.tag = path.get(1); ++ this.service = path.get(2); ++ this.instance = path.get(3); ++ } ++ ++ /** ++ * @return The region of the coordinate ++ */ ++ public String getRegion() { ++ return region; ++ } ++ ++ /** ++ * @return The tag of the coordinate ++ */ ++ public String getTag() { ++ return tag; ++ } ++ ++ /** ++ * @return The service name ++ */ ++ public String getService() { ++ return service; ++ } ++ ++ /** ++ * @return The instance identifier ++ */ ++ public String getInstance() { ++ return instance; ++ } ++ ++ /** ++ * @return A CloudnamePath instance representing this coordinate ++ */ ++ /* package-private */ CloudnamePath toCloudnamePath() { ++ return new CloudnamePath( ++ new String[] { this.region, this.tag, this.service, this.instance }); ++ } ++ ++ /** ++ * @return Canonical string representation of coordinate ++ */ ++ public String toCanonicalString() { ++ return new StringBuffer() ++ .append(instance).append(""."") ++ .append(service).append(""."") ++ .append(tag).append(""."") ++ .append(region) ++ .toString(); ++ } ++ ++ /** ++ * @return Coordinate represented as a JSON-formatted string ++ */ ++ /* package-private */ String toJsonString() { ++ return new JSONObject() ++ .put(REGION_NAME, this.region) ++ .put(TAG_NAME, this.tag) ++ .put(SERVICE_NAME, this.service) ++ .put(INSTANCE_NAME, this.instance) ++ .toString(); ++ } ++ ++ /** ++ * @param jsonString A coordinate serialized as a JSON-formatted string ++ * @return InstanceCoordinate built from the string ++ */ ++ /* package-private */ static InstanceCoordinate fromJson(final String jsonString) { ++ final JSONObject object = new JSONObject(jsonString); ++ final String[] pathElements = new String[4]; ++ pathElements[0] = object.getString(REGION_NAME); ++ pathElements[1] = object.getString(TAG_NAME); ++ pathElements[2] = object.getString(SERVICE_NAME); ++ pathElements[3] = object.getString(INSTANCE_NAME); ++ ++ return new InstanceCoordinate(new CloudnamePath(pathElements)); ++ } ++ ++ /** ++ * @param string A canonical string representation of a coordinate ++ * @return InstanceCoordinate built from the string ++ */ ++ public static InstanceCoordinate parse(final String string) { ++ if (string == null) { ++ return null; ++ } ++ final Matcher matcher = COORDINATE_PATTERN.matcher(string); ++ if (!matcher.matches()) { ++ return null; ++ } ++ final String[] path = new String[] { ++ matcher.group(4), matcher.group(3), matcher.group(2), matcher.group(1) ++ }; ++ return new InstanceCoordinate(new CloudnamePath(path)); ++ } ++ ++ @Override ++ public String toString() { ++ return ""[ Coordinate "" + toCanonicalString() + ""]""; ++ } ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java b/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java +new file mode 100644 +index 00000000..5d644b89 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/PermanentServiceListener.java +@@ -0,0 +1,25 @@ ++package org.cloudname.service; ++ ++/** ++ * Listener interface for permanent services. ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface PermanentServiceListener { ++ /** ++ * A service is created. This method will be called on start-up for all existing services. ++ * @param endpoint The endpoint of the service ++ */ ++ void onServiceCreated(final Endpoint endpoint); ++ ++ /** ++ * Service endpoint has changed. ++ * @param endpoint The new value of the service endpoint ++ */ ++ void onServiceChanged(final Endpoint endpoint); ++ ++ /** ++ * Service has been removed. ++ */ ++ void onServiceRemoved(); ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java b/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java +new file mode 100644 +index 00000000..02a74637 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/ServiceCoordinate.java +@@ -0,0 +1,107 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++ ++import java.util.regex.Matcher; ++import java.util.regex.Pattern; ++ ++/** ++ * A coordinate pointing to a set of services or a single permanent service. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class ServiceCoordinate { ++ private final String region; ++ private final String tag; ++ private final String service; ++ ++ // Pattern for string parsing ++ private static final Pattern COORDINATE_PATTERN = Pattern.compile(""(.*)\\.(.*)\\.(.*)""); ++ ++ /** ++ * @param path The CloudnamePath instance to use when building the coordinate. The coordinate ++ * must consist of three elements and can not be null. ++ * @throws IllegalArgumentException if parameter is invalid ++ */ ++ /* package-private */ ServiceCoordinate(final CloudnamePath path) { ++ if (path == null) { ++ throw new IllegalArgumentException(""Path can not be null""); ++ } ++ if (path.length() != 3) { ++ throw new IllegalArgumentException(""Path must have three elements""); ++ } ++ region = path.get(0); ++ tag = path.get(1); ++ service = path.get(2); ++ } ++ ++ /** ++ * @return The coordinate's region ++ */ ++ public String getRegion() { ++ return region; ++ } ++ ++ /** ++ * @return The coordinate's tag ++ */ ++ public String getTag() { ++ return tag; ++ } ++ ++ /** ++ * @return The coordinate's service name ++ */ ++ public String getService() { ++ return service; ++ } ++ ++ /** ++ * @param serviceCoordinateString String representation of coordinate ++ * @return ServiceCoordinate instance built from the string. Null if the coordinate ++ * can't be parsed correctly. ++ */ ++ public static ServiceCoordinate parse(final String serviceCoordinateString) { ++ final Matcher matcher = COORDINATE_PATTERN.matcher(serviceCoordinateString); ++ if (!matcher.matches()) { ++ return null; ++ } ++ final String[] path = new String[] { matcher.group(3), matcher.group(2), matcher.group(1) }; ++ return new ServiceCoordinate(new CloudnamePath(path)); ++ } ++ ++ /** ++ * @return CloudnamePath representing this coordinate ++ */ ++ /* package-private */ CloudnamePath toCloudnamePath() { ++ return new CloudnamePath(new String[] { this.region, this.tag, this.service }); ++ } ++ ++ @Override ++ public boolean equals(final Object o) { ++ if (this == o) { ++ return true; ++ } ++ if (o == null || getClass() != o.getClass()) { ++ return false; ++ } ++ ++ final ServiceCoordinate other = (ServiceCoordinate) o; ++ ++ if (!this.region.equals(other.region) ++ || !this.tag.equals(other.tag) ++ || !this.service.equals(other.service)) { ++ return false; ++ } ++ return true; ++ } ++ ++ @Override ++ public int hashCode() { ++ int result = region.hashCode(); ++ result = 31 * result + tag.hashCode(); ++ result = 31 * result + service.hashCode(); ++ return result; ++ } ++ ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceData.java b/cn-service/src/main/java/org/cloudname/service/ServiceData.java +new file mode 100644 +index 00000000..dec36ea1 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/ServiceData.java +@@ -0,0 +1,123 @@ ++package org.cloudname.service; ++ ++import org.json.JSONArray; ++import org.json.JSONObject; ++ ++import java.util.ArrayList; ++import java.util.HashMap; ++import java.util.List; ++import java.util.Map; ++ ++/** ++ * Service data stored for each service. This data only contains endpoints at the moment. Endpoint ++ * names must be unique. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class ServiceData { ++ private final Object syncObject = new Object(); ++ private final Map endpoints = new HashMap<>(); ++ ++ /** ++ * Create empty service data object with no endpoints. ++ */ ++ public ServiceData() { ++ ++ } ++ ++ /** ++ * Create a new instance with the given list of endpoints. If there's duplicates in the list ++ * the duplicates will be discarded. ++ * ++ * @param endpointList List of endpoints to add ++ */ ++ /* package-private */ ServiceData(final List endpointList) { ++ synchronized (syncObject) { ++ for (final Endpoint endpoint : endpointList) { ++ endpoints.put(endpoint.getName(), endpoint); ++ } ++ } ++ } ++ ++ /** ++ * @param name Name of endpoint ++ * @return The endpoint with the specified name. Null if the endpoint doesn't exist ++ */ ++ public Endpoint getEndpoint(final String name) { ++ synchronized (syncObject) { ++ for (final String epName : endpoints.keySet()) { ++ if (epName.equals(name)) { ++ return endpoints.get(name); ++ } ++ } ++ } ++ return null; ++ } ++ ++ /** ++ * @param endpoint Endpoint to add ++ * @return true if endpoint can be added. False if the endpoint already exists. ++ * @throws IllegalArgumentException if endpoint is invalid ++ */ ++ public boolean addEndpoint(final Endpoint endpoint) { ++ if (endpoint == null) { ++ throw new IllegalArgumentException(""Endpoint can not be null""); ++ } ++ synchronized (syncObject) { ++ if (endpoints.containsKey(endpoint.getName())) { ++ return false; ++ } ++ endpoints.put(endpoint.getName(), endpoint); ++ } ++ return true; ++ } ++ ++ /** ++ * @param endpoint endpoint to remove ++ * @return True if the endpoint has been removed, false if the endpoint can't be removed. Nulls ++ * @throws IllegalArgumentException if endpoint is invalid ++ */ ++ public boolean removeEndpoint(final Endpoint endpoint) { ++ if (endpoint == null) { ++ throw new IllegalArgumentException(""Endpoint can't be null""); ++ } ++ synchronized (syncObject) { ++ if (!endpoints.containsKey(endpoint.getName())) { ++ return false; ++ } ++ endpoints.remove(endpoint.getName()); ++ } ++ return true; ++ } ++ ++ /** ++ * @return Service data serialized as a JSON string ++ */ ++ /* package-private */ String toJsonString() { ++ final JSONArray epList = new JSONArray(); ++ int i = 0; ++ for (Map.Entry entry : endpoints.entrySet()) { ++ epList.put(i++, new JSONObject(entry.getValue().toJsonString())); ++ } ++ return new JSONObject().put(""endpoints"", epList).toString(); ++ } ++ ++ /** ++ * @param jsonString JSON string to create instance from ++ * @throws IllegalArgumentException if parameter is invalid ++ */ ++ /* package-private */ static ServiceData fromJsonString(final String jsonString) { ++ if (jsonString == null || jsonString.isEmpty()) { ++ throw new IllegalArgumentException(""json string can not be null or empty""); ++ } ++ ++ final List endpoints = new ArrayList<>(); ++ ++ final JSONObject json = new JSONObject(jsonString); ++ final JSONArray epList = json.getJSONArray(""endpoints""); ++ for (int i = 0; i < epList.length(); i++) { ++ endpoints.add(Endpoint.fromJson(epList.getJSONObject(i).toString())); ++ } ++ return new ServiceData(endpoints); ++ } ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java b/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java +new file mode 100644 +index 00000000..a9305bb2 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/ServiceHandle.java +@@ -0,0 +1,75 @@ ++package org.cloudname.service; ++import org.cloudname.core.LeaseHandle; ++ ++import java.util.logging.Level; ++import java.util.logging.Logger; ++ ++/** ++ * A handle to a service registration. The handle is used to modify the registered endpoints. The ++ * state is kept in the ServiceData instance held by the handle. Note that endpoints in the ++ * ServiceData instance isn't registered automatically when the handle is created. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class ServiceHandle implements AutoCloseable { ++ private static final Logger LOG = Logger.getLogger(ServiceHandle.class.getName()); ++ private final LeaseHandle leaseHandle; ++ private final InstanceCoordinate instanceCoordinate; ++ private final ServiceData serviceData; ++ ++ /** ++ * @param instanceCoordinate The instance coordinate this handle belongs to ++ * @param serviceData The service data object ++ * @param leaseHandle The Cloudname handle for the lease ++ * @throws IllegalArgumentException if parameters are invalid ++ */ ++ public ServiceHandle( ++ final InstanceCoordinate instanceCoordinate, ++ final ServiceData serviceData, ++ final LeaseHandle leaseHandle) { ++ if (instanceCoordinate == null) { ++ throw new IllegalArgumentException(""Instance coordinate cannot be null""); ++ } ++ if (serviceData == null) { ++ throw new IllegalArgumentException(""Service data must be set""); ++ } ++ if (leaseHandle == null) { ++ throw new IllegalArgumentException(""Lease handle cannot be null""); ++ } ++ this.leaseHandle = leaseHandle; ++ this.instanceCoordinate = instanceCoordinate; ++ this.serviceData = serviceData; ++ } ++ ++ /** ++ * @param endpoint The endpoint to register ++ * @return true if endpoint is registered ++ */ ++ boolean registerEndpoint(final Endpoint endpoint) { ++ if (!serviceData.addEndpoint(endpoint)) { ++ return false; ++ } ++ return this.leaseHandle.writeLeaseData(serviceData.toJsonString()); ++ } ++ ++ /** ++ * @param endpoint The endpoint to remove ++ * @return true if endpoint is removed ++ */ ++ boolean removeEndpoint(final Endpoint endpoint) { ++ if (!serviceData.removeEndpoint(endpoint)) { ++ return false; ++ } ++ return this.leaseHandle.writeLeaseData(serviceData.toJsonString()); ++ } ++ ++ @Override ++ public void close() { ++ try { ++ leaseHandle.close(); ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got exception closing lease for instance "" ++ + instanceCoordinate.toCanonicalString(), ex); ++ } ++ } ++} +diff --git a/cn-service/src/main/java/org/cloudname/service/ServiceListener.java b/cn-service/src/main/java/org/cloudname/service/ServiceListener.java +new file mode 100644 +index 00000000..ac36e6c8 +--- /dev/null ++++ b/cn-service/src/main/java/org/cloudname/service/ServiceListener.java +@@ -0,0 +1,33 @@ ++package org.cloudname.service; ++ ++/** ++ * Listener interface for services. ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface ServiceListener { ++ /** ++ * Service is created. Note that this method is called once for every service that already ++ * exists when the listener is attached. ++ * ++ * @param coordinate Coordinate of instance ++ * @param serviceData The instance's data, ie its endpoints ++ */ ++ void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData serviceData); ++ ++ /** ++ * Service's data have changed. ++ * @param coordinate Coordinate of instance ++ * @param data The instance's data ++ */ ++ void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data); ++ ++ /** ++ * Instance is removed. This means that the service has either closed its connection to ++ * the Cloudname backend or it has become unavailable for some other reason (f.e. caused ++ * by a network partition) ++ * ++ * @param coordinate The instance's coordinate ++ */ ++ void onServiceRemoved(final InstanceCoordinate coordinate); ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java b/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java +new file mode 100644 +index 00000000..d819931c +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/CloudnameServicePermanentTest.java +@@ -0,0 +1,261 @@ ++package org.cloudname.service; ++ ++import org.cloudname.backends.memory.MemoryBackend; ++import org.cloudname.core.CloudnameBackend; ++import org.junit.AfterClass; ++import org.junit.BeforeClass; ++import org.junit.Test; ++ ++import java.util.concurrent.CountDownLatch; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicInteger; ++ ++import static org.hamcrest.CoreMatchers.is; ++import static org.junit.Assert.assertThat; ++import static org.junit.Assert.assertTrue; ++import static org.junit.Assert.fail; ++ ++/** ++ * Test persistent services functions. ++ */ ++public class CloudnameServicePermanentTest { ++ private static final String SERVICE_COORDINATE = ""myoldskoolserver.test.local""; ++ private static final CloudnameBackend memoryBackend = new MemoryBackend(); ++ private static final Endpoint DEFAULT_ENDPOINT = new Endpoint(""serviceport"", ""localhost"", 80); ++ private final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(SERVICE_COORDINATE); ++ ++ @BeforeClass ++ public static void createServiceRegistration() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ assertThat( ++ cloudnameService.createPermanentService( ++ ServiceCoordinate.parse(SERVICE_COORDINATE), DEFAULT_ENDPOINT), ++ is(true)); ++ } ++ } ++ ++ @Test ++ public void testPersistentServiceChanges() throws InterruptedException { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ ++ final CountDownLatch callCounter = new CountDownLatch(2); ++ final int secondsToWait = 1; ++ ++ // ...a listener on the service will trigger when there's a change plus the initial ++ // onCreate call. ++ cloudnameService.addPermanentServiceListener(serviceCoordinate, ++ new PermanentServiceListener() { ++ private final AtomicInteger createCount = new AtomicInteger(0); ++ private final AtomicInteger changeCount = new AtomicInteger(0); ++ ++ @Override ++ public void onServiceCreated(Endpoint endpoint) { ++ // Expect this to be called once and only once, even on updates ++ assertThat(createCount.incrementAndGet(), is(1)); ++ callCounter.countDown(); ++ } ++ ++ @Override ++ public void onServiceChanged(Endpoint endpoint) { ++ // This will be called when the endpoint changes ++ assertThat(changeCount.incrementAndGet(), is(1)); ++ callCounter.countDown(); ++ } ++ ++ @Override ++ public void onServiceRemoved() { ++ // This won't be called ++ fail(""Did not expect onServiceRemoved to be called""); ++ } ++ }); ++ ++ // Updating with invalid endpoint name fails ++ assertThat(cloudnameService.updatePermanentService(serviceCoordinate, ++ new Endpoint(""wrongep"", DEFAULT_ENDPOINT.getHost(), 81)), ++ is(false)); ++ ++ // Using the right one, however, does work ++ assertThat(cloudnameService.updatePermanentService(serviceCoordinate, ++ new Endpoint( ++ DEFAULT_ENDPOINT.getName(), DEFAULT_ENDPOINT.getHost(), 81)), ++ is(true)); ++ // Wait for notifications ++ callCounter.await(secondsToWait, TimeUnit.SECONDS); ++ ++ } ++ ++ // At this point the service created above is closed; changes to the service won't ++ // trigger errors in the listener declared. Just do one change to make sure. ++ final CloudnameService cloudnameService = new CloudnameService(memoryBackend); ++ assertThat(cloudnameService.updatePermanentService( ++ ServiceCoordinate.parse(SERVICE_COORDINATE), DEFAULT_ENDPOINT), is(true)); ++ } ++ ++ @Test ++ public void testDuplicateRegistration() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ // Creating the same permanent service will fail ++ assertThat(""Can't create two identical permanent services"", ++ cloudnameService.createPermanentService(serviceCoordinate, DEFAULT_ENDPOINT), ++ is(false)); ++ } ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testNullCoordinateRegistration() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ cloudnameService.createPermanentService(null, DEFAULT_ENDPOINT); ++ } ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testInvalidEndpoint() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ cloudnameService.createPermanentService(serviceCoordinate, null); ++ } ++ } ++ ++ @Test ++ public void testListenerOnServiceThatDoesntExist() throws InterruptedException { ++ final String anotherServiceCoordinate = ""someother.service.coordinate""; ++ ++ // It should be possible to listen for a permanent service that doesn't exist yet. Once the ++ // service is created it must trigger a callback to the clients listening. ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ ++ final CountDownLatch createCalls = new CountDownLatch(1); ++ final CountDownLatch removeCalls = new CountDownLatch(1); ++ final CountDownLatch updateCalls = new CountDownLatch(1); ++ ++ cloudnameService.addPermanentServiceListener( ++ ServiceCoordinate.parse(anotherServiceCoordinate), ++ new PermanentServiceListener() { ++ final AtomicInteger order = new AtomicInteger(0); ++ @Override ++ public void onServiceCreated(Endpoint endpoint) { ++ createCalls.countDown(); ++ assertThat(order.incrementAndGet(), is(1)); ++ } ++ ++ @Override ++ public void onServiceChanged(Endpoint endpoint) { ++ updateCalls.countDown(); ++ assertThat(order.incrementAndGet(), is(2)); ++ } ++ ++ @Override ++ public void onServiceRemoved() { ++ removeCalls.countDown(); ++ assertThat(order.incrementAndGet(), is(3)); ++ } ++ }); ++ ++ // Create the new service registration, change the endpoint, then remove it. The ++ // count down latches should count down and the order should be create, change, remove ++ final ServiceCoordinate another = ServiceCoordinate.parse(anotherServiceCoordinate); ++ cloudnameService.createPermanentService(another, DEFAULT_ENDPOINT); ++ cloudnameService.updatePermanentService(another, ++ new Endpoint(DEFAULT_ENDPOINT.getName(), ""otherhost"", 4711)); ++ cloudnameService.removePermanentService(another); ++ ++ final int secondsToWait = 1; ++ assertTrue(""Expected callback for create to trigger but it didn't"", ++ createCalls.await(secondsToWait, TimeUnit.SECONDS)); ++ assertTrue(""Expected callback for update to trigger but it didn't"", ++ updateCalls.await(secondsToWait, TimeUnit.SECONDS)); ++ assertTrue(""Expected callback for remove to trigger but it didn't"", ++ removeCalls.await(secondsToWait, TimeUnit.SECONDS)); ++ } ++ } ++ ++ @Test ++ public void testLeaseUpdateOnLeaseThatDoesntExist() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ assertThat(""Can't update a service that doesn't exist"", ++ cloudnameService.updatePermanentService( ++ ServiceCoordinate.parse(""foo.bar.baz""), DEFAULT_ENDPOINT), ++ is(false)); ++ } ++ } ++ ++ @Test ++ public void testRemoveServiceThatDoesntExist() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ assertThat(""Can't remove a service that doesn't exist"", ++ cloudnameService.removePermanentService(ServiceCoordinate.parse(""foo.bar.baz"")), ++ is(false)); ++ } ++ } ++ ++ @AfterClass ++ public static void removeServiceRegistration() throws InterruptedException { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(SERVICE_COORDINATE); ++ final CountDownLatch callCounter = new CountDownLatch(2); ++ final int secondsToWait = 1; ++ cloudnameService.addPermanentServiceListener(serviceCoordinate, ++ new PermanentServiceListener() { ++ private final AtomicInteger createCount = new AtomicInteger(0); ++ private final AtomicInteger removeCount = new AtomicInteger(0); ++ ++ @Override ++ public void onServiceCreated(final Endpoint endpoint) { ++ // This will be called once and only once ++ assertThat(""Did not onServiceCreated to be called multiple times"", ++ createCount.incrementAndGet(), is(1)); ++ callCounter.countDown(); ++ } ++ ++ @Override ++ public void onServiceChanged(final Endpoint endpoint) { ++ fail(""Did not expect any calls to onServiceChanged""); ++ } ++ ++ @Override ++ public void onServiceRemoved() { ++ assertThat(""Did not expect onServiceRemoved to be called multiple"" ++ + "" times"", removeCount.incrementAndGet(), is(1)); ++ callCounter.countDown(); ++ } ++ }); ++ ++ // Remove the service created in the setup. ++ assertThat(cloudnameService.removePermanentService(serviceCoordinate), is(true)); ++ ++ assertTrue(""Did not receive the expected number of calls to listener. "" ++ + callCounter.getCount() + "" calls remaining."", ++ callCounter.await(secondsToWait, TimeUnit.SECONDS)); ++ ++ // Removing it twice will fail. ++ assertThat(cloudnameService.removePermanentService(serviceCoordinate), is(false)); ++ } ++ } ++ ++ private final ServiceCoordinate coordinate = ServiceCoordinate.parse(""service.tag.region""); ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void coordinateCanNotBeNullWhenUpdatingService() { ++ new CloudnameService(memoryBackend).updatePermanentService(null, null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void endpointCanNotBeNullWhenUpdatingService() { ++ new CloudnameService(memoryBackend).updatePermanentService(coordinate, null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void coordinateCanNotBeNullWhenRemovingService() { ++ new CloudnameService(memoryBackend).removePermanentService(null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void coordinateCanNotBeNullWhenAddingListener() { ++ new CloudnameService(memoryBackend).addPermanentServiceListener(null, null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void listenerCanNotBeNullWhenAddingListener() { ++ new CloudnameService(memoryBackend).addPermanentServiceListener(coordinate, null); ++ } ++ ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java b/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java +new file mode 100644 +index 00000000..6fe4a9a9 +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/CloudnameServiceTest.java +@@ -0,0 +1,316 @@ ++package org.cloudname.service; ++ ++import org.cloudname.backends.memory.MemoryBackend; ++import org.cloudname.core.CloudnameBackend; ++import org.junit.Test; ++ ++import java.util.ArrayList; ++import java.util.Arrays; ++import java.util.List; ++import java.util.Random; ++import java.util.concurrent.CountDownLatch; ++import java.util.concurrent.Executor; ++import java.util.concurrent.Executors; ++import java.util.concurrent.Semaphore; ++import java.util.concurrent.TimeUnit; ++ ++import static org.junit.Assert.assertTrue; ++import static org.junit.Assert.fail; ++import static org.junit.Assert.assertThat; ++import static org.hamcrest.CoreMatchers.is; ++ ++/** ++ * Test service registration with memory-based backend. ++ */ ++public class CloudnameServiceTest { ++ private static final CloudnameBackend memoryBackend = new MemoryBackend(); ++ ++ private final ServiceCoordinate coordinate = ServiceCoordinate.parse(""service.tag.region""); ++ ++ /** ++ * Max time to wait for changes to propagate to clients. In seconds. ++ */ ++ private static final int MAX_WAIT_S = 1; ++ ++ private final Random random = new Random(); ++ private int getRandomPort() { ++ return Math.max(1, Math.abs(random.nextInt(4096))); ++ } ++ ++ private ServiceHandle registerService(final CloudnameService cloudnameService, final String serviceCoordinateString) { ++ final ServiceCoordinate serviceCoordinate = ServiceCoordinate.parse(serviceCoordinateString); ++ ++ final Endpoint httpEndpoint = new Endpoint(""http"", ""127.0.0.1"", getRandomPort()); ++ final Endpoint webconsoleEndpoint = new Endpoint(""webconsole"", ""127.0.0.2"", getRandomPort()); ++ ++ final ServiceData serviceData = new ServiceData(Arrays.asList(httpEndpoint, webconsoleEndpoint)); ++ return cloudnameService.registerService(serviceCoordinate, serviceData); ++ } ++ ++ /** ++ * Create two sets of services, register both and check that notifications are sent to the ++ * subscribers. ++ */ ++ @Test ++ public void testServiceNotifications() throws InterruptedException { ++ final String SOME_COORDINATE = ""someservice.test.local""; ++ final String ANOTHER_COORDINATE = ""anotherservice.test.local""; ++ ++ final CloudnameService mainCloudname = new CloudnameService(memoryBackend); ++ ++ final int numOtherServices = 10; ++ final List handles = new ArrayList<>(); ++ for (int i = 0; i < numOtherServices; i++) { ++ handles.add(registerService(mainCloudname, ANOTHER_COORDINATE)); ++ } ++ ++ final Executor executor = Executors.newCachedThreadPool(); ++ final int numServices = 5; ++ final CountDownLatch registrationLatch = new CountDownLatch(numServices); ++ final CountDownLatch instanceLatch = new CountDownLatch(numServices * numOtherServices); ++ final CountDownLatch httpEndpointLatch = new CountDownLatch(numServices * numOtherServices); ++ final CountDownLatch webconsoleEndpointLatch = new CountDownLatch(numServices * numOtherServices); ++ final CountDownLatch removeLatch = new CountDownLatch(numServices * numOtherServices); ++ final Semaphore terminateSemaphore = new Semaphore(1); ++ final CountDownLatch completedLatch = new CountDownLatch(numServices); ++ ++ final Runnable service = new Runnable() { ++ @Override ++ public void run() { ++ try (final CloudnameService cloudnameService = new CloudnameService(memoryBackend)) { ++ try (final ServiceHandle handle = registerService(cloudnameService, SOME_COORDINATE)) { ++ registrationLatch.countDown(); ++ ++ final ServiceCoordinate otherServiceCoordinate = ServiceCoordinate.parse(ANOTHER_COORDINATE); ++ ++ // Do a service lookup on the other service. This will yield N elements. ++ cloudnameService.addServiceListener(otherServiceCoordinate, new ServiceListener() { ++ @Override ++ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) { ++ instanceLatch.countDown(); ++ if (data.getEndpoint(""http"") != null) { ++ httpEndpointLatch.countDown(); ++ } ++ if (data.getEndpoint(""webconsole"") != null) { ++ webconsoleEndpointLatch.countDown(); ++ } ++ } ++ ++ @Override ++ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) { ++ if (data.getEndpoint(""http"") != null) { ++ httpEndpointLatch.countDown(); ++ } ++ if (data.getEndpoint(""webconsole"") != null) { ++ webconsoleEndpointLatch.countDown(); ++ } ++ } ++ ++ @Override ++ public void onServiceRemoved(final InstanceCoordinate coordinate) { ++ removeLatch.countDown(); ++ } ++ }); ++ ++ // Wait for the go ahead before terminating ++ try { ++ terminateSemaphore.acquire(); ++ terminateSemaphore.release(); ++ } catch (final InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ } ++ // The service handle will close and the instance will be removed at this point. ++ } ++ completedLatch.countDown(); ++ } ++ }; ++ ++ // Grab the semaphore. This wil stop the services from terminating ++ terminateSemaphore.acquire(); ++ ++ // Start two threads which will register a service and look up a set of another. ++ for (int i = 0; i < numServices; i++) { ++ executor.execute(service); ++ } ++ ++ // Wait for the registrations and endpoints to propagate ++ assertTrue(""Expected registrations to complete"", ++ registrationLatch.await(MAX_WAIT_S, TimeUnit.SECONDS)); ++ ++ assertTrue(""Expected http endpoints to be registered but missing "" ++ + httpEndpointLatch.getCount(), ++ httpEndpointLatch.await(MAX_WAIT_S, TimeUnit.SECONDS)); ++ ++ assertTrue(""Expected webconsole endpoints to be registered but missing "" ++ + webconsoleEndpointLatch.getCount(), ++ webconsoleEndpointLatch.await(MAX_WAIT_S, TimeUnit.SECONDS)); ++ ++ // Registrations are now completed; remove the existing services ++ for (final ServiceHandle handle : handles) { ++ handle.close(); ++ } ++ ++ // This will trigger remove events in the threads. ++ assertTrue(""Expected services to be removed but "" + removeLatch.getCount() ++ + "" still remains"", removeLatch.await(MAX_WAIT_S, TimeUnit.SECONDS)); ++ ++ // Let the threads terminate. This will remove the registrations ++ terminateSemaphore.release(); ++ ++ assertTrue(""Expected services to complete but "" + completedLatch.getCount() ++ + "" still remains"", completedLatch.await(MAX_WAIT_S, TimeUnit.SECONDS)); ++ ++ // Success! There shouldn't be any more services registered at this point. Check to make sure ++ mainCloudname.addServiceListener(ServiceCoordinate.parse(SOME_COORDINATE), new ServiceListener() { ++ @Override ++ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) { ++ fail(""Should not have any services but "" + coordinate + "" is still there""); ++ } ++ ++ @Override ++ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) { ++ fail(""Should not have any services but "" + coordinate + "" reports data""); ++ } ++ ++ @Override ++ public void onServiceRemoved(final InstanceCoordinate coordinate) { ++ ++ } ++ }); ++ mainCloudname.addServiceListener(ServiceCoordinate.parse(ANOTHER_COORDINATE), new ServiceListener() { ++ @Override ++ public void onServiceCreated(final InstanceCoordinate coordinate, final ServiceData data) { ++ fail(""Should not have any services but "" + coordinate + "" is still there""); ++ } ++ ++ @Override ++ public void onServiceDataChanged(final InstanceCoordinate coordinate, final ServiceData data) { ++ fail(""Should not have any services but "" + coordinate + "" is still there""); ++ } ++ ++ @Override ++ public void onServiceRemoved(InstanceCoordinate coordinate) { ++ ++ } ++ }); ++ } ++ ++ /** ++ * Ensure data notifications works as expecte. Update a lot of endpoints on a single ++ * service and check that the subscribers get notified of all changes in the correct order. ++ */ ++ @Test ++ public void testDataNotifications() throws InterruptedException { ++ final CloudnameService cs = new CloudnameService(memoryBackend); ++ ++ final String serviceCoordinate = ""some.service.name""; ++ final ServiceHandle serviceHandle = cs.registerService( ++ ServiceCoordinate.parse(serviceCoordinate), ++ new ServiceData(new ArrayList())); ++ ++ final int numClients = 10; ++ final int numDataChanges = 50; ++ final int maxSecondsForNotifications = 1; ++ final CountDownLatch dataChangeLatch = new CountDownLatch(numClients * numDataChanges); ++ final CountDownLatch readyLatch = new CountDownLatch(numClients); ++ final String EP_NAME = ""endpoint""; ++ final Semaphore terminateSemaphore = new Semaphore(1); ++ ++ // Grab the semaphore, prevent threads from completing ++ terminateSemaphore.acquire(); ++ ++ final Runnable clientServices = new Runnable() { ++ @Override ++ public void run() { ++ try (final CloudnameService cn = new CloudnameService(memoryBackend)) { ++ cn.addServiceListener(ServiceCoordinate.parse(serviceCoordinate), new ServiceListener() { ++ int portNum = 0; ++ @Override ++ public void onServiceCreated(InstanceCoordinate coordinate, ServiceData serviceData) { ++ // ignore this ++ } ++ ++ @Override ++ public void onServiceDataChanged(InstanceCoordinate coordinate, ServiceData data) { ++ final Endpoint ep = data.getEndpoint(EP_NAME); ++ if (ep != null) { ++ dataChangeLatch.countDown(); ++ assertThat(ep.getPort(), is(portNum + 1)); ++ portNum = portNum + 1; ++ } ++ } ++ ++ @Override ++ public void onServiceRemoved(InstanceCoordinate coordinate) { ++ // ignore this ++ } ++ }); ++ readyLatch.countDown(); ++ ++ // Wait for the test to finish before closing. The endpoints will be ++ // processed once every thread is ready. ++ try { ++ terminateSemaphore.acquire(); ++ terminateSemaphore.release(); ++ } catch (final InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ } ++ } ++ }; ++ ++ final Executor executor = Executors.newCachedThreadPool(); ++ for (int i = 0; i < numClients; i++) { ++ executor.execute(clientServices); ++ } ++ ++ // Wait for the threads to be ready ++ readyLatch.await(); ++ ++ // Publish changes to the same endpoint; the endpoint is updated with a new port ++ // number for each update. ++ Endpoint oldEndpoint = null; ++ for (int portNum = 1; portNum < numDataChanges + 1; portNum++) { ++ if (oldEndpoint != null) { ++ serviceHandle.removeEndpoint(oldEndpoint); ++ } ++ final Endpoint newEndpoint = new Endpoint(EP_NAME, ""localhost"", portNum); ++ serviceHandle.registerEndpoint(newEndpoint); ++ oldEndpoint = newEndpoint; ++ } ++ ++ // Check if the threads have been notified of all the changes ++ assertTrue(""Expected "" + (numDataChanges * numClients) + "" changes but "" ++ + dataChangeLatch.getCount() + "" remains"", ++ dataChangeLatch.await(maxSecondsForNotifications, TimeUnit.SECONDS)); ++ ++ // Let threads terminate ++ terminateSemaphore.release(); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void coordinateCanNotBeNullWhenAddingListener() { ++ new CloudnameService(memoryBackend).addServiceListener(null, null); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void listenerCanNotBeNullWhenAddingListener() { ++ new CloudnameService(memoryBackend).addServiceListener(coordinate, null); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void serviceCannotBeNullWhenRegister() { ++ new CloudnameService(memoryBackend).registerService(null, null); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void serviceDataCannotBeNullWhenRegister() { ++ new CloudnameService(memoryBackend).registerService(coordinate, null); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void backendMustBeValid() { ++ new CloudnameService(null); ++ } ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/EndpointTest.java b/cn-service/src/test/java/org/cloudname/service/EndpointTest.java +new file mode 100644 +index 00000000..8d1b368e +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/EndpointTest.java +@@ -0,0 +1,97 @@ ++package org.cloudname.service; ++import org.junit.Test; ++ ++import static org.junit.Assert.assertThat; ++import static org.junit.Assert.fail; ++import static org.hamcrest.CoreMatchers.is; ++ ++/** ++ * Test the Endpoint class. Relatively straightforward; test creation and that ++ * fields are set correctly, test conversion to and from JSON, test the equals() ++ * implementation and test assertions in constructor. ++ */ ++public class EndpointTest { ++ @Test ++ public void testCreation() { ++ final Endpoint endpoint = new Endpoint(""foo"", ""localhost"", 80); ++ assertThat(endpoint.getName(), is(""foo"")); ++ assertThat(endpoint.getHost(), is(""localhost"")); ++ assertThat(endpoint.getPort(), is(80)); ++ } ++ ++ @Test ++ public void testJsonConversion() { ++ final Endpoint endpoint = new Endpoint(""bar"", ""baz"", 8888); ++ final String jsonString = endpoint.toJsonString(); ++ ++ final Endpoint endpointCopy = Endpoint.fromJson(jsonString); ++ ++ assertThat(endpointCopy.getName(), is(endpoint.getName())); ++ assertThat(endpointCopy.getHost(), is(endpoint.getHost())); ++ assertThat(endpointCopy.getPort(), is(endpoint.getPort())); ++ } ++ ++ @Test ++ public void testEquals() { ++ final Endpoint a = new Endpoint(""foo"", ""bar"", 1); ++ final Endpoint b = new Endpoint(""foo"", ""bar"", 1); ++ assertThat(a.equals(b), is(true)); ++ assertThat(b.equals(a), is(true)); ++ assertThat(b.hashCode(), is(a.hashCode())); ++ ++ final Endpoint c = new Endpoint(""bar"", ""foo"", 1); ++ assertThat(a.equals(c), is(false)); ++ assertThat(b.equals(c), is(false)); ++ ++ final Endpoint d = new Endpoint(""foo"", ""bar"", 2); ++ assertThat(a.equals(d), is(false)); ++ ++ final Endpoint e = new Endpoint(""foo"", ""baz"", 1); ++ assertThat(a.equals(e), is(false)); ++ ++ assertThat(a.equals(null), is(false)); ++ assertThat(a.equals(""some string""), is(false)); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testNullName() { ++ new Endpoint(null, ""foo"", 0); ++ fail(""Constructor should have thrown exception for null name""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testEmptyName() { ++ new Endpoint("""", ""foo"", 0); ++ fail(""Constructor should have thrown exception for null name""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testNullHost() { ++ new Endpoint(""foo"", null, 0); ++ fail(""Constructor should have thrown exception for null host""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testEmptyHost() { ++ new Endpoint(""foo"", """", 0); ++ fail(""Constructor should have thrown exception for null host""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testZeroPort() { ++ new Endpoint(""foo"", ""bar"", 0); ++ fail(""Constructor should have thrown exception for 0 port""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testNegativePort() { ++ new Endpoint(""foo"", ""bar"", -1); ++ fail(""Constructor should have thrown exception for 0 port""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testInvalidName() { ++ new Endpoint(""æøå"", ""bar"", 80); ++ fail(""Constructor should have thrown exception for 0 port""); ++ } ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java b/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java +new file mode 100644 +index 00000000..c7009f0b +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/InstanceCoordinateTest.java +@@ -0,0 +1,92 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++import org.junit.Test; ++ ++import static org.hamcrest.CoreMatchers.equalTo; ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.not; ++import static org.hamcrest.CoreMatchers.nullValue; ++import static org.junit.Assert.assertThat; ++ ++public class InstanceCoordinateTest { ++ @Test ++ public void testCreation() { ++ final String[] path = new String[] { ""region"", ""tag"", ""service"", ""instance"" }; ++ final InstanceCoordinate coordinate = new InstanceCoordinate(new CloudnamePath(path)); ++ ++ final String canonicalString = coordinate.toCanonicalString(); ++ assertThat(canonicalString, is(""instance.service.tag.region"")); ++ ++ final InstanceCoordinate fromCanonical = InstanceCoordinate.parse(canonicalString); ++ assertThat(fromCanonical.toCanonicalString(), is(canonicalString)); ++ assertThat(fromCanonical.getRegion(), is(coordinate.getRegion())); ++ assertThat(fromCanonical.getTag(), is(coordinate.getTag())); ++ assertThat(fromCanonical.getService(), is(coordinate.getService())); ++ assertThat(fromCanonical.getInstance(), is(coordinate.getInstance())); ++ ++ final String jsonString = coordinate.toJsonString(); ++ final InstanceCoordinate fromJson = InstanceCoordinate.fromJson(jsonString); ++ assertThat(fromJson.getRegion(), is(coordinate.getRegion())); ++ assertThat(fromJson.getTag(), is(coordinate.getTag())); ++ assertThat(fromJson.getService(), is(coordinate.getService())); ++ assertThat(fromJson.getInstance(), is(coordinate.getInstance())); ++ assertThat(fromJson.toCanonicalString(), is(coordinate.toCanonicalString())); ++ } ++ ++ @Test ++ public void testPathConversion() { ++ final CloudnamePath path = new CloudnamePath( ++ new String[] {""test"", ""local"", ""service"", ""instance"" }); ++ ++ final InstanceCoordinate coordinate = new InstanceCoordinate(path); ++ ++ final CloudnamePath cnPath = coordinate.toCloudnamePath(); ++ assertThat(cnPath.length(), is(path.length())); ++ assertThat(cnPath, is(equalTo(path))); ++ } ++ ++ /** ++ * Ensure toString() has a sensible representation ('ish) ++ */ ++ @Test ++ public void toStringMethod() { ++ final CloudnamePath pathA = new CloudnamePath( ++ new String[] {""test"", ""local"", ""service"", ""instance"" }); ++ final CloudnamePath pathB = new CloudnamePath( ++ new String[] {""test"", ""local"", ""service"", ""instance"" }); ++ final CloudnamePath pathC = new CloudnamePath( ++ new String[] {""test"", ""local"", ""service"", ""x"" }); ++ ++ final InstanceCoordinate a = new InstanceCoordinate(pathA); ++ final InstanceCoordinate b = new InstanceCoordinate(pathB); ++ final InstanceCoordinate c = new InstanceCoordinate(pathC); ++ assertThat(a.toString(), is(a.toString())); ++ assertThat(a.toString(), is(not(c.toString()))); ++ ++ assertThat(a.toCanonicalString(), is(b.toCanonicalString())); ++ } ++ ++ @Test ++ public void invalidStringConversion() { ++ assertThat(InstanceCoordinate.parse(""foo:bar.baz""), is(nullValue())); ++ assertThat(InstanceCoordinate.parse(null), is(nullValue())); ++ assertThat(InstanceCoordinate.parse(""foo.bar.baz""), is(nullValue())); ++ assertThat(InstanceCoordinate.parse(""""), is(nullValue())); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void invalidNames2() { ++ assertThat(InstanceCoordinate.parse(""æ.ø.å.a""), is(nullValue())); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void nullPathInConstructor() { ++ new InstanceCoordinate(null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void invalidPathInConstructor() { ++ new InstanceCoordinate(new CloudnamePath(new String[] { ""foo"" })); ++ } ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java +new file mode 100644 +index 00000000..c49126e0 +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/ServiceCoordinateTest.java +@@ -0,0 +1,87 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++import org.junit.Test; ++ ++import static org.hamcrest.CoreMatchers.equalTo; ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.not; ++import static org.hamcrest.CoreMatchers.nullValue; ++import static org.junit.Assert.assertThat; ++ ++public class ServiceCoordinateTest { ++ private final CloudnamePath cnPath = new CloudnamePath( ++ new String[] { ""local"", ""test"", ""service"" }); ++ ++ ++ @Test ++ public void testCreation() { ++ final ServiceCoordinate coordinate = new ServiceCoordinate(cnPath); ++ assertThat(coordinate.getRegion(), is(cnPath.get(0))); ++ assertThat(coordinate.getTag(), is(cnPath.get(1))); ++ assertThat(coordinate.getService(), is(cnPath.get(2))); ++ } ++ ++ @Test ++ public void testParse() { ++ final ServiceCoordinate coord = ServiceCoordinate.parse(""service.tag.region""); ++ assertThat(coord.getRegion(), is(""region"")); ++ assertThat(coord.getTag(), is(""tag"")); ++ assertThat(coord.getService(), is(""service"")); ++ } ++ ++ @Test ++ public void testEquals() { ++ final ServiceCoordinate coordA = ServiceCoordinate.parse(""a.b.c""); ++ final ServiceCoordinate coordB = ServiceCoordinate.parse(""a.b.c""); ++ final ServiceCoordinate coordC = ServiceCoordinate.parse(""a.b.d""); ++ final ServiceCoordinate coordD = ServiceCoordinate.parse(""a.a.c""); ++ final ServiceCoordinate coordE = ServiceCoordinate.parse(""a.a.a""); ++ final ServiceCoordinate coordF = ServiceCoordinate.parse(""c.b.c""); ++ ++ assertThat(coordA, is(equalTo(coordB))); ++ assertThat(coordB, is(equalTo(coordA))); ++ ++ assertThat(coordA, is(not(equalTo(coordC)))); ++ assertThat(coordA, is(not(equalTo(coordD)))); ++ assertThat(coordA, is(not(equalTo(coordE)))); ++ assertThat(coordA, is(not(equalTo(coordF)))); ++ ++ assertThat(coordA.equals(null), is(false)); ++ assertThat(coordA.equals(new Object()), is(false)); ++ } ++ ++ @Test ++ public void testHashCode() { ++ final ServiceCoordinate coordA = ServiceCoordinate.parse(""a.b.c""); ++ final ServiceCoordinate coordB = ServiceCoordinate.parse(""a.b.c""); ++ final ServiceCoordinate coordC = ServiceCoordinate.parse(""x.x.x""); ++ assertThat(coordA.hashCode(), is(coordB.hashCode())); ++ assertThat(coordC.hashCode(), is(not(coordA.hashCode()))); ++ } ++ @Test ++ public void testInvalidCoordinateString0() { ++ assertThat(ServiceCoordinate.parse(""foo bar baz""), is(nullValue())); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void testInvalidCoordinateString1() { ++ ServiceCoordinate.parse(""..""); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void testInvalidCoordinateString2() { ++ ServiceCoordinate.parse(""_._._""); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void nullPathParameter() { ++ new ServiceCoordinate(null); ++ } ++ ++ @Test(expected = IllegalArgumentException.class) ++ public void illegalPathParameter() { ++ new ServiceCoordinate(new CloudnamePath(new String[] { ""foo"" })); ++ } ++ ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java +new file mode 100644 +index 00000000..0154a78a +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/ServiceDataTest.java +@@ -0,0 +1,124 @@ ++package org.cloudname.service; ++ ++import org.junit.Test; ++ ++import java.util.ArrayList; ++import java.util.Arrays; ++ ++import static org.hamcrest.CoreMatchers.equalTo; ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.nullValue; ++import static org.junit.Assert.assertThat; ++ ++public class ServiceDataTest { ++ @Test ++ public void testCreation() { ++ final Endpoint ep1 = new Endpoint(""foo"", ""bar"", 1); ++ final Endpoint ep2 = new Endpoint(""bar"", ""baz"", 1); ++ ++ final ServiceData data = new ServiceData(Arrays.asList(ep1, ep2)); ++ assertThat(data.getEndpoint(""foo""), is(equalTo(ep1))); ++ assertThat(data.getEndpoint(""bar""), is(equalTo(ep2))); ++ assertThat(data.getEndpoint(""baz""), is(nullValue())); ++ } ++ ++ @Test ++ public void testAddRemoveEndpoint() { ++ final ServiceData data = new ServiceData(new ArrayList()); ++ assertThat(data.getEndpoint(""a""), is(nullValue())); ++ assertThat(data.getEndpoint(""b""), is(nullValue())); ++ ++ final Endpoint ep1 = new Endpoint(""a"", ""localhost"", 80); ++ final Endpoint ep1a = new Endpoint(""a"", ""localhost"", 80); ++ // Endpoint can only be added once ++ assertThat(data.addEndpoint(ep1), is(true)); ++ assertThat(data.addEndpoint(ep1), is(false)); ++ // Endpoints must be unique ++ assertThat(data.addEndpoint(ep1a), is(false)); ++ ++ // Another endpoint can be added ++ final Endpoint ep2 = new Endpoint(""b"", ""localhost"", 80); ++ final Endpoint ep2a = new Endpoint(""b"", ""localhost"", 80); ++ assertThat(data.addEndpoint(ep2), is(true)); ++ // But the same rules applies ++ assertThat(data.addEndpoint(ep2), is(false)); ++ assertThat(data.addEndpoint(ep2a), is(false)); ++ ++ // Data now contains both endpoints ++ assertThat(data.getEndpoint(""a""), is(equalTo(ep1))); ++ assertThat(data.getEndpoint(""b""), is(equalTo(ep2))); ++ ++ assertThat(data.removeEndpoint(ep1), is(true)); ++ assertThat(data.removeEndpoint(ep1a), is(false)); ++ ++ // ...ditto for next endpoint ++ assertThat(data.removeEndpoint(ep2), is(true)); ++ assertThat(data.removeEndpoint(ep2), is(false)); ++ ++ // The endpoints with identical names can be added ++ assertThat(data.addEndpoint(ep1a), is(true)); ++ assertThat(data.addEndpoint(ep2a), is(true)); ++ } ++ ++ @Test ++ public void testConversionToFromJson() { ++ final Endpoint endpointA = new Endpoint(""foo"", ""bar"", 80); ++ final Endpoint endpointB = new Endpoint(""baz"", ""bar"", 81); ++ final ServiceData dataA = new ServiceData( ++ Arrays.asList(endpointA, endpointB)); ++ ++ final String jsonString = dataA.toJsonString(); ++ ++ final ServiceData dataB = ServiceData.fromJsonString(jsonString); ++ ++ assertThat(dataB.getEndpoint(""foo""), is(endpointA)); ++ assertThat(dataB.getEndpoint(""baz""), is(endpointB)); ++ } ++ ++ @Test ++ public void uniqueNamesAreRequired() { ++ final Endpoint endpointA = new Endpoint(""foo"", ""bar"", 80); ++ final Endpoint endpointB = new Endpoint(""foo"", ""baz"", 82); ++ final Endpoint endpointC = new Endpoint(""foo"", ""localhost"", 80); ++ final Endpoint endpointD = new Endpoint(""foobar"", ""localhost"", 80); ++ ++ final ServiceData serviceData = new ServiceData(new ArrayList()); ++ assertThat(serviceData.addEndpoint(endpointA), is(true)); ++ assertThat(serviceData.addEndpoint(endpointB), is(false)); ++ assertThat(serviceData.addEndpoint(endpointC), is(false)); ++ assertThat(serviceData.addEndpoint(endpointD), is(true)); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testInvalidJson1() { ++ final String nullStr = null; ++ ServiceData.fromJsonString(nullStr); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testInvalidJson2() { ++ ServiceData.fromJsonString(""""); ++ } ++ ++ @Test (expected = org.json.JSONException.class) ++ public void testInvalidJson3() { ++ ServiceData.fromJsonString(""}{""); ++ } ++ ++ @Test (expected = org.json.JSONException.class) ++ public void testInvalidJson4() { ++ ServiceData.fromJsonString(""{ \""foo\"": 12 }""); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void addNullEndpoint() { ++ final ServiceData data = new ServiceData(); ++ data.addEndpoint(null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void removeNullEndpoint() { ++ final ServiceData data = new ServiceData(); ++ data.removeEndpoint(null); ++ } ++} +diff --git a/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java b/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java +new file mode 100644 +index 00000000..5b43e37c +--- /dev/null ++++ b/cn-service/src/test/java/org/cloudname/service/ServiceHandleTest.java +@@ -0,0 +1,104 @@ ++package org.cloudname.service; ++ ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++import org.junit.Test; ++ ++import java.io.IOException; ++import java.util.ArrayList; ++import java.util.Arrays; ++ ++import static org.hamcrest.CoreMatchers.is; ++import static org.junit.Assert.assertThat; ++ ++public class ServiceHandleTest { ++ ++ @Test ++ public void testCreation() { ++ final InstanceCoordinate instanceCoordinate ++ = InstanceCoordinate.parse(""instance.service.tag.region""); ++ final ServiceData serviceData = new ServiceData(new ArrayList()); ++ final LeaseHandle handle = new LeaseHandle() { ++ @Override ++ public boolean writeLeaseData(String data) { ++ return true; ++ } ++ ++ @Override ++ public CloudnamePath getLeasePath() { ++ return instanceCoordinate.toCloudnamePath(); ++ } ++ ++ @Override ++ public void close() throws IOException { ++ // nothing ++ } ++ }; ++ ++ final ServiceHandle serviceHandle ++ = new ServiceHandle(instanceCoordinate, serviceData, handle); ++ ++ final Endpoint ep1 = new Endpoint(""foo"", ""bar"", 80); ++ assertThat(serviceHandle.registerEndpoint(ep1), is(true)); ++ assertThat(serviceHandle.registerEndpoint(ep1), is(false)); ++ ++ assertThat(serviceHandle.removeEndpoint(ep1), is(true)); ++ assertThat(serviceHandle.removeEndpoint(ep1), is(false)); ++ ++ serviceHandle.close(); ++ } ++ ++ @Test ++ public void testFailingHandle() { ++ final InstanceCoordinate instanceCoordinate ++ = InstanceCoordinate.parse(""instance.service.tag.region""); ++ final Endpoint ep1 = new Endpoint(""foo"", ""bar"", 80); ++ ++ final ServiceData serviceData = new ServiceData(Arrays.asList(ep1)); ++ final LeaseHandle handle = new LeaseHandle() { ++ @Override ++ public boolean writeLeaseData(String data) { ++ return false; ++ } ++ ++ @Override ++ public CloudnamePath getLeasePath() { ++ return instanceCoordinate.toCloudnamePath(); ++ } ++ ++ @Override ++ public void close() throws IOException { ++ throw new IOException(""I broke""); ++ } ++ }; ++ ++ final ServiceHandle serviceHandle ++ = new ServiceHandle(instanceCoordinate, serviceData, handle); ++ ++ final Endpoint ep2 = new Endpoint(""bar"", ""baz"", 81); ++ assertThat(serviceHandle.registerEndpoint(ep2), is(false)); ++ ++ assertThat(serviceHandle.removeEndpoint(ep1), is(false)); ++ assertThat(serviceHandle.removeEndpoint(ep2), is(false)); ++ ++ serviceHandle.close(); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testWithNullParameters1() { ++ new ServiceHandle(null, null, null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testWithNullParameters2() { ++ new ServiceHandle(InstanceCoordinate.parse(""a.b.c.d""), null, null); ++ } ++ ++ @Test (expected = IllegalArgumentException.class) ++ public void testWithNullParameters3() { ++ new ServiceHandle( ++ InstanceCoordinate.parse(""a.b.c.d""), ++ new ServiceData(new ArrayList()), ++ null); ++ } ++} +diff --git a/cn-zookeeper/README.md b/cn-zookeeper/README.md +new file mode 100644 +index 00000000..3ce1e123 +--- /dev/null ++++ b/cn-zookeeper/README.md +@@ -0,0 +1,4 @@ ++# ZooKeeper backend ++ ++# Node structure ++The root path is set to `/cn` and the leases are stored in `/cn/temporary` and `/cn/permanent`. Temporary leases use ephemeral nodes with a randomly assigned 4-byte long ID. Permanent leases are named by the client. The Curator library is used for the majority of ZooKeeper access. The containing nodes have the `CONTAINER` bit set, i.e. they will be cleaned up by ZooKeeper when there's no more child nodes inside each of the containers. Note that this feature is slated for ZooKeeper 3.5 which is currently in Alpha (as of November 2015). Until then the Curator library uses regular nodes so if it is deployed on a ZooKeeper 3.4 or lower manual cleanups of nodes is necessary. +diff --git a/cn-zookeeper/pom.xml b/cn-zookeeper/pom.xml +new file mode 100644 +index 00000000..4d33d081 +--- /dev/null ++++ b/cn-zookeeper/pom.xml +@@ -0,0 +1,81 @@ ++ ++ 4.0.0 ++ ++ ++ org.cloudname ++ cloudname-parent ++ 3.0-SNAPSHOT ++ ++ ++ cn-zookeeper ++ jar ++ ++ Cloudname ZooKeeper backend ++ ZooKeeper backend for cloudname ++ https://github.com/Cloudname/cloudname ++ ++ ++ ++ org.cloudname ++ cn-core ++ ++ ++ ++ junit ++ junit ++ test ++ ++ ++ ++ org.hamcrest ++ hamcrest-all ++ 1.3 ++ ++ ++ ++ org.apache.curator ++ curator-framework ++ 2.9.0 ++ ++ ++ ++ org.apache.curator ++ curator-recipes ++ 2.9.0 ++ ++ ++ ++ org.apache.curator ++ curator-test ++ 2.9.0 ++ test ++ ++ ++ ++ org.slf4j ++ slf4j-nop ++ 1.7.6 ++ ++ ++ org.cloudname ++ testtools ++ test ++ ++ ++ ++ ++ ++ ++ ++ org.apache.maven.plugins ++ maven-surefire-plugin ++ ++ ++ org.apache.maven.plugins ++ maven-compiler-plugin ++ ++ ++ ++ ++ +diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java +new file mode 100644 +index 00000000..e8ccf998 +--- /dev/null ++++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeCollectionWatcher.java +@@ -0,0 +1,257 @@ ++package org.cloudname.backends.zookeeper; ++ ++import com.google.common.base.Charsets; ++import org.apache.zookeeper.KeeperException; ++import org.apache.zookeeper.WatchedEvent; ++import org.apache.zookeeper.Watcher; ++import org.apache.zookeeper.ZooKeeper; ++import org.apache.zookeeper.data.Stat; ++ ++import java.util.HashMap; ++import java.util.HashSet; ++import java.util.List; ++import java.util.Map; ++import java.util.Set; ++import java.util.concurrent.atomic.AtomicBoolean; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++ ++/** ++ * Monitor a set of child nodes for changes. Needs to do this with the ZooKeeper API since ++ * Curator doesn't provide the necessary interface and the PathChildrenCache is best effort ++ * (and not even a very good effort) ++ * ++ * Watches are kept as usual and the mzxid for each node is kept. If that changes between ++ * watches it mens we've missed an event and the appropriate event is generated to the ++ * listener. ++ * ++ * Note that this class only watches for changes one level down. Changes in children aren't ++ * monitored. The path must exist beforehand. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class NodeCollectionWatcher { ++ private static final Logger LOG = Logger.getLogger(NodeCollectionWatcher.class.getName()); ++ ++ private final Map childMzxid = new HashMap<>(); ++ private final Object syncObject = new Object(); ++ ++ private final ZooKeeper zk; ++ private final String pathToWatch; ++ private final AtomicBoolean shuttingDown = new AtomicBoolean(false); ++ private final NodeWatcherListener listener; ++ ++ ++ /** ++ * @param zk ZooKeeper instance to use ++ * @param pathToWatch Path to observe ++ * @param listener Listener for callbacks ++ */ ++ public NodeCollectionWatcher( ++ final ZooKeeper zk, final String pathToWatch, final NodeWatcherListener listener) { ++ this.pathToWatch = pathToWatch; ++ this.zk = zk; ++ this.listener = listener; ++ readChildNodes(); ++ } ++ ++ /** ++ * Shut down watchers. The listener won't get notified of changes after it has been shut down. ++ */ ++ public void shutdown() { ++ shuttingDown.set(true); ++ } ++ ++ /** ++ * Watcher for node collections. Set by getChildren() ++ */ ++ private final Watcher nodeCollectionWatcher = new Watcher() { ++ @Override ++ public void process(WatchedEvent watchedEvent) { ++ switch (watchedEvent.getType()) { ++ case NodeChildrenChanged: ++ // Child values have changed, read children, generate events ++ readChildNodes(); ++ break; ++ case None: ++ // Some zookeeper event. Watches might not apply anymore. Reapply. ++ switch (watchedEvent.getState()) { ++ case ConnectedReadOnly: ++ LOG.severe(""Connected to readonly cluster""); ++ // Connected to a cluster without quorum. Nodes might not be ++ // correct but re-read the nodes. ++ readChildNodes(); ++ break; ++ case SyncConnected: ++ LOG.info(""Connected to cluster""); ++ // (re-)Connected to the cluster. Nodes must be re-read. Discard ++ // those that aren't found, keep unchanged ones. ++ readChildNodes(); ++ break; ++ case Disconnected: ++ // Disconnected from the cluster. The nodes might not be ++ // up to date (but a reconnect might solve the issue) ++ LOG.log(Level.WARNING, ""Disconnected from zk cluster""); ++ break; ++ case Expired: ++ // Session has expired. Nodes are no longer available ++ removeAllChildNodes(); ++ break; ++ default: ++ break; ++ } ++ } ++ ++ } ++ }; ++ ++ /** ++ * A watcher for the child nodes (set via getData() ++ */ ++ private final Watcher changeWatcher = new Watcher() { ++ @Override ++ public void process(WatchedEvent watchedEvent) { ++ if (shuttingDown.get()) { ++ return; ++ } ++ switch (watchedEvent.getType()) { ++ case NodeDeleted: ++ removeChildNode(watchedEvent.getPath()); ++ break; ++ case NodeDataChanged: ++ processNode(watchedEvent.getPath()); ++ break; ++ ++ } ++ } ++ }; ++ ++ /** ++ * Remove all nodes. ++ */ ++ private void removeAllChildNodes() { ++ System.out.println(""Remove all child nodes""); ++ final Set nodesToRemove = new HashSet<>(); ++ synchronized (syncObject) { ++ nodesToRemove.addAll(childMzxid.keySet()); ++ } ++ for (final String node : nodesToRemove) { ++ removeChildNode(node); ++ } ++ } ++ ++ /** ++ * Read nodes from ZooKeeper, generating events as necessary. If a node is missing from the ++ * result it will generate a remove notification, ditto with new nodes and changes in nodes. ++ */ ++ private void readChildNodes() { ++ try { ++ final List childNodes = zk.getChildren(pathToWatch, nodeCollectionWatcher); ++ final Set childrenToDelete = new HashSet<>(); ++ synchronized (syncObject) { ++ childrenToDelete.addAll(childMzxid.keySet()); ++ } ++ for (final String nodeName : childNodes) { ++ processNode(pathToWatch + ""/"" + nodeName); ++ childrenToDelete.remove(pathToWatch + ""/"" + nodeName); ++ } ++ for (final String nodePath : childrenToDelete) { ++ removeChildNode(nodePath); ++ } ++ } catch (final KeeperException.ConnectionLossException e) { ++ // We've been disconnected. Let the watcher deal with it ++ if (!shuttingDown.get()) { ++ LOG.info(""Lost connection to ZooKeeper while reading child nodes.""); ++ } ++ } catch (final KeeperException.NoNodeException e) { ++ // Node has been removed. Ignore the error? ++ removeChildNode(e.getPath()); ++ } catch (final KeeperException|InterruptedException e) { ++ LOG.log(Level.WARNING, ""Got exception reading child nodes"", e); ++ } ++ } ++ ++ /** ++ * Add a node, generate create or data change notification if needed. ++ */ ++ private void processNode(final String nodePath) { ++ if (shuttingDown.get()) { ++ return; ++ } ++ try { ++ final Stat stat = new Stat(); ++ final byte[] nodeData = zk.getData(nodePath, changeWatcher, stat); ++ final String data = new String(nodeData, Charsets.UTF_8); ++ synchronized (syncObject) { ++ if (!childMzxid.containsKey(nodePath)) { ++ childMzxid.put(nodePath, stat.getMzxid()); ++ generateCreateEvent(nodePath, data); ++ return; ++ } ++ final Long zxid = childMzxid.get(nodePath); ++ if (zxid != stat.getMzxid()) { ++ // the data have changed. Generate event ++ childMzxid.put(nodePath, stat.getMzxid()); ++ generateDataChangeEvent(nodePath, data); ++ } ++ } ++ } catch (final KeeperException.ConnectionLossException e) { ++ // We've been disconnected. Let the watcher deal with it ++ if (!shuttingDown.get()) { ++ LOG.info(""Lost connection to ZooKeeper while reading child nodes.""); ++ } ++ } catch (final KeeperException.NoNodeException e) { ++ removeChildNode(e.getPath()); ++ // Node has been removed before we got to do anything. Ignore error? ++ } catch (final KeeperException|InterruptedException e) { ++ LOG.log(Level.WARNING, ""Got exception adding child node with path "" + nodePath, e); ++ } catch (Exception ex) { ++ LOG.log(Level.SEVERE, ""Pooop!"", ex); ++ } ++ } ++ ++ /** ++ * Remove node. Generate remove event if needed. ++ */ ++ private void removeChildNode(final String nodePath) { ++ synchronized (syncObject) { ++ if (childMzxid.containsKey(nodePath)) { ++ childMzxid.remove(nodePath); ++ generateRemoveEvent(nodePath); ++ } ++ } ++ } ++ ++ /** ++ * Invoke nodeCreated on listener ++ */ ++ private void generateCreateEvent(final String nodePath, final String data) { ++ try { ++ listener.nodeCreated(nodePath, data); ++ } catch (final Exception exception) { ++ LOG.log(Level.WARNING, ""Got exception calling listener.nodeCreated"", exception); ++ } ++ } ++ ++ /** ++ * Invoke dataChanged on listener ++ */ ++ private void generateDataChangeEvent(final String nodePath, final String data) { ++ try { ++ listener.dataChanged(nodePath, data); ++ } catch (final Exception exception) { ++ LOG.log(Level.WARNING, ""Got exception calling listener.dataChanged"", exception); ++ } ++ } ++ ++ /** ++ * Invoke nodeRemoved on listener ++ */ ++ private void generateRemoveEvent(final String nodePath) { ++ try { ++ listener.nodeRemoved(nodePath); ++ } catch (final Exception exception) { ++ LOG.log(Level.WARNING, ""Got exception calling listener.nodeRemoved"", exception); ++ } ++ } ++} +diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java +new file mode 100644 +index 00000000..91e6a77c +--- /dev/null ++++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/NodeWatcherListener.java +@@ -0,0 +1,38 @@ ++package org.cloudname.backends.zookeeper; ++ ++/** ++ * Listener interface for node change events ++ * ++ * @author stalehd@gmail.com ++ */ ++public interface NodeWatcherListener { ++ /** ++ * A node is created. Note that rapid changes with create, data update (and even ++ * create + delete + create + data change might yield just one create notification. ++ * ++ * @param zkPath path to node ++ * @param data data of node ++ */ ++ void nodeCreated(final String zkPath, final String data); ++ ++ /** ++ * Data on a node is changed. Note that you might not get data change notifications ++ * for nodes that are created and updated within a short time span, only a create ++ * notification. ++ * Nodes that are created, deleted, then recreated will also generate this event, even if ++ * the data is unchanged. ++ * ++ * @param zkPath path of node ++ * @param data data of node ++ */ ++ void dataChanged(final String zkPath, final String data); ++ ++ /** ++ * Node is removed. ++ * ++ * @param zkPath Path of the node that is removed. ++ */ ++ void nodeRemoved(final String zkPath); ++} ++ ++ +diff --git a/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java +new file mode 100644 +index 00000000..d51632d8 +--- /dev/null ++++ b/cn-zookeeper/src/main/java/org/cloudname/backends/zookeeper/ZooKeeperBackend.java +@@ -0,0 +1,342 @@ ++package org.cloudname.backends.zookeeper; ++import com.google.common.base.Charsets; ++import org.apache.curator.RetryPolicy; ++import org.apache.curator.framework.CuratorFramework; ++import org.apache.curator.framework.CuratorFrameworkFactory; ++import org.apache.curator.retry.ExponentialBackoffRetry; ++import org.apache.zookeeper.CreateMode; ++import org.apache.zookeeper.KeeperException; ++import org.apache.zookeeper.data.Stat; ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++import org.cloudname.core.LeaseListener; ++ ++import java.io.IOException; ++import java.util.HashMap; ++import java.util.Map; ++import java.util.Random; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicBoolean; ++import java.util.logging.Level; ++import java.util.logging.Logger; ++ ++/** ++ * A ZooKeeper backend for Cloudname. Leases are represented as nodes; client leases are ephemeral ++ * nodes inside container nodes and permanent leases are container nodes. ++ * ++ * @author stalehd@gmail.com ++ */ ++public class ZooKeeperBackend implements CloudnameBackend { ++ private static final Logger LOG = Logger.getLogger(ZooKeeperBackend.class.getName()); ++ private static final String TEMPORARY_ROOT = ""/cn/temporary/""; ++ private static final String PERMANENT_ROOT = ""/cn/permanent/""; ++ private static final int CONNECTION_TIMEOUT_SECONDS = 30; ++ ++ // PRNG for instance names. These will be ""random enough"" for instance identifiers ++ private final Random random = new Random(); ++ private final CuratorFramework curator; ++ private final Map clientListeners = new HashMap<>(); ++ private final Map permanentListeners = new HashMap<>(); ++ private final Object syncObject = new Object(); ++ /** ++ * @param connectionString ZooKeeper connection string ++ * @throws IllegalStateException if the cluster isn't available. ++ */ ++ public ZooKeeperBackend(final String connectionString) { ++ final RetryPolicy retryPolicy = new ExponentialBackoffRetry(200, 10); ++ curator = CuratorFrameworkFactory.newClient(connectionString, retryPolicy); ++ curator.start(); ++ ++ try { ++ curator.blockUntilConnected(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); ++ LOG.info(""Connected to zk cluster @ "" + connectionString); ++ } catch (final InterruptedException ie) { ++ throw new IllegalStateException(""Could not connect to ZooKeeper"", ie); ++ } ++ } ++ ++ @Override ++ public LeaseHandle createTemporaryLease(final CloudnamePath path, final String data) { ++ boolean created = false; ++ CloudnamePath tempInstancePath = null; ++ String tempZkPath = null; ++ while (!created) { ++ final long instanceId = random.nextLong(); ++ tempInstancePath = new CloudnamePath(path, Long.toHexString(instanceId)); ++ tempZkPath = TEMPORARY_ROOT + tempInstancePath.join('/'); ++ try { ++ ++ curator.create() ++ .creatingParentContainersIfNeeded() ++ .withMode(CreateMode.EPHEMERAL) ++ .forPath(tempZkPath, data.getBytes(Charsets.UTF_8)); ++ created = true; ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Could not create client node at "" + tempInstancePath, ex); ++ } ++ } ++ final CloudnamePath instancePath = tempInstancePath; ++ final String zkInstancePath = tempZkPath; ++ return new LeaseHandle() { ++ private AtomicBoolean closed = new AtomicBoolean(false); ++ ++ @Override ++ public boolean writeLeaseData(final String data) { ++ if (closed.get()) { ++ LOG.info(""Attempt to write data to closed leased handle "" + data); ++ return false; ++ } ++ return writeTemporaryLeaseData(instancePath, data); ++ } ++ ++ @Override ++ public CloudnamePath getLeasePath() { ++ if (closed.get()) { ++ return null; ++ } ++ return instancePath; ++ } ++ ++ @Override ++ public void close() throws IOException { ++ if (closed.get()) { ++ return; ++ } ++ try { ++ curator.delete().forPath(zkInstancePath); ++ closed.set(true); ++ } catch (final Exception ex) { ++ throw new IOException(ex); ++ } ++ } ++ }; ++ } ++ ++ @Override ++ public boolean writeTemporaryLeaseData(final CloudnamePath path, final String data) { ++ final String zkPath = TEMPORARY_ROOT + path.join('/'); ++ try { ++ final Stat nodeStat = curator.checkExists().forPath(zkPath); ++ if (nodeStat == null) { ++ LOG.log(Level.WARNING, ""Could not write client lease data for "" + path ++ + "" with data since the path does not exist. Data = "" + data); ++ } ++ curator.setData().forPath(zkPath, data.getBytes(Charsets.UTF_8)); ++ return true; ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got exception writing lease data to "" + path ++ + "" with data "" + data); ++ return false; ++ } ++ } ++ ++ @Override ++ public String readTemporaryLeaseData(final CloudnamePath path) { ++ if (path == null) { ++ return null; ++ } ++ final String zkPath = TEMPORARY_ROOT + path.join('/'); ++ try { ++ curator.sync().forPath(zkPath); ++ final byte[] bytes = curator.getData().forPath(zkPath); ++ return new String(bytes, Charsets.UTF_8); ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got exception reading client lease data at "" + path, ex); ++ } ++ return null; ++ } ++ ++ private CloudnamePath toCloudnamePath(final String zkPath, final String pathPrefix) { ++ final String clientPath = zkPath.substring(pathPrefix.length()); ++ final String[] elements = clientPath.split(""/""); ++ return new CloudnamePath(elements); ++ } ++ ++ @Override ++ public void addTemporaryLeaseListener( ++ final CloudnamePath pathToObserve, final LeaseListener listener) { ++ // Ideally the PathChildrenCache class in Curator would be used here to keep track of the ++ // changes but it is ever so slightly broken and misses most of the watches that ZooKeeper ++ // triggers, ignores the mzxid on the nodes and generally makes a mess of things. Enter ++ // custom code. ++ final String zkPath = TEMPORARY_ROOT + pathToObserve.join('/'); ++ try { ++ curator.createContainers(zkPath); ++ final NodeCollectionWatcher watcher = new NodeCollectionWatcher(curator.getZookeeperClient().getZooKeeper(), ++ zkPath, ++ new NodeWatcherListener() { ++ @Override ++ public void nodeCreated(final String path, final String data) { ++ listener.leaseCreated(toCloudnamePath(path, TEMPORARY_ROOT), data); ++ } ++ @Override ++ public void dataChanged(final String path, final String data) { ++ listener.dataChanged(toCloudnamePath(path, TEMPORARY_ROOT), data); ++ } ++ @Override ++ public void nodeRemoved(final String path) { ++ listener.leaseRemoved(toCloudnamePath(path, TEMPORARY_ROOT)); ++ } ++ }); ++ ++ synchronized (syncObject) { ++ clientListeners.put(listener, watcher); ++ } ++ } catch (final Exception exception) { ++ LOG.log(Level.WARNING, ""Got exception when creating node watcher"", exception); ++ } ++ } ++ ++ @Override ++ public void removeTemporaryLeaseListener(final LeaseListener listener) { ++ synchronized (syncObject) { ++ final NodeCollectionWatcher watcher = clientListeners.get(listener); ++ if (watcher != null) { ++ clientListeners.remove(listener); ++ watcher.shutdown(); ++ } ++ } ++ } ++ ++ @Override ++ public boolean createPermanantLease(final CloudnamePath path, final String data) { ++ final String zkPath = PERMANENT_ROOT + path.join('/'); ++ try { ++ curator.sync().forPath(zkPath); ++ final Stat nodeStat = curator.checkExists().forPath(zkPath); ++ if (nodeStat == null) { ++ curator.create() ++ .creatingParentContainersIfNeeded() ++ .forPath(zkPath, data.getBytes(Charsets.UTF_8)); ++ return true; ++ } ++ LOG.log(Level.INFO, ""Attempt to create permanent node at "" + path ++ + "" with data "" + data + "" but it already exists""); ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got exception creating parent container for permanent lease"" ++ + "" for lease "" + path + "" with data "" + data, ex); ++ } ++ return false; ++ } ++ ++ @Override ++ public boolean removePermanentLease(final CloudnamePath path) { ++ final String zkPath = PERMANENT_ROOT + path.join('/'); ++ try { ++ final Stat nodeStat = curator.checkExists().forPath(zkPath); ++ if (nodeStat != null) { ++ curator.delete() ++ .withVersion(nodeStat.getVersion()) ++ .forPath(zkPath); ++ return true; ++ } ++ return false; ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got error removing permanent lease for lease "" + path, ex); ++ return false; ++ } ++ } ++ ++ @Override ++ public boolean writePermanentLeaseData(final CloudnamePath path, final String data) { ++ final String zkPath = PERMANENT_ROOT + path.join('/'); ++ try { ++ curator.sync().forPath(zkPath); ++ final Stat nodeStat = curator.checkExists().forPath(zkPath); ++ if (nodeStat == null) { ++ LOG.log(Level.WARNING, ""Can't write permanent lease data for lease "" + path ++ + "" with data "" + data + "" since the lease doesn't exist""); ++ return false; ++ } ++ curator.setData() ++ .withVersion(nodeStat.getVersion()) ++ .forPath(zkPath, data.getBytes(Charsets.UTF_8)); ++ } catch (final Exception ex) { ++ LOG.log(Level.WARNING, ""Got exception writing permanent lease data for "" + path ++ + "" with data "" + data, ex); ++ return false; ++ } ++ return true; ++ } ++ ++ @Override ++ public String readPermanentLeaseData(final CloudnamePath path) { ++ final String zkPath = PERMANENT_ROOT + path.join('/'); ++ try { ++ curator.sync().forPath(zkPath); ++ final byte[] bytes = curator.getData().forPath(zkPath); ++ return new String(bytes, Charsets.UTF_8); ++ } catch (final Exception ex) { ++ if (ex instanceof KeeperException.NoNodeException) { ++ // OK - nothing to worry about ++ return null; ++ } ++ LOG.log(Level.WARNING, ""Got exception reading permanent lease data for "" + path, ex); ++ return null; ++ } ++ } ++ ++ @Override ++ public void addPermanentLeaseListener(final CloudnamePath pathToObserve, final LeaseListener listener) { ++ try { ++ ++ final String parentPath = PERMANENT_ROOT + pathToObserve.getParent().join('/'); ++ final String fullPath = PERMANENT_ROOT + pathToObserve.join('/'); ++ curator.createContainers(parentPath); ++ final NodeCollectionWatcher watcher = new NodeCollectionWatcher(curator.getZookeeperClient().getZooKeeper(), ++ parentPath, ++ new NodeWatcherListener() { ++ @Override ++ public void nodeCreated(final String path, final String data) { ++ if (path.equals(fullPath)) { ++ listener.leaseCreated(toCloudnamePath(path, PERMANENT_ROOT), data); ++ } ++ } ++ @Override ++ public void dataChanged(final String path, final String data) { ++ if (path.equals(fullPath)) { ++ listener.dataChanged(toCloudnamePath(path, PERMANENT_ROOT), data); ++ } ++ } ++ @Override ++ public void nodeRemoved(final String path) { ++ if (path.equals(fullPath)) { ++ listener.leaseRemoved(toCloudnamePath(path, PERMANENT_ROOT)); ++ } ++ } ++ }); ++ ++ synchronized (syncObject) { ++ permanentListeners.put(listener, watcher); ++ } ++ } catch (final Exception exception) { ++ LOG.log(Level.WARNING, ""Got exception when creating node watcher"", exception); ++ } ++ } ++ ++ @Override ++ public void removePermanentLeaseListener(final LeaseListener listener) { ++ synchronized (syncObject) { ++ final NodeCollectionWatcher watcher = permanentListeners.get(listener); ++ if (watcher != null) { ++ permanentListeners.remove(listener); ++ watcher.shutdown(); ++ } ++ } ++ } ++ ++ @Override ++ public void close() { ++ synchronized (syncObject) { ++ for (final NodeCollectionWatcher watcher : clientListeners.values()) { ++ watcher.shutdown(); ++ } ++ clientListeners.clear(); ++ for (final NodeCollectionWatcher watcher : permanentListeners.values()) { ++ watcher.shutdown(); ++ } ++ permanentListeners.clear(); ++ } ++ } ++} +diff --git a/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java +new file mode 100644 +index 00000000..adb41310 +--- /dev/null ++++ b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/NodeCollectionWatcherTest.java +@@ -0,0 +1,367 @@ ++package org.cloudname.backends.zookeeper; ++ ++import org.apache.curator.CuratorConnectionLossException; ++import org.apache.curator.RetryPolicy; ++import org.apache.curator.framework.CuratorFramework; ++import org.apache.curator.framework.CuratorFrameworkFactory; ++import org.apache.curator.retry.RetryUntilElapsed; ++import org.apache.curator.test.InstanceSpec; ++import org.apache.curator.test.TestingCluster; ++import org.apache.zookeeper.ZooKeeper; ++import org.apache.zookeeper.data.Stat; ++import org.junit.AfterClass; ++import org.junit.BeforeClass; ++import org.junit.Test; ++ ++import java.nio.charset.Charset; ++import java.util.concurrent.CountDownLatch; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicBoolean; ++import java.util.concurrent.atomic.AtomicInteger; ++ ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.not; ++import static org.hamcrest.CoreMatchers.notNullValue; ++import static org.junit.Assert.assertThat; ++import static org.junit.Assert.assertTrue; ++import static org.junit.Assume.assumeThat; ++ ++/** ++ * Test the node watching mechanism. ++ */ ++public class NodeCollectionWatcherTest { ++ private static TestingCluster zkServer; ++ private static CuratorFramework curator; ++ private static ZooKeeper zooKeeper; ++ ++ @BeforeClass ++ public static void setUp() throws Exception { ++ zkServer = new TestingCluster(3); ++ zkServer.start(); ++ final RetryPolicy retryPolicy = new RetryUntilElapsed(60000, 100); ++ curator = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), retryPolicy); ++ curator.start(); ++ curator.blockUntilConnected(10, TimeUnit.SECONDS); ++ zooKeeper = curator.getZookeeperClient().getZooKeeper(); ++ } ++ ++ @AfterClass ++ public static void tearDown() throws Exception { ++ zkServer.close(); ++ } ++ ++ private final AtomicInteger counter = new AtomicInteger(0); ++ ++ private byte[] getData() { ++ return ("""" + counter.incrementAndGet()).getBytes(Charset.defaultCharset()); ++ } ++ ++ /** ++ * A custom listener that counts and counts down notifications. ++ */ ++ private class ListenerCounter implements NodeWatcherListener { ++ // Then a few counters to check the number of events ++ public AtomicInteger createCount = new AtomicInteger(0); ++ public AtomicInteger dataCount = new AtomicInteger(0); ++ public AtomicInteger removeCount = new AtomicInteger(0); ++ public CountDownLatch createLatch; ++ public CountDownLatch dataLatch; ++ public CountDownLatch removeLatch; ++ ++ public ListenerCounter(final int createLatchCount, final int dataLatchCount, final int removeLatchCount) { ++ createLatch = new CountDownLatch(createLatchCount); ++ dataLatch = new CountDownLatch(dataLatchCount); ++ removeLatch = new CountDownLatch(removeLatchCount); ++ } ++ ++ @Override ++ public void nodeCreated(String zkPath, String data) { ++ createCount.incrementAndGet(); ++ createLatch.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(String zkPath, String data) { ++ dataCount.incrementAndGet(); ++ dataLatch.countDown(); ++ } ++ ++ @Override ++ public void nodeRemoved(String zkPath) { ++ removeCount.incrementAndGet(); ++ removeLatch.countDown(); ++ } ++ } ++ ++ @Test ++ public void sequentialNotifications() throws Exception { ++ final int maxPropagationTime = 4; ++ ++ final String pathPrefix = ""/foo/slow""; ++ curator.create().creatingParentsIfNeeded().forPath(pathPrefix); ++ ++ final ListenerCounter listener = new ListenerCounter(1, 1, 1); ++ ++ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener); ++ ++ // Create should trigger create notification (and no other notification) ++ curator.create().forPath(pathPrefix + ""/node1"", getData()); ++ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(0)); ++ assertThat(listener.removeCount.get(), is(0)); ++ ++ // Data change should trigger the data notification (and no other notification) ++ curator.setData().forPath(pathPrefix + ""/node1"", getData()); ++ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(1)); ++ assertThat(listener.removeCount.get(), is(0)); ++ ++ // Delete should trigger the remove notification (and no other notification) ++ curator.delete().forPath(pathPrefix + ""/node1""); ++ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(1)); ++ assertThat(listener.removeCount.get(), is(1)); ++ ++ nodeCollectionWatcher.shutdown(); ++ ++ // Ensure that there are no notifications when the watcher shuts down ++ curator.create().forPath(pathPrefix + ""node_9"", getData()); ++ Thread.sleep(maxPropagationTime); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(1)); ++ assertThat(listener.removeCount.get(), is(1)); ++ ++ curator.setData().forPath(pathPrefix + ""node_9"", getData()); ++ Thread.sleep(maxPropagationTime); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(1)); ++ assertThat(listener.removeCount.get(), is(1)); ++ ++ curator.delete().forPath(pathPrefix + ""node_9""); ++ Thread.sleep(maxPropagationTime); ++ assertThat(listener.createCount.get(), is(1)); ++ assertThat(listener.dataCount.get(), is(1)); ++ assertThat(listener.removeCount.get(), is(1)); ++ } ++ ++ /** ++ * Make rapid changes to ZooKeeper. The changes (most likely) won't be caught by the ++ * watcher events but must be generated by the class itself. Ensure the correct number ++ * of notifications is generated. ++ */ ++ @Test ++ public void rapidChanges() throws Exception { ++ final int maxPropagationTime = 100; ++ ++ final String pathPrefix = ""/foo/rapido""; ++ ++ curator.create().creatingParentsIfNeeded().forPath(pathPrefix); ++ ++ final int numNodes = 50; ++ final ListenerCounter listener = new ListenerCounter(numNodes, 0, numNodes); ++ ++ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener); ++ // Create all of the nodes at once ++ for (int i = 0; i < numNodes; i++) { ++ curator.create().forPath(pathPrefix + ""/node"" + i, getData()); ++ } ++ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(numNodes)); ++ assertThat(listener.dataCount.get(), is(0)); ++ assertThat(listener.removeCount.get(), is(0)); ++ ++ // Repeat data test multiple times to ensure data changes are detected ++ // repeatedly on the same nodes ++ int total = 0; ++ for (int j = 0; j < 5; j++) { ++ listener.dataLatch = new CountDownLatch(numNodes); ++ // Since there's a watch for every node all of the data changes should be detected ++ for (int i = 0; i < numNodes; i++) { ++ curator.setData().forPath(pathPrefix + ""/node"" + i, getData()); ++ } ++ total += numNodes; ++ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(numNodes)); ++ assertThat(listener.dataCount.get(), is(total)); ++ assertThat(listener.removeCount.get(), is(0)); ++ } ++ ++ // Finally, remove everything in rapid succession ++ // Create all of the nodes at once ++ for (int i = 0; i < numNodes; i++) { ++ curator.delete().forPath(pathPrefix + ""/node"" + i); ++ } ++ ++ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(numNodes)); ++ assertThat(listener.dataCount.get(), is(total)); ++ assertThat(listener.removeCount.get(), is(numNodes)); ++ ++ nodeCollectionWatcher.shutdown(); ++ } ++ ++ /** ++ * Emulate a network partition by killing off two out of three ZooKeeper instances ++ * and check the output. Set the system property NodeWatcher.SlowTests to ""ok"" to enable ++ * it. The test itself can be quite slow depending on what Curator is connected to. If ++ * Curator uses one of the servers that are killed it will try a reconnect and the whole ++ * test might take up to 120-180 seconds to complete. ++ */ ++ @Test ++ public void networkPartitionTest() throws Exception { ++ assumeThat(System.getProperty(""NodeCollectionWatcher.SlowTests""), is(""ok"")); ++ ++ final int maxPropagationTime = 10; ++ ++ final String pathPrefix = ""/foo/partition""; ++ curator.create().creatingParentsIfNeeded().forPath(pathPrefix); ++ ++ final int nodeCount = 10; ++ ++ final ListenerCounter listener = new ListenerCounter(nodeCount, nodeCount, nodeCount); ++ ++ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener); ++ ++ // Create a few nodes to set the initial state ++ for (int i = 0; i < nodeCount; i++) { ++ curator.create().forPath(pathPrefix + ""/node"" + i, getData()); ++ } ++ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(nodeCount)); ++ assertThat(listener.removeCount.get(), is(0)); ++ assertThat(listener.dataCount.get(), is(0)); ++ ++ final InstanceSpec firstInstance = zkServer.findConnectionInstance(zooKeeper); ++ zkServer.killServer(firstInstance); ++ ++ listener.createLatch = new CountDownLatch(1); ++ // Client should reconnect to one of the two remaining ++ curator.create().forPath(pathPrefix + ""/stillalive"", getData()); ++ // Wait for the notification to go through. This could take some time since there's ++ // reconnects and all sorts of magic happening under the hood ++ assertTrue(listener.createLatch.await(10, TimeUnit.SECONDS)); ++ assertThat(listener.createCount.get(), is(nodeCount + 1)); ++ assertThat(listener.removeCount.get(), is(0)); ++ assertThat(listener.dataCount.get(), is(0)); ++ ++ // Kill the 2nd server. The cluster won't have a quorum now ++ final InstanceSpec secondInstance = zkServer.findConnectionInstance(zooKeeper); ++ assertThat(firstInstance, is(not(secondInstance))); ++ zkServer.killServer(secondInstance); ++ ++ boolean retry; ++ do { ++ System.out.println(""Checking node with Curator... This might take a while...""); ++ try { ++ final Stat stat = curator.checkExists().forPath(pathPrefix); ++ retry = false; ++ assertThat(stat, is(notNullValue())); ++ } catch (CuratorConnectionLossException ex) { ++ System.out.println(""Missing connection. Retrying""); ++ retry = true; ++ } ++ } while (retry); ++ ++ zkServer.restartServer(firstInstance); ++ zkServer.restartServer(secondInstance); ++ listener.createLatch = new CountDownLatch(1); ++ ++ System.out.println(""Creating node via Curator... This might take a while...""); ++ curator.create().forPath(pathPrefix + ""/imback"", getData()); ++ ++ assertTrue(listener.createLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(nodeCount + 2)); ++ assertThat(listener.removeCount.get(), is(0)); ++ assertThat(listener.dataCount.get(), is(0)); ++ ++ // Ensure data notifications are propagated after a failure ++ for (int i = 0; i < nodeCount; i++) { ++ final Stat stat = curator.setData().forPath(pathPrefix + ""/node"" + i, getData()); ++ assertThat(stat, is(notNullValue())); ++ } ++ assertTrue(listener.dataLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(nodeCount + 2)); ++ assertThat(listener.removeCount.get(), is(0)); ++ assertThat(listener.dataCount.get(), is(nodeCount)); ++ ++ // ..and remove notifications are sent ++ for (int i = 0; i < nodeCount; i++) { ++ curator.delete().forPath(pathPrefix + ""/node"" + i); ++ } ++ assertTrue(listener.removeLatch.await(maxPropagationTime, TimeUnit.MILLISECONDS)); ++ assertThat(listener.createCount.get(), is(nodeCount + 2)); ++ assertThat(listener.removeCount.get(), is(nodeCount)); ++ assertThat(listener.dataCount.get(), is(nodeCount)); ++ ++ nodeCollectionWatcher.shutdown(); ++ ++ } ++ ++ /** ++ * Be a misbehaving client and throw exceptions in the listners. Ensure the watcher still works ++ * afterwards. ++ */ ++ @Test ++ public void misbehavingClient() throws Exception { ++ final int propagationTime = 5; ++ ++ final AtomicBoolean triggerExceptions = new AtomicBoolean(false); ++ final CountDownLatch createLatch = new CountDownLatch(1); ++ final CountDownLatch dataLatch = new CountDownLatch(1); ++ final CountDownLatch removeLatch = new CountDownLatch(1); ++ ++ final NodeWatcherListener listener = new NodeWatcherListener() { ++ @Override ++ public void nodeCreated(String zkPath, String data) { ++ if (triggerExceptions.get()) { ++ throw new RuntimeException(""boo!""); ++ } ++ createLatch.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(String zkPath, String data) { ++ if (triggerExceptions.get()) { ++ throw new RuntimeException(""boo!""); ++ } ++ dataLatch.countDown(); ++ } ++ ++ @Override ++ public void nodeRemoved(String zkPath) { ++ if (triggerExceptions.get()) { ++ throw new RuntimeException(""boo!""); ++ } ++ removeLatch.countDown(); ++ } ++ }; ++ ++ final String pathPrefix = ""/foo/misbehaving""; ++ ++ curator.create().creatingParentsIfNeeded().forPath(pathPrefix); ++ ++ final NodeCollectionWatcher nodeCollectionWatcher = new NodeCollectionWatcher(zooKeeper, pathPrefix, listener); ++ ++ triggerExceptions.set(true); ++ curator.create().forPath(pathPrefix + ""/first"", getData()); ++ Thread.sleep(propagationTime); ++ curator.setData().forPath(pathPrefix + ""/first"", getData()); ++ Thread.sleep(propagationTime); ++ curator.delete().forPath(pathPrefix + ""/first""); ++ Thread.sleep(propagationTime); ++ ++ // Now create a node but without setting the data field. ++ triggerExceptions.set(false); ++ curator.create().forPath(pathPrefix + ""/second""); ++ assertTrue(createLatch.await(propagationTime, TimeUnit.MILLISECONDS)); ++ curator.setData().forPath(pathPrefix + ""/second"", getData()); ++ assertTrue(dataLatch.await(propagationTime, TimeUnit.MILLISECONDS)); ++ curator.delete().forPath(pathPrefix + ""/second""); ++ assertTrue(removeLatch.await(propagationTime, TimeUnit.MILLISECONDS)); ++ ++ nodeCollectionWatcher.shutdown(); ++ } ++} +diff --git a/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java +new file mode 100644 +index 00000000..393b78b4 +--- /dev/null ++++ b/cn-zookeeper/src/test/java/org/cloudname/backends/zookeeper/ZooKeeperBackendTest.java +@@ -0,0 +1,36 @@ ++package org.cloudname.backends.zookeeper; ++ ++import org.apache.curator.test.TestingCluster; ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.testtools.backend.CoreBackendTest; ++import org.junit.AfterClass; ++import org.junit.BeforeClass; ++ ++import java.util.concurrent.atomic.AtomicReference; ++ ++/** ++ * Test the ZooKeeper backend. ++ */ ++public class ZooKeeperBackendTest extends CoreBackendTest { ++ private static TestingCluster testCluster; ++ private AtomicReference backend = new AtomicReference<>(null); ++ ++ @BeforeClass ++ public static void setUp() throws Exception { ++ testCluster = new TestingCluster(3); ++ testCluster.start(); ++ } ++ ++ @AfterClass ++ public static void tearDown() throws Exception { ++ testCluster.stop(); ++ } ++ ++ protected CloudnameBackend getBackend() { ++ if (backend.get() == null) { ++ backend.compareAndSet(null, new ZooKeeperBackend(testCluster.getConnectString())); ++ } ++ return backend.get(); ++ ++ } ++} +diff --git a/cn/pom.xml b/cn/pom.xml +deleted file mode 100644 +index f46d83ff..00000000 +--- a/cn/pom.xml ++++ /dev/null +@@ -1,93 +0,0 @@ +- +- 4.0.0 +- +- +- org.cloudname +- cloudname-parent +- 3.0-SNAPSHOT +- +- +- cn +- jar +- +- Cloudname Library +- Simple library for managing resources using ZooKeeper. +- https://github.com/Cloudname/cloudname +- +- +- +- org.cloudname +- testtools +- +- +- +- org.apache.zookeeper +- zookeeper +- +- +- +- com.fasterxml.jackson.core +- jackson-databind +- +- +- +- org.cloudname +- flags +- +- +- +- junit +- junit-dep +- test +- +- +- +- org.hamcrest +- hamcrest-all +- 1.3 +- +- +- +- +- +- +- org.dstovall +- onejar-maven-plugin +- 1.4.4 +- +- +- +- +- true +- org.cloudname.zk.ZkTool +- ZkTool.jar +- +- +- one-jar +- +- +- +- +- +- org.apache.maven.plugins +- maven-surefire-plugin +- +- +- org.apache.maven.plugins +- maven-antrun-plugin +- +- +- org.codehaus.mojo +- build-helper-maven-plugin +- +- +- org.apache.maven.plugins +- maven-compiler-plugin +- +- +- maven-failsafe-plugin +- +- +- +- +diff --git a/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java b/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java +deleted file mode 100644 +index b5d7daaa..00000000 +--- a/cn/src/integrationtest/java/org/cloudname/zk/ZkCloudnameIntegrationTest.java ++++ /dev/null +@@ -1,480 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +-import org.apache.zookeeper.ZooDefs; +-import org.apache.zookeeper.ZooKeeper; +-import org.cloudname.Cloudname; +-import org.cloudname.CloudnameException; +-import org.cloudname.Coordinate; +-import org.cloudname.CoordinateException; +-import org.cloudname.CoordinateExistsException; +-import org.cloudname.CoordinateListener; +-import org.cloudname.ServiceHandle; +-import org.cloudname.ServiceState; +-import org.cloudname.ServiceStatus; +-import org.cloudname.testtools.Net; +-import org.cloudname.testtools.network.PortForwarder; +-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper; +-import org.junit.After; +-import org.junit.Before; +-import org.junit.Rule; +-import org.junit.Test; +-import org.junit.rules.TemporaryFolder; +- +-import java.io.File; +-import java.util.ArrayList; +-import java.util.HashSet; +-import java.util.List; +-import java.util.Set; +-import java.util.concurrent.CopyOnWriteArrayList; +-import java.util.concurrent.CountDownLatch; +-import java.util.concurrent.TimeUnit; +-import java.util.logging.Logger; +- +-import static org.junit.Assert.*; +- +-/** +- * Integration tests for testing ZkCloudname. +- * Contains mostly heavy tests containing sleep calls not fit as a unit test. +- */ +-public class ZkCloudnameIntegrationTest { +- private static final Logger LOG = Logger.getLogger(ZkCloudnameIntegrationTest.class.getName()); +- +- private EmbeddedZooKeeper ezk; +- private ZooKeeper zk; +- private int zkport; +- private PortForwarder forwarder = null; +- private int forwarderPort; +- private ZkCloudname cn = null; +- +- @Rule +- public TemporaryFolder temp = new TemporaryFolder(); +- +- /** +- * Set up an embedded ZooKeeper instance backed by a temporary +- * directory. The setup procedure also allocates a port that is +- * free for the ZooKeeper server so that you should be able to run +- * multiple instances of this test. +- */ +- @Before +- public void setup() throws Exception { +- File rootDir = temp.newFolder(""zk-test""); +- zkport = Net.getFreePort(); +- +- LOG.info(""EmbeddedZooKeeper rootDir="" + rootDir.getCanonicalPath() + "", port="" + zkport); +- +- // Set up and initialize the embedded ZooKeeper +- ezk = new EmbeddedZooKeeper(rootDir, zkport); +- ezk.init(); +- +- // Set up a zookeeper client that we can use for inspection +- final CountDownLatch connectedLatch = new CountDownLatch(1); +- +- zk = new ZooKeeper(""localhost:"" + zkport, 1000, new Watcher() { +- @Override +- public void process(WatchedEvent event) { +- if (event.getState() == Event.KeeperState.SyncConnected) { +- connectedLatch.countDown(); +- } +- } +- }); +- connectedLatch.await(); +- +- LOG.info(""ZooKeeper port is "" + zkport); +- } +- +- @After +- public void tearDown() throws Exception { +- zk.close(); +- if (forwarder != null) { +- forwarder.close(); +- } +- ezk.shutdown(); +- } +- +- /** +- * A coordinate listener that stores events and calls a latch. +- */ +- class TestCoordinateListener implements CoordinateListener { +- private final List events = new CopyOnWriteArrayList(); +- +- private final Set listenerLatches; +- +- private final List waitForEvent = new ArrayList(); +- private final Object eventMonitor = new Object(); +- private final List waitForLatch = new ArrayList(); +- +- public boolean failOnWrongEvent = false; +- private CountDownLatch latestLatch = null; +- +- void waitForExpected() throws InterruptedException { +- final CountDownLatch latch; +- synchronized (eventMonitor) { +- if (waitForEvent.size() > 0) { +- LOG.info(""Waiting for event "" + waitForEvent.get(waitForEvent.size() - 1)); +- latch = latestLatch; +- } else { +- return; +- } +- } +- assert(latch.await(25, TimeUnit.SECONDS)); +- LOG.info(""Event happened.""); +- } +- +- public TestCoordinateListener(final Set listenerLatches) { +- this.listenerLatches = listenerLatches; +- } +- +- public void expectEvent(final Event event) { +- LOG.info(""Expecting event "" + event.name()); +- synchronized (eventMonitor) { +- waitForEvent.add(event); +- latestLatch = new CountDownLatch(1); +- waitForLatch.add(latestLatch); +- } +- } +- +- @Override +- public void onCoordinateEvent(Event event, String message) { +- LOG.info(""I got event ..."" + event.name() + "" "" + message); +- synchronized (eventMonitor) { +- if (waitForEvent.size() > 0) { +- LOG.info(""Waiting for event "" + waitForEvent.get(0)); +- } else { +- LOG.info(""not expecting any specific events""); +- } +- events.add(event); +- for (CountDownLatch countDownLatch :listenerLatches) { +- countDownLatch.countDown(); +- } +- if (waitForEvent.size() > 0 && waitForEvent.get(0) == event) { +- waitForLatch.remove(0).countDown(); +- waitForEvent.remove(0); +- } else { +- assertFalse(failOnWrongEvent); +- } +- } +- } +- } +- +- private TestCoordinateListener setUpListenerEnvironment( +- final CountDownLatch latch) throws Exception { +- Set latches = new HashSet(); +- latches.add(latch); +- return setUpListenerEnvironment(latches); +- } +- +- private TestCoordinateListener setUpListenerEnvironment( +- final Set listenerLatches) throws Exception { +- forwarderPort = Net.getFreePort(); +- forwarder = new PortForwarder(forwarderPort, ""127.0.0.1"", zkport); +- final Coordinate c = Coordinate.parse(""1.service.user.cell""); +- +- cn = makeLocalZkCloudname(forwarderPort); +- try { +- cn.createCoordinate(c); +- } catch (CoordinateException e) { +- fail(e.toString()); +- } +- final TestCoordinateListener listener = new TestCoordinateListener(listenerLatches); +- ServiceHandle serviceHandle = cn.claim(c); +- assert(serviceHandle.waitForCoordinateOkSeconds(3 /* secs */)); +- serviceHandle.registerCoordinateListener(listener); +- +- return listener; +- } +- +- @Test +- public void testCoordinateListenerInitialEvent() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(15, TimeUnit.SECONDS)); +- assertEquals(1, listener.events.size()); +- assertEquals(CoordinateListener.Event.COORDINATE_OK, listener.events.get(0)); +- } +- +- @Test +- public void testCoordinateListenerConnectionDies() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- forwarder.close(); +- forwarder = null; +- listener.waitForExpected(); +- } +- +- @Test +- public void testCoordinateListenerCoordinateCorrupted() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- +- listener.expectEvent(CoordinateListener.Event.NOT_OWNER); +- +- byte[] garbageBytes = ""sdfgsdfgsfgdsdfgsdfgsdfg"".getBytes(""UTF-16LE""); +- +- zk.setData(""/cn/cell/user/service/1/status"", garbageBytes, -1); +- listener.waitForExpected(); +- } +- +- @Test +- public void testCoordinateListenerCoordinateOutOfSync() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- +- listener.expectEvent(CoordinateListener.Event.NOT_OWNER); +- +- String source = ""\""{\\\""state\\\"":\\\""STARTING\\\"",\\\""message\\\"":\\\""Lost hamster.\\\""}\"" {}""; +- byte[] byteArray = source.getBytes(Util.CHARSET_NAME); +- +- zk.setData(""/cn/cell/user/service/1/status"", byteArray, -1); +- +- listener.waitForExpected(); +- } +- +- @Test +- public void testCoordinateListenerCoordinateLost() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- listener.expectEvent(CoordinateListener.Event.NOT_OWNER); +- +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- LOG.info(""Deleting coordinate""); +- forwarder.pause(); +- zk.delete(""/cn/cell/user/service/1/status"", -1); +- zk.delete(""/cn/cell/user/service/1/config"", -1); +- zk.delete(""/cn/cell/user/service/1"", -1); +- forwarder.unpause(); +- +- listener.waitForExpected(); +- +- } +- +- @Test +- public void testCoordinateListenerStolenCoordinate() throws Exception { +- +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- LOG.info(""Killing zookeeper""); +- assertTrue(zk.getState() == ZooKeeper.States.CONNECTED); +- +- LOG.info(""Killing connection""); +- forwarder.pause(); +- +- zk.delete(""/cn/cell/user/service/1/status"", -1); +- Util.mkdir(zk, ""/cn/cell/user/service/1/status"" , ZooDefs.Ids.OPEN_ACL_UNSAFE); +- +- forwarder.unpause(); +- +- listener.expectEvent(CoordinateListener.Event.NOT_OWNER); +- listener.waitForExpected(); +- } +- +- +- @Test +- public void testCoordinateListenerConnectionDiesReconnect() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- +- forwarder.pause(); +- listener.waitForExpected(); +- +- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK); +- forwarder.unpause(); +- listener.waitForExpected(); +- } +- +- /** +- * In this test the ZK server thinks the client is connected, but the client wants to reconnect +- * due to a disconnect. To trig this condition the connection needs to be down for +- * a specific time. This test does not fail even if it does not manage to create this +- * state. It will write the result to the log. The test is useful for development and +- * should not fail. +- */ +- @Test +- public void testCoordinateListenerConnectionDiesReconnectAfterTimeoutClient() +- throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- assertEquals(CoordinateListener.Event.COORDINATE_OK, +- listener.events.get(listener.events.size() -1 )); +- +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- LOG.info(""Killing connection""); +- forwarder.pause(); +- +- LOG.info(""Connection down.""); +- listener.waitForExpected(); +- +- // Client sees problem, server not. +- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK); +- +- // 3400 is a magic number for getting zookeeper and local client in a specific state. +- Thread.sleep(2400); +- LOG.info(""Recreating connection soon"" + forwarderPort + ""->"" + zkport); +- +- +- forwarder.unpause(); +- listener.waitForExpected(); // COORDINATE_OK +- +- // If the previous event is NOT_OWNER, the wanted situation was created by the test. +- if (listener.events.get(listener.events.size() - 2) == +- CoordinateListener.Event.NOT_OWNER) { +- LOG.info(""Manage to trig event inn ZooKeeper, true positive.""); +- } else { +- LOG.info(""Did NOT manage to trig event in ZooKeeper. This depends on timing, so "" + +- ""ignoring this problem""); +- } +- } +- +- @Test +- public void testCoordinateListenerConnectionDiesReconnectAfterTimeout() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- assertEquals(CoordinateListener.Event.COORDINATE_OK, +- listener.events.get(listener.events.size() -1 )); +- +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- +- forwarder.close(); +- forwarder = null; +- listener.waitForExpected(); +- // We do not want NOT OWNER event from ZooKeeper. Therefore this long time out. +- LOG.info(""Going into sleep, waiting for zookeeper to loose node""); +- Thread.sleep(10000); +- +- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK); +- forwarder = new PortForwarder(forwarderPort, ""127.0.0.1"", zkport); +- +- // We need to re-instantiate the forwarder, or zookeeper thinks +- // the connection is good and will not kill the ephemeral node. +- // This is probably because we keep the server socket against zookeeper open +- // in pause mode. +- +- listener.waitForExpected(); +- } +- +- +- /** +- * Tests the behavior of Zookeeper upon a restart. ZK should clean up old coordinates. +- * @throws Exception +- */ +- @Test +- public void testZookeeperRestarts() throws Exception { +- final CountDownLatch connectedLatch1 = new CountDownLatch(1); +- final TestCoordinateListener listener = setUpListenerEnvironment(connectedLatch1); +- assertTrue(connectedLatch1.await(20, TimeUnit.SECONDS)); +- +- +- listener.expectEvent(CoordinateListener.Event.NO_CONNECTION_TO_STORAGE); +- forwarder.pause(); +- listener.waitForExpected(); +- +- ezk.shutdown(); +- ezk.del(); +- ezk.init(); +- +- listener.expectEvent(CoordinateListener.Event.NOT_OWNER); +- +- forwarder.unpause(); +- listener.waitForExpected(); +- +- createCoordinateWithRetries(); +- +- listener.expectEvent(CoordinateListener.Event.COORDINATE_OK); +- listener.waitForExpected(); +- } +- +- private void createCoordinateWithRetries() throws CoordinateExistsException, +- InterruptedException, CloudnameException { +- Coordinate c = Coordinate.parse(""1.service.user.cell""); +- int retries = 10; +- for (;;) { +- try { +- cn.createCoordinate(c); +- break; +- } catch (CloudnameException e) { +- /* +- * CloudnameException indicates that the connection with +- * ZooKeeper isn't back up yet. Retry a few times. +- */ +- if (retries-- > 0) { +- LOG.info(""Failed to create coordinate: "" + e +- + "", retrying in 1 second""); +- Thread.sleep(1000); +- } else { +- throw e; +- } +- } +- } +- } +- +- /** +- * Tests that one process claims a coordinate, then another process tries to claim the same coordinate. +- * The first coordinate looses connection to ZooKeeper and the other process gets the coordinate. +- * @throws Exception +- */ +- @Test +- public void testFastHardRestart() throws Exception { +- final Coordinate c = Coordinate.parse(""1.service.user.cell""); +- final CountDownLatch claimLatch1 = new CountDownLatch(1); +- forwarderPort = Net.getFreePort(); +- forwarder = new PortForwarder(forwarderPort, ""127.0.0.1"", zkport); +- final Cloudname cn1 = new ZkCloudname.Builder().setConnectString( +- ""localhost:"" + forwarderPort).build().connect(); +- cn1.createCoordinate(c); +- +- ServiceHandle handle1 = cn1.claim(c); +- handle1.registerCoordinateListener(new CoordinateListener() { +- +- @Override +- public void onCoordinateEvent(Event event, String message) { +- if (event == Event.COORDINATE_OK) { +- claimLatch1.countDown(); +- } +- } +- }); +- assertTrue(claimLatch1.await(5, TimeUnit.SECONDS)); +- +- final Cloudname cn2 = new ZkCloudname.Builder().setConnectString( +- ""localhost:"" + zkport).build().connect(); +- +- ServiceHandle handle2 = cn2.claim(c); +- +- forwarder.close(); +- forwarder = null; +- +- assertTrue(handle2.waitForCoordinateOkSeconds(20)); +- +- ServiceStatus status = new ServiceStatus(ServiceState.RUNNING, ""updated status""); +- handle2.setStatus(status); +- +- final Cloudname cn3 = new ZkCloudname.Builder().setConnectString(""localhost:"" + zkport) +- .build().connect(); +- ServiceStatus statusRetrieved = cn3.getStatus(c); +- assertEquals(""updated status"", statusRetrieved.getMessage()); +- +- cn1.close(); +- cn2.close(); +- cn3.close(); +- } +- +- /** +- * Makes a local ZkCloudname instance with the port given by zkPort. +- * Then it connects to ZK. +- */ +- private ZkCloudname makeLocalZkCloudname(int port) throws CloudnameException { +- return new ZkCloudname.Builder().setConnectString(""localhost:"" + port).build().connect(); +- } +-} +diff --git a/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java b/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java +deleted file mode 100644 +index b0a01517..00000000 +--- a/cn/src/integrationtest/java/org/cloudname/zk/ZkResolverIntegrationTest.java ++++ /dev/null +@@ -1,420 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.*; +-import org.cloudname.*; +-import org.cloudname.testtools.Net; +-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper; +-import org.junit.After; +-import org.junit.Before; +-import org.junit.Rule; +-import org.junit.Test; +-import org.junit.rules.TemporaryFolder; +- +-import java.io.File; +-import java.util.ArrayList; +-import java.util.List; +-import java.util.Set; +-import java.util.concurrent.CountDownLatch; +-import java.util.concurrent.TimeUnit; +- +-import static org.junit.Assert.*; +-import static org.junit.Assert.assertEquals; +- +-/** +- * Integration tests for the ZkResolver class. +- * This test class contains tests dependent on timing or +- * tests depending on other modules, or both. +- */ +-public class ZkResolverIntegrationTest { +- private ZooKeeper zk; +- private Cloudname cn; +- private Coordinate coordinateRunning; +- private Coordinate coordinateDraining; +- @Rule +- public TemporaryFolder temp = new TemporaryFolder(); +- private ServiceHandle handleDraining; +- +- +- /** +- * Set up an embedded ZooKeeper instance backed by a temporary +- * directory. The setup procedure also allocates a port that is +- * free for the ZooKeeper server so that you should be able to run +- * multiple instances of this test. +- */ +- @Before +- public void setup() throws Exception { +- +- // Speed up tests waiting for this event to happen. +- DynamicExpression.TIME_BETWEEN_NODE_SCANNING_MS = 200; +- +- File rootDir = temp.newFolder(""zk-test""); +- final int zkport = Net.getFreePort(); +- +- // Set up and initialize the embedded ZooKeeper +- final EmbeddedZooKeeper ezk = new EmbeddedZooKeeper(rootDir, zkport); +- ezk.init(); +- +- // Set up a zookeeper client that we can use for inspection +- final CountDownLatch connectedLatch = new CountDownLatch(1); +- zk = new ZooKeeper(""localhost:"" + zkport, 1000, new Watcher() { +- public void process(WatchedEvent event) { +- if (event.getState() == Event.KeeperState.SyncConnected) { +- connectedLatch.countDown(); +- } +- } +- }); +- connectedLatch.await(); +- coordinateRunning = Coordinate.parse(""1.service.user.cell""); +- cn = new ZkCloudname.Builder().setConnectString(""localhost:"" + zkport).build().connect(); +- cn.createCoordinate(coordinateRunning); +- ServiceHandle handleRunning = cn.claim(coordinateRunning); +- assertTrue(handleRunning.waitForCoordinateOkSeconds(30)); +- +- handleRunning.putEndpoint(new Endpoint( +- coordinateRunning, ""foo"", ""localhost"", 1234, ""http"", ""data"")); +- handleRunning.putEndpoint(new Endpoint( +- coordinateRunning, ""bar"", ""localhost"", 1235, ""http"", null)); +- ServiceStatus statusRunning = new ServiceStatus(ServiceState.RUNNING, ""Running message""); +- handleRunning.setStatus(statusRunning); +- +- coordinateDraining = Coordinate.parse(""0.service.user.cell""); +- cn.createCoordinate(coordinateDraining); +- handleDraining = cn.claim(coordinateDraining); +- assertTrue(handleDraining.waitForCoordinateOkSeconds(10)); +- handleDraining.putEndpoint(new Endpoint( +- coordinateDraining, ""foo"", ""localhost"", 5555, ""http"", ""data"")); +- handleDraining.putEndpoint(new Endpoint( +- coordinateDraining, ""bar"", ""localhost"", 5556, ""http"", null)); +- +- ServiceStatus statusDraining = new ServiceStatus(ServiceState.DRAINING, ""Draining message""); +- handleDraining.setStatus(statusDraining); +- } +- +- @After +- public void tearDown() throws Exception { +- zk.close(); +- } +- +- +- public void undrain() throws CoordinateMissingException, CloudnameException { +- ServiceStatus statusDraining = new ServiceStatus(ServiceState.RUNNING, ""alive""); +- handleDraining.setStatus(statusDraining); +- } +- +- public void drain() throws CoordinateMissingException, CloudnameException { +- ServiceStatus statusDraining = new ServiceStatus(ServiceState.DRAINING, ""dead""); +- handleDraining.setStatus(statusDraining); +- } +- +- public void changeEndpointData() throws CoordinateMissingException, CloudnameException { +- handleDraining.putEndpoint(new Endpoint( +- coordinateDraining, ""foo"", ""localhost"", 5555, ""http"", ""dataChanged"")); +- } +- +- public void changeEndpointPort() throws CoordinateMissingException, CloudnameException { +- handleDraining.putEndpoint(new Endpoint( +- coordinateDraining, ""foo"", ""localhost"", 5551, ""http"", ""dataChanged"")); +- } +- +- @Test +- public void testStatus() throws Exception { +- ServiceStatus status = cn.getStatus(coordinateRunning); +- assertEquals(ServiceState.RUNNING, status.getState()); +- assertEquals(""Running message"", status.getMessage()); +- } +- +- @Test +- public void testBasicSyncResolving() throws Exception { +- List endpoints = cn.getResolver().resolve(""foo.1.service.user.cell""); +- assertEquals(1, endpoints.size()); +- assertEquals(""foo"", endpoints.get(0).getName()); +- assertEquals(""localhost"", endpoints.get(0).getHost()); +- assertEquals(""1.service.user.cell"", endpoints.get(0).getCoordinate().toString()); +- assertEquals(""data"", endpoints.get(0).getEndpointData()); +- assertEquals(""http"", endpoints.get(0).getProtocol()); +- } +- +- +- @Test +- public void testAnyResolving() throws Exception { +- List endpoints = cn.getResolver().resolve(""foo.any.service.user.cell""); +- assertEquals(1, endpoints.size()); +- assertEquals(""foo"", endpoints.get(0).getName()); +- assertEquals(""localhost"", endpoints.get(0).getHost()); +- assertEquals(""1.service.user.cell"", endpoints.get(0).getCoordinate().toString()); +- } +- +- @Test +- public void testAllResolving() throws Exception { +- List endpoints = cn.getResolver().resolve(""all.service.user.cell""); +- assertEquals(2, endpoints.size()); +- assertEquals(""foo"", endpoints.get(0).getName()); +- assertEquals(""bar"", endpoints.get(1).getName()); +- } +- +- /** +- * Tests that all registered endpoints are returned. +- */ +- @Test +- public void testGetCoordinateDataAll() throws Exception { +- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter(); +- Set endpoints = cn.getResolver().getEndpoints(filter); +- assertEquals(4, endpoints.size()); +- } +- +- /** +- * Tests that all methods of the filters are called and some basic filtering are functional. +- */ +- @Test +- public void testGetCoordinateDataFilterOptions() throws Exception { +- final StringBuilder filterCalls = new StringBuilder(); +- +- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter() { +- @Override +- public boolean includeCell(final String datacenter) { +- filterCalls.append(datacenter).append("":""); +- return true; +- } +- @Override +- public boolean includeUser(final String user) { +- filterCalls.append(user).append("":""); +- return true; +- } +- @Override +- public boolean includeService(final String service) { +- filterCalls.append(service).append("":""); +- return true; +- } +- @Override +- public boolean includeEndpointname(final String endpointName) { +- return endpointName.equals(""foo""); +- } +- @Override +- public boolean includeServiceState(final ServiceState state) { +- return state == ServiceState.RUNNING; +- } +- }; +- Set endpoints = cn.getResolver().getEndpoints(filter); +- assertEquals(1, endpoints.size()); +- Endpoint selectedEndpoint = endpoints.iterator().next(); +- +- assertEquals(""foo"", selectedEndpoint.getName()); +- assertEquals(""cell:user:service:"", filterCalls.toString()); +- } +- +- +- /** +- * Test an unclaimed coordinate and a path that is not complete. +- * Number of endpoints should not increase when inputting bad data. +- * @throws Exception +- */ +- @Test +- public void testGetCoordinateDataAllNoClaimedCoordinate() throws Exception { +- // Create unclaimned coordinate. +- Coordinate coordinateNoStatus = Coordinate.parse(""4.service.user.cell""); +- cn.createCoordinate(coordinateNoStatus); +- +- // Throw in a incomplete path. +- zk.create(""/cn/foo"", new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); +- +- Resolver resolver = cn.getResolver(); +- +- Resolver.CoordinateDataFilter filter = new Resolver.CoordinateDataFilter(); +- Set endpoints = resolver.getEndpoints(filter); +- assertEquals(4, endpoints.size()); +- } +- +- @Test +- public void testBasicAsyncResolving() throws Exception { +- Resolver resolver = cn.getResolver(); +- +- final List endpointListNew = new ArrayList(); +- final List endpointListRemoved = new ArrayList(); +- final List endpointListModified = new ArrayList(); +- +- // This class is needed since the abstract resolver listener class can only access final variables. +- class LatchWrapper { +- public CountDownLatch latch; +- } +- final LatchWrapper latchWrapper = new LatchWrapper(); +- +- latchWrapper.latch = new CountDownLatch(1); +- +- resolver.addResolverListener( +- ""foo.all.service.user.cell"", new Resolver.ResolverListener() { +- +- @Override +- public void endpointEvent(Event event, Endpoint endpoint) { +- switch (event) { +- case NEW_ENDPOINT: +- endpointListNew.add(endpoint); +- latchWrapper.latch.countDown(); +- break; +- case REMOVED_ENDPOINT: +- endpointListRemoved.add(endpoint); +- latchWrapper.latch.countDown(); +- break; +- case MODIFIED_ENDPOINT_DATA: +- endpointListModified.add(endpoint); +- latchWrapper.latch.countDown(); +- break; +- } +- } +- }); +- assertTrue(latchWrapper.latch.await(24000, TimeUnit.MILLISECONDS)); +- assertEquals(1, endpointListNew.size()); +- assertEquals(""foo"", endpointListNew.get(0).getName()); +- assertEquals(""1.service.user.cell"", endpointListNew.get(0).getCoordinate().toString()); +- endpointListNew.clear(); +- latchWrapper.latch = new CountDownLatch(1); +- +- undrain(); +- +- +- assertTrue(latchWrapper.latch.await(125000, TimeUnit.MILLISECONDS)); +- +- assertEquals(1, endpointListNew.size()); +- +- assertEquals(""foo"", endpointListNew.get(0).getName()); +- assertEquals(""0.service.user.cell"", endpointListNew.get(0).getCoordinate().toString()); +- +- latchWrapper.latch = new CountDownLatch(1); +- endpointListNew.clear(); +- +- changeEndpointData(); +- +- assertTrue(latchWrapper.latch.await(26000, TimeUnit.MILLISECONDS)); +- +- assertEquals(1, endpointListModified.size()); +- +- assertEquals(""0.service.user.cell"", endpointListModified.get(0).getCoordinate().toString()); +- assertEquals(""foo"", endpointListModified.get(0).getName()); +- assertEquals(""dataChanged"", endpointListModified.get(0).getEndpointData()); +- +- endpointListModified.clear(); +- +- latchWrapper.latch = new CountDownLatch(2); +- +- changeEndpointPort(); +- +- assertTrue(latchWrapper.latch.await(27000, TimeUnit.MILLISECONDS)); +- +- assertEquals(1, endpointListNew.size()); +- assertEquals(1, endpointListRemoved.size()); +- +- endpointListNew.clear(); +- endpointListRemoved.clear(); +- +- +- +- latchWrapper.latch = new CountDownLatch(1); +- +- drain(); +- +- assertTrue(latchWrapper.latch.await(27000, TimeUnit.MILLISECONDS)); +- +- assertEquals(1, endpointListRemoved.size()); +- +- assertEquals(""0.service.user.cell"", endpointListRemoved.get(0).getCoordinate().toString()); +- assertEquals(""foo"", endpointListRemoved.get(0).getName()); +- } +- +- @Test +- public void testBasicAsyncResolvingAnyStrategy() throws Exception { +- Resolver resolver = cn.getResolver(); +- +- final List endpointListNew = new ArrayList(); +- +- // This class is needed since the abstract resolver listener class can only access +- // final variables. +- class LatchWrapper { +- public CountDownLatch latch; +- } +- final LatchWrapper latchWrapper = new LatchWrapper(); +- +- latchWrapper.latch = new CountDownLatch(1); +- +- resolver.addResolverListener( +- ""foo.any.service.user.cell"", new Resolver.ResolverListener() { +- +- @Override +- public void endpointEvent(Event event, Endpoint endpoint) { +- switch (event) { +- case NEW_ENDPOINT: +- endpointListNew.add(endpoint); +- latchWrapper.latch.countDown(); +- break; +- case REMOVED_ENDPOINT: +- latchWrapper.latch.countDown(); +- break; +- } +- } +- }); +- assertTrue(latchWrapper.latch.await(5000, TimeUnit.MILLISECONDS)); +- assertEquals(1, endpointListNew.size()); +- assertEquals(""foo"", endpointListNew.get(0).getName()); +- assertEquals(""1.service.user.cell"", endpointListNew.get(0).getCoordinate().toString()); +- endpointListNew.clear(); +- +- latchWrapper.latch = new CountDownLatch(1); +- +- undrain(); +- +- assertFalse(latchWrapper.latch.await(3000, TimeUnit.MILLISECONDS)); +- } +- +- @Test +- public void testStopAsyncResolving() throws Exception { +- Resolver resolver = cn.getResolver(); +- +- final List endpointListNew = new ArrayList(); +- +- // This class is needed since the abstract resolver listener class can only access +- // final variables. +- class LatchWrapper { +- public CountDownLatch latch; +- } +- final LatchWrapper latchWrapper = new LatchWrapper(); +- +- latchWrapper.latch = new CountDownLatch(1); +- +- +- Resolver.ResolverListener resolverListener = new Resolver.ResolverListener() { +- @Override +- public void endpointEvent(Event event, Endpoint endpoint) { +- switch (event) { +- +- case NEW_ENDPOINT: +- endpointListNew.add(endpoint); +- latchWrapper.latch.countDown(); +- break; +- case REMOVED_ENDPOINT: +- latchWrapper.latch.countDown(); +- break; +- } +- } +- }; +- resolver.addResolverListener(""foo.all.service.user.cell"", resolverListener); +- assertTrue(latchWrapper.latch.await(5000, TimeUnit.MILLISECONDS)); +- assertEquals(1, endpointListNew.size()); +- assertEquals(""foo"", endpointListNew.get(0).getName()); +- assertEquals(""1.service.user.cell"", endpointListNew.get(0).getCoordinate().toString()); +- endpointListNew.clear(); +- +- latchWrapper.latch = new CountDownLatch(1); +- +- resolver.removeResolverListener(resolverListener); +- +- undrain(); +- +- assertFalse(latchWrapper.latch.await(100, TimeUnit.MILLISECONDS)); +- +- try { +- resolver.removeResolverListener(resolverListener); +- } catch (IllegalArgumentException e) { +- // This is expected. +- return; +- } +- fail(""Did not throw an exception on deleting a non existing listener.""); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/Cloudname.java b/cn/src/main/java/org/cloudname/Cloudname.java +deleted file mode 100644 +index d1fbb729..00000000 +--- a/cn/src/main/java/org/cloudname/Cloudname.java ++++ /dev/null +@@ -1,84 +0,0 @@ +-package org.cloudname; +- +-/** +- * The main interface for interacting with Cloudname. +- * +- * @author borud +- * @author dybdahl +- */ +-public interface Cloudname { +- /** +- * Claim a coordinate returning a {@link ServiceHandle} through +- * which the service can interact with the system. This is an asynchronous operation, to check result +- * use the returned Servicehandle. E.g. for waiting up to ten seconds for a claim to happen: +- * +- * Cloudname cn = ... +- * Coordinate coordinate = ... +- * ServiceHandle serviceHandle = cn.claim(coordinate); +- * boolean claimSuccess = serviceHandle.waitForCoordinateOkSeconds(10); +- * +- * @param coordinate of the service we wish to claim. +- * @return a ServiceHandle that can wait for the claim to be successful and listen to the state of the claim. +- */ +- ServiceHandle claim(Coordinate coordinate); +- +- /** +- * Get a resolver instance. +- */ +- Resolver getResolver(); +- +- /** +- * Create a coordinate in the persistent service store. Must +- * throw an exception if the coordinate has already been defined. +- * +- * +- * @param coordinate the coordinate we wish to create +- * @throws CoordinateExistsException if coordinate already exists. +- * @throws CloudnameException if problems with talking with storage. +- */ +- void createCoordinate(Coordinate coordinate) +- throws CloudnameException, CoordinateExistsException; +- +- /** +- * Deletes a coordinate in the persistent service store. It will throw an exception if the coordinate is claimed. +- * @param coordinate the coordinate we wish to destroy. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException if problems talking with storage. +- * @throws CoordinateDeletionException if problems occurred during deletion. +- */ +- void destroyCoordinate(Coordinate coordinate) +- throws CoordinateDeletionException, CoordinateMissingException, CloudnameException; +- +- /** +- * Get the ServiceStatus for a given Coordinate. +- * +- * @param coordinate the coordinate we want to get the status of +- * @return a ServiceStatus instance. +- * @throws CloudnameException if problems with talking with storage. +- */ +- ServiceStatus getStatus(Coordinate coordinate) +- throws CloudnameException; +- +- /** +- * Updates the config for a coordinate. If the oldConfig is set (not null) it will require that the old config +- * matches otherwise it will throw an exception +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException if problems including oldConfig does not match old config. +- */ +- void setConfig(final Coordinate coordinate, final String newConfig, final String oldConfig) +- throws CoordinateMissingException, CloudnameException; +- +- /** +- * Get config for a coordinate. +- * @return the new config. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException +- */ +- String getConfig(final Coordinate coordinate) +- throws CoordinateMissingException, CloudnameException; +- +- /** +- * Close down connection to storage. +- */ +- void close(); +-} +diff --git a/cn/src/main/java/org/cloudname/CloudnameException.java b/cn/src/main/java/org/cloudname/CloudnameException.java +deleted file mode 100644 +index 66da94f7..00000000 +--- a/cn/src/main/java/org/cloudname/CloudnameException.java ++++ /dev/null +@@ -1,21 +0,0 @@ +-package org.cloudname; +- +-/** +- * Exceptions for Cloudname caused by problems talking to storage. +- * +- * @author borud +- */ +-public class CloudnameException extends Exception { +- +- public CloudnameException(Throwable t) { +- super(t); +- } +- +- public CloudnameException(String message) { +- super(message); +- } +- +- public CloudnameException(String message, Throwable t) { +- super(message, t); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java b/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java +deleted file mode 100644 +index 5b29aae6..00000000 +--- a/cn/src/main/java/org/cloudname/CloudnameTestBootstrapper.java ++++ /dev/null +@@ -1,63 +0,0 @@ +-package org.cloudname; +- +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +- +-import java.io.File; +-import java.util.concurrent.CountDownLatch; +-import java.util.logging.Logger; +- +-import org.apache.zookeeper.ZooKeeper; +-import org.cloudname.testtools.Net; +-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper; +-import org.cloudname.zk.ZkCloudname; +- +- +-/** +- * Helper class for bootstrapping cloudname for unit-tests. It also exposes the ZooKeeper instance. +- * @author @author dybdahl +- */ +-public class CloudnameTestBootstrapper { +- +- private static final Logger LOGGER = Logger.getLogger(CloudnameTestBootstrapper.class.getName()); +- private EmbeddedZooKeeper embeddedZooKeeper; +- private ZooKeeper zooKeeper; +- private Cloudname cloudname; +- private File rootDir; +- +- public CloudnameTestBootstrapper(File rootDir) { +- this.rootDir = rootDir; +- } +- +- public void init() throws Exception, CloudnameException { +- int zookeeperPort = Net.getFreePort(); +- +- LOGGER.info(""EmbeddedZooKeeper rootDir="" + rootDir.getCanonicalPath() +- + "", port="" + zookeeperPort +- ); +- +- // Set up and initialize the embedded ZooKeeper +- embeddedZooKeeper = new EmbeddedZooKeeper(rootDir, zookeeperPort); +- embeddedZooKeeper.init(); +- +- // Set up a zookeeper client that we can use for inspection +- final CountDownLatch connectedLatch = new CountDownLatch(1); +- zooKeeper = new ZooKeeper(""localhost:"" + zookeeperPort, 1000, new Watcher() { +- public void process(WatchedEvent event) { +- if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { +- connectedLatch.countDown(); +- } +- } +- }); +- connectedLatch.await(); +- cloudname = new ZkCloudname.Builder().setConnectString(""localhost:"" + zookeeperPort).build().connect(); +- } +- +- public ZooKeeper getZooKeeper() { +- return zooKeeper; +- } +- +- public Cloudname getCloudname() { +- return cloudname; +- } +-} +diff --git a/cn/src/main/java/org/cloudname/ConfigListener.java b/cn/src/main/java/org/cloudname/ConfigListener.java +deleted file mode 100644 +index 04f3c5d8..00000000 +--- a/cn/src/main/java/org/cloudname/ConfigListener.java ++++ /dev/null +@@ -1,25 +0,0 @@ +-package org.cloudname; +- +-/** +- * This interface defines the callback interface used to notify of +- * config node changes. +- * +- * @author borud +- */ +- +-public interface ConfigListener { +- public enum Event { +- CREATE, +- UPDATED, +- DELETED, +- } +- +- /** +- * This method is called whenever the application needs to be +- * notified of events related to configuration. +- * +- * @param event the type of event observed on the config node. +- * @param data the contents of the config node +- */ +- public void onConfigEvent(Event event, String data); +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/Coordinate.java b/cn/src/main/java/org/cloudname/Coordinate.java +deleted file mode 100644 +index e35d8b8c..00000000 +--- a/cn/src/main/java/org/cloudname/Coordinate.java ++++ /dev/null +@@ -1,184 +0,0 @@ +-package org.cloudname; +- +-import java.util.regex.Pattern; +-import java.util.regex.Matcher; +- +-import com.fasterxml.jackson.databind.ObjectMapper; +-import com.fasterxml.jackson.annotation.JsonCreator; +-import com.fasterxml.jackson.annotation.JsonProperty; +- +-import java.io.IOException; +- +-/** +- * This class represents a service coordinate. A coordinate is given +- * by four pieces of data. +- * +- *
+- *
Cell +- *
A cell is roughly equivalent to ""data center"". The strict definition +- * is that a cell represents a ZooKeeper installation. You can have +- * multiple cells in a physical datacenter, but it is not advisable to +- * have ZooKeeper installations span physical data centers. +- * +- *
User +- *
The user owning the service. May or may not have any relation to +- * the operating system user. +- * +- *
Service +- *
The name of the service. +- * +- *
Instance +- * An integer [0, Integer.MAX_VALUE) indicating the instance number +- * of the service. +- * +- * The canonical form of a coordinate is {@code 0.service.user.dc}. +- * +- * This class is immutable. +- * +- * @author borud +- */ +-public class Coordinate { +- private final String cell; +- private final String user; +- private final String service; +- private final int instance; +- +- // TODO(borud): allow for numbers in service, user and cell. Just +- // not the first character. +- public static final Pattern coordinatePattern +- = Pattern.compile(""^(\\d+)\\."" // instance +- + ""([a-z][a-z0-9-_]*)\\."" // service +- + ""([a-z][a-z0-9-_]*)\\."" // user +- + ""([a-z][a-z0-9-_]*)\\z""); // cell +- +- /** +- * Create a new coordinate instance. +- * +- * @param instance the instance number +- * @param service the service name +- * @param user the user name +- * @param cell the cell name +- * @throws IllegalArgumentException if the coordinate is invalid. +- */ +- @JsonCreator +- public Coordinate (@JsonProperty(""instance"") int instance, +- @JsonProperty(""service"") String service, +- @JsonProperty(""user"") String user, +- @JsonProperty(""cell"") String cell) { +- // Enables validation of coordinate. +- this(instance, service, user, cell, true); +- } +- +- /** +- * Internal version of constructor. Makes validation optional. +- */ +- public Coordinate (int instance, String service, String user, String cell, boolean validate) { +- this.instance = instance; +- this.service = service; +- this.user = user; +- this.cell = cell; +- +- if (instance < 0) { +- throw new IllegalArgumentException(""Invalid instance number: "" + instance); +- } +- +- // If the coordinate was created by the parse() method the +- // coordinate has already been parsed using the +- // coordinatePattern so no validation is required. If the +- // coordinate was defined using the regular constructor we +- // need to validate the parts. And we do this by re-using the +- // coordinatePattern. +- if (validate) { +- if (! coordinatePattern.matcher(asString()).matches()) { +- throw new IllegalArgumentException(""Invalid coordinate: '"" + asString() + ""'""); +- } +- } +- } +- +- /** +- * Parse coordinate and create a {@code Coordinate} instance from +- * a {@code String}. +- * +- * @param s Coordinate we wish to parse as a string. +- * @return a Coordinate instance equivalent to {@code s} +- * @throws IllegalArgumentException if the coordinate string {@s} +- * is not a valid coordinate. +- */ +- public static Coordinate parse(String s) { +- Matcher m = coordinatePattern.matcher(s); +- if (! m.matches()) { +- throw new IllegalArgumentException(""Malformed coordinate: "" + s); +- } +- +- int instance = Integer.parseInt(m.group(1)); +- String service = m.group(2); +- String user = m.group(3); +- String cell = m.group(4); +- +- return new Coordinate(instance, service, user, cell, false); +- } +- +- public String getCell() { +- return cell; +- } +- +- public String getUser() { +- return user; +- } +- +- public String getService() { +- return service; +- } +- +- public int getInstance() { +- return instance; +- } +- +- public String asString() { +- return instance + ""."" + service + ""."" + user + ""."" + cell; +- } +- +- @Override +- public String toString() { +- return asString(); +- } +- +- @Override +- public boolean equals(Object o) { +- if (null == o) { +- return false; +- } +- +- if (this == o) { +- return true; +- } +- +- if (getClass() != o.getClass()) { +- return false; +- } +- +- Coordinate c = (Coordinate) o; +- return ((instance == c.instance) +- && service.equals(c.service) +- && user.equals(c.user) +- && cell.equals(c.cell)); +- } +- +- @Override +- public int hashCode() { +- return asString().hashCode(); +- } +- +- public String toJson() { +- try { +- return new ObjectMapper().writeValueAsString(this); +- } catch (IOException e) { +- return null; +- } +- } +- +- public static Coordinate fromJson(String json) throws IOException { +- return new ObjectMapper().readValue(json, Coordinate.class); +- } +- +-} +diff --git a/cn/src/main/java/org/cloudname/CoordinateDeletionException.java b/cn/src/main/java/org/cloudname/CoordinateDeletionException.java +deleted file mode 100644 +index c1ac89c7..00000000 +--- a/cn/src/main/java/org/cloudname/CoordinateDeletionException.java ++++ /dev/null +@@ -1,11 +0,0 @@ +-package org.cloudname; +- +-/** +- * Thrown when there are problems deleting a coordinate. +- * @auther dybdahl +- */ +-public class CoordinateDeletionException extends CoordinateException { +- public CoordinateDeletionException(String reason) { +- super(reason); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/CoordinateException.java b/cn/src/main/java/org/cloudname/CoordinateException.java +deleted file mode 100644 +index fadb25b7..00000000 +--- a/cn/src/main/java/org/cloudname/CoordinateException.java ++++ /dev/null +@@ -1,12 +0,0 @@ +-package org.cloudname; +- +-/** +- * Base class for exception related to a specific coordinate. +- * @auther dybdahl +- */ +-public abstract class CoordinateException extends Exception { +- +- public CoordinateException(String reason) { +- super(reason); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/CoordinateExistsException.java b/cn/src/main/java/org/cloudname/CoordinateExistsException.java +deleted file mode 100644 +index 7ba067a0..00000000 +--- a/cn/src/main/java/org/cloudname/CoordinateExistsException.java ++++ /dev/null +@@ -1,11 +0,0 @@ +-package org.cloudname; +- +-/** +- * It was assumed that the coordinate did not exist, but it did. +- * @auther dybdahl +- */ +-public class CoordinateExistsException extends CoordinateException { +- public CoordinateExistsException(String reason) { +- super(reason); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/CoordinateListener.java b/cn/src/main/java/org/cloudname/CoordinateListener.java +deleted file mode 100644 +index 9a057ae7..00000000 +--- a/cn/src/main/java/org/cloudname/CoordinateListener.java ++++ /dev/null +@@ -1,48 +0,0 @@ +-package org.cloudname; +- +-/** +- * Interface for listening to status on a claimed coordinate. +- * @author dybdahl +- */ +-public interface CoordinateListener { +- /** +- * Events that can be triggered when monitoring a coordinate. +- */ +- public enum Event { +- +- /** +- * Everything is fine. +- */ +- COORDINATE_OK, +- +- /** +- * Connection lost to storage, no more events will occur. +- */ +- NO_CONNECTION_TO_STORAGE, +- +- /** +- * Problems with parsing the data in storage for this coordinate. +- */ +- COORDINATE_CORRUPTED, +- +- /** +- * The data in the storage and memory is out of sync. +- */ +- COORDINATE_OUT_OF_SYNC, +- +- /** +- * No longer the owner of the coordinate. +- */ +- NOT_OWNER, +- } +- +- +- +- /** +- * Implement this function to receive the events. +- * Return false if no more events are wanted, will stop eventually. +- * @param event the event that happened. +- * @param message some message associated with the event. +- */ +- public void onCoordinateEvent(Event event, String message); +-} +diff --git a/cn/src/main/java/org/cloudname/CoordinateMissingException.java b/cn/src/main/java/org/cloudname/CoordinateMissingException.java +deleted file mode 100644 +index 6fcdb56a..00000000 +--- a/cn/src/main/java/org/cloudname/CoordinateMissingException.java ++++ /dev/null +@@ -1,11 +0,0 @@ +-package org.cloudname; +- +-/** +- * Exception related to a coordinate that is missing. +- * @auther dybdahl +- */ +-public class CoordinateMissingException extends CoordinateException { +- public CoordinateMissingException(String reason) { +- super(reason); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/Endpoint.java b/cn/src/main/java/org/cloudname/Endpoint.java +deleted file mode 100644 +index b892cfaf..00000000 +--- a/cn/src/main/java/org/cloudname/Endpoint.java ++++ /dev/null +@@ -1,102 +0,0 @@ +-package org.cloudname; +- +-import com.fasterxml.jackson.databind.ObjectMapper; +-import com.fasterxml.jackson.annotation.JsonCreator; +-import com.fasterxml.jackson.annotation.JsonProperty; +- +-import java.io.IOException; +- +-/** +- * Representation of an endpoint. This class is used to describe a +- * wide range of endpoints, but it is, initially geared mainly towards +- * services for which we need to know a hostname, port and protocol. +- * As a stop-gap measure we provide an {@code endpointData} field +- * which can be used in a pinch to communicate extra information about +- * the endpoint. +- * +- * Instances of this class are immutable. +- * +- * TODO(borud): decide if coordinate and name should be part of this +- * class. +- * +- * @author borud +- */ +-public class Endpoint { +- // This gets saved into ZooKeeper as well and is redundant info, +- // but it makes sense to have this information in the Endpoint +- // instances to make it possible for clients to get a list of +- // endpoints and be able to figure out what coordinates they come +- // from if they were gathered from multiple services. +- private final Coordinate coordinate; +- // Ditto for name. +- private final String name; +- private final String host; +- private final int port; +- private final String protocol; +- private final String endpointData; +- +- @JsonCreator +- public Endpoint(@JsonProperty(""coordinate"") Coordinate coordinate, +- @JsonProperty(""name"") String name, +- @JsonProperty(""host"") String host, +- @JsonProperty(""port"") int port, +- @JsonProperty(""protocol"") String protocol, +- @JsonProperty(""endpointData"") String endpointData) +- { +- this.coordinate = coordinate; +- this.name = name; +- this.host = host; +- this.port = port; +- this.protocol = protocol; +- this.endpointData = endpointData; +- } +- +- public Coordinate getCoordinate() { +- return coordinate; +- } +- +- public String getName() { +- return name; +- } +- +- public String getHost() { +- return host; +- } +- +- public int getPort() { +- return port; +- } +- +- public String getProtocol() { +- return protocol; +- } +- +- public String getEndpointData() { +- return endpointData; +- } +- +- @Override +- public boolean equals(Object endpoint) { +- return endpoint instanceof Endpoint && ((Endpoint) endpoint).toJson().equals(toJson()); +- } +- +- public int hashCode() { +- return toJson().hashCode(); +- } +- +- public static Endpoint fromJson(String json) throws IOException { +- return new ObjectMapper().readValue(json, Endpoint.class); +- } +- +- public String toJson() { +- try { +- return new ObjectMapper().writeValueAsString(this); +- } catch (IOException e) { +- return null; +- } +- } +- +- public String toString() { +- return toJson(); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/Resolver.java b/cn/src/main/java/org/cloudname/Resolver.java +deleted file mode 100644 +index e6c08728..00000000 +--- a/cn/src/main/java/org/cloudname/Resolver.java ++++ /dev/null +@@ -1,115 +0,0 @@ +-package org.cloudname; +- +-import java.util.List; +-import java.util.Set; +- +-/** +- * This interface defines how we resolve endpoints in Cloudname. The client has to keep a reference to this Resolver +- * object otherwise it will stop resolving. +- * +- * @author borud +- */ +-public interface Resolver { +- +- /** +- * Resolve an expression to a list of endpoints. The order of the +- * endpoints may be subject to ranking criteria. +- * +- * @param expression The expression to resolve, e.g. for ZooKeeper implementation there are various formats like +- * endpoint.instance.service.user.cell (see ZkResolver for details). +- * @throws CloudnameException if problems talking with storage. +- */ +- List resolve(String expression) throws CloudnameException; +- +- +- /** +- * Implement this interface to get dynamic information about what endpoints that are available. +- * If you want to register more than 1000 listeners in the same resolver, you might consider overriding +- * equals() and hashCode(), but the default implementation should work in normal cases. +- */ +- interface ResolverListener { +- enum Event { +- /** +- * New endpoint was added. +- */ +- NEW_ENDPOINT, +- /** +- * Endpoint removed. This include when the coordinate goes to draining. +- */ +- REMOVED_ENDPOINT, +- /** +- * Endpoint data has been modified. +- */ +- MODIFIED_ENDPOINT_DATA, +- /** +- * Lost connection to storage. The list of endpoints will get stale. The system will reconnect +- * automatically. +- */ +- LOST_CONNECTION, +- /** +- * Connection to storage is good, list of endpoints will be updated. +- */ +- CONNECTION_OK +- } +- +- /** +- * An Event happened related to the expression, see enum Event above. +- * @param endpoint is only populated for the Event NEW_ENDPOINT and REMOVED_ENDPOINT. +- */ +- void endpointEvent(Event event, final Endpoint endpoint); +- } +- +- /** +- * Registers a ResolverListener to get dynamic information about an expression. The expression is set in the +- * ResolverListener. You will only get updates as long as you keep a reference to Resolver. +- * If you don't have a reference, it is up to the garbage collector to decide how long you will receive callbacks. +- * One listener can only be registered once. +- * +- * @param expression The expression to resolve, e.g. for ZooKeeper implementation there are various formats like +- * endpoint.instance.service.user.cell (see ZkResolver for details). This should be static data, i.e. +- * the function might be called only once. +- */ +- void addResolverListener(String expression, ResolverListener listener) throws CloudnameException; +- +- /** +- * Calling this function unregisters the listener, i.e. stopping future callbacks. +- * The listener must be registered. For identification of listener, see comment on ResolverListener. +- * The default is to use object id. +- */ +- void removeResolverListener(ResolverListener listener); +- +- /** +- * This class is used as a parameter to {@link #getEndpoints(CoordinateDataFilter)}. Override methods to filter +- * the endpoints to be +- * returned. +- */ +- class CoordinateDataFilter { +- /** +- * Override these methods to filter on cell, user, service, endpointName, and/or service state. +- */ +- +- public boolean includeCell(final String cell) { +- return true; +- } +- public boolean includeUser(final String user) { +- return true; +- } +- public boolean includeService(final String service) { +- return true; +- } +- public boolean includeEndpointname(final String endpointName) { +- return true; +- } +- public boolean includeServiceState(final ServiceState state) { +- return true; +- } +- } +- +- /** +- * This method reads out all the nodes from the storage. IT CAN BE VERY EXPENSIVE AND SHOULD BE USED ONLY +- * WHEN NO OTHER METHODS ARE FEASIBLE. Do not call it frequently! +- * @param filter class for filtering out endpoints +- * @return list of endpoints. +- */ +- Set getEndpoints(CoordinateDataFilter filter) throws CloudnameException, InterruptedException; +-} +diff --git a/cn/src/main/java/org/cloudname/ResolverStrategy.java b/cn/src/main/java/org/cloudname/ResolverStrategy.java +deleted file mode 100644 +index b28ebfb2..00000000 +--- a/cn/src/main/java/org/cloudname/ResolverStrategy.java ++++ /dev/null +@@ -1,29 +0,0 @@ +-package org.cloudname; +- +-import java.util.List; +- +-/** +- * The ResolverStrategy is an interface for implementing a strategy when resolving endpoints. +- * +- * @auther dybdahl +- */ +- +-public interface ResolverStrategy { +- +- /** +- * Given a list of endpoints, return only those endpoints that are desired for this strategy. +- */ +- public List filter(List endpoints); +- +- /** +- * Returns the endpoints ordered according to strategy specific scheme. +- */ +- public List order(List endpoints); +- +- /** +- * Returns the name of this strategy. This is the same name that is used in the resolver +- * (e.g. ""all"", ""any"" etc). +- * @return name of strategy. +- */ +- public String getName(); +-} +diff --git a/cn/src/main/java/org/cloudname/ServiceHandle.java b/cn/src/main/java/org/cloudname/ServiceHandle.java +deleted file mode 100644 +index e0b9d81e..00000000 +--- a/cn/src/main/java/org/cloudname/ServiceHandle.java ++++ /dev/null +@@ -1,105 +0,0 @@ +-package org.cloudname; +- +-import java.util.List; +- +-/** +- * The service handle -- the interface through which services +- * communicate their state to the outside world and where services can +- * register listeners to handle configuration updates. +- * +- * @author borud +- */ +-public interface ServiceHandle { +- +- /** +- * This is a convenient function for waiting for the connection to storage to be ok. It is the same as +- * registering a CoordinateListener and waiting for event coordinate ok. +- */ +- boolean waitForCoordinateOkSeconds(int seconds) throws InterruptedException; +- +- /** +- * Set the status of this service. +- * +- * @param status the new status. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems +- * with ZooKeeper. +- */ +- void setStatus(ServiceStatus status) throws CoordinateMissingException, CloudnameException; +- +- /** +- * Publish a named endpoint. It is legal to push an endpoint with updated data. +- * +- * @param endpoint the endpoint data. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems +- * with ZooKeeper. +- */ +- void putEndpoint(Endpoint endpoint) throws CoordinateMissingException, CloudnameException; +- +- /** +- * Same as putEndpoints, but takes a list. +- * +- * @param endpoints the endpoints data. +- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems +- * with ZooKeeper. +- * @throws CoordinateMissingException if coordinate does not exist. +- */ +- void putEndpoints(List endpoints) throws CoordinateMissingException, CloudnameException; +- +- /** +- * Remove a published endpoint. +- * +- * @param name the name of the endpoint we wish to remove. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems +- * with ZooKeeper. +- */ +- void removeEndpoint(String name) throws CoordinateMissingException, CloudnameException; +- +- /** +- * Same as removeEndpoint() but takes a list of names. +- * +- * @throws CloudnameException if coordinate is not claimed, connection to storage is down, or problems +- * with ZooKeeper. +- * @throws CoordinateMissingException if coordinate does not exist. +- * @throws CoordinateMissingException if coordinate does not exist. +- */ +- void removeEndpoints(List names) throws CoordinateMissingException, CloudnameException; +- +- +- /** +- * Register a ConfigListener which will be called whenever there +- * is a configuration change. +- * +- * There may have been configuration pushed to the backing storage +- * already by the time a ConfigListener is registered. In that +- * case the ConfigListener will see these configuration items as +- * being created. +- */ +- // TODO(dybdahl): This logic lacks tests. Before used in any production code, tests have to be added. +- void registerConfigListener(ConfigListener listener); +- +- /** +- * After registering a new listener, a new event is triggered which include current state, even without change +- * of state. +- * Don't call the cloudname library, do any heavy lifting, or do any IO operation from this callback thread. +- * That might deadlock as there is no guarantee what kind of thread that runs the callback. +- * +- * @throws CloudnameException if problems talking with storage. +- */ +- void registerCoordinateListener(CoordinateListener listener) +- throws CloudnameException; +- +- /** +- * Close the service handle and free up the coordinate so it can +- * be claimed by others. After close() has been called all +- * operations on this instance of the service handle will result +- * in an exception being thrown. All endpoints are deleted. +- * @throws CloudnameException if problems removing the claim. +- */ +- void close() +- throws CloudnameException; +- +-} +- +diff --git a/cn/src/main/java/org/cloudname/ServiceState.java b/cn/src/main/java/org/cloudname/ServiceState.java +deleted file mode 100644 +index 6af89561..00000000 +--- a/cn/src/main/java/org/cloudname/ServiceState.java ++++ /dev/null +@@ -1,29 +0,0 @@ +-package org.cloudname; +- +-/** +- * The defined states of a service. +- * +- * @author borud +- */ +-public enum ServiceState { +- // This means that no service has claimed the coordinate, or in +- // more practical terms: there is no ephemeral node called +- // ""status"" in the service root path in ZooKeeper. +- UNASSIGNED, +- +- // A running process has claimed the coordinate and is in the +- // process of starting up. +- STARTING, +- +- // A running process has claimed the coordinate and is running +- // normally. +- RUNNING, +- +- // A running process has claimed the coordinate and is running, +- // but it is in the process of shutting down and will not accept +- // new work. +- DRAINING, +- +- // An error condition has occurred. +- ERROR +-} +diff --git a/cn/src/main/java/org/cloudname/ServiceStatus.java b/cn/src/main/java/org/cloudname/ServiceStatus.java +deleted file mode 100644 +index eba04e20..00000000 +--- a/cn/src/main/java/org/cloudname/ServiceStatus.java ++++ /dev/null +@@ -1,51 +0,0 @@ +-package org.cloudname; +- +-import com.fasterxml.jackson.databind.ObjectMapper; +-import com.fasterxml.jackson.annotation.JsonCreator; +-import com.fasterxml.jackson.annotation.JsonProperty; +- +-import java.io.IOException; +- +-/** +- * A representation of the basic runtime status of a service. +- * +- * Instances of ServiceStatus are immutable. +- * +- * @author borud +- */ +-public class ServiceStatus { +- private final ServiceState state; +- private final String message; +- +- /** +- * @param state the state of the service +- * @param message a human readable message +- */ +- @JsonCreator +- public ServiceStatus(@JsonProperty(""state"") ServiceState state, +- @JsonProperty(""message"") String message) +- { +- this.state = state; +- this.message = message; +- } +- +- public ServiceState getState() { +- return state; +- } +- +- public String getMessage() { +- return message; +- } +- +- public static ServiceStatus fromJson(String json) throws IOException { +- return new ObjectMapper().readValue(json, ServiceStatus.class); +- } +- +- public String toJson() { +- try { +- return new ObjectMapper().writeValueAsString(this); +- } catch (IOException e) { +- return null; +- } +- } +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/StrategyAll.java b/cn/src/main/java/org/cloudname/StrategyAll.java +deleted file mode 100644 +index 2bf6dcbb..00000000 +--- a/cn/src/main/java/org/cloudname/StrategyAll.java ++++ /dev/null +@@ -1,35 +0,0 @@ +-package org.cloudname; +- +-import java.util.List; +- +-/** +- * A strategy that implements ""all"" and returns everything and does not change order. +- * @author : dybdahl +- */ +-public class StrategyAll implements ResolverStrategy { +- +- /** +- * Returns all the endpoints. +- */ +- @Override +- public List filter(List endpoints) { +- return endpoints; +- } +- +- /** +- * Doesn't change ordering of endpoints. +- */ +- @Override +- public List order(List endpoints) { +- return endpoints; +- } +- +- /** +- * The name of the strategy is ""all"". +- */ +- @Override +- public String getName() { +- return ""all""; +- } +- +-} +diff --git a/cn/src/main/java/org/cloudname/StrategyAny.java b/cn/src/main/java/org/cloudname/StrategyAny.java +deleted file mode 100644 +index 76679a55..00000000 +--- a/cn/src/main/java/org/cloudname/StrategyAny.java ++++ /dev/null +@@ -1,60 +0,0 @@ +-package org.cloudname; +- +-import java.util.ArrayList; +-import java.util.Collection; +-import java.util.Collections; +-import java.util.Comparator; +-import java.util.List; +-import java.util.SortedSet; +- +-/** +- * A strategy that returns the first element of the sorted coordinates (by instance value) hashed with +- * the time of this object creation. This is useful for returning the same endpoint in most cases even +- * if an endpoint is removed or added. +- * @author : dybdahl +- */ +-public class StrategyAny implements ResolverStrategy { +- +- // Some systems might not have nano seconds accuracy and we do not want zeros in the least significant +- // numbers. +- private int sortSeed = (int) System.nanoTime() / 1000; +- +- /** +- * Returns a list of the first endpoint if any, else returns the empty list. +- */ +- @Override +- public List filter(List endpoints) { +- if (endpoints.size() > 0) { +- List retVal = new ArrayList(); +- retVal.add(endpoints.get(0)); +- return retVal; +- } +- // Empty list. +- return endpoints; +- } +- +- /** +- * We return a list that is sorted differently for different clients. In this way only a few +- * clients are touched when an endpoint is added/removed. +- */ +- @Override +- public List order(List endpoints) { +- Collections.sort(endpoints, new Comparator() { +- @Override +- public int compare(Endpoint endpointA, Endpoint endpointB) { +- int instanceA = endpointA.getCoordinate().getInstance() ^ sortSeed; +- int instanceB = endpointB.getCoordinate().getInstance() ^ sortSeed; +- return (instanceA > instanceB ? -1 : (instanceA == instanceB ? 0 : 1)); +- } +- }); +- return endpoints; +- } +- +- /** +- * The name of the strategy is ""any"" +- */ +- @Override +- public String getName() { +- return ""any""; +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java b/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java +deleted file mode 100644 +index f4d8e133..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ClaimedCoordinate.java ++++ /dev/null +@@ -1,535 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.*; +-import org.apache.zookeeper.data.Stat; +-import org.cloudname.*; +- +-import java.io.IOException; +- +-import java.io.UnsupportedEncodingException; +-import java.util.*; +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +-import java.util.concurrent.atomic.AtomicBoolean; +-import java.util.logging.Logger; +- +-/** +- * This class keeps track of coordinate data and endpoints for a coordinate. It is notified about +- * the state of ZooKeeper connection by implementing the ZkObjectHandler.ConnectionStateChanged. +- * It implements the Watcher interface to track the specific path of the coordinate. +- * This is useful for being notified if something happens to the coordinate (if it +- * is overwritten etc). +- * +- * @author dybdahl +- */ +-public class ClaimedCoordinate implements Watcher, ZkObjectHandler.ConnectionStateChanged { +- +- /** +- * True if we know that our state is in sync with zookeeper. +- */ +- private final AtomicBoolean isSynchronizedWithZooKeeper = new AtomicBoolean(false); +- +- /** +- * The client of the class has to call start. This will flip this bit. +- */ +- private final AtomicBoolean started = new AtomicBoolean(false); +- +- /** +- * The connection from client to ZooKeeper might go down. If it comes up again within some time +- * window the server might think an ephemeral node should be alive. The client lib might think +- * otherwise. If this flag is set, the class will eventually check version. +- */ +- private final AtomicBoolean checkVersion = new AtomicBoolean(false); +- +- /** +- * We keep track of the last version so we know if we are in sync. We set a large value to make +- * sure we do not accidentally overwrite an existing not owned coordinate. +- */ +- private int lastStatusVersion = Integer.MAX_VALUE; +- +- private final Object lastStatusVersionMonitor = new Object(); +- +- private static final Logger LOG = Logger.getLogger(ClaimedCoordinate.class.getName()); +- +- private final ZkObjectHandler.Client zkClient; +- +- /** +- * The claimed coordinate. +- */ +- private final Coordinate coordinate; +- +- /** +- * Status path of the coordinate. +- */ +- private final String path; +- +- /** +- * This is needed to make sure that the first message about state is sent while +- * other update messages are queued. +- */ +- private final Object callbacksMonitor = new Object(); +- +- /** +- * The endpoints and the status of the coordinate is stored here. +- */ +- private final ZkCoordinateData zkCoordinateData = new ZkCoordinateData(); +- +- /** +- * For running internal thread. +- */ +- private final ScheduledExecutorService scheduler = +- Executors.newSingleThreadScheduledExecutor(); +- +- /** +- * A list of the coordinate listeners that are registered for this coordinate. +- */ +- private final List coordinateListenerList = +- Collections.synchronizedList(new ArrayList()); +- +- /** +- * A list of tracked configs for this coordinate. +- */ +- private final List trackedConfigList = +- Collections.synchronizedList(new ArrayList()); +- +- +- /** +- * This class implements the logic for handling callbacks from ZooKeeper on claim. +- * In general we could just ignore errors since we have a time based retry mechanism. However, +- * we want to notify clients, and we need to update the consistencyState. +- */ +- class ClaimCallback implements AsyncCallback.StringCallback { +- +- @Override +- public void processResult( +- int rawReturnCode, String notUsed, Object parent, String notUsed2) { +- +- KeeperException.Code returnCode = KeeperException.Code.get(rawReturnCode); +- ClaimedCoordinate claimedCoordinate = (ClaimedCoordinate) parent; +- LOG.fine(""Claim callback with "" + returnCode.name() + "" "" + claimedCoordinate.path +- + "" synched: "" + isSynchronizedWithZooKeeper.get() + "" thread: "" + this); +- switch (returnCode) { +- // The claim was successful. This means that the node was created. We need to +- // populate the status and endpoints. +- case OK: +- +- // We should be the first one to write to the new node, or fail. +- // This requires that the first version is 0, have not seen this documented +- // but it should be a fair assumption and is verified by unit tests. +- synchronized (lastStatusVersionMonitor) { +- lastStatusVersion = 0; +- } +- +- // We need to set this to synced or updateCoordinateData will complain. +- // updateCoordinateData will set it to out-of-sync in case of problems. +- isSynchronizedWithZooKeeper.set(true); +- +- +- try { +- registerWatcher(); +- } catch (CloudnameException e) { +- LOG.fine(""Failed register watcher after claim. Going to state out of sync: "" +- + e.getMessage()); +- +- isSynchronizedWithZooKeeper.set(false); +- return; +- +- } catch (InterruptedException e) { +- +- LOG.fine(""Interrupted while setting up new watcher. Going to state out of sync.""); +- isSynchronizedWithZooKeeper.set(false); +- return; +- +- } +- // No exceptions, let's celebrate with a log message. +- LOG.info(""Claim processed ok, path: "" + path); +- claimedCoordinate.sendEventToCoordinateListener( +- CoordinateListener.Event.COORDINATE_OK, ""claimed""); +- return; +- +- case NODEEXISTS: +- // Someone has already claimed the coordinate. It might have been us in a +- // different thread. If we already have claimed the coordinate then don't care. +- // Else notify the client. If everything is fine, this is not a true negative, +- // so ignore it. It might happen if two attempts to tryClaim the coordinate run +- // in parallel. +- if (isSynchronizedWithZooKeeper.get() && started.get()) { +- LOG.fine(""Everything is fine, ignoring NODEEXISTS message, path: "" + path); +- return; +- } +- +- LOG.info(""Claimed fail, node already exists, will retry: "" + path); +- claimedCoordinate.sendEventToCoordinateListener( +- CoordinateListener.Event.NOT_OWNER, ""Node already exists.""); +- LOG.info(""isSynchronizedWithZooKeeper: "" + isSynchronizedWithZooKeeper.get()); +- checkVersion.set(true); +- return; +- case NONODE: +- LOG.info(""Could not claim due to missing coordinate, path: "" + path); +- claimedCoordinate.sendEventToCoordinateListener( +- CoordinateListener.Event.NOT_OWNER, +- ""No node on claiming coordinate: "" + returnCode.name()); +- return; +- +- default: +- // Random problem, report the problem to the client. +- claimedCoordinate.sendEventToCoordinateListener( +- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, +- ""Could not reclaim coordinate. Return code: "" + returnCode.name()); +- return; +- } +- } +- } +- +- +- private class ResolveProblems implements Runnable { +- @Override +- public void run() { +- if (isSynchronizedWithZooKeeper.get() || ! zkClient.isConnected() || +- ! started.get()) { +- +- return; +- } +- if (checkVersion.getAndSet(false)) { +- try { +- synchronized (lastStatusVersionMonitor) { +- final Stat stat = zkClient.getZookeeper().exists(path, null); +- if (stat != null && zkClient.getZookeeper().getSessionId() == +- stat.getEphemeralOwner()) { +- zkClient.getZookeeper().delete(path, lastStatusVersion); +- } +- } +- } catch (InterruptedException e) { +- LOG.info(""Interrupted""); +- checkVersion.set(true); +- } catch (KeeperException e) { +- LOG.info(""exception ""+ e.getMessage()); +- checkVersion.set(true); +- } +- +- } +- LOG.info(""We are out-of-sync, have a zookeeper connection, and are started, trying reclaim: "" +- + path + this); +- tryClaim(); +- } +- } +- +- /** +- * Constructor. +- * @param coordinate The coordinate that is claimed. +- * @param zkClient for getting access to ZooKeeper. +- */ +- public ClaimedCoordinate(final Coordinate coordinate, final ZkObjectHandler.Client zkClient) { +- this.coordinate = coordinate; +- path = ZkCoordinatePath.getStatusPath(coordinate); +- this.zkClient = zkClient; +- } +- +- /** +- * Claims a coordinate. To know if it was successful or not you need to register a listener. +- * @return this. +- */ +- public ClaimedCoordinate start() { +- zkClient.registerListener(this); +- started.set(true); +- final long periodicDelayMs = 2000; +- scheduler.scheduleWithFixedDelay(new ResolveProblems(), 1 /* initial delay ms */, +- periodicDelayMs, TimeUnit.MILLISECONDS); +- return this; +- } +- +- /** +- * Callbacks from zkClient +- */ +- @Override +- public void connectionUp() { +- isSynchronizedWithZooKeeper.set(false); +- } +- +- /** +- * Callbacks from zkClient +- */ +- @Override +- public void connectionDown() { +- List coordinateListenerListCopy = new ArrayList(); +- synchronized (coordinateListenerList) { +- coordinateListenerListCopy.addAll(coordinateListenerList); +- } +- for (CoordinateListener coordinateListener : coordinateListenerListCopy) { +- coordinateListener.onCoordinateEvent( +- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, ""down""); +- } +- isSynchronizedWithZooKeeper.set(false); +- } +- +- @Override +- public void shutDown() { +- scheduler.shutdown(); +- } +- +- /** +- * Updates the ServiceStatus and persists it. Only allowed if we claimed the coordinate. +- * @param status The new value for serviceStatus. +- */ +- public void updateStatus(final ServiceStatus status) +- throws CloudnameException, CoordinateMissingException { +- zkCoordinateData.setStatus(status); +- updateCoordinateData(); +- } +- +- /** +- * Adds new endpoints and persist them. Requires that this instance owns the tryClaim to the +- * coordinate. +- * @param newEndpoints endpoints to be added. +- */ +- public void putEndpoints(final List newEndpoints) +- throws CloudnameException, CoordinateMissingException { +- zkCoordinateData.putEndpoints(newEndpoints); +- updateCoordinateData(); +- } +- +- /** +- * Remove endpoints and persist it. Requires that this instance owns the tryClaim to the +- * coordinate. +- * @param names names of endpoints to be removed. +- */ +- public void removeEndpoints(final List names) +- throws CloudnameException, CoordinateMissingException { +- zkCoordinateData.removeEndpoints(names); +- updateCoordinateData(); +- } +- +- /** +- * Release the tryClaim of the coordinate. It means that nobody owns the coordinate anymore. +- * Requires that that this instance owns the tryClaim to the coordinate. +- */ +- public void releaseClaim() throws CloudnameException { +- scheduler.shutdown(); +- zkClient.deregisterListener(this); +- +- while (true) { +- final TrackedConfig config; +- synchronized (trackedConfigList) { +- if (trackedConfigList.isEmpty()) { +- break; +- } +- config = trackedConfigList.remove(0); +- } +- config.stop(); +- } +- +- sendEventToCoordinateListener( +- CoordinateListener.Event.NOT_OWNER, ""Released claim of coordinate""); +- +- synchronized (lastStatusVersionMonitor) { +- try { +- zkClient.getZookeeper().delete(path, lastStatusVersion); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- } +- +- +- /** +- * Creates a string for debugging etc +- * @return serialized version of the instance data. +- */ +- public synchronized String toString() { +- return zkCoordinateData.snapshot().toString(); +- } +- +- /** +- * Registers a coordinatelistener that will receive events when there are changes to the status +- * node. Don't do any heavy lifting in the callback and don't call cloudname from the callback +- * as this might create a deadlock. +- * @param coordinateListener +- */ +- public void registerCoordinateListener(final CoordinateListener coordinateListener) { +- +- String message = ""New listener added, resending current state.""; +- synchronized (callbacksMonitor) { +- coordinateListenerList.add(coordinateListener); +- if (isSynchronizedWithZooKeeper.get()) { +- coordinateListener.onCoordinateEvent( +- CoordinateListener.Event.COORDINATE_OK, message); +- } +- } +- } +- +- +- public void deregisterCoordinateListener(final CoordinateListener coordinateListener) { +- coordinateListenerList.remove(coordinateListener); +- } +- +- /** +- * Registers a configlistener that will receive events when there are changes to the config node. +- * Don't do any heavy lifting in the callback and don't call cloudname from the callback as +- * this might create a deadlock. +- * @param trackedConfig +- */ +- public void registerTrackedConfig(final TrackedConfig trackedConfig) { +- trackedConfigList.add(trackedConfig); +- } +- +- /** +- * Handles event from ZooKeeper for this coordinate. +- * @param event +- */ +- @Override public void process(WatchedEvent event) { +- LOG.info(""Got an event from ZooKeeper "" + event.toString()); +- synchronized (lastStatusVersionMonitor) { +- switch (event.getType()) { +- +- case None: +- switch (event.getState()) { +- case SyncConnected: +- break; +- case Disconnected: +- case AuthFailed: +- case Expired: +- default: +- // If we lost connection, we don't attempt to register another watcher as +- // this might be blocking forever. Parent will try to reconnect (reclaim) +- // later. +- isSynchronizedWithZooKeeper.set(false); +- sendEventToCoordinateListener( +- CoordinateListener.Event.NO_CONNECTION_TO_STORAGE, +- event.toString()); +- +- return; +- } +- return; +- +- case NodeDeleted: +- // If node is deleted, we have no node to place a new watcher so we stop watching. +- isSynchronizedWithZooKeeper.set(false); +- sendEventToCoordinateListener(CoordinateListener.Event.NOT_OWNER, event.toString()); +- return; +- +- case NodeDataChanged: +- LOG.fine(""Node data changed, check versions.""); +- boolean verifiedSynchronized = false; +- try { +- final Stat stat = zkClient.getZookeeper().exists(path, this); +- if (stat == null) { +- LOG.info(""Could not stat path, setting out of synch, will retry claim""); +- } else { +- LOG.fine(""Previous version is "" + lastStatusVersion + "" now is "" +- + stat.getVersion()); +- if (stat.getVersion() != lastStatusVersion) { +- LOG.fine(""Version mismatch, sending out of sync.""); +- } else { +- verifiedSynchronized = true; +- } +- } +- } catch (KeeperException e) { +- LOG.fine(""Problems with zookeeper, sending consistencyState out of sync: "" +- + e.getMessage()); +- } catch (InterruptedException e) { +- LOG.fine(""Got interrupted: "" + e.getMessage()); +- return; +- } finally { +- isSynchronizedWithZooKeeper.set(verifiedSynchronized); +- } +- +- if (verifiedSynchronized) { +- sendEventToCoordinateListener( +- CoordinateListener.Event.COORDINATE_OUT_OF_SYNC, event.toString()); +- } +- return; +- +- case NodeChildrenChanged: +- case NodeCreated: +- // This should not happen.. +- isSynchronizedWithZooKeeper.set(false); +- sendEventToCoordinateListener( +- CoordinateListener.Event.COORDINATE_OUT_OF_SYNC, event.toString()); +- return; +- } +- } +- } +- +- private void tryClaim() { +- try { +- zkClient.getZookeeper().create( +- path, zkCoordinateData.snapshot().serialize().getBytes(Util.CHARSET_NAME), +- ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new ClaimCallback(), this); +- } catch (IOException e) { +- LOG.info(""Got IO exception on claim with new ZooKeeper instance "" + e.getMessage()); +- } +- } +- +- +- /** +- * Sends an event too all coordinate listeners. Note that the event is sent from this thread so +- * if the callback code does the wrong calls, deadlocks might occur. +- * @param event +- * @param message +- */ +- private void sendEventToCoordinateListener( +- final CoordinateListener.Event event, final String message) { +- synchronized (callbacksMonitor) { +- LOG.fine(""Event "" + event.name() + "" "" + message); +- List coordinateListenerListCopy = +- new ArrayList(); +- synchronized (coordinateListenerList) { +- coordinateListenerListCopy.addAll(coordinateListenerList); +- } +- for (CoordinateListener listener : coordinateListenerListCopy) { +- listener.onCoordinateEvent(event, message); +- } +- } +- } +- +- /** +- * Register a watcher for the coordinate. +- */ +- private void registerWatcher() throws CloudnameException, InterruptedException { +- LOG.fine(""Register watcher for ZooKeeper..""); +- try { +- zkClient.getZookeeper().exists(path, this); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- +- /** +- * Creates the serialized value of the object and stores this in ZooKeeper under the path. +- * It updates the lastStatusVersion. It does not set a watcher for the path. +- */ +- private void updateCoordinateData() throws CoordinateMissingException, CloudnameException { +- if (! started.get()) { +- throw new IllegalStateException(""Not started.""); +- } +- +- if (! zkClient.isConnected()) { +- throw new CloudnameException(""No proper connection with zookeeper.""); +- } +- +- synchronized (lastStatusVersionMonitor) { +- try { +- Stat stat = zkClient.getZookeeper().setData(path, +- zkCoordinateData.snapshot().serialize().getBytes(Util.CHARSET_NAME), +- lastStatusVersion); +- LOG.fine(""Updated coordinate, latest version is "" + stat.getVersion()); +- lastStatusVersion = stat.getVersion(); +- } catch (KeeperException.NoNodeException e) { +- throw new CoordinateMissingException(""Coordinate does not exist "" + path); +- } catch (KeeperException e) { +- throw new CloudnameException(""ZooKeeper errror in updateCoordinateData: "" +- + e.getMessage(), e); +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (IOException e) { +- throw new CloudnameException(e); +- } +- } +- +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/DynamicExpression.java b/cn/src/main/java/org/cloudname/zk/DynamicExpression.java +deleted file mode 100644 +index 3811e640..00000000 +--- a/cn/src/main/java/org/cloudname/zk/DynamicExpression.java ++++ /dev/null +@@ -1,379 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +-import org.cloudname.CloudnameException; +-import org.cloudname.Endpoint; +-import org.cloudname.Resolver; +- +-import java.util.ArrayList; +-import java.util.HashMap; +-import java.util.HashSet; +-import java.util.Iterator; +-import java.util.List; +-import java.util.Map; +-import java.util.Random; +-import java.util.Set; +-import java.util.concurrent.Executors; +-import java.util.concurrent.RejectedExecutionException; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-/** +- * Class that is capable of tracking an expression. An expression can include many nodes. +- * The number of nodes is dynamic and can change over time. +- * For now, the implementation is rather simple. For single endpoints it does use feedback from +- * ZooKeeper watcher events. For keeping track of new nodes, it does a scan on regular intervals. +- * @author dybdahl +- */ +-class DynamicExpression implements Watcher, TrackedCoordinate.ExpressionResolverNotify, +- ZkObjectHandler.ConnectionStateChanged { +- +- /** +- * Keeps track of what picture (what an expression has resolved to) is sent to the user so that +- * we know when to send new events. +- */ +- private final Map clientPicture = new HashMap(); +- +- /** +- * Where to notify changes. +- */ +- private final Resolver.ResolverListener clientCallback; +- +- /** +- * This is the expression to dynamically resolved represented as ZkResolver.Parameters. +- */ +- private final ZkResolver.Parameters parameters; +- +- /** +- * When ZooKeeper reports an error about an path, when to try to read it again. +- */ +- private final long RETRY_INTERVAL_ZOOKEEPER_ERROR_MS = 30000; // 30 seconds +- +- /** +- * We wait a bit after a node has changed because in many cases there might be several updates, +- * e.g. an application registers several endpoints, each causing an update. +- */ +- private final long REFRESH_NODE_AFTER_CHANGE_MS = 2000; // two seconds +- +- /** +- * Does a full scan with this interval. Non-final so unit test can run faster. +- */ +- protected static long TIME_BETWEEN_NODE_SCANNING_MS = 1 * 60 * 1000; // one minute +- +- /** +- * A Map with all the coordinate we care about for now. +- */ +- final private Map coordinateByPath = +- new HashMap(); +- +- /** +- * We always add some random noise to when to do things so not all servers fire at the same time +- * against +- * ZooKeeper. +- */ +- private final Random random = new Random(); +- +- private static final Logger log = Logger.getLogger(DynamicExpression.class.getName()); +- +- private boolean stopped = false; +- +- private final ZkResolver zkResolver; +- +- private final ZkObjectHandler.Client zkClient; +- +- private final ScheduledExecutorService scheduler = +- Executors.newSingleThreadScheduledExecutor(); +- +- private final Object instanceLock = new Object(); +- +- /** +- * Start getting notified about changes to expression. +- * @param expression Coordinate expression. +- * @param clientCallback called on changes and initially. +- */ +- public DynamicExpression( +- final String expression, +- final Resolver.ResolverListener clientCallback, +- final ZkResolver zkResolver, +- final ZkObjectHandler.Client zkClient) { +- this.clientCallback = clientCallback; +- this.parameters = new ZkResolver.Parameters(expression); +- this.zkResolver = zkResolver; +- this.zkClient = zkClient; +- } +- +- public void start() { +- zkClient.registerListener(this); +- scheduler.scheduleWithFixedDelay(new NodeScanner(""""), 1 /* initial delay ms */, +- TIME_BETWEEN_NODE_SCANNING_MS, TimeUnit.MILLISECONDS); +- } +- +- /** +- * Stop receiving callbacks about coordinate. +- */ +- public void stop() { +- scheduler.shutdown(); +- +- synchronized (instanceLock) { +- stopped = true; +- for (TrackedCoordinate trackedCoordinate : coordinateByPath.values()) { +- trackedCoordinate.stop(); +- } +- coordinateByPath.clear(); +- } +- } +- +- private void scheduleRefresh(String path, long delayMs) { +- try { +- scheduler.schedule(new NodeScanner(path), delayMs, TimeUnit.MILLISECONDS); +- } catch (RejectedExecutionException e) { +- if (scheduler.isShutdown()) { +- return; +- } +- log.log(Level.SEVERE, ""Got exception while scheduling new refresh"", e); +- } +- } +- +- @Override +- public void connectionUp() { +- } +- +- @Override +- public void connectionDown() { +- } +- +- @Override +- public void shutDown() { +- scheduler.shutdown(); +- } +- +- /** +- * The method will try to resolve the expression and find new nodes. +- */ +- private class NodeScanner implements Runnable { +- final String path; +- +- public NodeScanner(final String path) { +- this.path = path; +- } +- +- @Override +- public void run() { +- if (path.isEmpty()) { +- resolve(); +- } else { +- refreshPathWithWatcher(path); +- } +- notifyClient(); +- } +- } +- +- /** +- * Callback from zookeeper watcher. +- */ +- @Override +- public void process(WatchedEvent watchedEvent) { +- synchronized (instanceLock) { +- if (stopped) { +- return; +- } +- } +- String path = watchedEvent.getPath(); +- Event.KeeperState state = watchedEvent.getState(); +- Event.EventType type = watchedEvent.getType(); +- +- switch (state) { +- case Expired: +- case AuthFailed: +- case Disconnected: +- // Something bad happened to the path, try again later. +- scheduleRefresh(path, RETRY_INTERVAL_ZOOKEEPER_ERROR_MS); +- break; +- } +- switch (type) { +- case NodeChildrenChanged: +- case None: +- case NodeCreated: +- scheduleRefresh(path, REFRESH_NODE_AFTER_CHANGE_MS); +- break; +- case NodeDeleted: +- synchronized (instanceLock) { +- coordinateByPath.remove(path); +- notifyClient(); +- return; +- } +- case NodeDataChanged: +- refreshPathWithWatcher(path); +- break; +- } +- +- } +- +- /** +- * Implements interface TrackedCoordinate.ExpressionResolverNotify +- */ +- @Override +- public void nodeDead(final String path) { +- synchronized (instanceLock) { +- TrackedCoordinate trackedCoordinate = coordinateByPath.remove(path); +- if (trackedCoordinate == null) { +- return; +- } +- trackedCoordinate.stop(); +- // Triggers a new scan, and potential client updates. +- scheduleRefresh("""" /** scan for all nodes */, 50 /* ms*/); +- } +- } +- +- /** +- * Implements interface TrackedCoordinate.ExpressionResolverNotify +- */ +- @Override +- public void stateChanged(final String path) { +- // Something happened to a path, schedule a refetch. +- scheduleRefresh(path, 50); +- } +- +- private void resolve() { +- final List endpoints; +- try { +- endpoints = zkResolver.resolve(parameters.getExpression()); +- } catch (CloudnameException e) { +- log.warning(""Exception from cloudname: "" + e.toString()); +- return; +- } +- +- final Set validEndpointsPaths = new HashSet(); +- +- for (Endpoint endpoint : endpoints) { +- +- final String statusPath = ZkCoordinatePath.getStatusPath(endpoint.getCoordinate()); +- validEndpointsPaths.add(statusPath); +- +- final TrackedCoordinate trackedCoordinate; +- +- synchronized (instanceLock) { +- +- // If already discovered, do nothing. +- if (coordinateByPath.containsKey(statusPath)) { +- continue; +- } +- trackedCoordinate = new TrackedCoordinate(this, statusPath, zkClient); +- coordinateByPath.put(statusPath, trackedCoordinate); +- } +- // Tracked coordinate has to be in coordinateByPath before start is called, or events +- // gets lost. +- trackedCoordinate.start(); +- try { +- trackedCoordinate.waitForFirstData(); +- } catch (InterruptedException e) { +- log.log(Level.SEVERE, ""Got interrupt while waiting for data."", e); +- return; +- } +- } +- +- // Remove tracked coordinates that does not resolve. +- synchronized (instanceLock) { +- for (Iterator > it = +- coordinateByPath.entrySet().iterator(); +- it.hasNext(); /* nop */) { +- Map.Entry entry = it.next(); +- +- if (! validEndpointsPaths.contains(entry.getKey())) { +- log.info(""Killing endpoint "" + entry.getKey() + "": No longer resolved.""); +- entry.getValue().stop(); +- it.remove(); +- } +- } +- } +- } +- +- private String getEndpointKey(final Endpoint endpoint) { +- return endpoint.getCoordinate().asString() + ""@"" + endpoint.getName(); +- } +- +- +- private List getNewEndpoints() { +- final List newEndpoints = new ArrayList(); +- for (TrackedCoordinate trackedCoordinate : coordinateByPath.values()) { +- if (trackedCoordinate.getCoordinatedata() != null) { +- ZkResolver.addEndpoints( +- trackedCoordinate.getCoordinatedata(), +- newEndpoints, parameters.getEndpointName()); +- } +- } +- return newEndpoints; +- } +- +- private void notifyClient() { +- synchronized (instanceLock) { +- if (stopped) { +- return; +- } +- } +- // First generate a fresh list of endpoints. +- final List newEndpoints = getNewEndpoints(); +- +- synchronized (instanceLock) { +- final Map newEndpointsByName = new HashMap(); +- for (final Endpoint endpoint : newEndpoints) { +- newEndpointsByName.put(getEndpointKey(endpoint), endpoint); +- } +- final Iterator> it = clientPicture.entrySet().iterator(); +- while (it.hasNext()) { +- +- final Map.Entry endpointEntry = it.next(); +- +- final String key = endpointEntry.getKey(); +- if (! newEndpointsByName.containsKey(key)) { +- it.remove(); +- clientCallback.endpointEvent( +- Resolver.ResolverListener.Event.REMOVED_ENDPOINT, +- endpointEntry.getValue()); +- } +- } +- for (final Endpoint endpoint : newEndpoints) { +- final String key = getEndpointKey(endpoint); +- +- if (! clientPicture.containsKey(key)) { +- clientCallback.endpointEvent( +- Resolver.ResolverListener.Event.NEW_ENDPOINT, endpoint); +- clientPicture.put(key, endpoint); +- continue; +- } +- final Endpoint clientEndpoint = clientPicture.get(key); +- if (endpoint.equals(clientEndpoint)) { continue; } +- if (endpoint.getHost().equals(clientEndpoint.getHost()) && +- endpoint.getName().equals(clientEndpoint.getName()) && +- endpoint.getPort() == clientEndpoint.getPort() && +- endpoint.getProtocol().equals(clientEndpoint.getProtocol())) { +- clientCallback.endpointEvent( +- Resolver.ResolverListener.Event.MODIFIED_ENDPOINT_DATA, endpoint); +- clientPicture.put(key, endpoint); +- continue; +- } +- clientCallback.endpointEvent( +- Resolver.ResolverListener.Event.REMOVED_ENDPOINT, +- clientPicture.get(key)); +- clientCallback.endpointEvent( +- Resolver.ResolverListener.Event.NEW_ENDPOINT, endpoint); +- clientPicture.put(key, endpoint); +- } +- } +- } +- +- private void refreshPathWithWatcher(String path) { +- synchronized (instanceLock) { +- TrackedCoordinate trackedCoordinate = coordinateByPath.get(path); +- if (trackedCoordinate == null) { +- // Endpoint has been removed while waiting for refresh. +- return; +- } +- trackedCoordinate.refreshAsync(); +- } +- } +- +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/zk/TrackedConfig.java b/cn/src/main/java/org/cloudname/zk/TrackedConfig.java +deleted file mode 100644 +index aacd1908..00000000 +--- a/cn/src/main/java/org/cloudname/zk/TrackedConfig.java ++++ /dev/null +@@ -1,220 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.KeeperException; +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +-import org.apache.zookeeper.data.Stat; +-import org.cloudname.CloudnameException; +-import org.cloudname.ConfigListener; +- +-import java.io.IOException; +-import java.io.UnsupportedEncodingException; +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +-import java.util.concurrent.atomic.AtomicBoolean; +-import java.util.logging.Logger; +- +- +-/** +- * This class keeps track of config for a coordinate. +- * +- * @author dybdahl +- */ +-public class TrackedConfig implements Watcher, ZkObjectHandler.ConnectionStateChanged { +- +- private String configData = null; +- private final Object configDataMonitor = new Object(); +- private final ConfigListener configListener; +- +- private static final Logger log = Logger.getLogger(TrackedConfig.class.getName()); +- +- private final String path; +- +- private final AtomicBoolean isSynchronizedWithZookeeper = new AtomicBoolean(false); +- +- private final ZkObjectHandler.Client zkClient; +- private final ScheduledExecutorService scheduler = +- Executors.newSingleThreadScheduledExecutor(); +- /** +- * Constructor, the ZooKeeper instances is retrieved from ZkObjectHandler.Client, +- * so we won't get it until the client reports we have a Zk Instance in the handler. +- * @param path is the path of the configuration of the coordinate. +- */ +- public TrackedConfig( +- String path, ConfigListener configListener, ZkObjectHandler.Client zkClient) { +- this.path = path; +- this.configListener = configListener; +- this.zkClient = zkClient; +- } +- +- +- @Override +- public void connectionUp() { +- } +- +- @Override +- public void connectionDown() { +- isSynchronizedWithZookeeper.set(false); +- } +- +- @Override +- public void shutDown() { +- scheduler.shutdown(); +- } +- +- /** +- * Starts tracking the config. +- */ +- public void start() { +- zkClient.registerListener(this); +- final long periodicDelayMs = 2000; +- scheduler.scheduleWithFixedDelay(new ReloadConfigOnErrors(), 1 /* initial delay ms */, +- periodicDelayMs, TimeUnit.MILLISECONDS); +- } +- +- /** +- * Stops the tracker. +- */ +- public void stop() { +- scheduler.shutdown(); +- zkClient.deregisterListener(this); +- } +- +- /** +- * If connection to zookeeper is away, we need to reload because messages might have been +- * lost. This class has a method for checking this. +- */ +- private class ReloadConfigOnErrors implements Runnable { +- @Override +- public void run() { +- +- if (isSynchronizedWithZookeeper.get()) +- return; +- +- try { +- if (refreshConfigData()) { +- configListener.onConfigEvent(ConfigListener.Event.UPDATED, getConfigData()); +- } +- } catch (CloudnameException e) { +- // No worries, we try again later +- } +- } +- } +- +- /** +- * Returns current config. +- * @return config +- */ +- public String getConfigData() { +- synchronized (configDataMonitor) { +- return configData; +- } +- } +- +- /** +- * Creates a string for debugging etc +- * @return serialized version of the instance data. +- */ +- public String toString() { +- return ""Config: "" + getConfigData(); +- } +- +- +- /** +- * Handles event from ZooKeeper for this coordinate. +- * @param event Event to handle +- */ +- @Override public void process(WatchedEvent event) { +- log.severe(""Got an event from ZooKeeper "" + event.toString() + "" path: "" + path); +- +- switch (event.getType()) { +- case None: +- switch (event.getState()) { +- case SyncConnected: +- break; +- case Disconnected: +- case AuthFailed: +- case Expired: +- default: +- isSynchronizedWithZookeeper.set(false); +- // If we lost connection, we don't attempt to register another watcher as +- // this might be blocking forever. Parent might try to reconnect. +- return; +- } +- break; +- case NodeDeleted: +- synchronized (configDataMonitor) { +- isSynchronizedWithZookeeper.set(false); +- configData = null; +- } +- configListener.onConfigEvent(ConfigListener.Event.DELETED, """"); +- return; +- case NodeDataChanged: +- isSynchronizedWithZookeeper.set(false); +- return; +- case NodeChildrenChanged: +- case NodeCreated: +- break; +- } +- // We are only interested in registering a watcher in a few cases. E.g. if the event is lost +- // connection, registerWatcher does not make sense as it is blocking. In NodeDataChanged +- // above, a watcher is registerred in refreshConfigData(). +- try { +- registerWatcher(); +- } catch (CloudnameException e) { +- log.info(""Got cloudname exception: "" + e.getMessage()); +- return; +- } catch (InterruptedException e) { +- log.info(""Got interrupted exception: "" + e.getMessage()); +- return; +- } +- } +- +- +- /** +- * Loads the config from ZooKeeper. In case of failure, we keep the old data. +- * +- * @return Returns true if data has changed. +- */ +- private boolean refreshConfigData() throws CloudnameException { +- if (! zkClient.isConnected()) { +- throw new CloudnameException(""No connection to storage.""); +- } +- synchronized (configDataMonitor) { +- +- String oldConfig = configData; +- Stat stat = new Stat(); +- try { +- byte[] data; +- +- data = zkClient.getZookeeper().getData(path, this, stat); +- if (data == null) { +- configData = """"; +- } else { +- configData = new String(data, Util.CHARSET_NAME); +- } +- isSynchronizedWithZookeeper.set(true); +- return oldConfig == null || ! oldConfig.equals(configData); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (IOException e) { +- throw new CloudnameException(e); +- } +- } +- } +- +- private void registerWatcher() throws CloudnameException, InterruptedException { +- try { +- zkClient.getZookeeper().exists(path, this); +- +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java b/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java +deleted file mode 100644 +index 37b314c0..00000000 +--- a/cn/src/main/java/org/cloudname/zk/TrackedCoordinate.java ++++ /dev/null +@@ -1,220 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.*; +-import org.cloudname.*; +- +-import java.util.concurrent.CountDownLatch; +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +-import java.util.concurrent.atomic.AtomicBoolean; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-/** +- * This class keeps track of serviceStatus and endpoints for a coordinate. +- * +- * @author dybdahl +- */ +-public class TrackedCoordinate implements Watcher, ZkObjectHandler.ConnectionStateChanged { +- +- +- /** +- * The client can implement this to get notified on changes. +- */ +- public interface ExpressionResolverNotify { +- /** +- * This is called when the state has changed, it might have become unavailable. +- * @param statusPath path of the coordinate in zookeeper. +- */ +- void stateChanged(final String statusPath); +- +- /** +- * This is called when node is deleted, or it can not be read. +- * @param statusPath path of the coordinate in zookeeper. +- */ +- void nodeDead(final String statusPath); +- } +- +- private ZkCoordinateData.Snapshot coordinateData = null; +- private final Object coordinateDataMonitor = new Object(); +- +- private static final Logger LOG = Logger.getLogger(TrackedCoordinate.class.getName()); +- private final String path; +- private final ExpressionResolverNotify client; +- private final AtomicBoolean isSynchronizedWithZookeeper = new AtomicBoolean(false); +- private final ZkObjectHandler.Client zkClient; +- +- private final ScheduledExecutorService scheduler = +- Executors.newSingleThreadScheduledExecutor(); +- +- private final CountDownLatch firstRound = new CountDownLatch(1); +- /** +- * Constructor, the ZooKeeper instances is retrieved from implementing the ZkUserInterface so +- * the object is not ready to be used before the ZooKeeper instance is received. +- * @param path is the path of the status of the coordinate. +- */ +- public TrackedCoordinate( +- final ExpressionResolverNotify client, final String path, +- final ZkObjectHandler.Client zkClient) { +- LOG.finest(""Tracking coordinate with path "" + path); +- this.path = path; +- this.client = client; +- this.zkClient = zkClient; +- } +- +- // Implementation of ZkObjectHandler.ConnectionStateChanged. +- @Override +- public void connectionUp() { +- } +- +- // Implementation of ZkObjectHandler.ConnectionStateChanged. +- @Override +- public void connectionDown() { +- isSynchronizedWithZookeeper.set(false); +- } +- +- @Override +- public void shutDown() { +- scheduler.shutdown(); +- } +- +- /** +- * Signalize that the class should reload its data. +- */ +- public void refreshAsync() { +- isSynchronizedWithZookeeper.set(false); +- } +- +- public void start() { +- zkClient.registerListener(this); +- final long periodicDelayMs = 2000; +- scheduler.scheduleWithFixedDelay(new ReloadCoordinateData(), 1 /* initial delay ms */, +- periodicDelayMs, TimeUnit.MILLISECONDS); +- } +- +- public void stop() { +- scheduler.shutdown(); +- zkClient.deregisterListener(this); +- } +- +- public void waitForFirstData() throws InterruptedException { +- firstRound.await(); +- } +- +- +- +- /** +- * This class handles reloading new data from zookeeper if we are out of synch. +- */ +- class ReloadCoordinateData implements Runnable { +- @Override +- public void run() { +- if (! isSynchronizedWithZookeeper.getAndSet(true)) { return; } +- try { +- refreshCoordinateData(); +- } catch (CloudnameException e) { +- LOG.log(Level.INFO, ""exception on reloading coordinate data."", e); +- isSynchronizedWithZookeeper.set(false); +- } +- firstRound.countDown(); +- } +- } +- +- +- public ZkCoordinateData.Snapshot getCoordinatedata() { +- synchronized (coordinateDataMonitor) { +- return coordinateData; +- } +- } +- +- +- /** +- * Creates a string for debugging etc +- * @return serialized version of the instance data. +- */ +- public String toString() { +- synchronized (coordinateDataMonitor) { +- return coordinateData.toString(); +- } +- } +- +- +- /** +- * Handles event from ZooKeeper for this coordinate. +- * @param event Event to handle +- */ +- @Override public void process(WatchedEvent event) { +- LOG.fine(""Got an event from ZooKeeper "" + event.toString() + "" path: "" + path); +- +- switch (event.getType()) { +- case None: +- switch (event.getState()) { +- case SyncConnected: +- break; +- case Disconnected: +- case AuthFailed: +- case Expired: +- default: +- // If we lost connection, we don't attempt to register another watcher as +- // this might be blocking forever. Parent might try to reconnect. +- return; +- } +- break; +- case NodeDeleted: +- synchronized (coordinateDataMonitor) { +- coordinateData = new ZkCoordinateData().snapshot(); +- } +- client.nodeDead(path); +- return; +- case NodeDataChanged: +- isSynchronizedWithZookeeper.set(false); +- return; +- case NodeChildrenChanged: +- case NodeCreated: +- break; +- } +- try { +- registerWatcher(); +- } catch (CloudnameException e) { +- LOG.log(Level.INFO, ""Got cloudname exception."", e); +- } catch (InterruptedException e) { +- LOG.log(Level.INFO, ""Got interrupted exception."", e); +- } +- } +- +- +- /** +- * Loads the coordinate from ZooKeeper. In case of failure, we keep the old data. +- * Notifies the client if state changes. +- */ +- private void refreshCoordinateData() throws CloudnameException { +- +- if (! zkClient.isConnected()) { +- throw new CloudnameException(""No connection to storage.""); +- } +- synchronized (coordinateDataMonitor) { +- String oldDataSerialized = (null == coordinateData) ? """" : coordinateData.serialize(); +- try { +- coordinateData = ZkCoordinateData.loadCoordinateData( +- path, zkClient.getZookeeper(), this).snapshot(); +- } catch (CloudnameException e) { +- client.nodeDead(path); +- LOG.log(Level.FINER, ""Exception while reading path "" + path, e); +- return; +- } +- isSynchronizedWithZookeeper.set(true); +- if (! oldDataSerialized.equals(coordinateData.toString())) { +- client.stateChanged(path); +- } +- } +- } +- +- private void registerWatcher() throws CloudnameException, InterruptedException { +- try { +- zkClient.getZookeeper().exists(path, this); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/zk/Util.java b/cn/src/main/java/org/cloudname/zk/Util.java +deleted file mode 100644 +index 6bcd21e0..00000000 +--- a/cn/src/main/java/org/cloudname/zk/Util.java ++++ /dev/null +@@ -1,177 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.CloudnameException; +- +-import org.apache.zookeeper.ZooKeeper; +-import org.apache.zookeeper.CreateMode; +-import org.apache.zookeeper.data.ACL; +-import org.apache.zookeeper.KeeperException; +-import org.cloudname.CoordinateMissingException; +- +-import java.util.ArrayList; +-import java.util.List; +- +-/** +- * Various ZooKeeper utilities. +- * +- * @author borud +- */ +-public final class Util { +- // Constants +- public static final String CHARSET_NAME = ""UTF-8""; +- +- /** +- * Create a path in ZooKeeper. We just start at the top and work +- * our way down. Nodes that exist will throw an exception but we +- * will just ignore those. The result should be a path consisting +- * of ZooKeeper nodes with the names specified by the path and +- * with their data element set to null. +- * @throws CloudnameException if problems talking with ZooKeeper. +- */ +- public static void mkdir(final ZooKeeper zk, String path, final List acl) +- throws CloudnameException, InterruptedException { +- if (path.startsWith(""/"")) { +- path = path.substring(1); +- } +- +- String[] parts = path.split(""/""); +- +- String createPath = """"; +- for (String p : parts) { +- // Sonar will complain about this. Usually it would be +- // right but in this case it isn't. +- createPath += ""/"" + p; +- try { +- zk.create(createPath, null, acl, CreateMode.PERSISTENT); +- } catch (KeeperException.NodeExistsException e) { +- // This is okay. Ignore. +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- } +- +- /** +- * Lists sub nodes of a path in a ZooKeeper instance. +- * @param path starts from this path +- * @param nodeList put sub-nodes in this list +- */ +- public static void listRecursively( +- final ZooKeeper zk, final String path, final List nodeList) +- throws CloudnameException, InterruptedException { +- +- List children = null; +- try { +- children = zk.getChildren(path, false); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- if (children.size() == 0) { +- nodeList.add(path); +- return; +- } +- for (String childPath : children) { +- listRecursively(zk, path + ""/"" +childPath, nodeList); +- } +- } +- +- /** +- * Figures out if there are sub-nodes under the path in a ZooKeeper instance. +- * @return true if the node exists and has children. +- * @throws CoordinateMissingException if the path does not exist in ZooKeeper. +- */ +- public static boolean hasChildren(final ZooKeeper zk, final String path) +- throws CloudnameException, CoordinateMissingException, InterruptedException { +- if (! exist(zk, path)) { +- throw new CoordinateMissingException(""Could not get children due to non-existing path "" +- + path); +- } +- List children = null; +- try { +- children = zk.getChildren(path, false); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- return ((children != null) && (children.size() > 0)); +- } +- +- /** +- * Figures out if a path exists in a ZooKeeper instance. +- * @throws CloudnameException if there are problems taking to the ZooKeeper instance. +- * @return true if the path exists. +- */ +- public static boolean exist(final ZooKeeper zk, final String path) +- throws CloudnameException, InterruptedException { +- try { +- return zk.exists(path, false) != null; +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- +- /** +- * Returns the version of the path. +- * @param zk +- * @param path +- * @return version number +- */ +- public static int getVersionForDeletion(final ZooKeeper zk, final String path) +- throws CloudnameException, InterruptedException { +- +- try { +- int version = zk.exists(path, false).getVersion(); +- if (version < 0) { +- throw new CloudnameException( +- new RuntimeException(""Got negative version for path "" + path)); +- } +- return version; +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- } +- +- /** +- * Deletes nodes from a path from the right to the left. +- * @param zk +- * @param path to be deleted +- * @param keepMinLevels is the minimum number of levels (depths) to keep in the path. +- * @return the number of deleted levels. +- */ +- public static int deletePathKeepRootLevels( +- final ZooKeeper zk, String path, int keepMinLevels) +- throws CloudnameException, CoordinateMissingException, InterruptedException { +- if (path.startsWith(""/"")) { +- path = path.substring(1); +- } +- +- String[] parts = path.split(""/""); +- +- // We are happy if only the first two deletions went through. The other deletions are just +- // cleaning up if there are no more coordinates on the same rootPath. +- int deletedNodes = 0; +- List paths = new ArrayList(); +- String incrementalPath = """"; +- for (String p : parts) { +- incrementalPath += ""/"" + p; +- paths.add(incrementalPath); +- } +- +- for (int counter = paths.size() - 1; counter >= keepMinLevels; counter--) { +- String deletePath = paths.get(counter); +- int version = getVersionForDeletion(zk, deletePath); +- if (hasChildren(zk, deletePath)) { +- return deletedNodes; +- } +- try { +- zk.delete(deletePath, version); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- deletedNodes++; +- } +- return deletedNodes; +- } +- +- // Should not be instantiated. +- private Util() {} +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkCloudname.java b/cn/src/main/java/org/cloudname/zk/ZkCloudname.java +deleted file mode 100644 +index c14e5e7b..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkCloudname.java ++++ /dev/null +@@ -1,419 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.data.Stat; +-import org.cloudname.*; +- +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +-import org.apache.zookeeper.ZooKeeper; +-import org.apache.zookeeper.CreateMode; +-import org.apache.zookeeper.ZooDefs.Ids; +-import org.apache.zookeeper.KeeperException; +- +-import java.io.UnsupportedEncodingException; +-import java.util.List; +- +-import java.util.concurrent.Executors; +-import java.util.concurrent.ScheduledExecutorService; +-import java.util.concurrent.TimeUnit; +- +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-import java.util.concurrent.CountDownLatch; +- +-import java.io.IOException; +- +- +-/** +- * An implementation of Cloudname using ZooKeeper. +- * +- * This implementation assumes that the path prefix defined by +- * CN_PATH_PREFIX is only used by Cloudname. The structure and +- * semantics of things under this prefix are defined by this library +- * and will be subject to change. +- * +- * +- * @author borud +- * @author dybdahl +- * @author storsveen +- */ +-public final class ZkCloudname implements Cloudname, Watcher, Runnable { +- +- private static final int SESSION_TIMEOUT = 5000; +- +- private static final Logger log = Logger.getLogger(ZkCloudname.class.getName()); +- +- private ZkObjectHandler zkObjectHandler = null; +- +- private final String connectString; +- +- // Latches that count down when ZooKeeper is connected +- private final CountDownLatch connectedSignal = new CountDownLatch(1); +- +- private ZkResolver resolver = null; +- +- private int connectingCounter = 0; +- +- private final ScheduledExecutorService scheduler = +- Executors.newSingleThreadScheduledExecutor(); +- +- private ZkCloudname(final Builder builder) { +- connectString = builder.getConnectString(); +- +- } +- +- /** +- * Checks state of zookeeper connection and try to keep it running. +- */ +- @Override +- public void run() { +- final ZooKeeper.States state = zkObjectHandler.getClient().getZookeeper().getState(); +- +- if (state == ZooKeeper.States.CONNECTED) { +- connectingCounter = 0; +- return; +- } +- +- if (state == ZooKeeper.States.CONNECTING) { +- connectingCounter++; +- if (connectingCounter > 10) { +- log.fine(""Long time in connecting, forcing a close of zookeeper client.""); +- zkObjectHandler.close(); +- connectingCounter = 0; +- } +- return; +- } +- +- if (state == ZooKeeper.States.CLOSED) { +- log.fine(""Retrying connection to ZooKeeper.""); +- try { +- zkObjectHandler.setZooKeeper( +- new ZooKeeper(connectString, SESSION_TIMEOUT, this)); +- } catch (IOException e) { +- log.log(Level.SEVERE, ""RetryConnection failed for some reason:"" +- + e.getMessage(), e); +- } +- return; +- } +- +- log.severe(""Unknown state "" + state + "" closing....""); +- zkObjectHandler.close(); +- } +- +- +- /** +- * Connect to ZooKeeper instance with time-out value. +- * @param waitTime time-out value for establishing connection. +- * @param waitUnit time unit for time-out when establishing connection. +- * @throws CloudnameException if connection can not be established +- * @return +- */ +- public ZkCloudname connectWithTimeout(long waitTime, TimeUnit waitUnit) +- throws CloudnameException { +- boolean connected = false; +- try { +- +- zkObjectHandler = new ZkObjectHandler( +- new ZooKeeper(connectString, SESSION_TIMEOUT, this)); +- +- if (! connectedSignal.await(waitTime, waitUnit)) { +- throw new CloudnameException(""Connecting to ZooKeeper timed out.""); +- } +- log.fine(""Connected to ZooKeeper "" + connectString); +- connected = true; +- } catch (IOException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } finally { +- if (!connected && zkObjectHandler != null) { +- zkObjectHandler.close(); +- } +- } +- resolver = new ZkResolver.Builder().addStrategy(new StrategyAll()) +- .addStrategy(new StrategyAny()).build(zkObjectHandler.getClient()); +- scheduler.scheduleWithFixedDelay(this, 1 /* initial delay ms */, +- 1000 /* check state every second */, TimeUnit.MILLISECONDS); +- return this; +- } +- +- /** +- * Connect to ZooKeeper instance with long time-out, however, it might fail fast. +- * @return connected ZkCloudname object +- * @throws CloudnameException if connection can not be established. +- */ +- public ZkCloudname connect() throws CloudnameException { +- // We wait up to 100 years. +- return connectWithTimeout(365 * 100, TimeUnit.DAYS); +- } +- +- +- +- @Override +- public void process(WatchedEvent event) { +- log.fine(""Got event in ZkCloudname: "" + event.toString()); +- if (event.getState() == Event.KeeperState.Disconnected +- || event.getState() == Event.KeeperState.Expired) { +- zkObjectHandler.connectionDown(); +- } +- +- // Initial connection to ZooKeeper is completed. +- if (event.getState() == Event.KeeperState.SyncConnected) { +- zkObjectHandler.connectionUp(); +- // The first connection set up is blocking, this will unblock the connection. +- connectedSignal.countDown(); +- } +- } +- +- /** +- * Create a given coordinate in the ZooKeeper node tree. +- * +- * Just blindly creates the entire path. Elements of the path may +- * exist already, but it seems wasteful to +- * @throws CoordinateExistsException if coordinate already exists- +- * @throws CloudnameException if problems with zookeeper connection. +- */ +- @Override +- public void createCoordinate(final Coordinate coordinate) +- throws CloudnameException, CoordinateExistsException { +- // Create the root path for the coordinate. We do this +- // blindly, meaning that if the path already exists, then +- // that's ok -- so a more correct name for this method would +- // be ensureCoordinate(), but that might confuse developers. +- String root = ZkCoordinatePath.getCoordinateRoot(coordinate); +- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper(); +- try { +- if (Util.exist(zk, root)) { +- throw new CoordinateExistsException(""Coordinate already created:"" +root); +- } +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- +- try { +- Util.mkdir(zk, root, Ids.OPEN_ACL_UNSAFE); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- +- // Create the nodes that represent subdirectories. +- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null); +- try { +- log.fine(""Creating config node "" + configPath); +- zk.create(configPath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- } +- +- /** +- * Deletes a coordinate in the persistent service store. This includes deletion +- * of config. It will fail if the coordinate is claimed. +- * @param coordinate the coordinate we wish to destroy. +- */ +- @Override +- public void destroyCoordinate(final Coordinate coordinate) +- throws CoordinateDeletionException, CoordinateMissingException, CloudnameException { +- String statusPath = ZkCoordinatePath.getStatusPath(coordinate); +- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null); +- String rootPath = ZkCoordinatePath.getCoordinateRoot(coordinate); +- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper(); +- try { +- if (! Util.exist(zk, rootPath)) { +- throw new CoordinateMissingException(""Coordinate not found: "" + rootPath); +- } +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- +- +- // Do this early to raise the error before anything is deleted. However, there might be a +- // race condition if someone claims while we delete configPath and instance (root) node. +- try { +- if (Util.exist(zk, configPath) && Util.hasChildren(zk, configPath)) { +- throw new CoordinateDeletionException(""Coordinate has config node.""); +- } +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- +- try { +- if (Util.exist(zk, statusPath)) { +- throw new CoordinateDeletionException(""Coordinate is claimed.""); +- } +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- +- // Delete config, the instance node, and continue with as much as possible. +- // We might have a raise condition if someone is creating a coordinate with a shared path +- // in parallel. We want to keep 3 levels of nodes (/cn/%CELL%/%USER%). +- int deletedNodes = 0; +- try { +- deletedNodes = Util.deletePathKeepRootLevels(zk, configPath, 3); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- if (deletedNodes == 0) { +- throw new CoordinateDeletionException(""Failed deleting config node, nothing deleted..""); +- } +- if (deletedNodes == 1) { +- throw new CoordinateDeletionException(""Failed deleting instance node.""); +- } +- } +- +- /** +- * Claim a coordinate. +- * +- * In this implementation a coordinate is claimed by creating an +- * ephemeral with the name defined in CN_STATUS_NAME. If the node +- * already exists the coordinate has already been claimed. +- */ +- @Override +- public ServiceHandle claim(final Coordinate coordinate) { +- String statusPath = ZkCoordinatePath.getStatusPath(coordinate); +- log.fine(""Claiming "" + coordinate.asString() + "" ("" + statusPath + "")""); +- +- ClaimedCoordinate statusAndEndpoints = new ClaimedCoordinate( +- coordinate, zkObjectHandler.getClient()); +- +- // If we have come thus far we have succeeded in creating the +- // CN_STATUS_NAME node within the service coordinate directory +- // in ZooKeeper and we can give the client a ServiceHandle. +- ZkServiceHandle handle = new ZkServiceHandle( +- statusAndEndpoints, coordinate, zkObjectHandler.getClient()); +- statusAndEndpoints.start(); +- return handle; +- } +- +- @Override +- public Resolver getResolver() { +- +- return resolver; +- } +- +- @Override +- public ServiceStatus getStatus(Coordinate coordinate) throws CloudnameException { +- String statusPath = ZkCoordinatePath.getStatusPath(coordinate); +- ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData( +- statusPath, zkObjectHandler.getClient().getZookeeper(), null); +- return zkCoordinateData.snapshot().getServiceStatus(); +- } +- +- @Override +- public void setConfig( +- final Coordinate coordinate, final String newConfig, final String oldConfig) +- throws CoordinateMissingException, CloudnameException { +- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null); +- int version = -1; +- final ZooKeeper zk = zkObjectHandler.getClient().getZookeeper(); +- if (oldConfig != null) { +- Stat stat = new Stat(); +- byte [] data = null; +- try { +- data = zk.getData(configPath, false, stat); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- try { +- String stringData = new String(data, Util.CHARSET_NAME); +- if (! stringData.equals(oldConfig)) { +- throw new CloudnameException(""Data did not match old config. Actual old "" +- + stringData + "" specified old "" + oldConfig); +- } +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } +- version = stat.getVersion(); +- } +- try { +- zk.setData(configPath, newConfig.getBytes(Util.CHARSET_NAME), version); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } +- } +- +- +- @Override +- public String getConfig(final Coordinate coordinate) +- throws CoordinateMissingException, CloudnameException { +- String configPath = ZkCoordinatePath.getConfigPath(coordinate, null); +- Stat stat = new Stat(); +- try { +- byte[] data = zkObjectHandler.getClient().getZookeeper().getData( +- configPath, false, stat); +- if (data == null) { +- return null; +- } +- return new String(data, Util.CHARSET_NAME); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } +- } +- +- /** +- * Close the connection to ZooKeeper. +- */ +- @Override +- public void close() { +- zkObjectHandler.shutdown(); +- log.fine(""ZooKeeper session closed for "" + connectString); +- scheduler.shutdown(); +- } +- +- /** +- * List the sub-nodes in ZooKeeper owned by Cloudname. +- * @param nodeList +- */ +- public void listRecursively(List nodeList) +- throws CloudnameException, InterruptedException { +- Util.listRecursively(zkObjectHandler.getClient().getZookeeper(), +- ZkCoordinatePath.getCloudnameRoot(), nodeList); +- } +- +- /** +- * This class builds parameters for ZkCloudname. +- */ +- public static class Builder { +- private String connectString; +- +- public Builder setConnectString(String connectString) { +- this.connectString = connectString; +- return this; +- } +- +- // TODO(borud, dybdahl): Make this smarter, some ideas: +- // Connect to one node and read from a magic path +- // how many zookeepers that are running and build +- // the path based on this information. +- public Builder setDefaultConnectString() { +- this.connectString = ""z1:2181,z2:2181,z3:2181""; +- return this; +- } +- +- public String getConnectString() { +- return connectString; +- } +- +- public ZkCloudname build() { +- if (connectString.isEmpty()) { +- throw new RuntimeException( +- ""You need to specify connection string before you can build.""); +- } +- return new ZkCloudname(this); +- } +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java b/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java +deleted file mode 100644 +index 622b6482..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkCoordinateData.java ++++ /dev/null +@@ -1,228 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.KeeperException; +-import org.apache.zookeeper.Watcher; +-import org.apache.zookeeper.ZooKeeper; +-import org.apache.zookeeper.data.Stat; +-import org.cloudname.CloudnameException; +-import org.cloudname.Endpoint; +-import org.cloudname.ServiceState; +-import org.cloudname.ServiceStatus; +-import com.fasterxml.jackson.core.JsonFactory; +-import com.fasterxml.jackson.core.JsonGenerator; +-import com.fasterxml.jackson.core.JsonParser; +-import com.fasterxml.jackson.core.type.TypeReference; +-import com.fasterxml.jackson.databind.ObjectMapper; +- +-import java.io.IOException; +-import java.io.StringWriter; +-import java.io.UnsupportedEncodingException; +-import java.util.Collection; +-import java.util.HashMap; +-import java.util.HashSet; +-import java.util.List; +-import java.util.Map; +-import java.util.Set; +- +-/** +- * ZkCoordinateData represent the data regarding a coordinate. It can return an immutable snapshot. +- * The class has support for deserializing and serializing the data and methods for accessing +- * endpoints. The class is fully thread-safe. +- * +- * @auther dybdahl +- */ +-public final class ZkCoordinateData { +- /** +- * The status of the coordinate, is it running etc. +- */ +- private ServiceStatus serviceStatus = new ServiceStatus(ServiceState.UNASSIGNED, +- ""No service state has been assigned""); +- +- /** +- * The endpoints registered at the coordinate mapped by endpoint name. +- */ +- private final Map endpointsByName = new HashMap(); +- +- // Used for deserializing. +- private final ObjectMapper objectMapper = new ObjectMapper(); +- +- private final Object localVariablesMonitor = new Object(); +- +- /** +- * Create a new immutable snapshot object. +- */ +- public Snapshot snapshot() { +- synchronized (localVariablesMonitor) { +- return new Snapshot(serviceStatus, endpointsByName); +- } +- } +- +- /** +- * Sets status, overwrite any existing status information. +- */ +- public ZkCoordinateData setStatus(ServiceStatus status) { +- synchronized (localVariablesMonitor) { +- this.serviceStatus = status; +- return this; +- } +- } +- +- /** +- * Adds new endpoints to the builder. It is legal to add a new endpoint with an endpoint +- * that already exists. +- */ +- public ZkCoordinateData putEndpoints(final List newEndpoints) { +- synchronized (localVariablesMonitor) { +- for (Endpoint endpoint : newEndpoints) { +- endpointsByName.put(endpoint.getName(), endpoint); +- } +- } +- return this; +- } +- +- /** +- * Remove endpoints from the Dynamic object. +- */ +- public ZkCoordinateData removeEndpoints(final List names) { +- synchronized (localVariablesMonitor) { +- for (String name : names) { +- if (! endpointsByName.containsKey(name)) { +- throw new IllegalArgumentException(""endpoint does not exist: "" + name); +- } +- if (null == endpointsByName.remove(name)) { +- throw new IllegalArgumentException( +- ""Endpoint does not exists, null in internal structure."" + name); +- } +- } +- } +- return this; +- } +- +- /** +- * Sets the state of the Dynamic object based on a serialized byte string. +- * Any old data is overwritten. +- * @throws IOException if something went wrong, should not happen on valid data. +- */ +- public ZkCoordinateData deserialize(byte[] data) throws IOException { +- synchronized (localVariablesMonitor) { +- final String stringData = new String(data, Util.CHARSET_NAME); +- final JsonFactory jsonFactory = new JsonFactory(); +- final JsonParser jp = jsonFactory.createJsonParser(stringData); +- final String statusString = objectMapper.readValue(jp, new TypeReference() {}); +- serviceStatus = ServiceStatus.fromJson(statusString); +- endpointsByName.clear(); +- endpointsByName.putAll((Map)objectMapper.readValue(jp, +- new TypeReference >() {})); +- } +- return this; +- } +- +- /** +- * An immutable representation of the coordinate data. +- */ +- public static class Snapshot { +- /** +- * The status of the coordinate, is it running etc. +- */ +- private final ServiceStatus serviceStatus; +- +- /** +- * The endpoints registered at the coordinate mapped by endpoint name. +- */ +- private final Map endpointsByName; +- +- /** +- * Getter for status of coordinate. +- * @return the service status of the coordinate. +- */ +- public ServiceStatus getServiceStatus() { +- return serviceStatus; +- } +- +- /** +- * Getter for endpoint of the coordinate given the endpoint name. +- * @param name of the endpoint. +- * @return the endpoint or null if non-existing. +- */ +- public Endpoint getEndpoint(final String name) { +- return endpointsByName.get(name); +- } +- +- /** +- * Returns all the endpoints. +- * @return set of endpoints. +- */ +- public Set getEndpoints() { +- Set endpoints = new HashSet(); +- endpoints.addAll(endpointsByName.values()); +- return endpoints; +- } +- +- /** +- * A method for getting all endpoints. +- * @param endpoints The endpoints are put in this list. +- */ +- public void appendAllEndpoints(final Collection endpoints) { +- endpoints.addAll(endpointsByName.values()); +- } +- +- /** +- * Return a serialized string representing the status and endpoint. It can be de-serialize +- * by the inner class. +- * @return The serialized string. +- * @throws IOException if something goes wrong, should not be a common problem though. +- */ +- public String serialize() { +- final StringWriter stringWriter = new StringWriter(); +- final JsonGenerator generator; +- +- try { +- generator = new JsonFactory(new ObjectMapper()).createJsonGenerator(stringWriter); +- generator.writeString(serviceStatus.toJson()); +- generator.writeObject(endpointsByName); +- +- generator.flush(); +- } catch (IOException e) { +- throw new RuntimeException( +- ""Got IOException while serializing coordinate data."" , e); +- } +- return new String(stringWriter.getBuffer()); +- } +- +- /** +- * Private constructor, only ZkCoordinateData can build this. +- */ +- private Snapshot(ServiceStatus serviceStatus, Map endpointsByName) { +- this.serviceStatus = serviceStatus; +- this.endpointsByName = endpointsByName; +- } +- } +- +- /** +- * Utility function to create and load a ZkCoordinateData from ZooKeeper. +- * @param watcher for callbacks from ZooKeeper. It is ok to pass null. +- * @throws CloudnameException when problems loading data. +- */ +- static public ZkCoordinateData loadCoordinateData( +- final String statusPath, final ZooKeeper zk, final Watcher watcher) +- throws CloudnameException { +- Stat stat = new Stat(); +- try { +- byte[] data; +- if (watcher == null) { +- data = zk.getData(statusPath, false, stat); +- } else { +- data = zk.getData(statusPath, watcher, stat); +- } +- return new ZkCoordinateData().deserialize(data); +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } catch (UnsupportedEncodingException e) { +- throw new CloudnameException(e); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } catch (IOException e) { +- throw new CloudnameException(e); +- } +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java b/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java +deleted file mode 100644 +index 6e4eb847..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkCoordinatePath.java ++++ /dev/null +@@ -1,87 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.Coordinate; +- +- +-/** +- * A class for creating paths for ZooKeeper. +- * The semantic of a path is string of the form /cn/%cell%/%user%/%service%/%instance%/[status]|[config/%name%] +- +- * The prefix /cn indicates that the content is owned by the CloudName library. +- * Anything that lives under this prefix can only be touched by the Cloudname library. +- * If clients begin to fiddle with nodes under this prefix directly, all deals are off. +- * @author: dybdahl +- */ +-public final class ZkCoordinatePath { +- private static final String CN_PATH_PREFIX = ""/cn""; +- private static final String CN_STATUS_NAME = ""status""; +- private static final String CN_CONFIG_NAME = ""config""; +- +- public static String getCloudnameRoot() { +- return CN_PATH_PREFIX; +- } +- /** +- * Builds the root path of a coordinate. +- * @param coordinate +- * @return the path of the coordinate in ZooKeeper (/cn/%cell%/%user%/%service%/%instance%). +- */ +- public static String getCoordinateRoot(final Coordinate coordinate) { +- return coordinateAsPath(coordinate.getCell(), coordinate.getUser(), coordinate.getService(), +- coordinate.getInstance()); +- } +- +- /** +- * Builds the status path of a coordinate. +- * @param coordinate +- * @return full status path (/cn/%cell%/%user%/%service%/%instance%/status) +- */ +- public static String getStatusPath(final Coordinate coordinate) { +- return getCoordinateRoot(coordinate) + ""/"" + CN_STATUS_NAME; +- } +- +- /** +- * Builds the config path of a coordinate. +- * @param coordinate +- * @param name if null, the last path of the path (/%name%) is not included. +- * @return config path /cn/%cell%/%user%/%service%/%instance%/config or +- * /cn/%cell%/%user%/%service%/%instance%/config/%name% +- */ +- public static String getConfigPath(final Coordinate coordinate, final String name) { +- if (name == null) { +- return getCoordinateRoot(coordinate) + ""/"" + CN_CONFIG_NAME; +- } +- return getCoordinateRoot(coordinate) + ""/"" + CN_CONFIG_NAME + ""/"" + name; +- } +- +- /** +- * Builds first part of a ZooKeeper path. +- * @param cell +- * @param user +- * @param service +- * @return path (/cn/%cell%/%user%/%service%) +- */ +- public static String coordinateWithoutInstanceAsPath( +- final String cell, final String user, final String service) { +- return CN_PATH_PREFIX + ""/"" + cell + ""/"" + user + ""/"" + service; +- } +- +- public static String getStatusPath(String cell, String user, String service, Integer instance) { +- return coordinateAsPath(cell, user, service, instance) + ""/"" + CN_STATUS_NAME; +- } +- +- /** +- * Builds first part of a ZooKeeper path. +- * @param cell +- * @param user +- * @param service +- * @param instance +- * @return path (/cn/%cell%/%user%/%service%/%instance%) +- */ +- private static String coordinateAsPath( +- final String cell, final String user, final String service, Integer instance) { +- return coordinateWithoutInstanceAsPath(cell, user, service) + ""/"" + instance.toString(); +- } +- +- // Should not be instantiated. +- private ZkCoordinatePath() {} +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java b/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java +deleted file mode 100644 +index e17e0009..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkObjectHandler.java ++++ /dev/null +@@ -1,157 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.ZooKeeper; +- +-import java.util.HashSet; +-import java.util.Set; +-import java.util.concurrent.atomic.AtomicBoolean; +- +-/** +- * Class that keeps an instance of zookeeper. It has a sub-class with read access and +- * a listener service. +- * @author dybdahl +- */ +-public class ZkObjectHandler { +- private ZooKeeper zooKeeper = null; +- private final Object zooKeeperMonitor = new Object(); +- +- private final Set registeredCallbacks = +- new HashSet(); +- private final Object callbacksMonitor = new Object(); +- +- private final AtomicBoolean isConnected = new AtomicBoolean(true); +- +- /** +- * Constructor +- * @param zooKeeper first zooKeeper to use, should not be null. +- */ +- public ZkObjectHandler(final ZooKeeper zooKeeper) { +- this.zooKeeper = zooKeeper; +- } +- +- /** +- * Interface for notification of connection state changes. +- */ +- public interface ConnectionStateChanged { +- void connectionUp(); +- void connectionDown(); +- void shutDown(); +- } +- +- /** +- * Indicate that zookeeper connection is working by calling this method. +- */ +- public void connectionUp() { +- boolean previous = isConnected.getAndSet(true); +- if (previous == true) { return; } +- synchronized (callbacksMonitor) { +- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) { +- connectionStateChanged.connectionUp(); +- } +- } +- } +- +- /** +- * Indicate that zookeeper connection is broken by calling this method. +- */ +- public void connectionDown() { +- boolean previous = isConnected.getAndSet(false); +- if (previous == false) { return; } +- synchronized (callbacksMonitor) { +- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) { +- connectionStateChanged.connectionDown(); +- } +- } +- } +- +- /** +- * Every class using Zookeeper has an instance of this Client class +- * to check the connection and fetch the instance. +- */ +- public class Client { +- public ZooKeeper getZookeeper() { +- synchronized (zooKeeperMonitor) { +- return zooKeeper; +- } +- } +- +- /** +- * Check if we are connected to Zookeeper +- * @return True if zkCloudname confirmed connection <1000ms ago. +- */ +- public boolean isConnected() { +- return isConnected.get(); +- } +- +- /** +- * Register a callback. +- * @param connectionStateChanged Callback to register +- * @return true if this is a new callback. +- */ +- public boolean registerListener(ConnectionStateChanged connectionStateChanged) { +- synchronized (callbacksMonitor) { +- return registeredCallbacks.add(connectionStateChanged); +- } +- } +- +- /** +- * Deregister a callback. +- * @param connectionStateChanged Callback to deregister. +- * @return true if the callback was registered. +- */ +- public boolean deregisterListener(ConnectionStateChanged connectionStateChanged) { +- synchronized (callbacksMonitor) { +- return registeredCallbacks.remove(connectionStateChanged); +- } +- } +- } +- +- /** +- * Returns client +- * @return client object. +- */ +- public Client getClient() { +- return new Client(); +- } +- +- /** +- * Update zooKeeper instance. +- * @param zooKeeper +- */ +- public void setZooKeeper(final ZooKeeper zooKeeper) { +- synchronized (zooKeeperMonitor) { +- this.zooKeeper = zooKeeper; +- } +- } +- +- /** +- * Closes zooKeeper object. +- */ +- public void close() { +- synchronized (zooKeeperMonitor) { +- if (zooKeeper == null) { return; } +- +- try { +- zooKeeper.close(); +- } catch (InterruptedException e) { +- // ignore +- } +- } +- } +- +- /** +- * Shut down all listeners. +- */ +- public void shutdown() { +- synchronized (callbacksMonitor) { +- for (ConnectionStateChanged connectionStateChanged : registeredCallbacks) { +- connectionStateChanged.shutDown(); +- } +- } +- try { +- zooKeeper.close(); +- } catch (InterruptedException e) { +- // ignore +- } +- } +-} +\ No newline at end of file +diff --git a/cn/src/main/java/org/cloudname/zk/ZkResolver.java b/cn/src/main/java/org/cloudname/zk/ZkResolver.java +deleted file mode 100644 +index 80b49197..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkResolver.java ++++ /dev/null +@@ -1,460 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.zookeeper.KeeperException; +-import org.apache.zookeeper.ZooKeeper; +-import org.cloudname.*; +- +-import java.util.*; +-import java.util.logging.Level; +-import java.util.logging.Logger; +-import java.util.regex.Pattern; +-import java.util.regex.Matcher; +- +- +-/** +- * This class is used to resolve Cloudname coordinates into endpoints. +- * +- * @author borud +- */ +-public final class ZkResolver implements Resolver, ZkObjectHandler.ConnectionStateChanged { +- +- private static final Logger log = Logger.getLogger(ZkResolver.class.getName()); +- +- private Map strategies; +- +- private final ZkObjectHandler.Client zkGetter; +- +- private final Object dynamicAddressMonitor = new Object(); +- +- private Map dynamicAddressesByListener = new HashMap(); +- +- @Override +- public void connectionUp() { +- synchronized (dynamicAddressMonitor) { +- for (ResolverListener listener : dynamicAddressesByListener.keySet()) { +- listener.endpointEvent(ResolverListener.Event.CONNECTION_OK, null); +- } +- } +- } +- +- @Override +- public void connectionDown() { +- synchronized (dynamicAddressMonitor) { +- for (ResolverListener listener : dynamicAddressesByListener.keySet()) { +- listener.endpointEvent(ResolverListener.Event.LOST_CONNECTION, null); +- } +- } +- } +- +- @Override +- public void shutDown() { +- // Nothing to shut down here. +- } +- +- public static class Builder { +- +- final private Map strategies = new HashMap(); +- +- public Builder addStrategy(ResolverStrategy strategy) { +- strategies.put(strategy.getName(), strategy); +- return this; +- } +- +- public Map getStrategies() { +- return strategies; +- } +- +- public ZkResolver build(ZkObjectHandler.Client zkGetter) { +- return new ZkResolver(this, zkGetter); +- } +- +- } +- +- +- // Matches coordinate with endpoint of the form: +- // endpoint.instance.service.user.cell +- public static final Pattern endpointPattern +- = Pattern.compile( ""^([a-z][a-z0-9-_]*)\\."" // endpoint +- + ""(\\d+)\\."" // instance +- + ""([a-z][a-z0-9-_]*)\\."" // service +- + ""([a-z][a-z0-9-_]*)\\."" // user +- + ""([a-z][a-z-_]*)\\z""); // cell +- +- // Parses abstract coordinate of the form: +- // strategy.service.user.cell. This pattern is useful for +- // resolving hosts, but not endpoints. +- public static final Pattern strategyPattern +- = Pattern.compile( ""^([a-z][a-z0-9-_]*)\\."" // strategy +- + ""([a-z][a-z0-9-_]*)\\."" // service +- + ""([a-z][a-z0-9-_]*)\\."" // user +- + ""([a-z][a-z0-9-_]*)\\z""); // cell +- +- // Parses abstract coordinate of the form: +- // strategy.service.user.cell. This pattern is useful for +- // resolving hosts, but not endpoints. +- public static final Pattern instancePattern +- = Pattern.compile( ""^([a-z0-9-_]*)\\."" // strategy +- + ""([a-z][a-z0-9-_]*)\\."" // service +- + ""([a-z][a-z0-9-_]*)\\."" // user +- + ""([a-z][a-z0-9-_]*)\\z""); // cell +- +- // Parses abstract coordinate of the form: +- // endpoint.strategy.service.user.cell. +- public static final Pattern endpointStrategyPattern +- = Pattern.compile( ""^([a-z][a-z0-9-_]*)\\."" // endpoint +- + ""([a-z][a-z0-9-_]*)\\."" // strategy +- + ""([a-z][a-z0-9-_]*)\\."" // service +- + ""([a-z][a-z0-9-_]*)\\."" // user +- + ""([a-z][a-z0-9-_]*)\\z""); // cell +- +- +- /** +- * Inner class to keep track of parameters parsed from addressExpression. +- */ +- static class Parameters { +- private String endpointName = null; +- private Integer instance = null; +- private String service = null; +- private String user = null; +- private String cell = null; +- private String strategy = null; +- private String expression = null; +- +- /** +- * Constructor that takes an addressExperssion and sets the inner variables. +- * @param addressExpression +- */ +- public Parameters(String addressExpression) { +- this.expression = addressExpression; +- if (! (trySetEndPointPattern(addressExpression) || +- trySetStrategyPattern(addressExpression) || +- trySetInstancePattern(addressExpression) || +- trySetEndpointStrategyPattern(addressExpression))) { +- throw new IllegalStateException( +- ""Could not parse addressExpression:"" + addressExpression); +- } +- +- } +- +- /** +- * Returns the original expression set in the constructor of Parameters. +- * @return expression to be resolved. +- */ +- public String getExpression() { +- return expression; +- } +- +- /** +- * Returns strategy. +- * @return the string (e.g. ""all"" or ""any"", or """" if there is no strategy +- * (but instance is specified). +- */ +- public String getStrategy() { +- return strategy; +- } +- +- /** +- * Returns endpoint name if set or """" if not set. +- * @return endpointname. +- */ +- public String getEndpointName() { +- return endpointName; +- } +- +- /** +- * Returns instance if set or negative number if not set. +- * @return instance number. +- */ +- public Integer getInstance() { +- return instance; +- } +- +- /** +- * Returns service +- * @return service name. +- */ +- public String getService() { +- return service; +- } +- +- /** +- * Returns user +- * @return user. +- */ +- public String getUser() { +- return user; +- } +- +- /** +- * Returns cell. +- * @return cell. +- */ +- public String getCell() { +- return cell; +- } +- +- private boolean trySetEndPointPattern(String addressExperssion) { +- Matcher m = endpointPattern.matcher(addressExperssion); +- if (! m.matches()) { +- return false; +- } +- endpointName = m.group(1); +- instance = Integer.parseInt(m.group(2)); +- strategy = """"; +- service = m.group(3); +- user = m.group(4); +- cell = m.group(5); +- return true; +- +- } +- +- private boolean trySetStrategyPattern(String addressExpression) { +- Matcher m = strategyPattern.matcher(addressExpression); +- if (! m.matches()) { +- return false; +- } +- endpointName = """"; +- strategy = m.group(1); +- service = m.group(2); +- user = m.group(3); +- cell = m.group(4); +- instance = -1; +- return true; +- } +- +- private boolean trySetInstancePattern(String addressExpression) { +- Matcher m = instancePattern.matcher(addressExpression); +- if (! m.matches()) { +- return false; +- } +- endpointName = """"; +- instance = Integer.parseInt(m.group(1)); +- service = m.group(2); +- user = m.group(3); +- cell = m.group(4); +- strategy = """"; +- return true; +- } +- +- private boolean trySetEndpointStrategyPattern(String addressExperssion) { +- Matcher m = endpointStrategyPattern.matcher(addressExperssion); +- if (! m.matches()) { +- return false; +- } +- endpointName = m.group(1); +- strategy = m.group(2); +- service = m.group(3); +- user = m.group(4); +- cell = m.group(5); +- instance = -1; +- return true; +- } +- +- } +- +- /** +- * Constructor, to be called from the inner Dynamic class. +- * @param builder +- */ +- private ZkResolver(Builder builder, ZkObjectHandler.Client zkGetter) { +- this.strategies = builder.getStrategies(); +- this.zkGetter = zkGetter; +- zkGetter.registerListener(this); +- } +- +- +- @Override +- public List resolve(String addressExpression) throws CloudnameException { +- Parameters parameters = new Parameters(addressExpression); +- // TODO(borud): add some comments on the decision logic. I'm +- // not sure I am too fond of the check for negative values to +- // have some particular semantics. That smells like a problem +- // waiting to happen. +- +- ZooKeeper localZkPointer = zkGetter.getZookeeper(); +- if (localZkPointer == null) { +- throw new CloudnameException(""No connection to ZooKeeper.""); +- } +- List instances = resolveInstances(parameters, localZkPointer); +- +- List endpoints = new ArrayList(); +- for (Integer instance : instances) { +- String statusPath = ZkCoordinatePath.getStatusPath( +- parameters.getCell(), parameters.getUser(), +- parameters.getService(), instance); +- +- try { +- if (! Util.exist(localZkPointer, statusPath)) { +- continue; +- } +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- +- } +- final ZkCoordinateData zkCoordinateData = ZkCoordinateData.loadCoordinateData( +- statusPath, localZkPointer, null); +- addEndpoints(zkCoordinateData.snapshot(), endpoints, parameters.getEndpointName()); +- +- } +- if (parameters.getStrategy().equals("""")) { +- return endpoints; +- } +- ResolverStrategy strategy = strategies.get(parameters.getStrategy()); +- return strategy.order(strategy.filter(endpoints)); +- } +- +- @Override +- public void removeResolverListener(final ResolverListener listener) { +- synchronized (dynamicAddressMonitor) { +- DynamicExpression expression = dynamicAddressesByListener.remove(listener); +- if (expression == null) { +- throw new IllegalArgumentException(""Do not have the listener in my list.""); +- } +- expression.stop(); +- } +- log.fine(""Removed listener.""); +- } +- +- /** +- * The implementation does filter while listing out nodes. In this way paths that are not of +- * interest are not traversed. +- * @param filter class for filtering out endpoints +- * @return the endpoints that passes the filter +- */ +- @Override +- public Set getEndpoints(final Resolver.CoordinateDataFilter filter) +- throws CloudnameException, InterruptedException { +- +- final Set endpointsIncluded = new HashSet(); +- final String cellPath = ZkCoordinatePath.getCloudnameRoot(); +- final ZooKeeper zk = zkGetter.getZookeeper(); +- try { +- final List cells = zk.getChildren(cellPath, false); +- for (final String cell : cells) { +- if (! filter.includeCell(cell)) { +- continue; +- } +- final String userPath = cellPath + ""/"" + cell; +- final List users = zk.getChildren(userPath, false); +- +- for (final String user : users) { +- if (! filter.includeUser(user)) { +- continue; +- } +- final String servicePath = userPath + ""/"" + user; +- final List services = zk.getChildren(servicePath, false); +- +- for (final String service : services) { +- if (! filter.includeService(service)) { +- continue; +- } +- final String instancePath = servicePath + ""/"" + service; +- final List instances = zk.getChildren(instancePath, false); +- +- for (final String instance : instances) { +- final String statusPath; +- try { +- statusPath = ZkCoordinatePath.getStatusPath( +- cell, user, service, Integer.parseInt(instance)); +- } catch (NumberFormatException e) { +- log.log( +- Level.WARNING, +- ""Got non-number as instance in cn path: "" + instancePath + ""/"" +- + instance + "" skipping."", +- e); +- continue; +- } +- +- ZkCoordinateData zkCoordinateData = null; +- try { +- zkCoordinateData = ZkCoordinateData.loadCoordinateData( +- statusPath, zk, null); +- } catch (CloudnameException e) { +- // This is ok, an unclaimed node will not have status data, we +- // ignore it even though there might also be other exception +- // (this should be rare). The advantage is that we don't need to +- // check if the node exists and hence reduce the load on zookeeper. +- continue; +- } +- final Set endpoints = zkCoordinateData.snapshot().getEndpoints(); +- for (final Endpoint endpoint : endpoints) { +- if (filter.includeEndpointname(endpoint.getName())) { +- if (filter.includeServiceState( +- zkCoordinateData.snapshot().getServiceStatus().getState())) { +- endpointsIncluded.add(endpoint); +- } +- } +- } +- } +- } +- } +- } +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- return endpointsIncluded; +- } +- +- @Override +- public void addResolverListener(String expression, ResolverListener listener) +- throws CloudnameException { +- final DynamicExpression dynamicExpression = +- new DynamicExpression(expression, listener, this, zkGetter); +- +- synchronized (dynamicAddressMonitor) { +- DynamicExpression previousExpression = dynamicAddressesByListener.put( +- listener, dynamicExpression); +- if (previousExpression != null) { +- throw new IllegalArgumentException(""It is not legal to register a listener twice.""); +- } +- } +- dynamicExpression.start(); +- } +- +- public static void addEndpoints( +- ZkCoordinateData.Snapshot statusAndEndpoints, List endpoints, +- String endpointname) { +- if (statusAndEndpoints.getServiceStatus().getState() != ServiceState.RUNNING) { +- return; +- } +- if (endpointname.equals("""")) { +- statusAndEndpoints.appendAllEndpoints(endpoints); +- } else { +- Endpoint e = statusAndEndpoints.getEndpoint(endpointname); +- if (e != null) { +- endpoints.add(e); +- } +- } +- } +- +- private List resolveInstances(Parameters parameters, ZooKeeper zk) +- throws CloudnameException { +- List instances = new ArrayList(); +- if (parameters.getInstance() > -1) { +- instances.add(parameters.getInstance()); +- } else { +- try { +- instances = getInstances(zk, +- ZkCoordinatePath.coordinateWithoutInstanceAsPath(parameters.getCell(), +- parameters.getUser(), parameters.getService())); +- } catch (InterruptedException e) { +- throw new CloudnameException(e); +- } +- } +- return instances; +- } +- +- private List getInstances(ZooKeeper zk, String path) +- throws CloudnameException, InterruptedException { +- List paths = new ArrayList(); +- try { +- List children = zk.getChildren(path, false /* watcher */); +- for (String child : children) { +- paths.add(Integer.parseInt(child)); +- } +- } catch (KeeperException e) { +- throw new CloudnameException(e); +- } +- return paths; +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java b/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java +deleted file mode 100644 +index eb8fb837..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkServiceHandle.java ++++ /dev/null +@@ -1,116 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.*; +- +-import java.util.ArrayList; +-import java.util.concurrent.CountDownLatch; +-import java.util.concurrent.TimeUnit; +-import java.util.logging.Logger; +- +-import java.util.List; +- +-/** +- * A service handle implementation. It does not have a lot of logic, it wraps ClaimedCoordinate, and +- * handles some config logic. +- * +- * @author borud +- */ +-public class ZkServiceHandle implements ServiceHandle { +- private final ClaimedCoordinate claimedCoordinate; +- private static final Logger LOG = Logger.getLogger(ZkServiceHandle.class.getName()); +- +- private final ZkObjectHandler.Client zkClient; +- +- private final Coordinate coordinate; +- +- /** +- * Create a ZkServiceHandle for a given coordinate. +- * +- * @param claimedCoordinate the claimed coordinate for this service handle. +- */ +- public ZkServiceHandle( +- ClaimedCoordinate claimedCoordinate, Coordinate coordinate, +- ZkObjectHandler.Client zkClient) { +- this.claimedCoordinate = claimedCoordinate; +- this.coordinate = coordinate; +- this.zkClient = zkClient; +- } +- +- +- @Override +- public boolean waitForCoordinateOkSeconds(int seconds) throws InterruptedException { +- final CountDownLatch latch = new CountDownLatch(1); +- +- CoordinateListener listner = new CoordinateListener() { +- +- @Override +- public void onCoordinateEvent(Event event, String message) { +- if (event == Event.COORDINATE_OK) { +- latch.countDown(); +- } +- } +- }; +- registerCoordinateListener(listner); +- boolean result = latch.await(seconds, TimeUnit.SECONDS); +- claimedCoordinate.deregisterCoordinateListener(listner); +- return result; +- } +- +- +- @Override +- public void setStatus(ServiceStatus status) +- throws CoordinateMissingException, CloudnameException { +- claimedCoordinate.updateStatus(status); +- } +- +- @Override +- public void putEndpoints(List endpoints) +- throws CoordinateMissingException, CloudnameException { +- claimedCoordinate.putEndpoints(endpoints); +- } +- +- @Override +- public void putEndpoint(Endpoint endpoint) +- throws CoordinateMissingException, CloudnameException { +- List endpoints = new ArrayList(); +- endpoints.add(endpoint); +- putEndpoints(endpoints); +- } +- +- @Override +- public void removeEndpoints(List names) +- throws CoordinateMissingException, CloudnameException { +- claimedCoordinate.removeEndpoints(names); +- } +- +- @Override +- public void removeEndpoint(String name) +- throws CoordinateMissingException, CloudnameException { +- List names = new ArrayList(); +- names.add(name); +- removeEndpoints(names); +- } +- +- @Override +- public void registerConfigListener(ConfigListener listener) { +- TrackedConfig trackedConfig = new TrackedConfig( +- ZkCoordinatePath.getConfigPath(coordinate, null), listener, zkClient); +- claimedCoordinate.registerTrackedConfig(trackedConfig); +- trackedConfig.start(); +- } +- +- @Override +- public void registerCoordinateListener(CoordinateListener listener) { +- claimedCoordinate.registerCoordinateListener(listener); +- } +- +- @Override +- public void close() throws CloudnameException { +- claimedCoordinate.releaseClaim(); +- } +- +- @Override +- public String toString() { +- return ""Claimed coordinate instance: ""+ claimedCoordinate.toString(); +- } +-} +diff --git a/cn/src/main/java/org/cloudname/zk/ZkTool.java b/cn/src/main/java/org/cloudname/zk/ZkTool.java +deleted file mode 100644 +index 7be0f8cf..00000000 +--- a/cn/src/main/java/org/cloudname/zk/ZkTool.java ++++ /dev/null +@@ -1,359 +0,0 @@ +-package org.cloudname.zk; +- +-import org.apache.log4j.BasicConfigurator; +-import org.apache.log4j.ConsoleAppender; +-import org.apache.log4j.Level; +-import org.apache.log4j.PatternLayout; +-import org.cloudname.*; +-import org.cloudname.Resolver.ResolverListener; +-import org.cloudname.flags.Flag; +-import org.cloudname.flags.Flags; +-import java.io.BufferedReader; +-import java.io.FileNotFoundException; +-import java.io.FileReader; +-import java.io.IOException; +-import java.io.InputStreamReader; +-import java.util.ArrayList; +-import java.util.List; +-import java.util.regex.Matcher; +-import java.util.regex.Pattern; +- +- +-/** +- * Command line tool for using the Cloudname library. Run with +- * --help option to see available flags. +- * +- * @author dybdahl +- */ +-public final class ZkTool { +- @Flag(name=""zookeeper"", description=""A list of host:port for connecting to ZooKeeper."") +- private static String zooKeeperFlag = null; +- +- @Flag(name=""coordinate"", description=""The coordinate to work on."") +- private static String coordinateFlag = null; +- +- @Flag(name=""operation"", options = Operation.class, +- description = ""The operation to do on coordinate."") +- private static Operation operationFlag = Operation.STATUS; +- +- @Flag(name = ""setup-file"", +- description = ""Path to file containing a list of coordinates to create (1 coordinate per line)."") +- private static String filePath = null; +- +- @Flag(name = ""config"", +- description = ""New config if setting new config."") +- private static String configFlag = """"; +- +- @Flag(name = ""resolver-expression"", +- description = ""The resolver expression to listen to events for."") +- private static String resolverExpression = null; +- +- @Flag(name = ""list"", +- description = ""Print the coordinates in ZooKeeper."") +- private static Boolean listFlag = null; +- +- /** +- * List of flag names for flags that select which action the tool should +- * perform. These flags are mutually exclusive. +- */ +- private static String actionSelectingFlagNames = +- ""--setup-file, --resolver, --coordinate, --list""; +- +- /** +- * The possible operations to do on a coordinate. +- */ +- public enum Operation { +- /** +- * Create a new coordinate. +- */ +- CREATE, +- /** +- * Delete a coordinate. +- */ +- DELETE, +- /** +- * Print out some status about a coordinate. +- */ +- STATUS, +- /** +- * Print the host of a coordinate. +- */ +- HOST, +- /** +- * Set config +- */ +- SET_CONFIG, +- /** +- * Read config +- */ +- READ_CONFIG; +- } +- +- /** +- * Matches coordinate of type: cell.user.service.instance.config. +- */ +- public static final Pattern instanceConfigPattern +- = Pattern.compile(""\\/cn\\/([a-z][a-z-_]*)\\/"" // cell +- + ""([a-z][a-z0-9-_]*)\\/"" // user +- + ""([a-z][a-z0-9-_]*)\\/"" // service +- + ""(\\d+)\\/config\\z""); // instance +- +- private static ZkCloudname cloudname = null; +- +- public static void main(final String[] args) { +- +- // Disable log system, we want full control over what is sent to console. +- final ConsoleAppender consoleAppender = new ConsoleAppender(); +- consoleAppender.activateOptions(); +- consoleAppender.setLayout(new PatternLayout(""%p %t %C:%M %m%n"")); +- consoleAppender.setThreshold(Level.OFF); +- BasicConfigurator.configure(consoleAppender); +- +- // Parse the flags. +- Flags flags = new Flags() +- .loadOpts(ZkTool.class) +- .parse(args); +- +- // Check if we wish to print out help text +- if (flags.helpFlagged()) { +- flags.printHelp(System.out); +- System.out.println(""Must specify one of the following options:""); +- System.out.println(actionSelectingFlagNames); +- return; +- } +- +- checkArgumentCombinationValid(flags); +- +- ZkCloudname.Builder builder = new ZkCloudname.Builder(); +- if (zooKeeperFlag == null) { +- builder.setDefaultConnectString(); +- } else { +- builder.setConnectString(zooKeeperFlag); +- } +- try { +- cloudname = builder.build().connect(); +- } catch (CloudnameException e) { +- System.err.println(""Could not connect to zookeeper "" + e.getMessage()); +- return; +- } +- +- try { +- if (filePath != null) { +- handleFilepath(); +- } else if (coordinateFlag != null) { +- handleCoordinateOperation(); +- } else if (resolverExpression != null) { +- handleResolverExpression(); +- } else if (listFlag) { +- listCoordinates(); +- } else { +- System.err.println(""No action specified""); +- } +- } catch (Exception e) { +- System.err.println(""An error occurred: "" + e.getMessage()); +- e.printStackTrace(); +- } finally { +- cloudname.close(); +- } +- } +- +- private static void checkArgumentCombinationValid(final Flags flags) { +- int actionSelectedCount = 0; +- final Object[] actionSelectingFlags = { +- filePath, coordinateFlag, resolverExpression, listFlag +- }; +- for (Object flag: actionSelectingFlags) { +- if (flag != null) { +- actionSelectedCount++; +- } +- } +- if (actionSelectedCount != 1) { +- System.err.println(""Must specify exactly one of the following options:""); +- System.err.println(actionSelectingFlagNames); +- flags.printHelp(System.err); +- System.exit(1); +- } +- } +- +- private static void handleResolverExpression() { +- final Resolver resolver = cloudname.getResolver(); +- try { +- System.out.println(""Added a resolver listener for expression: "" + resolverExpression + "". Will print out all events for the given expression.""); +- resolver.addResolverListener(resolverExpression, new ResolverListener() { +- @Override +- public void endpointEvent(Event event, Endpoint endpoint) { +- System.out.println(""Received event: "" + event + "" for endpoint: "" + endpoint); +- } +- }); +- } catch (CloudnameException e) { +- System.err.println(""Problem with cloudname: "" + e.getMessage()); +- } +- final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); +- while(true) { +- System.out.println(""Press enter to exit""); +- String s = null; +- try { +- s = br.readLine(); +- } catch (IOException e) { +- e.printStackTrace(); +- } +- if (s.length() == 0) { +- System.out.println(""Exiting""); +- System.exit(0); +- } +- } +- } +- +- private static void handleCoordinateOperation() { +- final Resolver resolver = cloudname.getResolver(); +- final Coordinate coordinate = Coordinate.parse(coordinateFlag); +- switch (operationFlag) { +- case CREATE: +- try { +- cloudname.createCoordinate(coordinate); +- } catch (CloudnameException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- break; +- } catch (CoordinateExistsException e) { +- e.printStackTrace(); +- break; +- } +- System.err.println(""Created coordinate.""); +- break; +- case DELETE: +- try { +- cloudname.destroyCoordinate(coordinate); +- } catch (CoordinateDeletionException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- return; +- } catch (CoordinateMissingException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- break; +- } catch (CloudnameException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- break; +- } +- System.err.println(""Deleted coordinate.""); +- break; +- case STATUS: { +- ServiceStatus status; +- try { +- status = cloudname.getStatus(coordinate); +- } catch (CloudnameException e) { +- System.err.println(""Problems loading status, is service running? Error:\n"" + e.getMessage()); +- break; +- } +- System.err.println(""Status:\n"" + status.getState().toString() + "" "" + status.getMessage()); +- List endpoints = null; +- try { +- endpoints = resolver.resolve(""all."" + coordinate.getService() +- + ""."" + coordinate.getUser() + ""."" + coordinate.getCell()); +- } catch (CloudnameException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- break; +- } +- System.err.println(""Endpoints:""); +- for (Endpoint endpoint : endpoints) { +- if (endpoint.getCoordinate().getInstance() == coordinate.getInstance()) { +- System.err.println(endpoint.getName() + ""-->"" + endpoint.getHost() + "":"" + endpoint.getPort() +- + "" protocol:"" + endpoint.getProtocol()); +- System.err.println(""Endpoint data:\n"" + endpoint.getEndpointData()); +- } +- } +- break; +- } +- case HOST: { +- List endpoints = null; +- try { +- endpoints = resolver.resolve(coordinate.asString()); +- } catch (CloudnameException e) { +- System.err.println(""Could not resolve "" + coordinate.asString() + "" Error:\n"" + e.getMessage()); +- break; +- } +- for (Endpoint endpoint : endpoints) { +- System.out.println(""Host: "" + endpoint.getHost()); +- } +- } +- break; +- case SET_CONFIG: +- try { +- cloudname.setConfig(coordinate, configFlag, null); +- } catch (CloudnameException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- break; +- +- } catch (CoordinateMissingException e) { +- System.err.println(""Non-existing coordinate.""); +- } +- System.err.println(""Config updated.""); +- break; +- +- case READ_CONFIG: +- try { +- System.out.println(""Config is:"" + cloudname.getConfig(coordinate)); +- } catch (CoordinateMissingException e) { +- System.err.println(""Non-existing coordinate.""); +- } catch (CloudnameException e) { +- System.err.println(""Problem with cloudname: "" + e.getMessage()); +- } +- break; +- default: +- System.out.println(""Unknown command "" + operationFlag); +- } +- } +- +- private static void listCoordinates() { +- try { +- final List nodeList = new ArrayList(); +- cloudname.listRecursively(nodeList); +- for (final String node : nodeList) { +- final Matcher m = instanceConfigPattern.matcher(node); +- +- /* +- * We only parse config paths, and we convert these to +- * Cloudname coordinates to not confuse the user. +- */ +- if (m.matches()) { +- System.out.printf(""%s.%s.%s.%s\n"", +- m.group(4), m.group(3), m.group(2), m.group(1)); +- } +- } +- } catch (final CloudnameException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- } catch (final InterruptedException e) { +- System.err.println(""Got error: "" + e.getMessage()); +- } +- } +- +- private static void handleFilepath() { +- final BufferedReader br; +- try { +- br = new BufferedReader(new FileReader(filePath)); +- } catch (FileNotFoundException e) { +- throw new RuntimeException(""File not found: "" + filePath, e); +- } +- String line; +- try { +- while ((line = br.readLine()) != null) { +- try { +- cloudname.createCoordinate(Coordinate.parse(line)); +- System.out.println(""Created "" + line); +- } catch (Exception e) { +- System.err.println(""Could not create: "" + line + ""Got error: "" + e.getMessage()); +- } +- } +- } catch (IOException e) { +- throw new RuntimeException(""Failed to read coordinate from file. "" + e.getMessage(), e); +- } finally { +- cloudname.close(); +- try { +- br.close(); +- } catch (IOException e) { +- System.err.println(""Failed while trying to close file reader. "" + e.getMessage()); +- } +- } +- } +- +- // Should not be instantiated. +- private ZkTool() {} +-} +diff --git a/cn/src/test/java/org/cloudname/CoordinateTest.java b/cn/src/test/java/org/cloudname/CoordinateTest.java +deleted file mode 100644 +index 42ee09cc..00000000 +--- a/cn/src/test/java/org/cloudname/CoordinateTest.java ++++ /dev/null +@@ -1,74 +0,0 @@ +-package org.cloudname; +- +-import org.junit.*; +-import static org.junit.Assert.*; +- +-/** +- * Unit tests for Coordinate. +- * +- * @author borud +- */ +-public class CoordinateTest { +- @Test +- public void testSimple() throws Exception { +- Coordinate c = Coordinate.parse(""1.service.user.cell""); +- assertNotNull(c); +- assertEquals(1, c.getInstance()); +- assertEquals(""service"", c.getService()); +- assertEquals(""user"", c.getUser()); +- assertEquals(""cell"", c.getCell()); +- } +- +- @Test (expected = IllegalArgumentException.class) +- public void testInvalidInstanceNumber() throws Exception { +- new Coordinate(-1, ""service"", ""user"", ""cell""); +- } +- +- @Test +- public void testEquals() throws Exception { +- assertEquals( +- new Coordinate(1,""foo"", ""bar"", ""baz""), +- new Coordinate(1, ""foo"", ""bar"", ""baz"") +- ); +- } +- +- @Test +- public void testSymmetry() throws Exception { +- String s = ""0.fooservice.baruser.bazcell""; +- assertEquals(s, Coordinate.parse(s).asString()); +- assertEquals(s, new Coordinate(0, +- ""fooservice"", +- ""baruser"", +- ""bazcell"").asString()); +- +- System.out.println(Coordinate.parse(s)); +- } +- +- @Test (expected = IllegalArgumentException.class) +- public void testInvalidInstance() throws Exception { +- Coordinate.parse(""invalid.service.user.cell""); +- } +- +- @Test (expected = IllegalArgumentException.class) +- public void testInvalidCharacters() throws Exception { +- Coordinate.parse(""0.ser!vice.user.cell""); +- } +- +- @Test +- public void testLegalCharacters() throws Exception { +- Coordinate.parse(""0.service-test.user.cell""); +- Coordinate.parse(""0.service_test.user.cell""); +- Coordinate.parse(""0.service.user-foo.cell""); +- Coordinate.parse(""0.service.user_foo.ce_ll""); +- } +- +- @Test (expected = IllegalArgumentException.class) +- public void testRequireStartsWithLetter() throws Exception { +- Coordinate.parse(""0._aaa._bbb._ccc""); +- } +- +- @Test (expected = IllegalArgumentException.class) +- public void testIllegalArgumentsConstructor() throws Exception { +- new Coordinate(1, ""service"", ""_user"", ""cell""); +- } +-} +\ No newline at end of file +diff --git a/cn/src/test/java/org/cloudname/EndpointTest.java b/cn/src/test/java/org/cloudname/EndpointTest.java +deleted file mode 100644 +index 0769ac51..00000000 +--- a/cn/src/test/java/org/cloudname/EndpointTest.java ++++ /dev/null +@@ -1,31 +0,0 @@ +-package org.cloudname; +- +-import org.junit.*; +-import static org.junit.Assert.*; +- +-/** +- * Unit tests for Endpoint. +- * +- * @author borud +- */ +-public class EndpointTest { +- @Test +- public void testSimple() throws Exception { +- Endpoint endpoint = new Endpoint(Coordinate.parse(""1.foo.bar.zot""), +- ""rest-api"", +- ""somehost"", +- 4711, +- ""http"", +- null); +- String json = endpoint.toJson(); +- Endpoint endpoint2 = Endpoint.fromJson(json); +- +- assertEquals(endpoint.getCoordinate(), endpoint2.getCoordinate()); +- assertEquals(endpoint.getName(), endpoint2.getName()); +- assertEquals(endpoint.getHost(), endpoint2.getHost()); +- assertEquals(endpoint.getPort(), endpoint2.getPort()); +- assertEquals(endpoint.getEndpointData(), endpoint2.getEndpointData()); +- +- System.out.println(json); +- } +-} +\ No newline at end of file +diff --git a/cn/src/test/java/org/cloudname/ServiceStatusTest.java b/cn/src/test/java/org/cloudname/ServiceStatusTest.java +deleted file mode 100644 +index ec7fe5b3..00000000 +--- a/cn/src/test/java/org/cloudname/ServiceStatusTest.java ++++ /dev/null +@@ -1,24 +0,0 @@ +-package org.cloudname; +- +-import org.junit.*; +-import static org.junit.Assert.*; +- +-/** +- * Unit tests for ServiceStatus. +- * +- * @author borud +- */ +-public class ServiceStatusTest { +- @Test +- public void testSimple() throws Exception { +- ServiceStatus status = new ServiceStatus(ServiceState.STARTING, +- ""Loading hamster into wheel""); +- String json = status.toJson(); +- assertNotNull(json); +- +- ServiceStatus status2 = ServiceStatus.fromJson(json); +- +- assertEquals(status.getMessage(), status2.getMessage()); +- assertSame(status.getState(), status2.getState()); +- } +-} +\ No newline at end of file +diff --git a/cn/src/test/java/org/cloudname/StrategyAnyTest.java b/cn/src/test/java/org/cloudname/StrategyAnyTest.java +deleted file mode 100644 +index d6f56f54..00000000 +--- a/cn/src/test/java/org/cloudname/StrategyAnyTest.java ++++ /dev/null +@@ -1,88 +0,0 @@ +-package org.cloudname; +- +-import static org.hamcrest.Matchers.is; +-import static org.hamcrest.Matchers.lessThan; +-import org.junit.Before; +-import org.junit.Test; +- +-import java.util.ArrayList; +-import java.util.List; +- +-import static org.junit.Assert.assertThat; +-import static org.junit.Assert.assertTrue; +- +- +-/** +- * Unit tests for StrategyAny. +- * @author dybdahl +- */ +-public class StrategyAnyTest { +- private List endpoints; +- +- /** +- * Adds a list endpoints with even instance number to the endpoints list. +- */ +- @Before +- public void setup() { +- endpoints = new ArrayList(); +- // Only even instance numbers. +- for (int i = 0; i < 100; i+= 2) { +- endpoints.add(new Endpoint(Coordinate.parse(String.valueOf(i) + "".foo.bar.zot""), +- ""rest-api"", +- ""somehost"", +- 4711, +- ""http"", +- null)); +- } +- } +- +- /** +- * Different clients should have different lists. +- */ +- @Test +- public void testDifferentLists() { +- StrategyAny strategyAny = new StrategyAny(); +- +- List sortedResult = strategyAny.order(new ArrayList(endpoints)); +- +- // Try with up tp 150 clients, if they all have the same first element, something is wrong. +- // In each iteration there is 1/50 probability for this. For 150 runs, the probability for +- // false negative is 1,42724769 × 10^-255 (e.g. zero). +- for (int z = 0; z < 150; z++) { +- StrategyAny strategyAny2 = new StrategyAny(); +- List sortedResult2 = strategyAny2.order(new ArrayList(endpoints)); +- if (sortedResult.get(0).getCoordinate().getInstance() != +- sortedResult2.get(0).getCoordinate().getInstance()) { +- return; +- } +- } +- assertTrue(false); +- } +- +- /** +- * Test that insertion does only create a new first element now and then. +- */ +- @Test +- public void testInsertions() { +- StrategyAny strategyAny = new StrategyAny(); +- +- List sortedResult = strategyAny.order(new ArrayList(endpoints)); +- int newFrontEndpoint = 0; +- for (int c = 1; c < 30; c +=2) { +- int headInstance = sortedResult.get(0).getCoordinate().getInstance(); +- sortedResult.add(new Endpoint(Coordinate.parse(String.valueOf(c) + "".foo.bar.zot""), +- ""rest-api"", +- ""somehost"", +- 4711, +- ""http"", +- null)); +- sortedResult = strategyAny.order(sortedResult); +- if (headInstance != sortedResult.get(0).getCoordinate().getInstance()) { +- ++newFrontEndpoint; +- } +- } +- // For each insertion it a probability of less than 1/50 that front element is changed. The probability +- // that more than 10 front elements are changed should be close to zero. +- assertThat(newFrontEndpoint, is(lessThan(10))); +- } +-} +diff --git a/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java b/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java +deleted file mode 100644 +index 5bccc3f6..00000000 +--- a/cn/src/test/java/org/cloudname/zk/ZkCloudnameTest.java ++++ /dev/null +@@ -1,324 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.*; +- +-import org.apache.zookeeper.WatchedEvent; +-import org.apache.zookeeper.Watcher; +-import org.apache.zookeeper.ZooKeeper; +- +-import java.io.IOException; +-import java.util.ArrayList; +-import java.util.List; +-import java.util.concurrent.*; +- +-import org.junit.*; +-import org.junit.rules.TemporaryFolder; +-import static org.junit.Assert.*; +-import static org.junit.Assert.assertTrue; +- +-import org.cloudname.testtools.Net; +-import org.cloudname.testtools.zookeeper.EmbeddedZooKeeper; +- +-import java.io.File; +-import java.util.logging.Logger; +- +-/** +- * Unit test for the ZkCloudname class. +- * +- * @author borud, dybdahl +- */ +-public class ZkCloudnameTest { +- private static final Logger LOG = Logger.getLogger(ZkCloudnameTest.class.getName()); +- +- private ZooKeeper zk; +- private int zkport; +- +- @Rule public TemporaryFolder temp = new TemporaryFolder(); +- +- /** +- * Set up an embedded ZooKeeper instance backed by a temporary +- * directory. The setup procedure also allocates a port that is +- * free for the ZooKeeper server so that you should be able to run +- * multiple instances of this test. +- */ +- @Before +- public void setup() throws Exception { +- File rootDir = temp.newFolder(""zk-test""); +- zkport = Net.getFreePort(); +- +- LOG.info(""EmbeddedZooKeeper rootDir="" + rootDir.getCanonicalPath() + "", port="" + zkport +- ); +- +- // Set up and initialize the embedded ZooKeeper +- final EmbeddedZooKeeper ezk = new EmbeddedZooKeeper(rootDir, zkport); +- ezk.init(); +- +- // Set up a zookeeper client that we can use for inspection +- final CountDownLatch connectedLatch = new CountDownLatch(1); +- +- zk = new ZooKeeper(""localhost:"" + zkport, 1000, new Watcher() { +- public void process(WatchedEvent event) { +- if (event.getState() == Event.KeeperState.SyncConnected) { +- connectedLatch.countDown(); +- } +- } +- }); +- connectedLatch.await(); +- +- LOG.info(""ZooKeeper port is "" + zkport); +- } +- +- @After +- public void tearDown() throws Exception { +- zk.close(); +- } +- +- /** +- * Tests that the time-out mechanism on connecting to ZooKeeper works. +- */ +- @Test +- public void testTimeout() throws IOException, InterruptedException { +- int deadPort = Net.getFreePort(); +- try { +- new ZkCloudname.Builder().setConnectString(""localhost:"" + deadPort).build() +- .connectWithTimeout(1000, TimeUnit.NANOSECONDS); +- fail(""Expected time-out exception.""); +- } catch (CloudnameException e) { +- // Expected. +- } +- } +- +- /** +- * A relatively simple voyage through a typical lifecycle. +- */ +- @Test +- public void testSimple() throws Exception { +- final Coordinate c = Coordinate.parse(""1.service.user.cell""); +- final ZkCloudname cn = makeLocalZkCloudname(); +- +- assertFalse(pathExists(""/cn/cell/user/service/1"")); +- cn.createCoordinate(c); +- +- // Coordinate should exist, but no status node +- assertTrue(pathExists(""/cn/cell/user/service/1"")); +- assertTrue(pathExists(""/cn/cell/user/service/1/config"")); +- assertFalse(pathExists(""/cn/cell/user/service/1/status"")); +- +- // Claiming the coordinate creates the status node +- final ServiceHandle handle = cn.claim(c); +- assertTrue(handle.waitForCoordinateOkSeconds(3)); +- assertNotNull(handle); +- final CountDownLatch latch = new CountDownLatch(1); +- handle.registerCoordinateListener(new CoordinateListener() { +- +- @Override +- public void onCoordinateEvent(Event event, String message) { +- if (event == Event.COORDINATE_OK) { +- latch.countDown(); +- } +- } +- }); +- assertTrue(latch.await(2, TimeUnit.SECONDS)); +- +- final CountDownLatch configLatch1 = new CountDownLatch(1); +- final CountDownLatch configLatch2 = new CountDownLatch(2); +- final StringBuilder buffer = new StringBuilder(); +- handle.registerConfigListener(new ConfigListener() { +- @Override +- public void onConfigEvent(Event event, String data) { +- buffer.append(data); +- configLatch1.countDown(); +- configLatch2.countDown(); +- } +- }); +- assertTrue(configLatch1.await(5, TimeUnit.SECONDS)); +- assertEquals(buffer.toString(), """"); +- zk.setData(""/cn/cell/user/service/1/config"", ""hello"".getBytes(), -1); +- assertTrue(configLatch2.await(5, TimeUnit.SECONDS)); +- assertEquals(buffer.toString(), ""hello""); +- +- assertTrue(pathExists(""/cn/cell/user/service/1/status"")); +- +- List nodes = new ArrayList(); +- cn.listRecursively(nodes); +- assertEquals(2, nodes.size()); +- assertEquals(nodes.get(0), ""/cn/cell/user/service/1/config""); +- assertEquals(nodes.get(1), ""/cn/cell/user/service/1/status""); +- +- // Try to set the status to something else +- String msg = ""Hamster getting quite eager now""; +- handle.setStatus(new ServiceStatus(ServiceState.STARTING,msg)); +- ServiceStatus status = cn.getStatus(c); +- assertEquals(msg, status.getMessage()); +- assertSame(ServiceState.STARTING, status.getState()); +- +- // Publish two endpoints +- handle.putEndpoint(new Endpoint(c, ""foo"", ""localhost"", 1234, ""http"", null)); +- handle.putEndpoint(new Endpoint(c, ""bar"", ""localhost"", 1235, ""http"", null)); +- +- handle.setStatus(new ServiceStatus(ServiceState.RUNNING, msg)); +- +- // Remove one of them +- handle.removeEndpoint(""bar""); +- +- List endpointList = cn.getResolver().resolve(""bar.1.service.user.cell""); +- assertEquals(0, endpointList.size()); +- +- endpointList = cn.getResolver().resolve(""foo.1.service.user.cell""); +- assertEquals(1, endpointList.size()); +- Endpoint endpointFoo = endpointList.get(0); +- +- String fooData = endpointFoo.getName(); +- assertEquals(""foo"", fooData); +- assertEquals(""foo"", endpointFoo.getName()); +- assertEquals(""localhost"", endpointFoo.getHost()); +- assertEquals(1234, endpointFoo.getPort()); +- assertEquals(""http"", endpointFoo.getProtocol()); +- assertNull(endpointFoo.getEndpointData()); +- +- // Close handle just invalidates handle +- handle.close(); +- +- // These nodes are ephemeral and will be cleaned out when we +- // call cn.releaseClaim(), but calling handle.releaseClaim() explicitly +- // cleans out the ephemeral nodes. +- assertFalse(pathExists(""/cn/cell/user/service/1/status"")); +- +- // Closing Cloudname instance disconnects the zk client +- // connection and thus should kill all ephemeral nodes. +- cn.close(); +- +- // But the coordinate and its persistent subnodes should +- assertTrue(pathExists(""/cn/cell/user/service/1"")); +- assertFalse(pathExists(""/cn/cell/user/service/1/endpoints"")); +- assertTrue(pathExists(""/cn/cell/user/service/1/config"")); +- } +- +- /** +- * Claim non-existing coordinate +- */ +- @Test +- public void testCoordinateNotFound() throws CloudnameException, InterruptedException { +- final Coordinate c = Coordinate.parse(""3.service.user.cell""); +- final Cloudname cn = makeLocalZkCloudname(); +- +- final ExecutorService executor = Executors.newCachedThreadPool(); +- final Callable task = new Callable() { +- public Object call() throws InterruptedException { +- return cn.claim(c); +- } +- }; +- final Future future = executor.submit(task); +- try { +- future.get(300, TimeUnit.MILLISECONDS); +- } catch (TimeoutException ex) { +- // handle the timeout +- LOG.info(""Got time out, nice!""); +- } catch (InterruptedException e) { +- fail(""Interrupted""); +- } catch (ExecutionException e) { +- fail(""Some error "" + e.getMessage()); +- // handle other exceptions +- } finally { +- future.cancel(true); +- } +- } +- +- /** +- * Try to claim coordinate twice +- */ +- @Test +- public void testDoubleClaim() throws CloudnameException, InterruptedException { +- final Coordinate c = Coordinate.parse(""2.service.user.cell""); +- final CountDownLatch okCounter = new CountDownLatch(1); +- final CountDownLatch failCounter = new CountDownLatch(1); +- +- final CoordinateListener listener = new CoordinateListener() { +- @Override +- public void onCoordinateEvent(Event event, String message) { +- switch (event) { +- case COORDINATE_OK: +- okCounter.countDown(); +- break; +- case NOT_OWNER: +- failCounter.countDown(); +- default: //Any other Event is unexpected. +- assert(false); +- break; +- } +- } +- }; +- final Cloudname cn; +- try { +- cn = makeLocalZkCloudname(); +- } catch (CloudnameException e) { +- fail(""connecting to localhost failed.""); +- return; +- } +- +- try { +- cn.createCoordinate(c); +- } catch (CoordinateExistsException e) { +- fail(""should not happen.""); +- } +- final ServiceHandle handle1 = cn.claim(c); +- assert(handle1.waitForCoordinateOkSeconds(4)); +- handle1.registerCoordinateListener(listener); +- ServiceHandle handle2 = cn.claim(c); +- assertFalse(handle2.waitForCoordinateOkSeconds(1)); +- handle2.registerCoordinateListener(listener); +- assert(okCounter.await(4, TimeUnit.SECONDS)); +- assert(failCounter.await(2, TimeUnit.SECONDS)); +- } +- +- +- @Test +- public void testDestroyBasic() throws Exception { +- final Coordinate c = Coordinate.parse(""1.service.user.cell""); +- final Cloudname cn = makeLocalZkCloudname(); +- cn.createCoordinate(c); +- assertTrue(pathExists(""/cn/cell/user/service/1/config"")); +- cn.destroyCoordinate(c); +- assertFalse(pathExists(""/cn/cell/user/service"")); +- assertTrue(pathExists(""/cn/cell/user"")); +- } +- +- @Test +- public void testDestroyTwoInstances() throws Exception { +- final Coordinate c1 = Coordinate.parse(""1.service.user.cell""); +- final Coordinate c2 = Coordinate.parse(""2.service.user.cell""); +- final Cloudname cn = makeLocalZkCloudname(); +- cn.createCoordinate(c1); +- cn.createCoordinate(c2); +- assertTrue(pathExists(""/cn/cell/user/service/1/config"")); +- assertTrue(pathExists(""/cn/cell/user/service/2/config"")); +- cn.destroyCoordinate(c1); +- assertFalse(pathExists(""/cn/cell/user/service/1"")); +- assertTrue(pathExists(""/cn/cell/user/service/2/config"")); +- } +- +- @Test +- public void testDestroyClaimed() throws Exception { +- final Coordinate c = Coordinate.parse(""1.service.user.cell""); +- final Cloudname cn = makeLocalZkCloudname(); +- cn.createCoordinate(c); +- ServiceHandle handle = cn.claim(c); +- handle.waitForCoordinateOkSeconds(1); +- try { +- cn.destroyCoordinate(c); +- fail(""Expected exception to happen""); +- } catch (CoordinateException e) { +- } +- } +- +- private boolean pathExists(String path) throws Exception { +- return (null != zk.exists(path, false)); +- } +- +- /** +- * Makes a local ZkCloudname instance with the port given by zkPort. +- */ +- private ZkCloudname makeLocalZkCloudname() throws CloudnameException { +- return new ZkCloudname.Builder().setConnectString(""localhost:"" + zkport).build().connect(); +- } +-} +diff --git a/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java b/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java +deleted file mode 100644 +index 9e9f6dcf..00000000 +--- a/cn/src/test/java/org/cloudname/zk/ZkCoordinatePathTest.java ++++ /dev/null +@@ -1,31 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.Coordinate; +-import org.junit.Test; +- +-import static org.junit.Assert.assertEquals; +- +-/** +- * Unit tests for class ZkCoordinatePathTest. +- * @author dybdahl +- */ +-public class ZkCoordinatePathTest { +- @Test +- public void testSimple() throws Exception { +- final Coordinate coordinate = new Coordinate( +- 42 /*instance*/, ""service"", ""user"", ""cell"", false /*validate*/); +- assertEquals(""/cn/cell/user/service/42/config"", +- ZkCoordinatePath.getConfigPath(coordinate, null)); +- assertEquals(""/cn/cell/user/service/42/config/name"", +- ZkCoordinatePath.getConfigPath(coordinate, ""name"")); +- assertEquals(""/cn/cell/user/service/42"", +- ZkCoordinatePath.getCoordinateRoot(coordinate)); +- assertEquals(""/cn/cell/user/service/42/status"", +- ZkCoordinatePath.getStatusPath(coordinate)); +- assertEquals(""/cn/cell/user/service"", +- ZkCoordinatePath.coordinateWithoutInstanceAsPath( +- ""cell"", ""user"", ""service"")); +- assertEquals(""/cn/cell/user/service/42/status"", +- ZkCoordinatePath.getStatusPath(""cell"", ""user"", ""service"", 42)); +- } +-} +diff --git a/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java b/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java +deleted file mode 100644 +index 3dd868f6..00000000 +--- a/cn/src/test/java/org/cloudname/zk/ZkResolverTest.java ++++ /dev/null +@@ -1,134 +0,0 @@ +-package org.cloudname.zk; +- +-import org.cloudname.*; +-import org.junit.Before; +-import org.junit.Rule; +-import org.junit.Test; +-import org.junit.rules.TemporaryFolder; +- +-import static org.junit.Assert.*; +- +- +-/** +- * This class contains the unit tests for the ZkResolver class. +- * +- * TODO(borud): add tests for when the input is a coordinate. +- * +- * @author borud +- */ +-public class ZkResolverTest { +- private Resolver resolver; +- +- @Rule +- public TemporaryFolder temp = new TemporaryFolder(); +- +- /** +- * Set up an embedded ZooKeeper instance backed by a temporary +- * directory. The setup procedure also allocates a port that is +- * free for the ZooKeeper server so that you should be able to run +- * multiple instances of this test. +- */ +- @Before +- public void setup() throws Exception { +- resolver = new ZkResolver.Builder() +- .addStrategy(new StrategyAll()) +- .addStrategy(new StrategyAny()) +- .build(new ZkObjectHandler(null).getClient()); +- } +- +- // Valid endpoints. +- public static final String[] validEndpointPatterns = new String[] { +- ""http.1.service.user.cell"", +- ""foo-bar.3245.service.user.cell"", +- ""foo_bar.3245.service.user.cell"", +- }; +- +- // Valid strategy. +- public static final String[] validStrategyPatterns = new String[] { +- ""any.service.user.cell"", +- ""all.service.user.cell"", +- ""somestrategy.service.user.cell"", +- }; +- +- // Valid endpoint strategy. +- public static final String[] validEndpointStrategyPatterns = new String[] { +- ""http.any.service.user.cell"", +- ""thrift.all.service.user.cell"", +- ""some-endpoint.somestrategy.service.user.cell"", +- }; +- +- @Test(expected=IllegalArgumentException.class) +- public void testRegisterSameListenerTwice() throws Exception { +- Resolver.ResolverListener resolverListener = new Resolver.ResolverListener() { +- @Override +- public void endpointEvent(Event event, Endpoint endpoint) { +- +- } +- }; +- resolver.addResolverListener(""foo.all.service.user.cell"", resolverListener); +- resolver.addResolverListener(""bar.all.service.user.cell"", resolverListener); +- } +- +- @Test +- public void testEndpointPatterns() throws Exception { +- // Test input that should match +- for (String s : validEndpointPatterns) { +- assertTrue(""Didn't match '"" + s + ""'"", +- ZkResolver.endpointPattern.matcher(s).matches()); +- } +- +- // Test input that should not match +- for (String s : validStrategyPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.endpointPattern.matcher(s).matches()); +- } +- +- // Test input that should not match +- for (String s : validEndpointStrategyPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.endpointPattern.matcher(s).matches()); +- } +- } +- +- @Test +- public void testStrategyPatterns() throws Exception { +- // Test input that should match +- for (String s : validStrategyPatterns) { +- assertTrue(""Didn't match '"" + s + ""'"", +- ZkResolver.strategyPattern.matcher(s).matches()); +- } +- +- // Test input that should not match +- for (String s : validEndpointPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.strategyPattern.matcher(s).matches()); +- } +- // Test input that should not match +- for (String s : validEndpointStrategyPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.endpointPattern.matcher(s).matches()); +- } +- } +- +- @Test +- public void testEndpointStrategyPatterns() throws Exception { +- // Test input that should match +- for (String s : validEndpointStrategyPatterns) { +- assertTrue(""Didn't match '"" + s + ""'"", +- ZkResolver.endpointStrategyPattern.matcher(s).matches()); +- } +- +- // Test input that should not match +- for (String s : validStrategyPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.endpointStrategyPattern.matcher(s).matches()); +- } +- +- +- // Test input that should not match +- for (String s : validEndpointPatterns) { +- assertFalse(""Matched '"" + s + ""'"", +- ZkResolver.endpointStrategyPattern.matcher(s).matches()); +- } +- } +-} +\ No newline at end of file +diff --git a/flags/src/test/java/org/cloudname/flags/FlagsTest.java b/flags/src/test/java/org/cloudname/flags/FlagsTest.java +index 7db55632..4cc3aa75 100644 +--- a/flags/src/test/java/org/cloudname/flags/FlagsTest.java ++++ b/flags/src/test/java/org/cloudname/flags/FlagsTest.java +@@ -4,7 +4,7 @@ + import java.io.File; + import java.io.FileOutputStream; + import javax.annotation.PostConstruct; +-import junit.framework.Assert; ++import org.junit.Assert; + import org.junit.Rule; + import org.junit.Test; + import org.junit.rules.ExpectedException; +diff --git a/pom.xml b/pom.xml +index bde06f53..19b35348 100644 +--- a/pom.xml ++++ b/pom.xml +@@ -39,7 +39,7 @@ + 2.9.0 + 2.1.1 + 4.11 +- 4.0.32.Final ++ 3.7.0.Final + 2.6.1 + 0.9.94 + 1.2.1 +@@ -47,13 +47,14 @@ + 0.3m + 2.1 + 1.16 +- src/integrationtest +- target/integrationtest-classes + + + + a3 +- cn ++ cn-core ++ cn-service ++ cn-memory ++ cn-zookeeper + testtools + log + timber +@@ -82,15 +83,6 @@ + false + + +- +- org.codehaus.mojo +- cobertura-maven-plugin +- 2.5.2 +- +- xml +- true +- +- + + + +@@ -108,7 +100,13 @@ + + + org.cloudname +- cn ++ cn-core ++ ${project.version} ++ ++ ++ ++ org.cloudname ++ cn-memory + ${project.version} + + +@@ -139,7 +137,7 @@ + + + io.netty +- netty-all ++ netty + ${cn.netty.version} + + +@@ -157,34 +155,6 @@ + ${cn.protobuf.version} + + +- +- +- org.apache.zookeeper +- zookeeper +- ${cn.zookeeper.version} +- +- +- com.sun.jmx +- jmxri +- +- +- com.sun.jdmk +- jmxtools +- +- +- javax.jms +- jms +- +- +- +- +- +- +- org.apache.curator +- curator-framework +- ${cn.curator.version} +- +- + + + com.fasterxml.jackson.core +@@ -254,135 +224,4 @@ + + + +- +- +- +- src/integrationtest +- +- it +- +- +- +- +- org.apache.maven.plugins +- maven-surefire-plugin +- 2.10 +- +- **/*.java +- +- +- +- org.apache.maven.plugins +- maven-antrun-plugin +- +- +- create-directory +- pre-integration-test +- +- run +- +- +- +- +- +- +- +- +- +- +- +- org.codehaus.mojo +- build-helper-maven-plugin +- 1.5 +- +- +- add-test-sources +- pre-integration-test +- +- add-test-source +- +- +- +- ${integrationSourceDirectory}/java +- +- +- +- +- add-test-resources +- pre-integration-test +- +- add-test-resource +- +- +- +- +- ${integrationSourceDirectory}/java +- ${integrationOutputDirectory} +- +- +- +- +- +- add-empty-directory +- pre-integration-test +- +- add-test-resource +- +- +- +- +- ${integrationSourceDirectory}/java +- ${integrationOutputDirectory} +- +- **/* +- +- +- +- +- +- +- +- +- org.apache.maven.plugins +- maven-compiler-plugin +- 2.3.2 +- +- +- pre-integration-test +- +- testCompile +- +- +- +- ${basedir}/${integrationOutputDirectory} +- +- +- +- +- +- +- maven-failsafe-plugin +- 2.8 +- +- ${integrationOutputDirectory} +- ${integrationOutputDirectory}/failsafe-reports +- **/*.java +- +- ${integrationSourceDirectory}/resources +- +- +- +- +- +- integration-test +- verify +- +- +- +- +- +- +- +- +- + +diff --git a/testtools/pom.xml b/testtools/pom.xml +index c50037e1..817a9a87 100644 +--- a/testtools/pom.xml ++++ b/testtools/pom.xml +@@ -15,17 +15,16 @@ + https://github.com/Cloudname/cloudname + + +- +- org.apache.curator +- curator-test +- ${cn.curator.version} +- + + + junit + junit +- test ++ compile + + ++ ++ org.cloudname ++ cn-core ++ + + +diff --git a/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java b/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java +new file mode 100644 +index 00000000..3525b4d6 +--- /dev/null ++++ b/testtools/src/main/java/org/cloudname/testtools/backend/CoreBackendTest.java +@@ -0,0 +1,635 @@ ++package org.cloudname.testtools.backend; ++ ++import org.cloudname.core.CloudnameBackend; ++import org.cloudname.core.CloudnamePath; ++import org.cloudname.core.LeaseHandle; ++import org.cloudname.core.LeaseListener; ++import org.junit.Test; ++ ++import java.util.ArrayList; ++import java.util.HashSet; ++import java.util.List; ++import java.util.Random; ++import java.util.Set; ++import java.util.concurrent.CountDownLatch; ++import java.util.concurrent.Executor; ++import java.util.concurrent.Executors; ++import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicInteger; ++ ++import static org.hamcrest.CoreMatchers.equalTo; ++import static org.hamcrest.CoreMatchers.is; ++import static org.hamcrest.CoreMatchers.notNullValue; ++import static org.hamcrest.CoreMatchers.nullValue; ++import static org.junit.Assert.assertFalse; ++import static org.junit.Assert.assertThat; ++import static org.junit.Assert.assertTrue; ++import static org.junit.Assert.fail; ++ ++/** ++ * Core backend tests. This ensures the backend implementation works as expected on the most ++ * basic level. Override this class in your backend implementation to test it. ++ * ++ * @author stalehd@gmail.com ++ */ ++public abstract class CoreBackendTest { ++ private final CloudnamePath serviceA = new CloudnamePath( ++ new String[] { ""local"", ""test"", ""service-a"" }); ++ private final CloudnamePath serviceB = new CloudnamePath( ++ new String[] { ""local"", ""test"", ""service-b"" }); ++ ++ private final Random random = new Random(); ++ ++ /** ++ * Max data propagation time (in ms) for notifications from the backend. Override if your ++ * backend implementation is slow. 5 ms is a lot of time though so do it carefully. ++ */ ++ protected int getBackendPropagationTime() { ++ return 5; ++ } ++ /** ++ * Ensure multiple clients can connect and that leases get an unique path for each client. ++ */ ++ @Test ++ public void temporaryLeaseCreation() throws Exception { ++ try (final CloudnameBackend backend = getBackend()) { ++ final String data = Long.toHexString(random.nextLong()); ++ final LeaseHandle lease = backend.createTemporaryLease(serviceA, data); ++ assertThat(""Expected lease to be not null"", lease, is(notNullValue())); ++ ++ assertTrue(""Expected lease path to be a subpath of the supplied lease ("" + serviceA ++ + "") but it is "" + lease.getLeasePath(), ++ serviceA.isSubpathOf(lease.getLeasePath())); ++ ++ assertThat(""The temporary lease data can be read"", ++ backend.readTemporaryLeaseData(lease.getLeasePath()), is(data)); ++ ++ final String newData = Long.toHexString(random.nextLong()); ++ assertThat(""Expected to be able to write lease data but didn't"", ++ lease.writeLeaseData(newData), is(true)); ++ ++ assertThat(""Expected to be able to read data back but didn't"", ++ backend.readTemporaryLeaseData(lease.getLeasePath()), is(newData)); ++ lease.close(); ++ ++ assertThat(""Expect the lease path to be null"", lease.getLeasePath(), is(nullValue())); ++ ++ assertFalse(""Did not expect to be able to write lease data for a closed lease"", ++ lease.writeLeaseData(Long.toHexString(random.nextLong()))); ++ assertThat(""The temporary lease data can not be read"", ++ backend.readTemporaryLeaseData(lease.getLeasePath()), is(nullValue())); ++ ++ ++ final int numberOfLeases = 50; ++ ++ final Set leasePaths = new HashSet<>(); ++ for (int i = 0; i < numberOfLeases; i++) { ++ final String randomData = Long.toHexString(random.nextLong()); ++ final LeaseHandle handle = backend.createTemporaryLease(serviceB, randomData); ++ leasePaths.add(handle.getLeasePath().join(':')); ++ handle.close(); ++ } ++ ++ assertThat(""Expected "" + numberOfLeases + "" unique paths but it was "" + leasePaths.size(), ++ leasePaths.size(), is(numberOfLeases)); ++ } ++ } ++ ++ /** ++ * A very simple single-threaded notification. Make sure this works before implementing ++ * the multiple notifications elsewhere in this test. ++ */ ++ @Test ++ public void simpleTemporaryNotification() throws Exception { ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ ++ final CloudnamePath rootPath = new CloudnamePath(new String[]{""simple""}); ++ final CountDownLatch createCounter = new CountDownLatch(1); ++ final CountDownLatch removeCounter = new CountDownLatch(1); ++ final CountDownLatch dataCounter = new CountDownLatch(1); ++ ++ final String firstData = ""first data""; ++ final String lastData = ""last data""; ++ final LeaseListener listener = new LeaseListener() { ++ @Override ++ public void leaseCreated(CloudnamePath path, String data) { ++ createCounter.countDown(); ++ if (data.equals(lastData)) { ++ dataCounter.countDown(); ++ } ++ } ++ ++ @Override ++ public void leaseRemoved(CloudnamePath path) { ++ removeCounter.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(CloudnamePath path, String data) { ++ dataCounter.countDown(); ++ } ++ }; ++ backend.addTemporaryLeaseListener(rootPath, listener); ++ final LeaseHandle handle = backend.createTemporaryLease(rootPath, firstData); ++ assertThat(handle, is(notNullValue())); ++ Thread.sleep(getBackendPropagationTime()); ++ ++ handle.writeLeaseData(lastData); ++ Thread.sleep(getBackendPropagationTime()); ++ ++ handle.close(); ++ ++ assertTrue(""Expected create notification but didn't get one"", ++ createCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ assertTrue(""Expected remove notification but didn't get one"", ++ removeCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ assertTrue(""Expected data notification but didn't get one"", ++ dataCounter.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ ++ backend.removeTemporaryLeaseListener(listener); ++ } ++ } ++ ++ /** ++ * Ensure permanent leases can be created and that they can't be overwritten by clients using ++ * the library. ++ */ ++ @Test ++ public void permanentLeaseCreation() throws Exception { ++ final CloudnamePath leasePath = new CloudnamePath(new String[]{""some"", ""path""}); ++ final String dataString = ""some data string""; ++ final String newDataString = ""new data string""; ++ ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ backend.removePermanentLease(leasePath); ++ ++ assertThat(""Permanent lease can be created"", ++ backend.createPermanantLease(leasePath, dataString), is(true)); ++ ++ assertThat(""Permanent lease data can be read"", ++ backend.readPermanentLeaseData(leasePath), is(dataString)); ++ ++ assertThat(""Permanent lease can't be created twice"", ++ backend.createPermanantLease(leasePath, dataString), is(false)); ++ ++ assertThat(""Permanent lease can be updated"", ++ backend.writePermanentLeaseData(leasePath, newDataString), is(true)); ++ ++ assertThat(""Permanent lease data can be read after update"", ++ backend.readPermanentLeaseData(leasePath), is(newDataString)); ++ } ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ assertThat(""Permanent lease data can be read from another backend"", ++ backend.readPermanentLeaseData(leasePath), is(newDataString)); ++ assertThat(""Permanent lease can be removed"", ++ backend.removePermanentLease(leasePath), is(true)); ++ assertThat(""Lease can't be removed twice"", ++ backend.removePermanentLease(leasePath), is(false)); ++ assertThat(""Lease data can't be read from deleted lease"", ++ backend.readPermanentLeaseData(leasePath), is(nullValue())); ++ } ++ } ++ ++ /** ++ * Ensure clients are notified of changes ++ */ ++ @Test ++ public void multipleTemporaryNotifications() throws Exception { ++ try (final CloudnameBackend backend = getBackend()) { ++ final CloudnamePath rootPath = new CloudnamePath(new String[]{""root"", ""lease""}); ++ final String clientData = ""client data here""; ++ ++ final LeaseHandle lease = backend.createTemporaryLease(rootPath, clientData); ++ assertThat(""Handle to lease is returned"", lease, is(notNullValue())); ++ assertThat(""Lease is a child of the root lease"", ++ rootPath.isSubpathOf(lease.getLeasePath()), is(true)); ++ ++ int numListeners = 10; ++ final int numUpdates = 10; ++ ++ // Add some listeners to the temporary lease. Each should be notified once on ++ // creation, once on removal and once every time the data is updated ++ final CountDownLatch createNotifications = new CountDownLatch(numListeners); ++ final CountDownLatch dataNotifications = new CountDownLatch(numListeners * numUpdates); ++ final CountDownLatch removeNotifications = new CountDownLatch(numListeners); ++ ++ final List listeners = new ArrayList<>(); ++ for (int i = 0; i < numListeners; i++) { ++ final LeaseListener listener = new LeaseListener() { ++ private AtomicInteger lastData = new AtomicInteger(-1); ++ ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ createNotifications.countDown(); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ removeNotifications.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ assertThat(lastData.incrementAndGet(), is(Integer.parseInt(data))); ++ dataNotifications.countDown(); ++ } ++ }; ++ listeners.add(listener); ++ backend.addTemporaryLeaseListener(rootPath, listener); ++ } ++ ++ // Change the data a few times. Every change should be propagated to the listeners ++ // in the same order they have changed ++ for (int i = 0; i < numUpdates; i++) { ++ lease.writeLeaseData(Integer.toString(i)); ++ Thread.sleep(getBackendPropagationTime()); ++ } ++ ++ // Remove the lease. Removal notifications will be sent to the clients ++ ++ assertThat(""All create notifications are received but "" + createNotifications.getCount() ++ + "" remains out of "" + numListeners, ++ createNotifications.await(getBackendPropagationTime(), TimeUnit.MICROSECONDS), is(true)); ++ ++ assertThat(""All data notifications are received but "" + dataNotifications.getCount() ++ + "" remains out of "" + (numListeners * numUpdates), ++ dataNotifications.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS), is(true)); ++ ++ lease.close(); ++ assertThat(""All remove notifications are received but "" + removeNotifications.getCount() ++ + "" remains out of "" + numListeners, ++ removeNotifications.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS), is(true)); ++ ++ // Remove the listeners ++ for (final LeaseListener listener : listeners) { ++ lease.close(); ++ backend.removeTemporaryLeaseListener(listener); ++ } ++ } ++ } ++ ++ /** ++ * Test a simple peer to peer scheme; all clients grabbing a lease and listening on other ++ * clients. ++ */ ++ @Test ++ public void multipleServicesWithMultipleClients() throws Exception { ++ try (final CloudnameBackend backend = getBackend()) { ++ ++ final CloudnamePath rootLease = new CloudnamePath(new String[]{""multi"", ""multi""}); ++ final int numberOfClients = 5; ++ ++ // All clients will be notified of all other clients (including themselves) ++ final CountDownLatch createNotifications ++ = new CountDownLatch(numberOfClients * numberOfClients); ++ // All clients will write one change each ++ final CountDownLatch dataNotifications = new CountDownLatch(numberOfClients); ++ // There will be 99 + 98 + 97 + 96 ... 1 notifications, in all n (n + 1) / 2 ++ // remove notifications ++ final int n = numberOfClients - 1; ++ final CountDownLatch removeNotifications = new CountDownLatch(n * (n + 1) / 2); ++ ++ final Runnable clientProcess = new Runnable() { ++ @Override ++ public void run() { ++ final String myData = Long.toHexString(random.nextLong()); ++ final LeaseHandle handle = backend.createTemporaryLease(rootLease, myData); ++ assertThat(""Got a valid handle back"", handle, is(notNullValue())); ++ backend.addTemporaryLeaseListener(rootLease, new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ assertThat(""Notification belongs to root path"", ++ rootLease.isSubpathOf(path), is(true)); ++ createNotifications.countDown(); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ removeNotifications.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ dataNotifications.countDown(); ++ } ++ }); ++ ++ try { ++ assertThat(createNotifications.await( ++ getBackendPropagationTime(), TimeUnit.MILLISECONDS), ++ is(true)); ++ } catch (InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ ++ // Change the data for my own lease, wait for it to propagate ++ assertThat(handle.writeLeaseData(Long.toHexString(random.nextLong())), ++ is(true)); ++ try { ++ Thread.sleep(getBackendPropagationTime()); ++ } catch (final InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ ++ try { ++ assertThat(dataNotifications.await( ++ getBackendPropagationTime(), TimeUnit.MILLISECONDS), ++ is(true)); ++ } catch (InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ ++ // ..and close my lease ++ try { ++ handle.close(); ++ } catch (Exception ex) { ++ throw new RuntimeException(ex); ++ } ++ } ++ }; ++ ++ final Executor executor = Executors.newCachedThreadPool(); ++ for (int i = 0; i < numberOfClients; i++) { ++ executor.execute(clientProcess); ++ } ++ ++ removeNotifications.await(getBackendPropagationTime(), TimeUnit.SECONDS); ++ } ++ } ++ ++ ++ /** ++ * Just make sure unknown listeners doesn't throw exceptions ++ */ ++ @Test ++ public void removeInvalidListener() throws Exception { ++ try (final CloudnameBackend backend = getBackend()) { ++ final LeaseListener unknownnListener = new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ } ++ }; ++ backend.removeTemporaryLeaseListener(unknownnListener); ++ } ++ } ++ ++ ++ /** ++ * Create a whole set of different listener pairs that runs in parallel. They won't ++ * receive notifications from any other lease - listener pairs. ++ */ ++ @Test ++ public void multipleIndependentListeners() throws Exception { ++ try (final CloudnameBackend backend = getBackend()) { ++ final int leasePairs = 10; ++ ++ class LeaseWorker { ++ private final String id; ++ private final CloudnamePath rootPath; ++ private final LeaseListener listener; ++ private final AtomicInteger createNotifications = new AtomicInteger(0); ++ private final AtomicInteger dataNotifications = new AtomicInteger(0); ++ private LeaseHandle handle; ++ ++ public LeaseWorker(final String id) { ++ this.id = id; ++ rootPath = new CloudnamePath(new String[]{""pair"", id}); ++ listener = new LeaseListener() { ++ ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ createNotifications.incrementAndGet(); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ dataNotifications.incrementAndGet(); ++ } ++ }; ++ } ++ ++ public void createLease() { ++ backend.addTemporaryLeaseListener(rootPath, listener); ++ try { ++ Thread.sleep(getBackendPropagationTime()); ++ } catch (final InterruptedException ie) { ++ throw new RuntimeException(ie); ++ } ++ handle = backend.createTemporaryLease(rootPath, id); ++ } ++ ++ public void writeData() { ++ handle.writeLeaseData(id); ++ } ++ ++ public void checkNumberOfNotifications() { ++ // There will be two notifications; one for this lease, one for the other ++ assertThat(""Expected 2 create notifications"", createNotifications.get(), is(2)); ++ // There will be two notifications; one for this lease, one for the other ++ assertThat(""Expected 2 data notifications"", dataNotifications.get(), is(2)); ++ } ++ ++ public void closeLease() { ++ try { ++ handle.close(); ++ } catch (Exception ex) { ++ throw new RuntimeException(ex); ++ } ++ } ++ } ++ ++ final List workers = new ArrayList<>(); ++ ++ for (int i = 0; i < leasePairs; i++) { ++ final String id = Long.toHexString(random.nextLong()); ++ final LeaseWorker leaseWorker1 = new LeaseWorker(id); ++ leaseWorker1.createLease(); ++ workers.add(leaseWorker1); ++ final LeaseWorker leaseWorker2 = new LeaseWorker(id); ++ leaseWorker2.createLease(); ++ workers.add(leaseWorker2); ++ } ++ ++ for (final LeaseWorker worker : workers) { ++ worker.writeData(); ++ } ++ Thread.sleep(getBackendPropagationTime()); ++ for (final LeaseWorker worker : workers) { ++ worker.checkNumberOfNotifications(); ++ } ++ for (final LeaseWorker worker : workers) { ++ worker.closeLease(); ++ } ++ } ++ } ++ ++ /** ++ * Ensure permanent leases distribute notifications as well ++ */ ++ @Test ++ public void permanentLeaseNotifications() throws Exception { ++ final CloudnamePath rootLease = new CloudnamePath(new String[] { ""permanent"", ""vacation"" }); ++ final String leaseData = ""the aero smiths""; ++ final String newLeaseData = ""popcultural reference""; ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ backend.removePermanentLease(rootLease); ++ assertThat(""Can create permanent node"", ++ backend.createPermanantLease(rootLease, leaseData), is(true)); ++ } ++ ++ final AtomicInteger numberOfNotifications = new AtomicInteger(0); ++ final CountDownLatch createLatch = new CountDownLatch(1); ++ final CountDownLatch removeLatch = new CountDownLatch(1); ++ final CountDownLatch dataLatch = new CountDownLatch(1); ++ ++ final LeaseListener listener = new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(rootLease))); ++ assertThat(data, is(equalTo(leaseData))); ++ numberOfNotifications.incrementAndGet(); ++ createLatch.countDown(); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ assertThat(path, is(equalTo(rootLease))); ++ numberOfNotifications.incrementAndGet(); ++ removeLatch.countDown(); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(rootLease))); ++ assertThat(data, is(equalTo(newLeaseData))); ++ numberOfNotifications.incrementAndGet(); ++ dataLatch.countDown(); ++ } ++ }; ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ ++ assertThat(""Lease still exists"", ++ backend.readPermanentLeaseData(rootLease), is(leaseData)); ++ ++ // Add the lease back ++ backend.addPermanentLeaseListener(rootLease, listener); ++ ++ assertThat(""New data can be written"", ++ backend.writePermanentLeaseData(rootLease, newLeaseData), is(true)); ++ ++ // Write new data ++ assertThat(""Lease can be removed"", backend.removePermanentLease(rootLease), is(true)); ++ ++ assertTrue(createLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ assertTrue(dataLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ assertTrue(removeLatch.await(getBackendPropagationTime(), TimeUnit.MILLISECONDS)); ++ // This includes one created, one data, one close ++ assertThat(""One notifications is expected but only got "" ++ + numberOfNotifications.get(), numberOfNotifications.get(), is(3)); ++ ++ backend.removePermanentLeaseListener(listener); ++ // just to be sure - this won't upset anything ++ backend.removePermanentLeaseListener(listener); ++ } ++ } ++ ++ ++ /** ++ * Set up two listeners listening to different permanent leases. There should be no crosstalk ++ * between the listeners. ++ */ ++ @Test ++ public void multiplePermanentListeners() throws Exception { ++ final CloudnamePath permanentA = new CloudnamePath(new String[] { ""primary"" }); ++ final CloudnamePath permanentB = new CloudnamePath(new String[] { ""secondary"" }); ++ final CloudnamePath permanentC = new CloudnamePath( ++ new String[] { ""tertiary"", ""permanent"", ""lease"" }); ++ ++ try (final CloudnameBackend backend = getBackend()) { ++ backend.addPermanentLeaseListener(permanentA, new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(permanentA))); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ assertThat(path, is(equalTo(permanentA))); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(permanentA))); ++ } ++ }); ++ ++ backend.addPermanentLeaseListener(permanentB, new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(permanentB))); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ assertThat(path, is(equalTo(permanentB))); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ assertThat(path, is(equalTo(permanentB))); ++ } ++ }); ++ ++ backend.addPermanentLeaseListener(permanentC, new LeaseListener() { ++ @Override ++ public void leaseCreated(final CloudnamePath path, final String data) { ++ fail(""Did not expect any leases to be created at "" + permanentC); ++ } ++ ++ @Override ++ public void leaseRemoved(final CloudnamePath path) { ++ fail(""Did not expect any leases to be created at "" + permanentC); ++ } ++ ++ @Override ++ public void dataChanged(final CloudnamePath path, final String data) { ++ fail(""Did not expect any leases to be created at "" + permanentC); ++ } ++ }); ++ ++ backend.createPermanantLease(permanentA, ""Some data that belongs to A""); ++ backend.createPermanantLease(permanentB, ""Some data that belongs to B""); ++ ++ // Some might say this is a dirty trick but permanent and temporary leases should not ++ // interfere with eachother. ++ final LeaseHandle handle = backend.createTemporaryLease( ++ permanentC, ""Some data that belongs to C""); ++ assertThat(handle, is(notNullValue())); ++ handle.writeLeaseData(""Some other data that belongs to C""); ++ try { ++ handle.close(); ++ } catch (Exception ex) { ++ fail(ex.getMessage()); ++ } ++ } ++ } ++ ++ protected abstract CloudnameBackend getBackend(); ++} +diff --git a/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java b/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java +deleted file mode 100644 +index cadbb470..00000000 +--- a/testtools/src/main/java/org/cloudname/testtools/network/ClientThread.java ++++ /dev/null +@@ -1,121 +0,0 @@ +-package org.cloudname.testtools.network; +- +-import java.io.IOException; +-import java.io.InputStream; +-import java.io.OutputStream; +-import java.net.Socket; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-/** +- * ClientThread forwards communication for one pair of sockets. +- * TODO(borud): this class lacks unit tests +- * +- * @author dybdahl +- */ +-class ClientThread { +- private final static Logger log = Logger.getLogger(ClientThread.class.getName()); +- +- private Socket serverSocket = null; +- private Socket clientSocket = null; +- private Object threadMonitor = new Object(); +- +- +- /** +- * Constructor +- * @param clientSocket socket crated for incomming call +- * @param hostName destination host name +- * @param hostPort destination host port +- */ +- public ClientThread(final Socket clientSocket, final String hostName, final int hostPort) { +- this.clientSocket = clientSocket; +- Runnable myRunnable = new Runnable() { +- @Override +- public void run() { +- final InputStream clientIn, serverIn; +- final OutputStream clientOut, serverOut; +- +- try { +- synchronized (threadMonitor) { +- serverSocket = new Socket(hostName, hostPort); +- } +- clientIn = clientSocket.getInputStream(); +- clientOut = clientSocket.getOutputStream(); +- serverIn = serverSocket.getInputStream(); +- serverOut = serverSocket.getOutputStream(); +- } catch (IOException ioe) { +- log.severe(""Portforwarder: Can not connect to "" + hostName + "":"" + hostPort); +- try { +- if (serverSocket != null) { +- serverSocket.close(); +- } +- } catch (IOException e) { +- log.severe(""Could not close server socket""); +- } +- return; +- } +- synchronized (threadMonitor) { +- startForwarderThread(clientIn, serverOut); +- startForwarderThread(serverIn, clientOut); +- } +- } +- }; +- Thread fireAndForget = new Thread(myRunnable); +- fireAndForget.start(); +- } +- +- /** +- * Closes sockets, which again closes the running threads. +- */ +- public void close() { +- synchronized (threadMonitor) { +- try { +- if (serverSocket != null) { +- serverSocket.close(); +- serverSocket = null; +- } +- } catch (Exception e) { +- log.log(Level.SEVERE, ""Error while closing server socket"", e); +- } +- try { +- if (clientSocket != null) { +- clientSocket.close(); +- clientSocket = null; +- } +- } catch (Exception e) { +- log.log(Level.SEVERE, ""Error while closing client socket"", e); +- } +- } +- } +- +- private Thread startForwarderThread( +- final InputStream inputStream, final OutputStream outputStream) { +- final int BUFFER_SIZE = 4096; +- Runnable myRunnable = new Runnable() { +- @Override +- public void run() { +- byte[] buffer = new byte[BUFFER_SIZE]; +- try { +- while (true) { +- int bytesRead = inputStream.read(buffer); +- +- if (bytesRead == -1) +- // End of stream is reached --> exit +- break; +- +- outputStream.write(buffer, 0, bytesRead); +- outputStream.flush(); +- } +- } catch (IOException e) { +- // Read/write failed --> connection is broken +- log.log(Level.SEVERE, ""Forwarding in loop died.""); +- } +- // Notify parent thread that the connection is broken +- close(); +- } +- }; +- Thread forwarder = new Thread(myRunnable); +- forwarder.start(); +- return forwarder; +- } +-} +diff --git a/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java b/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java +deleted file mode 100644 +index 35c2ec5e..00000000 +--- a/testtools/src/main/java/org/cloudname/testtools/network/PortForwarder.java ++++ /dev/null +@@ -1,145 +0,0 @@ +-package org.cloudname.testtools.network; +- +-import java.io.IOException; +-import java.net.InetSocketAddress; +-import java.net.ServerSocket; +-import java.net.Socket; +-import java.util.ArrayList; +-import java.util.List; +-import java.util.concurrent.atomic.AtomicBoolean; +-import java.util.logging.Level; +-import java.util.logging.Logger; +- +-/** +- * Simple class for setting up port forwarding in unit tests. This +- * enables killing the connection. +- * +- * TODO(stalehd): Remove? Replace with TestCluster class. Makes for better integration tests. +- * TODO(borud): this class lacks unit tests +- * +- * @author dybdahl +- */ +-public class PortForwarder { +- private final static Logger log = Logger.getLogger(PortForwarder.class.getName()); +- +- private final int myPort; +- private final AtomicBoolean isAlive = new AtomicBoolean(true); +- private ServerSocket serverSocket = null; +- +- private Thread portThread; +- private final Object threadMonitor = new Object(); +- +- private final List clientThreadList = new ArrayList(); +- private final AtomicBoolean pause = new AtomicBoolean(false); +- +- private final String hostName; +- private final int hostPort; +- +- /** +- * Constructor for port-forwarder. Does stat the forwarder. +- * @param myPort client port +- * @param hostName name of host to forward to. +- * @param hostPort port of host to forward to. +- * @throws IOException if unable to open server socket +- */ +- public PortForwarder(final int myPort, final String hostName, final int hostPort) throws IOException { +- this.myPort = myPort; +- this.hostName = hostName; +- this.hostPort = hostPort; +- log.info(""Starting port forwarder "" + myPort + "" -> "" + hostPort); +- startServerSocketThread(); +- } +- +- private void startServerSocketThread() +- throws IOException { +- openServerSocket(); +- Runnable myRunnable = new Runnable() { +- @Override +- public void run() { +- log.info(""Forwarder running""); +- while (isAlive.get() && !pause.get()) { +- try { +- final Socket clientSocket = serverSocket.accept(); +- synchronized (threadMonitor) { +- if (isAlive.get() && !pause.get()) { +- clientThreadList.add(new ClientThread(clientSocket, hostName, hostPort)); +- } else { +- clientSocket.close(); +- } +- } +- } catch (IOException e) { +- log.log(Level.SEVERE, ""Got exception in forwarder"", e); +- // Keep going, maybe later connections will succeed. +- } +- } +- log.info(""Forwarder stopped""); +- } +- }; +- portThread = new Thread(myRunnable); +- // Make this a daemon thread, so it won't keep the VM running at shutdown. +- portThread.setDaemon(true); +- portThread.start(); +- } +- +- private void openServerSocket() throws IOException { +- serverSocket = new ServerSocket(); +- serverSocket.setReuseAddress(true); +- serverSocket.bind(new InetSocketAddress(""localhost"", myPort)); +- } +- +- /** +- * Forces client to loose connection and refuses to create new (closing attempts to connect). +- * @throws IOException +- * @throws InterruptedException +- */ +- public void pause() throws IOException, InterruptedException { +- final Thread currentServerThread; +- synchronized (threadMonitor) { +- if (!pause.compareAndSet(false, true)) { +- return; +- } +- for (ClientThread clientThread: clientThreadList) { +- clientThread.close(); +- +- } +- clientThreadList.clear(); +- serverSocket.close(); +- /* +- * Make a copy of the server socket thread, so we can wait for it +- * to complete outside any monitor. +- */ +- currentServerThread = portThread; +- } +- currentServerThread.join(); +- } +- +- /** +- * Lets client start connecting again. +- * @throws IOException +- */ +- public void unpause() throws IOException { +- synchronized (threadMonitor) { +- if (pause.compareAndSet(true, false)) { +- startServerSocketThread(); +- } +- } +- } +- +- /** +- * Shuts down the forwarder. +- */ +- public void close() { +- isAlive.set(false); +- try { +- pause(); +- } catch (final IOException e) { +- // Ignore this +- log.severe(""Could not close server socket.""); +- } catch (InterruptedException e) { +- log.severe(""Interrupted while waiting for server thread to finish.""); +- // Reassert interrupt. +- Thread.currentThread().interrupt(); +- } +- } +-} +- +diff --git a/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java b/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java +deleted file mode 100644 +index c081434f..00000000 +--- a/testtools/src/main/java/org/cloudname/testtools/zookeeper/EmbeddedZooKeeper.java ++++ /dev/null +@@ -1,88 +0,0 @@ +-package org.cloudname.testtools.zookeeper; +- +-import org.apache.curator.test.TestingServer; +- +-import java.io.File; +-import java.io.IOException; +- +-/** +- * Utility class to fire up an embedded ZooKeeper server in the +- * current JVM for testing purposes. +- * +- * @author borud +- * @author stalehd +- */ +-public final class EmbeddedZooKeeper { +- private final File rootDir; +- private final int port; +- private TestingServer server; +- +- /** +- * @param rootDir the root directory of where the ZooKeeper +- * instance will keep its files. If null, a temporary directory is created +- * @param port the port where ZooKeeper will listen for client +- * connections. +- */ +- public EmbeddedZooKeeper(File rootDir, int port) { +- this.rootDir = rootDir; +- this.port = port; +- } +- +- private void delDir(File path) throws IOException { +- for(File f : path.listFiles()) +- { +- if(f.isDirectory()) { +- delDir(f); +- } else { +- if (!f.delete() && f.exists()) { +- throw new IOException(""Failed to delete file "" + f); +- } +- } +- } +- if (!path.delete() && path.exists()) { +- throw new IOException(""Failed to delete directory "" + path); +- } +- +- } +- +- /** +- * Delete all data owned by the ZooKeeper instance. +- * @throws IOException if some file could not be deleted +- */ +- public void del() throws IOException { +- File path = new File(rootDir, ""data""); +- delDir(path); +- } +- +- +- /** +- * Set up the ZooKeeper instance. +- */ +- public void init() throws Exception { +- this.server = new TestingServer(this.port, this.rootDir); +- // Create the data directory +- File dataDir = new File(rootDir, ""data""); +- dataDir.mkdir(); +- +- this.server.start(); +- } +- +- /** +- * Shut the ZooKeeper instance down. +- * @throws IOException if shutdown encountered I/O errors +- */ +- public void shutdown() throws IOException { +- this.server.stop(); +- del(); +- } +- +- /** +- * Get the client connection string for the ZooKeeper instance. +- * +- * @return a String containing a comma-separated list of host:port +- * entries for use as a parameter to the ZooKeeper client class. +- */ +- public String getClientConnectionString() { +- return ""127.0.0.1:"" + port; +- } +-} +diff --git a/timber/pom.xml b/timber/pom.xml +index 3ed79030..6dca5385 100644 +--- a/timber/pom.xml ++++ b/timber/pom.xml +@@ -62,7 +62,7 @@ + + + io.netty +- netty-all ++ netty + + + +@@ -75,11 +75,13 @@ + junit + test + ++ + + org.cloudname + idgen + test + ++ + + joda-time + joda-time" +3990e8b478b1d958479c173c74946e38360cfd17,hadoop,Merge r1503933 from trunk to branch-2 for YARN-513.- Create common proxy client for communicating with RM (Xuan Gong & Jian He via- bikas)--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1503935 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 65d19bff9d839..4d6cb00b23eca 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -465,6 +465,9 @@ Release 2.1.0-beta - 2013-07-02 + YARN-521. Augment AM - RM client module to be able to request containers + only at specific locations (Sandy Ryza via bikas) + ++ YARN-513. Create common proxy client for communicating with RM. (Xuan Gong ++ & Jian He via bikas) ++ + OPTIMIZATIONS + + YARN-512. Log aggregation root directory check is more expensive than it +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +index 44c35c3d58b28..b14e65225200d 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/conf/YarnConfiguration.java +@@ -655,17 +655,17 @@ public class YarnConfiguration extends Configuration { + public static final long DEFAULT_NM_PROCESS_KILL_WAIT_MS = + 2000; + +- /** Max time to wait to establish a connection to RM when NM starts ++ /** Max time to wait to establish a connection to RM + */ +- public static final String RESOURCEMANAGER_CONNECT_WAIT_SECS = +- NM_PREFIX + ""resourcemanager.connect.wait.secs""; +- public static final int DEFAULT_RESOURCEMANAGER_CONNECT_WAIT_SECS = ++ public static final String RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS = ++ RM_PREFIX + ""resourcemanager.connect.max.wait.secs""; ++ public static final int DEFAULT_RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS = + 15*60; + +- /** Time interval between each NM attempt to connect to RM ++ /** Time interval between each attempt to connect to RM + */ + public static final String RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS = +- NM_PREFIX + ""resourcemanager.connect.retry_interval.secs""; ++ RM_PREFIX + ""resourcemanager.connect.retry_interval.secs""; + public static final long DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + = 30; + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java +new file mode 100644 +index 0000000000000..f70b44ce3a8db +--- /dev/null ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/ClientRMProxy.java +@@ -0,0 +1,65 @@ ++/** ++* Licensed to the Apache Software Foundation (ASF) under one ++* or more contributor license agreements. See the NOTICE file ++* distributed with this work for additional information ++* regarding copyright ownership. The ASF licenses this file ++* to you under the Apache License, Version 2.0 (the ++* ""License""); you may not use this file except in compliance ++* with the License. You may obtain a copy of the License at ++* ++* http://www.apache.org/licenses/LICENSE-2.0 ++* ++* Unless required by applicable law or agreed to in writing, software ++* distributed under the License is distributed on an ""AS IS"" BASIS, ++* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++* See the License for the specific language governing permissions and ++* limitations under the License. ++*/ ++ ++package org.apache.hadoop.yarn.client; ++ ++import java.io.IOException; ++import java.net.InetSocketAddress; ++ ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.yarn.api.ApplicationClientProtocol; ++import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; ++import org.apache.hadoop.yarn.conf.YarnConfiguration; ++import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; ++ ++public class ClientRMProxy extends RMProxy{ ++ ++ private static final Log LOG = LogFactory.getLog(ClientRMProxy.class); ++ ++ public static T createRMProxy(final Configuration conf, ++ final Class protocol) throws IOException { ++ InetSocketAddress rmAddress = getRMAddress(conf, protocol); ++ return createRMProxy(conf, protocol, rmAddress); ++ } ++ ++ private static InetSocketAddress getRMAddress(Configuration conf, Class protocol) { ++ if (protocol == ApplicationClientProtocol.class) { ++ return conf.getSocketAddr(YarnConfiguration.RM_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_PORT); ++ } else if (protocol == ResourceManagerAdministrationProtocol.class) { ++ return conf.getSocketAddr( ++ YarnConfiguration.RM_ADMIN_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_ADMIN_PORT); ++ } else if (protocol == ApplicationMasterProtocol.class) { ++ return conf.getSocketAddr( ++ YarnConfiguration.RM_SCHEDULER_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); ++ } else { ++ String message = ""Unsupported protocol found when creating the proxy "" + ++ ""connection to ResourceManager: "" + ++ ((protocol != null) ? protocol.getClass().getName() : ""null""); ++ LOG.error(message); ++ throw new IllegalStateException(message); ++ } ++ } ++} +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java +index e8dca61d32a0b..22d80c6e8d90b 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java +@@ -19,7 +19,6 @@ + package org.apache.hadoop.yarn.client.api; + + import java.io.IOException; +-import java.net.InetSocketAddress; + import java.util.List; + import java.util.Set; + +@@ -54,25 +53,6 @@ public static YarnClient createYarnClient() { + return client; + } + +- /** +- * Create a new instance of YarnClient. +- */ +- @Public +- public static YarnClient createYarnClient(InetSocketAddress rmAddress) { +- YarnClient client = new YarnClientImpl(rmAddress); +- return client; +- } +- +- /** +- * Create a new instance of YarnClient. +- */ +- @Public +- public static YarnClient createYarnClient(String name, +- InetSocketAddress rmAddress) { +- YarnClient client = new YarnClientImpl(name, rmAddress); +- return client; +- } +- + @Private + protected YarnClient(String name) { + super(name); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java +index 0f088a0604b6e..4119a0cb1de7e 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/AMRMClientImpl.java +@@ -19,8 +19,6 @@ + package org.apache.hadoop.yarn.client.api.impl; + + import java.io.IOException; +-import java.net.InetSocketAddress; +-import java.security.PrivilegedAction; + import java.util.ArrayList; + import java.util.Collection; + import java.util.Collections; +@@ -42,7 +40,6 @@ + import org.apache.hadoop.classification.InterfaceStability.Unstable; + import org.apache.hadoop.conf.Configuration; + import org.apache.hadoop.ipc.RPC; +-import org.apache.hadoop.security.UserGroupInformation; + import org.apache.hadoop.yarn.api.ApplicationMasterProtocol; + import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest; + import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse; +@@ -56,16 +53,16 @@ + import org.apache.hadoop.yarn.api.records.Priority; + import org.apache.hadoop.yarn.api.records.Resource; + import org.apache.hadoop.yarn.api.records.ResourceRequest; ++import org.apache.hadoop.yarn.client.ClientRMProxy; + import org.apache.hadoop.yarn.client.api.AMRMClient; ++import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; + import org.apache.hadoop.yarn.client.api.InvalidContainerRequestException; + import org.apache.hadoop.yarn.client.api.NMTokenCache; +-import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest; + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.exceptions.YarnException; + import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.ipc.YarnRPC; + import org.apache.hadoop.yarn.util.RackResolver; + + import com.google.common.annotations.VisibleForTesting; +@@ -171,28 +168,11 @@ protected void serviceInit(Configuration conf) throws Exception { + @Override + protected void serviceStart() throws Exception { + final YarnConfiguration conf = new YarnConfiguration(getConfig()); +- final YarnRPC rpc = YarnRPC.create(conf); +- final InetSocketAddress rmAddress = conf.getSocketAddr( +- YarnConfiguration.RM_SCHEDULER_ADDRESS, +- YarnConfiguration.DEFAULT_RM_SCHEDULER_ADDRESS, +- YarnConfiguration.DEFAULT_RM_SCHEDULER_PORT); +- +- UserGroupInformation currentUser; + try { +- currentUser = UserGroupInformation.getCurrentUser(); ++ rmClient = ClientRMProxy.createRMProxy(conf, ApplicationMasterProtocol.class); + } catch (IOException e) { + throw new YarnRuntimeException(e); + } +- +- // CurrentUser should already have AMToken loaded. +- rmClient = currentUser.doAs(new PrivilegedAction() { +- @Override +- public ApplicationMasterProtocol run() { +- return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rmAddress, +- conf); +- } +- }); +- LOG.debug(""Connecting to ResourceManager at "" + rmAddress); + super.serviceStart(); + } + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java +index b3b8bdf4316bb..4398359862b06 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/impl/YarnClientImpl.java +@@ -59,11 +59,12 @@ + import org.apache.hadoop.yarn.api.records.Token; + import org.apache.hadoop.yarn.api.records.YarnApplicationState; + import org.apache.hadoop.yarn.api.records.YarnClusterMetrics; ++import org.apache.hadoop.yarn.client.ClientRMProxy; + import org.apache.hadoop.yarn.client.api.YarnClient; + import org.apache.hadoop.yarn.client.api.YarnClientApplication; + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.exceptions.YarnException; +-import org.apache.hadoop.yarn.ipc.YarnRPC; ++import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; + import org.apache.hadoop.yarn.util.Records; + + import com.google.common.annotations.VisibleForTesting; +@@ -81,16 +82,7 @@ public class YarnClientImpl extends YarnClient { + private static final String ROOT = ""root""; + + public YarnClientImpl() { +- this(null); +- } +- +- public YarnClientImpl(InetSocketAddress rmAddress) { +- this(YarnClientImpl.class.getName(), rmAddress); +- } +- +- public YarnClientImpl(String name, InetSocketAddress rmAddress) { +- super(name); +- this.rmAddress = rmAddress; ++ super(YarnClientImpl.class.getName()); + } + + private static InetSocketAddress getRmAddress(Configuration conf) { +@@ -100,9 +92,7 @@ private static InetSocketAddress getRmAddress(Configuration conf) { + + @Override + protected void serviceInit(Configuration conf) throws Exception { +- if (this.rmAddress == null) { +- this.rmAddress = getRmAddress(conf); +- } ++ this.rmAddress = getRmAddress(conf); + statePollIntervalMillis = conf.getLong( + YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS, + YarnConfiguration.DEFAULT_YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS); +@@ -111,12 +101,11 @@ protected void serviceInit(Configuration conf) throws Exception { + + @Override + protected void serviceStart() throws Exception { +- YarnRPC rpc = YarnRPC.create(getConfig()); +- +- this.rmClient = (ApplicationClientProtocol) rpc.getProxy( +- ApplicationClientProtocol.class, rmAddress, getConfig()); +- if (LOG.isDebugEnabled()) { +- LOG.debug(""Connecting to ResourceManager at "" + rmAddress); ++ try { ++ rmClient = ClientRMProxy.createRMProxy(getConfig(), ++ ApplicationClientProtocol.class); ++ } catch (IOException e) { ++ throw new YarnRuntimeException(e); + } + super.serviceStart(); + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java +index 6426fe9dbc77e..11335c0d8f68d 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java +@@ -19,8 +19,6 @@ + package org.apache.hadoop.yarn.client.cli; + + import java.io.IOException; +-import java.net.InetSocketAddress; +-import java.security.PrivilegedAction; + import java.util.Arrays; + + import org.apache.hadoop.classification.InterfaceAudience.Private; +@@ -31,11 +29,11 @@ + import org.apache.hadoop.security.UserGroupInformation; + import org.apache.hadoop.util.Tool; + import org.apache.hadoop.util.ToolRunner; ++import org.apache.hadoop.yarn.client.ClientRMProxy; + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.exceptions.YarnException; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.ipc.YarnRPC; + import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol; + import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest; + import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest; +@@ -164,32 +162,10 @@ private static void printUsage(String cmd) { + } + } + +- private static UserGroupInformation getUGI(Configuration conf +- ) throws IOException { +- return UserGroupInformation.getCurrentUser(); +- } +- + private ResourceManagerAdministrationProtocol createAdminProtocol() throws IOException { + // Get the current configuration + final YarnConfiguration conf = new YarnConfiguration(getConf()); +- +- // Create the client +- final InetSocketAddress addr = conf.getSocketAddr( +- YarnConfiguration.RM_ADMIN_ADDRESS, +- YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, +- YarnConfiguration.DEFAULT_RM_ADMIN_PORT); +- final YarnRPC rpc = YarnRPC.create(conf); +- +- ResourceManagerAdministrationProtocol adminProtocol = +- getUGI(conf).doAs(new PrivilegedAction() { +- @Override +- public ResourceManagerAdministrationProtocol run() { +- return (ResourceManagerAdministrationProtocol) rpc.getProxy(ResourceManagerAdministrationProtocol.class, +- addr, conf); +- } +- }); +- +- return adminProtocol; ++ return ClientRMProxy.createRMProxy(conf, ResourceManagerAdministrationProtocol.class); + } + + private int refreshQueues() throws IOException, YarnException { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java +new file mode 100644 +index 0000000000000..e4493b5a469b9 +--- /dev/null ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/client/RMProxy.java +@@ -0,0 +1,125 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.apache.hadoop.yarn.client; ++ ++import java.io.IOException; ++import java.net.ConnectException; ++import java.net.InetSocketAddress; ++import java.security.PrivilegedAction; ++import java.util.HashMap; ++import java.util.Map; ++import java.util.concurrent.TimeUnit; ++ ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; ++import org.apache.hadoop.classification.InterfaceAudience; ++import org.apache.hadoop.classification.InterfaceStability; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.io.retry.RetryPolicies; ++import org.apache.hadoop.io.retry.RetryPolicy; ++import org.apache.hadoop.io.retry.RetryProxy; ++import org.apache.hadoop.security.UserGroupInformation; ++import org.apache.hadoop.yarn.conf.YarnConfiguration; ++import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; ++import org.apache.hadoop.yarn.ipc.YarnRPC; ++ ++@InterfaceAudience.Public ++@InterfaceStability.Evolving ++public class RMProxy { ++ ++ private static final Log LOG = LogFactory.getLog(RMProxy.class); ++ ++ @SuppressWarnings(""unchecked"") ++ public static T createRMProxy(final Configuration conf, ++ final Class protocol, InetSocketAddress rmAddress) throws IOException { ++ RetryPolicy retryPolicy = createRetryPolicy(conf); ++ T proxy = RMProxy.getProxy(conf, protocol, rmAddress); ++ LOG.info(""Connecting to ResourceManager at "" + rmAddress); ++ return (T) RetryProxy.create(protocol, proxy, retryPolicy); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ protected static T getProxy(final Configuration conf, ++ final Class protocol, final InetSocketAddress rmAddress) ++ throws IOException { ++ return (T) UserGroupInformation.getCurrentUser().doAs( ++ new PrivilegedAction() { ++ ++ @Override ++ public T run() { ++ return (T) YarnRPC.create(conf).getProxy(protocol, rmAddress, conf); ++ } ++ }); ++ } ++ ++ public static RetryPolicy createRetryPolicy(Configuration conf) { ++ long rmConnectWaitMS = ++ conf.getInt( ++ YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, ++ YarnConfiguration.DEFAULT_RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS) ++ * 1000; ++ long rmConnectionRetryIntervalMS = ++ conf.getLong( ++ YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, ++ YarnConfiguration ++ .DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS) ++ * 1000; ++ ++ if (rmConnectionRetryIntervalMS < 0) { ++ throw new YarnRuntimeException(""Invalid Configuration. "" + ++ YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + ++ "" should not be negative.""); ++ } ++ ++ boolean waitForEver = (rmConnectWaitMS == -1000); ++ ++ if (waitForEver) { ++ return RetryPolicies.RETRY_FOREVER; ++ } else { ++ if (rmConnectWaitMS < 0) { ++ throw new YarnRuntimeException(""Invalid Configuration. "" ++ + YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS ++ + "" can be -1, but can not be other negative numbers""); ++ } ++ ++ // try connect once ++ if (rmConnectWaitMS < rmConnectionRetryIntervalMS) { ++ LOG.warn(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS ++ + "" is smaller than "" ++ + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS ++ + "". Only try connect once.""); ++ rmConnectWaitMS = 0; ++ } ++ } ++ ++ RetryPolicy retryPolicy = ++ RetryPolicies.retryUpToMaximumTimeWithFixedSleep(rmConnectWaitMS, ++ rmConnectionRetryIntervalMS, ++ TimeUnit.MILLISECONDS); ++ ++ Map, RetryPolicy> exceptionToPolicyMap = ++ new HashMap, RetryPolicy>(); ++ exceptionToPolicyMap.put(ConnectException.class, retryPolicy); ++ //TO DO: after HADOOP-9576, IOException can be changed to EOFException ++ exceptionToPolicyMap.put(IOException.class, retryPolicy); ++ ++ return RetryPolicies.retryByException(RetryPolicies.TRY_ONCE_THEN_FAIL, ++ exceptionToPolicyMap); ++ } ++} +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java +new file mode 100644 +index 0000000000000..ef9154fde1b5f +--- /dev/null ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/ServerRMProxy.java +@@ -0,0 +1,55 @@ ++/** ++* Licensed to the Apache Software Foundation (ASF) under one ++* or more contributor license agreements. See the NOTICE file ++* distributed with this work for additional information ++* regarding copyright ownership. The ASF licenses this file ++* to you under the Apache License, Version 2.0 (the ++* ""License""); you may not use this file except in compliance ++* with the License. You may obtain a copy of the License at ++* ++* http://www.apache.org/licenses/LICENSE-2.0 ++* ++* Unless required by applicable law or agreed to in writing, software ++* distributed under the License is distributed on an ""AS IS"" BASIS, ++* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++* See the License for the specific language governing permissions and ++* limitations under the License. ++*/ ++ ++package org.apache.hadoop.yarn.server.api; ++ ++import java.io.IOException; ++import java.net.InetSocketAddress; ++ ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.yarn.client.RMProxy; ++import org.apache.hadoop.yarn.conf.YarnConfiguration; ++ ++public class ServerRMProxy extends RMProxy{ ++ ++ private static final Log LOG = LogFactory.getLog(ServerRMProxy.class); ++ ++ public static T createRMProxy(final Configuration conf, ++ final Class protocol) throws IOException { ++ InetSocketAddress rmAddress = getRMAddress(conf, protocol); ++ return createRMProxy(conf, protocol, rmAddress); ++ } ++ ++ private static InetSocketAddress getRMAddress(Configuration conf, Class protocol) { ++ if (protocol == ResourceTracker.class) { ++ return conf.getSocketAddr( ++ YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_ADDRESS, ++ YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_PORT); ++ } ++ else { ++ String message = ""Unsupported protocol found when creating the proxy "" + ++ ""connection to ResourceManager: "" + ++ ((protocol != null) ? protocol.getClass().getName() : ""null""); ++ LOG.error(message); ++ throw new IllegalStateException(message); ++ } ++ } ++} +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java +index 396204cf2dbdb..40f6874623fdf 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/impl/pb/client/ResourceTrackerPBClientImpl.java +@@ -18,6 +18,7 @@ + + package org.apache.hadoop.yarn.server.api.impl.pb.client; + ++import java.io.Closeable; + import java.io.IOException; + import java.net.InetSocketAddress; + +@@ -41,7 +42,7 @@ + + import com.google.protobuf.ServiceException; + +-public class ResourceTrackerPBClientImpl implements ResourceTracker { ++public class ResourceTrackerPBClientImpl implements ResourceTracker, Closeable { + + private ResourceTrackerPB proxy; + +@@ -50,7 +51,14 @@ public ResourceTrackerPBClientImpl(long clientVersion, InetSocketAddress addr, C + proxy = (ResourceTrackerPB)RPC.getProxy( + ResourceTrackerPB.class, clientVersion, addr, conf); + } +- ++ ++ @Override ++ public void close() { ++ if(this.proxy != null) { ++ RPC.stopProxy(this.proxy); ++ } ++ } ++ + @Override + public RegisterNodeManagerResponse registerNodeManager( + RegisterNodeManagerRequest request) throws YarnException, +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java +index 550cdc5a98f4f..b0e71e915633e 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeStatusUpdaterImpl.java +@@ -19,7 +19,7 @@ + package org.apache.hadoop.yarn.server.nodemanager; + + import java.io.IOException; +-import java.net.InetSocketAddress; ++import java.net.ConnectException; + import java.util.ArrayList; + import java.util.Collections; + import java.util.HashMap; +@@ -33,6 +33,7 @@ + import org.apache.commons.logging.LogFactory; + import org.apache.hadoop.classification.InterfaceAudience.Private; + import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.ipc.RPC; + import org.apache.hadoop.security.UserGroupInformation; + import org.apache.hadoop.service.AbstractService; + import org.apache.hadoop.yarn.api.records.ApplicationId; +@@ -47,9 +48,9 @@ + import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.ipc.YarnRPC; + import org.apache.hadoop.yarn.server.api.ResourceManagerConstants; + import org.apache.hadoop.yarn.server.api.ResourceTracker; ++import org.apache.hadoop.yarn.server.api.ServerRMProxy; + import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; + import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; + import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; +@@ -77,7 +78,6 @@ public class NodeStatusUpdaterImpl extends AbstractService implements + private NodeId nodeId; + private long nextHeartBeatInterval; + private ResourceTracker resourceTracker; +- private InetSocketAddress rmAddress; + private Resource totalResource; + private int httpPort; + private volatile boolean isStopped; +@@ -91,9 +91,6 @@ public class NodeStatusUpdaterImpl extends AbstractService implements + + private final NodeHealthCheckerService healthChecker; + private final NodeManagerMetrics metrics; +- private long rmConnectWaitMS; +- private long rmConnectionRetryIntervalMS; +- private boolean waitForEver; + + private Runnable statusUpdaterRunnable; + private Thread statusUpdater; +@@ -110,11 +107,6 @@ public NodeStatusUpdaterImpl(Context context, Dispatcher dispatcher, + + @Override + protected void serviceInit(Configuration conf) throws Exception { +- this.rmAddress = conf.getSocketAddr( +- YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, +- YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_ADDRESS, +- YarnConfiguration.DEFAULT_RM_RESOURCE_TRACKER_PORT); +- + int memoryMb = + conf.getInt( + YarnConfiguration.NM_PMEM_MB, YarnConfiguration.DEFAULT_NM_PMEM_MB); +@@ -153,6 +145,7 @@ protected void serviceStart() throws Exception { + try { + // Registration has to be in start so that ContainerManager can get the + // perNM tokens needed to authenticate ContainerTokens. ++ this.resourceTracker = getRMClient(); + registerWithRM(); + super.serviceStart(); + startStatusUpdater(); +@@ -167,6 +160,7 @@ protected void serviceStart() throws Exception { + protected void serviceStop() throws Exception { + // Interrupt the updater. + this.isStopped = true; ++ stopRMProxy(); + super.serviceStop(); + } + +@@ -188,6 +182,13 @@ protected void rebootNodeStatusUpdater() { + } + } + ++ @VisibleForTesting ++ protected void stopRMProxy() { ++ if(this.resourceTracker != null) { ++ RPC.stopProxy(this.resourceTracker); ++ } ++ } ++ + @Private + protected boolean isTokenKeepAliveEnabled(Configuration conf) { + return conf.getBoolean(YarnConfiguration.LOG_AGGREGATION_ENABLED, +@@ -195,93 +196,22 @@ protected boolean isTokenKeepAliveEnabled(Configuration conf) { + && UserGroupInformation.isSecurityEnabled(); + } + +- protected ResourceTracker getRMClient() { ++ @VisibleForTesting ++ protected ResourceTracker getRMClient() throws IOException { + Configuration conf = getConfig(); +- YarnRPC rpc = YarnRPC.create(conf); +- return (ResourceTracker) rpc.getProxy(ResourceTracker.class, rmAddress, +- conf); ++ return ServerRMProxy.createRMProxy(conf, ResourceTracker.class); + } + + @VisibleForTesting + protected void registerWithRM() throws YarnException, IOException { +- Configuration conf = getConfig(); +- rmConnectWaitMS = +- conf.getInt( +- YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, +- YarnConfiguration.DEFAULT_RESOURCEMANAGER_CONNECT_WAIT_SECS) +- * 1000; +- rmConnectionRetryIntervalMS = +- conf.getLong( +- YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, +- YarnConfiguration +- .DEFAULT_RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS) +- * 1000; +- +- if(rmConnectionRetryIntervalMS < 0) { +- throw new YarnRuntimeException(""Invalid Configuration. "" + +- YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS + +- "" should not be negative.""); +- } +- +- waitForEver = (rmConnectWaitMS == -1000); +- +- if(! waitForEver) { +- if(rmConnectWaitMS < 0) { +- throw new YarnRuntimeException(""Invalid Configuration. "" + +- YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS + +- "" can be -1, but can not be other negative numbers""); +- } +- +- //try connect once +- if(rmConnectWaitMS < rmConnectionRetryIntervalMS) { +- LOG.warn(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS +- + "" is smaller than "" +- + YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS +- + "". Only try connect once.""); +- rmConnectWaitMS = 0; +- } +- } +- +- int rmRetryCount = 0; +- long waitStartTime = System.currentTimeMillis(); +- + RegisterNodeManagerRequest request = + recordFactory.newRecordInstance(RegisterNodeManagerRequest.class); + request.setHttpPort(this.httpPort); + request.setResource(this.totalResource); + request.setNodeId(this.nodeId); +- RegisterNodeManagerResponse regNMResponse; +- +- while(true) { +- try { +- rmRetryCount++; +- LOG.info(""Connecting to ResourceManager at "" + this.rmAddress +- + "". current no. of attempts is "" + rmRetryCount); +- this.resourceTracker = getRMClient(); +- regNMResponse = +- this.resourceTracker.registerNodeManager(request); +- this.rmIdentifier = regNMResponse.getRMIdentifier(); +- break; +- } catch(Throwable e) { +- LOG.warn(""Trying to connect to ResourceManager, "" + +- ""current no. of failed attempts is ""+rmRetryCount); +- if(System.currentTimeMillis() - waitStartTime < rmConnectWaitMS +- || waitForEver) { +- try { +- LOG.info(""Sleeping for "" + rmConnectionRetryIntervalMS/1000 +- + "" seconds before next connection retry to RM""); +- Thread.sleep(rmConnectionRetryIntervalMS); +- } catch(InterruptedException ex) { +- //done nothing +- } +- } else { +- String errorMessage = ""Failed to Connect to RM, "" + +- ""no. of failed attempts is ""+rmRetryCount; +- LOG.error(errorMessage,e); +- throw new YarnRuntimeException(errorMessage,e); +- } +- } +- } ++ RegisterNodeManagerResponse regNMResponse = ++ resourceTracker.registerNodeManager(request); ++ this.rmIdentifier = regNMResponse.getRMIdentifier(); + // if the Resourcemanager instructs NM to shutdown. + if (NodeAction.SHUTDOWN.equals(regNMResponse.getNodeAction())) { + String message = +@@ -426,8 +356,6 @@ public void run() { + // Send heartbeat + try { + NodeHeartbeatResponse response = null; +- int rmRetryCount = 0; +- long waitStartTime = System.currentTimeMillis(); + NodeStatus nodeStatus = getNodeStatusAndUpdateContainersInContext(); + nodeStatus.setResponseId(lastHeartBeatID); + +@@ -440,31 +368,7 @@ public void run() { + request + .setLastKnownNMTokenMasterKey(NodeStatusUpdaterImpl.this.context + .getNMTokenSecretManager().getCurrentKey()); +- while (!isStopped) { +- try { +- rmRetryCount++; +- response = resourceTracker.nodeHeartbeat(request); +- break; +- } catch (Throwable e) { +- LOG.warn(""Trying to heartbeat to ResourceManager, "" +- + ""current no. of failed attempts is "" + rmRetryCount); +- if(System.currentTimeMillis() - waitStartTime < rmConnectWaitMS +- || waitForEver) { +- try { +- LOG.info(""Sleeping for "" + rmConnectionRetryIntervalMS/1000 +- + "" seconds before next heartbeat to RM""); +- Thread.sleep(rmConnectionRetryIntervalMS); +- } catch(InterruptedException ex) { +- //done nothing +- } +- } else { +- String errorMessage = ""Failed to heartbeat to RM, "" + +- ""no. of failed attempts is ""+rmRetryCount; +- LOG.error(errorMessage,e); +- throw new YarnRuntimeException(errorMessage,e); +- } +- } +- } ++ response = resourceTracker.nodeHeartbeat(request); + //get next heartbeat interval from response + nextHeartBeatInterval = response.getNextHeartBeatInterval(); + updateMasterKeys(response); +@@ -508,11 +412,11 @@ public void run() { + dispatcher.getEventHandler().handle( + new CMgrCompletedAppsEvent(appsToCleanup)); + } +- } catch (YarnRuntimeException e) { ++ } catch (ConnectException e) { + //catch and throw the exception if tried MAX wait time to connect RM + dispatcher.getEventHandler().handle( + new NodeManagerEvent(NodeManagerEventType.SHUTDOWN)); +- throw e; ++ throw new YarnRuntimeException(e); + } catch (Throwable e) { + // TODO Better error handling. Thread can die with the rest of the + // NM still running. +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java +index e93778e2987ef..a3e1faf310e54 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/MockNodeStatusUpdater.java +@@ -61,6 +61,10 @@ public MockNodeStatusUpdater(Context context, Dispatcher dispatcher, + protected ResourceTracker getRMClient() { + return resourceTracker; + } ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } + + private static class MockResourceTracker implements ResourceTracker { + private int heartBeatID; +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java +index 668b85b6511bd..294c93ed3b84a 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java +@@ -107,6 +107,11 @@ protected ResourceTracker getRMClient() { + return new LocalRMInterface(); + }; + ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } ++ + @Override + protected void startStatusUpdater() { + return; // Don't start any updating thread. +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java +index e17131fd3a1dc..2a3e3d579ca03 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java +@@ -41,6 +41,8 @@ + import org.apache.hadoop.conf.Configuration; + import org.apache.hadoop.fs.FileContext; + import org.apache.hadoop.fs.Path; ++import org.apache.hadoop.io.retry.RetryPolicy; ++import org.apache.hadoop.io.retry.RetryProxy; + import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; + import org.apache.hadoop.net.NetUtils; + import org.apache.hadoop.service.ServiceOperations; +@@ -53,6 +55,7 @@ + import org.apache.hadoop.yarn.api.records.ContainerStatus; + import org.apache.hadoop.yarn.api.records.NodeId; + import org.apache.hadoop.yarn.api.records.Resource; ++import org.apache.hadoop.yarn.client.RMProxy; + import org.apache.hadoop.yarn.conf.YarnConfiguration; + import org.apache.hadoop.yarn.event.Dispatcher; + import org.apache.hadoop.yarn.event.EventHandler; +@@ -60,9 +63,9 @@ + import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; + import org.apache.hadoop.yarn.factories.RecordFactory; + import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; +-import org.apache.hadoop.yarn.ipc.RPCUtil; + import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; + import org.apache.hadoop.yarn.server.api.ResourceTracker; ++import org.apache.hadoop.yarn.server.api.ServerRMProxy; + import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatRequest; + import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse; + import org.apache.hadoop.yarn.server.api.protocolrecords.RegisterNodeManagerRequest; +@@ -103,11 +106,17 @@ public class TestNodeStatusUpdater { + volatile int heartBeatID = 0; + volatile Throwable nmStartError = null; + private final List registeredNodes = new ArrayList(); +- private final Configuration conf = createNMConfig(); ++ private boolean triggered = false; ++ private Configuration conf; + private NodeManager nm; + private boolean containerStatusBackupSuccessfully = true; + private List completedContainerStatusList = new ArrayList(); + ++ @Before ++ public void setUp() { ++ conf = createNMConfig(); ++ } ++ + @After + public void tearDown() { + this.registeredNodes.clear(); +@@ -274,6 +283,11 @@ public MyNodeStatusUpdater(Context context, Dispatcher dispatcher, + protected ResourceTracker getRMClient() { + return resourceTracker; + } ++ ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } + } + + private class MyNodeStatusUpdater2 extends NodeStatusUpdaterImpl { +@@ -290,6 +304,10 @@ protected ResourceTracker getRMClient() { + return resourceTracker; + } + ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } + } + + private class MyNodeStatusUpdater3 extends NodeStatusUpdaterImpl { +@@ -307,7 +325,12 @@ public MyNodeStatusUpdater3(Context context, Dispatcher dispatcher, + protected ResourceTracker getRMClient() { + return resourceTracker; + } +- ++ ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } ++ + @Override + protected boolean isTokenKeepAliveEnabled(Configuration conf) { + return true; +@@ -315,21 +338,16 @@ protected boolean isTokenKeepAliveEnabled(Configuration conf) { + } + + private class MyNodeStatusUpdater4 extends NodeStatusUpdaterImpl { +- public ResourceTracker resourceTracker = +- new MyResourceTracker(this.context); ++ + private Context context; +- private long waitStartTime; + private final long rmStartIntervalMS; + private final boolean rmNeverStart; +- private volatile boolean triggered = false; +- private long durationWhenTriggered = -1; +- ++ public ResourceTracker resourceTracker; + public MyNodeStatusUpdater4(Context context, Dispatcher dispatcher, + NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics, + long rmStartIntervalMS, boolean rmNeverStart) { + super(context, dispatcher, healthChecker, metrics); + this.context = context; +- this.waitStartTime = System.currentTimeMillis(); + this.rmStartIntervalMS = rmStartIntervalMS; + this.rmNeverStart = rmNeverStart; + } +@@ -337,25 +355,16 @@ public MyNodeStatusUpdater4(Context context, Dispatcher dispatcher, + @Override + protected void serviceStart() throws Exception { + //record the startup time +- this.waitStartTime = System.currentTimeMillis(); + super.serviceStart(); + } + + @Override +- protected ResourceTracker getRMClient() { +- if (!triggered) { +- long t = System.currentTimeMillis(); +- long duration = t - waitStartTime; +- if (duration <= rmStartIntervalMS +- || rmNeverStart) { +- throw new YarnRuntimeException(""Faking RM start failure as start "" + +- ""delay timer has not expired.""); +- } else { +- //triggering +- triggered = true; +- durationWhenTriggered = duration; +- } +- } ++ protected ResourceTracker getRMClient() throws IOException { ++ RetryPolicy retryPolicy = RMProxy.createRetryPolicy(conf); ++ resourceTracker = ++ (ResourceTracker) RetryProxy.create(ResourceTracker.class, ++ new MyResourceTracker6(this.context, rmStartIntervalMS, ++ rmNeverStart), retryPolicy); + return resourceTracker; + } + +@@ -363,37 +372,35 @@ private boolean isTriggered() { + return triggered; + } + +- private long getWaitStartTime() { +- return waitStartTime; +- } +- +- private long getDurationWhenTriggered() { +- return durationWhenTriggered; +- } +- + @Override +- public String toString() { +- return ""MyNodeStatusUpdater4{"" + +- ""rmNeverStart="" + rmNeverStart + +- "", triggered="" + triggered + +- "", duration="" + durationWhenTriggered + +- "", rmStartIntervalMS="" + rmStartIntervalMS + +- '}'; ++ protected void stopRMProxy() { ++ return; + } + } + ++ ++ + private class MyNodeStatusUpdater5 extends NodeStatusUpdaterImpl { + private ResourceTracker resourceTracker; ++ private Configuration conf; + + public MyNodeStatusUpdater5(Context context, Dispatcher dispatcher, +- NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics) { ++ NodeHealthCheckerService healthChecker, NodeManagerMetrics metrics, Configuration conf) { + super(context, dispatcher, healthChecker, metrics); + resourceTracker = new MyResourceTracker5(); ++ this.conf = conf; + } + + @Override + protected ResourceTracker getRMClient() { +- return resourceTracker; ++ RetryPolicy retryPolicy = RMProxy.createRetryPolicy(conf); ++ return (ResourceTracker) RetryProxy.create(ResourceTracker.class, ++ resourceTracker, retryPolicy); ++ } ++ ++ @Override ++ protected void stopRMProxy() { ++ return; + } + } + +@@ -417,15 +424,18 @@ private class MyNodeManager2 extends NodeManager { + public boolean isStopped = false; + private NodeStatusUpdater nodeStatusUpdater; + private CyclicBarrier syncBarrier; +- public MyNodeManager2 (CyclicBarrier syncBarrier) { ++ private Configuration conf; ++ ++ public MyNodeManager2 (CyclicBarrier syncBarrier, Configuration conf) { + this.syncBarrier = syncBarrier; ++ this.conf = conf; + } + @Override + protected NodeStatusUpdater createNodeStatusUpdater(Context context, + Dispatcher dispatcher, NodeHealthCheckerService healthChecker) { + nodeStatusUpdater = + new MyNodeStatusUpdater5(context, dispatcher, healthChecker, +- metrics); ++ metrics, conf); + return nodeStatusUpdater; + } + +@@ -577,7 +587,7 @@ public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) + .get(4).getState() == ContainerState.RUNNING + && request.getNodeStatus().getContainersStatuses().get(4) + .getContainerId().getId() == 5); +- throw new YarnRuntimeException(""Lost the heartbeat response""); ++ throw new java.net.ConnectException(""Lost the heartbeat response""); + } else if (heartBeatID == 2) { + Assert.assertEquals(request.getNodeStatus().getContainersStatuses() + .size(), 7); +@@ -646,7 +656,63 @@ public RegisterNodeManagerResponse registerNodeManager( + public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) + throws YarnException, IOException { + heartBeatID++; +- throw RPCUtil.getRemoteException(""NodeHeartbeat exception""); ++ throw new java.net.ConnectException( ++ ""NodeHeartbeat exception""); ++ } ++ } ++ ++ private class MyResourceTracker6 implements ResourceTracker { ++ ++ private final Context context; ++ private long rmStartIntervalMS; ++ private boolean rmNeverStart; ++ private final long waitStartTime; ++ ++ public MyResourceTracker6(Context context, long rmStartIntervalMS, ++ boolean rmNeverStart) { ++ this.context = context; ++ this.rmStartIntervalMS = rmStartIntervalMS; ++ this.rmNeverStart = rmNeverStart; ++ this.waitStartTime = System.currentTimeMillis(); ++ } ++ ++ @Override ++ public RegisterNodeManagerResponse registerNodeManager( ++ RegisterNodeManagerRequest request) throws YarnException, IOException, ++ IOException { ++ if (System.currentTimeMillis() - waitStartTime <= rmStartIntervalMS ++ || rmNeverStart) { ++ throw new java.net.ConnectException(""Faking RM start failure as start "" ++ + ""delay timer has not expired.""); ++ } else { ++ NodeId nodeId = request.getNodeId(); ++ Resource resource = request.getResource(); ++ LOG.info(""Registering "" + nodeId.toString()); ++ // NOTE: this really should be checking against the config value ++ InetSocketAddress expected = NetUtils.getConnectAddress( ++ conf.getSocketAddr(YarnConfiguration.NM_ADDRESS, null, -1)); ++ Assert.assertEquals(NetUtils.getHostPortString(expected), ++ nodeId.toString()); ++ Assert.assertEquals(5 * 1024, resource.getMemory()); ++ registeredNodes.add(nodeId); ++ ++ RegisterNodeManagerResponse response = recordFactory ++ .newRecordInstance(RegisterNodeManagerResponse.class); ++ triggered = true; ++ return response; ++ } ++ } ++ ++ @Override ++ public NodeHeartbeatResponse nodeHeartbeat(NodeHeartbeatRequest request) ++ throws YarnException, IOException { ++ NodeStatus nodeStatus = request.getNodeStatus(); ++ nodeStatus.setResponseId(heartBeatID++); ++ ++ NodeHeartbeatResponse nhResponse = YarnServerBuilderUtils. ++ newNodeHeartbeatResponse(heartBeatID, NodeAction.NORMAL, null, ++ null, null, null, 1000L); ++ return nhResponse; + } + } + +@@ -843,8 +909,7 @@ public void testNMConnectionToRM() throws Exception { + final long connectionRetryIntervalSecs = 1; + //Waiting for rmStartIntervalMS, RM will be started + final long rmStartIntervalMS = 2*1000; +- YarnConfiguration conf = createNMConfig(); +- conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, ++ conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, + connectionWaitSecs); + conf.setLong(YarnConfiguration + .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, +@@ -907,8 +972,6 @@ protected NodeStatusUpdater createUpdater(Context context, + } + long duration = System.currentTimeMillis() - waitStartTime; + MyNodeStatusUpdater4 myUpdater = (MyNodeStatusUpdater4) updater; +- Assert.assertTrue(""Updater was never started"", +- myUpdater.getWaitStartTime()>0); + Assert.assertTrue(""NM started before updater triggered"", + myUpdater.isTriggered()); + Assert.assertTrue(""NM should have connected to RM after "" +@@ -1037,13 +1100,13 @@ public void testNodeStatusUpdaterRetryAndNMShutdown() + final long connectionWaitSecs = 1; + final long connectionRetryIntervalSecs = 1; + YarnConfiguration conf = createNMConfig(); +- conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_WAIT_SECS, ++ conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_MAX_WAIT_SECS, + connectionWaitSecs); + conf.setLong(YarnConfiguration + .RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_SECS, + connectionRetryIntervalSecs); + CyclicBarrier syncBarrier = new CyclicBarrier(2); +- nm = new MyNodeManager2(syncBarrier); ++ nm = new MyNodeManager2(syncBarrier, conf); + nm.init(conf); + nm.start(); + try { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java +index 83d21e1640721..cfcf7f6445e63 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java +@@ -117,6 +117,11 @@ protected ResourceTracker getRMClient() { + return new LocalRMInterface(); + }; + ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } ++ + @Override + protected void startStatusUpdater() { + return; // Don't start any updating thread. +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java +index cc529739dea79..144b111f83072 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java +@@ -390,6 +390,11 @@ public RegisterNodeManagerResponse registerNodeManager( + } + }; + }; ++ ++ @Override ++ protected void stopRMProxy() { ++ return; ++ } + }; + }; + }" +367a2b8bf66addf6fd731c54b8436ffdd8ed9061,hadoop,HDFS-2465. Add HDFS support for fadvise readahead- and drop-behind. Contributed by Todd Lipcon.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1190625 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt +index 08a78a07e6a31..8bd74374ac678 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt ++++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt +@@ -772,6 +772,8 @@ Release 0.23.0 - Unreleased + HDFS-2500. Avoid file system operations in BPOfferService thread while + processing deletes. (todd) + ++ HDFS-2465. Add HDFS support for fadvise readahead and drop-behind. (todd) ++ + BUG FIXES + + HDFS-2344. Fix the TestOfflineEditsViewer test failure in 0.23 branch. +diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java +index 9c53bc08796cd..6c10d0e8473bf 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java ++++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java +@@ -54,6 +54,15 @@ public class DFSConfigKeys extends CommonConfigurationKeys { + public static final String DFS_NAMENODE_BACKUP_SERVICE_RPC_ADDRESS_KEY = ""dfs.namenode.backup.dnrpc-address""; + public static final String DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY = ""dfs.datanode.balance.bandwidthPerSec""; + public static final long DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_DEFAULT = 1024*1024; ++ public static final String DFS_DATANODE_READAHEAD_BYTES_KEY = ""dfs.datanode.readahead.bytes""; ++ public static final long DFS_DATANODE_READAHEAD_BYTES_DEFAULT = 0; ++ public static final String DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY = ""dfs.datanode.drop.cache.behind.writes""; ++ public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT = false; ++ public static final String DFS_DATANODE_SYNC_BEHIND_WRITES_KEY = ""dfs.datanode.sync.behind.writes""; ++ public static final boolean DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT = false; ++ public static final String DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY = ""dfs.datanode.drop.cache.behind.reads""; ++ public static final boolean DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT = false; ++ + public static final String DFS_NAMENODE_HTTP_ADDRESS_KEY = ""dfs.namenode.http-address""; + public static final String DFS_NAMENODE_HTTP_ADDRESS_DEFAULT = ""0.0.0.0:50070""; + public static final String DFS_NAMENODE_RPC_ADDRESS_KEY = ""dfs.namenode.rpc-address""; +diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java +index 50e118aaa0093..b935aafd412fb 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java ++++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java +@@ -24,6 +24,7 @@ + import java.io.DataInputStream; + import java.io.DataOutputStream; + import java.io.EOFException; ++import java.io.FileDescriptor; + import java.io.FileOutputStream; + import java.io.IOException; + import java.io.OutputStream; +@@ -46,6 +47,7 @@ + import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration; + import org.apache.hadoop.hdfs.util.DataTransferThrottler; + import org.apache.hadoop.io.IOUtils; ++import org.apache.hadoop.io.nativeio.NativeIO; + import org.apache.hadoop.util.Daemon; + import org.apache.hadoop.util.DataChecksum; + import org.apache.hadoop.util.PureJavaCrc32; +@@ -57,10 +59,13 @@ + class BlockReceiver implements Closeable { + public static final Log LOG = DataNode.LOG; + static final Log ClientTraceLog = DataNode.ClientTraceLog; ++ ++ private static final long CACHE_DROP_LAG_BYTES = 8 * 1024 * 1024; + + private DataInputStream in = null; // from where data are read + private DataChecksum checksum; // from where chunks of a block can be read + private OutputStream out = null; // to block file at local disk ++ private FileDescriptor outFd; + private OutputStream cout = null; // output stream for cehcksum file + private DataOutputStream checksumOut = null; // to crc file at local disk + private int bytesPerChecksum; +@@ -80,6 +85,11 @@ class BlockReceiver implements Closeable { + private final DataNode datanode; + volatile private boolean mirrorError; + ++ // Cache management state ++ private boolean dropCacheBehindWrites; ++ private boolean syncBehindWrites; ++ private long lastCacheDropOffset = 0; ++ + /** The client name. It is empty if a datanode is the client */ + private final String clientname; + private final boolean isClient; +@@ -170,6 +180,8 @@ class BlockReceiver implements Closeable { + this.checksum = DataChecksum.newDataChecksum(in); + this.bytesPerChecksum = checksum.getBytesPerChecksum(); + this.checksumSize = checksum.getChecksumSize(); ++ this.dropCacheBehindWrites = datanode.shouldDropCacheBehindWrites(); ++ this.syncBehindWrites = datanode.shouldSyncBehindWrites(); + + final boolean isCreate = isDatanode || isTransfer + || stage == BlockConstructionStage.PIPELINE_SETUP_CREATE; +@@ -177,6 +189,12 @@ class BlockReceiver implements Closeable { + this.bytesPerChecksum, this.checksumSize); + if (streams != null) { + this.out = streams.dataOut; ++ if (out instanceof FileOutputStream) { ++ this.outFd = ((FileOutputStream)out).getFD(); ++ } else { ++ LOG.warn(""Could not get file descriptor for outputstream of class "" + ++ out.getClass()); ++ } + this.cout = streams.checksumOut; + this.checksumOut = new DataOutputStream(new BufferedOutputStream( + streams.checksumOut, HdfsConstants.SMALL_BUFFER_SIZE)); +@@ -631,6 +649,8 @@ private int receivePacket(long offsetInBlock, long seqno, + ); + + datanode.metrics.incrBytesWritten(len); ++ ++ dropOsCacheBehindWriter(offsetInBlock); + } + } catch (IOException iex) { + datanode.checkDiskError(iex); +@@ -645,6 +665,28 @@ private int receivePacket(long offsetInBlock, long seqno, + return lastPacketInBlock?-1:len; + } + ++ private void dropOsCacheBehindWriter(long offsetInBlock) throws IOException { ++ try { ++ if (outFd != null && ++ offsetInBlock > lastCacheDropOffset + CACHE_DROP_LAG_BYTES) { ++ long twoWindowsAgo = lastCacheDropOffset - CACHE_DROP_LAG_BYTES; ++ if (twoWindowsAgo > 0 && dropCacheBehindWrites) { ++ NativeIO.posixFadviseIfPossible(outFd, 0, lastCacheDropOffset, ++ NativeIO.POSIX_FADV_DONTNEED); ++ } ++ ++ if (syncBehindWrites) { ++ NativeIO.syncFileRangeIfPossible(outFd, lastCacheDropOffset, CACHE_DROP_LAG_BYTES, ++ NativeIO.SYNC_FILE_RANGE_WRITE); ++ } ++ ++ lastCacheDropOffset += CACHE_DROP_LAG_BYTES; ++ } ++ } catch (Throwable t) { ++ LOG.warn(""Couldn't drop os cache behind writer for "" + block, t); ++ } ++ } ++ + void writeChecksumHeader(DataOutputStream mirrorOut) throws IOException { + checksum.writeHeader(mirrorOut); + } +diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockSender.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockSender.java +index 84b38b37e9a14..ca9765ce3ea0f 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockSender.java ++++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockSender.java +@@ -20,6 +20,7 @@ + import java.io.BufferedInputStream; + import java.io.DataInputStream; + import java.io.DataOutputStream; ++import java.io.FileDescriptor; + import java.io.FileInputStream; + import java.io.IOException; + import java.io.InputStream; +@@ -36,6 +37,9 @@ + import org.apache.hadoop.hdfs.protocol.datatransfer.PacketHeader; + import org.apache.hadoop.hdfs.util.DataTransferThrottler; + import org.apache.hadoop.io.IOUtils; ++import org.apache.hadoop.io.ReadaheadPool; ++import org.apache.hadoop.io.ReadaheadPool.ReadaheadRequest; ++import org.apache.hadoop.io.nativeio.NativeIO; + import org.apache.hadoop.net.SocketOutputStream; + import org.apache.hadoop.util.DataChecksum; + +@@ -118,7 +122,9 @@ class BlockSender implements java.io.Closeable { + private DataInputStream checksumIn; + /** Checksum utility */ + private final DataChecksum checksum; +- /** Starting position to read */ ++ /** Initial position to read */ ++ private long initialOffset; ++ /** Current position of read */ + private long offset; + /** Position of last byte to read from block file */ + private final long endOffset; +@@ -142,6 +148,24 @@ class BlockSender implements java.io.Closeable { + private final String clientTraceFmt; + private volatile ChunkChecksum lastChunkChecksum = null; + ++ /** The file descriptor of the block being sent */ ++ private FileDescriptor blockInFd; ++ ++ // Cache-management related fields ++ private final long readaheadLength; ++ private boolean shouldDropCacheBehindRead; ++ private ReadaheadRequest curReadahead; ++ private long lastCacheDropOffset; ++ private static final long CACHE_DROP_INTERVAL_BYTES = 1024 * 1024; // 1MB ++ /** ++ * Minimum length of read below which management of the OS ++ * buffer cache is disabled. ++ */ ++ private static final long LONG_READ_THRESHOLD_BYTES = 256 * 1024; ++ ++ private static ReadaheadPool readaheadPool = ++ ReadaheadPool.getInstance(); ++ + /** + * Constructor + * +@@ -165,6 +189,8 @@ class BlockSender implements java.io.Closeable { + this.corruptChecksumOk = corruptChecksumOk; + this.verifyChecksum = verifyChecksum; + this.clientTraceFmt = clientTraceFmt; ++ this.readaheadLength = datanode.getReadaheadLength(); ++ this.shouldDropCacheBehindRead = datanode.shouldDropCacheBehindReads(); + + synchronized(datanode.data) { + this.replica = getReplica(block, datanode); +@@ -277,6 +303,11 @@ class BlockSender implements java.io.Closeable { + DataNode.LOG.debug(""replica="" + replica); + } + blockIn = datanode.data.getBlockInputStream(block, offset); // seek to offset ++ if (blockIn instanceof FileInputStream) { ++ blockInFd = ((FileInputStream)blockIn).getFD(); ++ } else { ++ blockInFd = null; ++ } + } catch (IOException ioe) { + IOUtils.closeStream(this); + IOUtils.closeStream(blockIn); +@@ -288,6 +319,20 @@ class BlockSender implements java.io.Closeable { + * close opened files. + */ + public void close() throws IOException { ++ if (blockInFd != null && shouldDropCacheBehindRead) { ++ // drop the last few MB of the file from cache ++ try { ++ NativeIO.posixFadviseIfPossible( ++ blockInFd, lastCacheDropOffset, offset - lastCacheDropOffset, ++ NativeIO.POSIX_FADV_DONTNEED); ++ } catch (Exception e) { ++ LOG.warn(""Unable to drop cache on file close"", e); ++ } ++ } ++ if (curReadahead != null) { ++ curReadahead.cancel(); ++ } ++ + IOException ioe = null; + if(checksumIn!=null) { + try { +@@ -304,6 +349,7 @@ public void close() throws IOException { + ioe = e; + } + blockIn = null; ++ blockInFd = null; + } + // throw IOException if there is any + if(ioe!= null) { +@@ -538,10 +584,20 @@ long sendBlock(DataOutputStream out, OutputStream baseStream, + if (out == null) { + throw new IOException( ""out stream is null"" ); + } +- final long initialOffset = offset; ++ initialOffset = offset; + long totalRead = 0; + OutputStream streamForSendChunks = out; + ++ lastCacheDropOffset = initialOffset; ++ ++ if (isLongRead() && blockInFd != null) { ++ // Advise that this file descriptor will be accessed sequentially. ++ NativeIO.posixFadviseIfPossible(blockInFd, 0, 0, NativeIO.POSIX_FADV_SEQUENTIAL); ++ } ++ ++ // Trigger readahead of beginning of file if configured. ++ manageOsCache(); ++ + final long startTime = ClientTraceLog.isInfoEnabled() ? System.nanoTime() : 0; + try { + writeChecksumHeader(out); +@@ -569,6 +625,7 @@ long sendBlock(DataOutputStream out, OutputStream baseStream, + ByteBuffer pktBuf = ByteBuffer.allocate(pktSize); + + while (endOffset > offset) { ++ manageOsCache(); + long len = sendPacket(pktBuf, maxChunksPerPacket, streamForSendChunks, + transferTo, throttler); + offset += len; +@@ -595,6 +652,45 @@ long sendBlock(DataOutputStream out, OutputStream baseStream, + } + return totalRead; + } ++ ++ /** ++ * Manage the OS buffer cache by performing read-ahead ++ * and drop-behind. ++ */ ++ private void manageOsCache() throws IOException { ++ if (!isLongRead() || blockInFd == null) { ++ // don't manage cache manually for short-reads, like ++ // HBase random read workloads. ++ return; ++ } ++ ++ // Perform readahead if necessary ++ if (readaheadLength > 0 && readaheadPool != null) { ++ curReadahead = readaheadPool.readaheadStream( ++ clientTraceFmt, blockInFd, ++ offset, readaheadLength, Long.MAX_VALUE, ++ curReadahead); ++ } ++ ++ // Drop what we've just read from cache, since we aren't ++ // likely to need it again ++ long nextCacheDropOffset = lastCacheDropOffset + CACHE_DROP_INTERVAL_BYTES; ++ if (shouldDropCacheBehindRead && ++ offset >= nextCacheDropOffset) { ++ long dropLength = offset - lastCacheDropOffset; ++ if (dropLength >= 1024) { ++ NativeIO.posixFadviseIfPossible(blockInFd, ++ lastCacheDropOffset, dropLength, ++ NativeIO.POSIX_FADV_DONTNEED); ++ } ++ lastCacheDropOffset += CACHE_DROP_INTERVAL_BYTES; ++ } ++ } ++ ++ private boolean isLongRead() { ++ return (endOffset - offset) > LONG_READ_THRESHOLD_BYTES; ++ } ++ + + /** + * Write checksum header to the output stream +diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java +index 3f7733608999c..5be82dd59d8cf 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java ++++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java +@@ -104,6 +104,7 @@ + import org.apache.hadoop.fs.LocalFileSystem; + import org.apache.hadoop.fs.Path; + import org.apache.hadoop.fs.permission.FsPermission; ++import org.apache.hadoop.hdfs.DFSConfigKeys; + import org.apache.hadoop.hdfs.DFSUtil; + import org.apache.hadoop.hdfs.HDFSPolicyProvider; + import org.apache.hadoop.hdfs.HdfsConfiguration; +@@ -410,6 +411,11 @@ void refreshNamenodes(Configuration conf) + int socketTimeout; + int socketWriteTimeout = 0; + boolean transferToAllowed = true; ++ private boolean dropCacheBehindWrites = false; ++ private boolean syncBehindWrites = false; ++ private boolean dropCacheBehindReads = false; ++ private long readaheadLength = 0; ++ + int writePacketSize = 0; + boolean isBlockTokenEnabled; + BlockPoolTokenSecretManager blockPoolTokenSecretManager; +@@ -493,6 +499,20 @@ private void initConfig(Configuration conf) { + DFS_DATANODE_TRANSFERTO_ALLOWED_DEFAULT); + this.writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY, + DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT); ++ ++ this.readaheadLength = conf.getLong( ++ DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_KEY, ++ DFSConfigKeys.DFS_DATANODE_READAHEAD_BYTES_DEFAULT); ++ this.dropCacheBehindWrites = conf.getBoolean( ++ DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_KEY, ++ DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_WRITES_DEFAULT); ++ this.syncBehindWrites = conf.getBoolean( ++ DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_KEY, ++ DFSConfigKeys.DFS_DATANODE_SYNC_BEHIND_WRITES_DEFAULT); ++ this.dropCacheBehindReads = conf.getBoolean( ++ DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_KEY, ++ DFSConfigKeys.DFS_DATANODE_DROP_CACHE_BEHIND_READS_DEFAULT); ++ + this.blockReportInterval = conf.getLong(DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, + DFS_BLOCKREPORT_INTERVAL_MSEC_DEFAULT); + this.initialBlockReportDelay = conf.getLong( +@@ -2859,4 +2879,20 @@ public Long getBalancerBandwidth() { + (DataXceiverServer) this.dataXceiverServer.getRunnable(); + return dxcs.balanceThrottler.getBandwidth(); + } ++ ++ long getReadaheadLength() { ++ return readaheadLength; ++ } ++ ++ boolean shouldDropCacheBehindWrites() { ++ return dropCacheBehindWrites; ++ } ++ ++ boolean shouldDropCacheBehindReads() { ++ return dropCacheBehindReads; ++ } ++ ++ boolean shouldSyncBehindWrites() { ++ return syncBehindWrites; ++ } + }" +e15bf1a95abeec1a39f212d65887d88a19f9f68e,drools,-fixed MVEL parser context naming issue.--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@23995 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java +index 8206e2099a2..4ddff78583d 100644 +--- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java ++++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/mvel/MVELDialect.java +@@ -134,9 +134,7 @@ public class MVELDialect + + private boolean strictMode; + private int languageLevel; +- public static final Object COMPILER_LOCK = new Object(); +- +- private static AtomicInteger nameCounter = new AtomicInteger(); ++ public static final Object COMPILER_LOCK = new Object(); + + public MVELDialect(PackageBuilder builder, + PackageRegistry pkgRegistry, +@@ -666,13 +664,17 @@ public ParserContext getParserContext(final Dialect.AnalysisResult analysis, + // @todo proper source file name + String name; + if ( context != null && context.getPkg() != null & context.getPkg().getName() != null ) { +- name = context.getPkg().getName(); ++ if ( context instanceof RuleBuildContext ) { ++ name = context.getPkg().getName() + ""."" + ((RuleBuildContext)context).getRuleDescr().getClassName(); ++ } else { ++ name = context.getPkg().getName() + "".Unknown""; ++ } + } else { +- name = """"; ++ name = ""Unknown""; + } + final ParserContext parserContext = new ParserContext( this.imports, + null, +- name + ""_"" + nameCounter.getAndIncrement() ); ++ name ); + // getRuleDescr().getClassName() ); + + for ( Iterator it = this.packageImports.values().iterator(); it.hasNext(); ) {" +a09d266b247b185054d0ab0dfdb6e8dc2e8898bc,orientdb,Minor: removed some warnings--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +ca849f196990eec942468efaef3719f829c265eb,orientdb,Improved management of distributed cluster nodes--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +10c4f93ae28a5c0746783dd4cbec6bf20a11bad8,evllabs$jgaap,"slight optimizations to distances +",p,https://github.com/evllabs/jgaap,"diff --git a/src/com/jgaap/distances/BrayCurtisDistance.java b/src/com/jgaap/distances/BrayCurtisDistance.java +index 6021e5466..14de61bc5 100644 +--- a/src/com/jgaap/distances/BrayCurtisDistance.java ++++ b/src/com/jgaap/distances/BrayCurtisDistance.java +@@ -3,7 +3,6 @@ + import java.util.HashSet; + import java.util.Set; + +-import com.jgaap.generics.DistanceCalculationException; + import com.jgaap.generics.DistanceFunction; + import com.jgaap.generics.Event; + import com.jgaap.generics.EventMap; +@@ -34,8 +33,7 @@ public boolean showInGUI() { + } + + @Override +- public double distance(EventMap unknownEventMap, EventMap knownEventMap) +- throws DistanceCalculationException { ++ public double distance(EventMap unknownEventMap, EventMap knownEventMap) { + + Set events = new HashSet(unknownEventMap.uniqueEvents()); + events.addAll(knownEventMap.uniqueEvents()); +@@ -43,8 +41,10 @@ public double distance(EventMap unknownEventMap, EventMap knownEventMap) + double distance = 0.0, sumNumer = 0.0, sumDenom = 0.0; + + for(Event event: events){ +- sumNumer += Math.abs(unknownEventMap.relativeFrequency(event) - knownEventMap.relativeFrequency(event)); +- sumDenom += unknownEventMap.relativeFrequency(event) + knownEventMap.relativeFrequency(event); ++ double known = knownEventMap.relativeFrequency(event); ++ double unknown = unknownEventMap.relativeFrequency(event); ++ sumNumer += Math.abs(unknown - known); ++ sumDenom += unknown + known; + } + distance = sumNumer / sumDenom; + return distance; +diff --git a/src/com/jgaap/distances/SoergleDistance.java b/src/com/jgaap/distances/SoergleDistance.java +index 8cfef0782..432182454 100644 +--- a/src/com/jgaap/distances/SoergleDistance.java ++++ b/src/com/jgaap/distances/SoergleDistance.java +@@ -43,8 +43,10 @@ public double distance(EventMap unknownEventMap, EventMap knownEventMap) + double distance = 0.0, sumNumer = 0.0, sumDenom = 0.0; + + for(Event event : events){ +- sumNumer += Math.abs(unknownEventMap.relativeFrequency(event) - knownEventMap.relativeFrequency(event)); +- sumDenom += Math.max(unknownEventMap.relativeFrequency(event), knownEventMap.relativeFrequency(event)); ++ double known = knownEventMap.relativeFrequency(event); ++ double unknown = unknownEventMap.relativeFrequency(event); ++ sumNumer += Math.abs(unknown - known); ++ sumDenom += Math.max(unknown, known); + } + distance = sumNumer / sumDenom;" +741dd3b80dc20cf513cf374ad938a1a4fe965887,Vala,"Change many static delegates to has_target = false +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +3d53bdc3d320973bcb0ca67047a59e0e58cee0b3,Mylyn Reviews,"cleanup warnings + +* Fix build path issue +* Minor Cleanup for Action + +Change-Id: I4e4bda10624e16d4f69545a953ae80d84939c1dd +",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties +index e10dcceb..cc91072e 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.dsl/build.properties +@@ -1,5 +1,4 @@ +-source.. = src/,\ +- src-gen/ ++source.. = src/ + bin.includes = META-INF/,\ + .,\ +- plugin.xml +\ No newline at end of file ++ plugin.xml +diff --git a/tbr/org.eclipse.mylyn.versions.context.ui/src/org/eclipse/mylyn/versions/tasks/context/ImportAsContextAction.java b/tbr/org.eclipse.mylyn.versions.context.ui/src/org/eclipse/mylyn/versions/tasks/context/ImportAsContextAction.java +index 059158ce..68ea94c6 100644 +--- a/tbr/org.eclipse.mylyn.versions.context.ui/src/org/eclipse/mylyn/versions/tasks/context/ImportAsContextAction.java ++++ b/tbr/org.eclipse.mylyn.versions.context.ui/src/org/eclipse/mylyn/versions/tasks/context/ImportAsContextAction.java +@@ -41,7 +41,7 @@ public ImportAsContextAction() { + } + + public void run() { +- ++ throw new java.lang.UnsupportedOperationException(); + } + + private String formatHandleString(Change c) { +@@ -71,11 +71,9 @@ public void run(ITaskVersionsModel model) { + if (elementNotDeleted(c)) { + InteractionEvent interactionEvent = new InteractionEvent( + Kind.SELECTION, null, formatHandleString(c), ORIGIN); ++ ContextCore.getContextManager().processInteractionEvent(interactionEvent); + +- ContextCore.getContextManager().processInteractionEvent( +- interactionEvent); +- MonitorUiPlugin.getDefault().notifyInteractionObserved( +- interactionEvent); ++ MonitorUiPlugin.getDefault().notifyInteractionObserved(interactionEvent); + } + } + } +diff --git a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java +index 18c1d070..bc4cb83d 100644 +--- a/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java ++++ b/tbr/org.eclipse.mylyn.versions.tasks.mapper.tests/src/org/eclipse/mylyn/versions/tasks/mapper/generic/GenericTaskChangesetMapperTest.java +@@ -1,3 +1,13 @@ ++/******************************************************************************* ++ * Copyright (c) 2012 Research Group for Industrial Software (INSO), Vienna University of Technology. ++ * 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: ++ * Research Group for Industrial Software (INSO), Vienna University of Technology - initial API and implementation ++ *******************************************************************************/ + package org.eclipse.mylyn.versions.tasks.mapper.generic; + + import static org.junit.Assert.*; +@@ -16,7 +26,11 @@ + import org.junit.Test; + import org.mockito.invocation.InvocationOnMock; + import org.mockito.stubbing.Answer; +- ++/** ++ * ++ * @author Kilian Matt ++ * ++ */ + public class GenericTaskChangesetMapperTest { + + private GenericTaskChangesetMapper mapper; +diff --git a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/internal/versions/tasks/ui/ChangesetPart.java b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/internal/versions/tasks/ui/ChangesetPart.java +index 49563f3c..bcfffdae 100644 +--- a/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/internal/versions/tasks/ui/ChangesetPart.java ++++ b/tbr/org.eclipse.mylyn.versions.tasks.ui/src/org/eclipse/mylyn/internal/versions/tasks/ui/ChangesetPart.java +@@ -45,14 +45,13 @@ + import org.eclipse.ui.forms.widgets.Section; + + /** +- * + * @author Kilian Matt +- * + */ + @SuppressWarnings(""restriction"") + public class ChangesetPart extends AbstractTaskEditorPart { + private TableViewer table; +- private ChangesetModel model = new ChangesetModel(); ++ ++ private final ChangesetModel model = new ChangesetModel(); + + public ChangesetPart() { + setPartName(""Changeset""); +@@ -67,8 +66,7 @@ public void createControl(Composite parent, FormToolkit toolkit) { + createTable(composite); + } + +- private Composite createContentComposite(FormToolkit toolkit, +- Section createSection) { ++ private Composite createContentComposite(FormToolkit toolkit, Section createSection) { + Composite composite = toolkit.createComposite(createSection); + createSection.setClient(composite); + composite.setLayout(new FillLayout()); +@@ -107,10 +105,10 @@ protected void fillToolBar(ToolBarManager toolBarManager) { + super.fillToolBar(toolBarManager); + toolBarManager.add(new IncludeSubTasksAction(model)); + List contributions = InternalExtensionPointLoader.loadActionContributions(); +- for(final ITaskVersionsContributionAction action : contributions) { ++ for (final ITaskVersionsContributionAction action : contributions) { + toolBarManager.add(new ActionDelegate(action) { +- @Override +- public void runWithEvent(Event event) { ++ @Override ++ public void runWithEvent(Event event) { + action.run(model); + } + }); +@@ -120,37 +118,33 @@ public void runWithEvent(Event event) { + private void registerContextMenu(TableViewer table) { + MenuManager menuManager = new MenuManager(); + menuManager.setRemoveAllWhenShown(true); +- getTaskEditorPage().getEditorSite().registerContextMenu( +- ""org.eclipse.mylyn.versions.changesets"", menuManager, table, +- true); ++ getTaskEditorPage().getEditorSite().registerContextMenu(""org.eclipse.mylyn.versions.changesets"", menuManager, ++ table, true); + Menu menu = menuManager.createContextMenu(table.getControl()); + table.getTable().setMenu(menu); + } + + private void addColumn(TableViewer table, String name) { +- TableViewerColumn tableViewerColumn = new TableViewerColumn(table, +- SWT.LEFT); ++ TableViewerColumn tableViewerColumn = new TableViewerColumn(table, SWT.LEFT); + tableViewerColumn.getColumn().setText(name); + tableViewerColumn.getColumn().setWidth(100); + } + +- private AbstractChangesetMappingProvider determineBestProvider( +- final ITask task) { ++ private AbstractChangesetMappingProvider determineBestProvider(final ITask task) { + AbstractChangesetMappingProvider bestProvider = new NullProvider(); + int score = Integer.MIN_VALUE; +- for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil +- .getMappingProviders()) { ++ for (AbstractChangesetMappingProvider mappingProvider : TaskChangesetUtil.getMappingProviders()) { + if (score < mappingProvider.getScoreFor(task)) { + bestProvider = mappingProvider; + } + } + return bestProvider; + } +- private static class NullProvider extends AbstractChangesetMappingProvider{ ++ ++ private static class NullProvider extends AbstractChangesetMappingProvider { + + @Override +- public void getChangesetsForTask(IChangeSetMapping mapping, +- IProgressMonitor monitor) throws CoreException { ++ public void getChangesetsForTask(IChangeSetMapping mapping, IProgressMonitor monitor) throws CoreException { + } + + @Override +@@ -160,8 +154,7 @@ public int getScoreFor(ITask task) { + + } + +- private IChangeSetMapping createChangeSetMapping(final ITask task, +- final List changesets) { ++ private IChangeSetMapping createChangeSetMapping(final ITask task, final List changesets) { + return new IChangeSetMapping() { + + public ITask getTask() { +@@ -207,8 +200,7 @@ public List getInput() { + if (task instanceof ITaskContainer) { + ITaskContainer taskContainer = (ITaskContainer) task; + for (ITask subTask : taskContainer.getChildren()) { +- changesetsMapping.add(createChangeSetMapping(subTask, +- changesets)); ++ changesetsMapping.add(createChangeSetMapping(subTask, changesets)); + } + } + } +@@ -221,7 +213,8 @@ public void run() { + provider.getChangesetsForTask(csm, new NullProgressMonitor()); + } + } catch (CoreException e) { +- getTaskEditorPage().getTaskEditor().setMessage(""An exception occurred "" + e.getMessage(), IMessageProvider.ERROR); ++ getTaskEditorPage().getTaskEditor().setMessage(""An exception occurred "" + e.getMessage(), ++ IMessageProvider.ERROR); + } + }" +770ee735efa935a21b9992090eb063732e826ba5,ReactiveX-RxJava,Add unit tests for recursive scheduler usage--These tests came from @mairbek at https://github.com/Netflix/RxJava/pull/229-issuecomment-16115941-,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java +index ec247d0b95..a4760ff65e 100644 +--- a/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java ++++ b/rxjava-core/src/test/java/rx/concurrency/TestSchedulers.java +@@ -16,20 +16,24 @@ + package rx.concurrency; + + import static org.junit.Assert.*; ++import static org.mockito.Mockito.*; + + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; ++import java.util.concurrent.atomic.AtomicBoolean; + import java.util.concurrent.atomic.AtomicInteger; +-import java.util.concurrent.atomic.AtomicReference; + + import org.junit.Test; + + import rx.Observable; + import rx.Observer; ++import rx.Scheduler; + import rx.Subscription; ++import rx.subscriptions.BooleanSubscription; + import rx.subscriptions.Subscriptions; + import rx.util.functions.Action1; + import rx.util.functions.Func1; ++import rx.util.functions.Func2; + + public class TestSchedulers { + +@@ -245,4 +249,114 @@ public void call(Integer t) { + assertEquals(5, count.get()); + } + ++ @Test ++ public void testRecursiveScheduler1() { ++ Observable obs = Observable.create(new Func1, Subscription>() { ++ @Override ++ public Subscription call(final Observer observer) { ++ return Schedulers.currentThread().schedule(0, new Func2() { ++ @Override ++ public Subscription call(Scheduler scheduler, Integer i) { ++ if (i > 42) { ++ observer.onCompleted(); ++ return Subscriptions.empty(); ++ } ++ ++ observer.onNext(i); ++ ++ return scheduler.schedule(i + 1, this); ++ } ++ }); ++ } ++ }); ++ ++ final AtomicInteger lastValue = new AtomicInteger(); ++ obs.forEach(new Action1() { ++ ++ @Override ++ public void call(Integer v) { ++ System.out.println(""Value: "" + v); ++ lastValue.set(v); ++ } ++ }); ++ ++ assertEquals(42, lastValue.get()); ++ } ++ ++ @Test ++ public void testRecursiveScheduler2() throws InterruptedException { ++ // use latches instead of Thread.sleep ++ final CountDownLatch latch = new CountDownLatch(10); ++ final CountDownLatch completionLatch = new CountDownLatch(1); ++ ++ Observable obs = Observable.create(new Func1, Subscription>() { ++ @Override ++ public Subscription call(final Observer observer) { ++ ++ return Schedulers.threadPoolForComputation().schedule(new BooleanSubscription(), new Func2() { ++ @Override ++ public Subscription call(Scheduler scheduler, BooleanSubscription cancel) { ++ if (cancel.isUnsubscribed()) { ++ observer.onCompleted(); ++ completionLatch.countDown(); ++ return Subscriptions.empty(); ++ } ++ ++ observer.onNext(42); ++ latch.countDown(); ++ ++ try { ++ Thread.sleep(1); ++ } catch (InterruptedException e) { ++ e.printStackTrace(); ++ } ++ ++ scheduler.schedule(cancel, this); ++ ++ return cancel; ++ } ++ }); ++ } ++ }); ++ ++ @SuppressWarnings(""unchecked"") ++ Observer o = mock(Observer.class); ++ ++ final AtomicInteger count = new AtomicInteger(); ++ final AtomicBoolean completed = new AtomicBoolean(false); ++ Subscription subscribe = obs.subscribe(new Observer() { ++ @Override ++ public void onCompleted() { ++ System.out.println(""Completed""); ++ completed.set(true); ++ } ++ ++ @Override ++ public void onError(Exception e) { ++ System.out.println(""Error""); ++ } ++ ++ @Override ++ public void onNext(Integer args) { ++ count.incrementAndGet(); ++ System.out.println(args); ++ } ++ }); ++ ++ if (!latch.await(5000, TimeUnit.MILLISECONDS)) { ++ fail(""Timed out waiting on onNext latch""); ++ } ++ ++ // now unsubscribe and ensure it stops the recursive loop ++ subscribe.unsubscribe(); ++ System.out.println(""unsubscribe""); ++ ++ if (!completionLatch.await(5000, TimeUnit.MILLISECONDS)) { ++ fail(""Timed out waiting on completion latch""); ++ } ++ ++ assertEquals(10, count.get()); // wondering if this could be 11 in a race condition (which would be okay due to how unsubscribe works ... just it would make this test non-deterministic) ++ assertTrue(completed.get()); ++ } ++ + }" +1257196d255cf3697ab869a86eb6f84034232f78,orientdb,Fixed problem of ConcurrentModificationException- reported by Bayoda: the problem should be due to a wrong isolation on Map in- cache: used exclusive lock even for keys() and get().--,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +3a5efd71396f7febeee17b268071b5a07cba27c3,camel,CAMEL-4071 clean up the camel OSGi integration- test and load the karaf spring feature first--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1133394 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/tests/camel-itest-osgi/pom.xml b/tests/camel-itest-osgi/pom.xml +index a1352a1716b4f..f6b8abc19f577 100644 +--- a/tests/camel-itest-osgi/pom.xml ++++ b/tests/camel-itest-osgi/pom.xml +@@ -345,6 +345,7 @@ + + + ${spring-version} ++ ${karaf-version} + + + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java +index 8c9c2a2932c97..692426aa17002 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/OSGiIntegrationTestSupport.java +@@ -72,39 +72,46 @@ protected void setThreadContextClassLoader() { + } + + public static UrlReference getCamelKarafFeatureUrl() { +- String springVersion = System.getProperty(""springVersion""); +- System.out.println(""*** The spring version is "" + springVersion + "" ***""); +- ++ + String type = ""xml/features""; + return mavenBundle().groupId(""org.apache.camel.karaf""). + artifactId(""apache-camel"").versionAsInProject().type(type); + } + + public static UrlReference getKarafFeatureUrl() { +- String karafVersion = ""2.2.1""; ++ String karafVersion = System.getProperty(""karafVersion""); + System.out.println(""*** The karaf version is "" + karafVersion + "" ***""); + + String type = ""xml/features""; + return mavenBundle().groupId(""org.apache.karaf.assemblies.features""). + artifactId(""standard"").version(karafVersion).type(type); + } +- +- @Configuration +- public static Option[] configure() throws Exception { ++ ++ public static Option[] getDefaultCamelKarafOptions() { + Option[] options = combine( + // Default karaf environment + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), ++ Helper.setLogLevel(""WARN"")), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test""), +- ++ ""camel-core"", ""camel-spring"", ""camel-test""), ++ + workingDirectory(""target/paxrunner/""), + + equinox(), + felix()); ++ return options; ++ } ++ ++ @Configuration ++ public static Option[] configure() throws Exception { ++ Option[] options = combine( ++ getDefaultCamelKarafOptions()); + + // for remote debugging + // vmOption(""-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5008""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java +index 9cc421830c948..d6b6da8a274ba 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ahc/AhcTest.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -26,11 +25,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * +@@ -70,17 +66,11 @@ public void configure() { + @Configuration + public static Option[] configure() throws Exception { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components ++ getDefaultCamelKarafOptions(), ++ ++ // using the features to install other camel components + scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-ahc""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ ""camel-jetty"", ""camel-ahc"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java +index 48a5708219c28..6be307e76766e 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3IntegrationTest.java +@@ -25,25 +25,15 @@ + import org.apache.camel.Processor; + import org.apache.camel.component.aws.s3.S3Constants; + import org.apache.camel.component.mock.MockEndpoint; +-import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +-import org.ops4j.pax.exam.Option; +-import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.OptionUtils.combine; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; +- + @RunWith(JUnit4TestRunner.class) + @Ignore(""Test fails"") +-public class AwsS3IntegrationTest extends OSGiIntegrationSpringTestSupport { ++public class AwsS3IntegrationTest extends AwsTestSupport { + + @EndpointInject(uri = ""mock:result"") + private MockEndpoint result; +@@ -109,22 +99,4 @@ private void assertResponseMessage(Message message) { + assertEquals(""3a5c8b1ad448bca04584ecb55b836264"", message.getHeader(S3Constants.E_TAG)); + assertNull(message.getHeader(S3Constants.VERSION_ID)); + } +- +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java +index 7a5ec944a0cfc..c6adb7c93c858 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsS3Test.java +@@ -41,7 +41,7 @@ + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) +-public class AwsS3Test extends OSGiIntegrationSpringTestSupport { ++public class AwsS3Test extends AwsTestSupport { + + @EndpointInject(uri = ""mock:result-s3"") + private MockEndpoint result; +@@ -108,21 +108,4 @@ private void assertResponseMessage(Message message) { + assertNull(message.getHeader(S3Constants.VERSION_ID)); + } + +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java +index 3be6631b863e8..68c9439be01ae 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsIntegrationTest.java +@@ -20,25 +20,15 @@ + import org.apache.camel.ExchangePattern; + import org.apache.camel.Processor; + import org.apache.camel.component.aws.sns.SnsConstants; +-import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +-import org.ops4j.pax.exam.Option; +-import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.OptionUtils.combine; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; +- + @RunWith(JUnit4TestRunner.class) + @Ignore(""Must be manually tested. Provide your own accessKey and secretKey in CamelIntegrationContext.xml!"") +-public class AwsSnsIntegrationTest extends OSGiIntegrationSpringTestSupport { ++public class AwsSnsIntegrationTest extends AwsTestSupport { + + @Override + protected OsgiBundleXmlApplicationContext createApplicationContext() { +@@ -69,21 +59,5 @@ public void process(Exchange exchange) throws Exception { + assertNotNull(exchange.getOut().getHeader(SnsConstants.MESSAGE_ID)); + } + +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java +index a9f08d891612d..1c601d647842e 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSnsTest.java +@@ -36,7 +36,7 @@ + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) +-public class AwsSnsTest extends OSGiIntegrationSpringTestSupport { ++public class AwsSnsTest extends AwsTestSupport { + + @Override + protected OsgiBundleXmlApplicationContext createApplicationContext() { +@@ -66,22 +66,5 @@ public void process(Exchange exchange) throws Exception { + + assertEquals(""dcc8ce7a-7f18-4385-bedd-b97984b4363c"", exchange.getOut().getHeader(SnsConstants.MESSAGE_ID)); + } +- +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java +index a6938b3829655..3b9288a88da0d 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsIntegrationTest.java +@@ -22,25 +22,15 @@ + import org.apache.camel.Processor; + import org.apache.camel.component.aws.sqs.SqsConstants; + import org.apache.camel.component.mock.MockEndpoint; +-import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +-import org.ops4j.pax.exam.Option; +-import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.OptionUtils.combine; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; +- + @RunWith(JUnit4TestRunner.class) + @Ignore(""Must be manually tested. Provide your own accessKey and secretKey in CamelIntegrationContext.xml!"") +-public class AwsSqsIntegrationTest extends OSGiIntegrationSpringTestSupport { ++public class AwsSqsIntegrationTest extends AwsTestSupport { + + @EndpointInject(uri = ""mock:result"") + private MockEndpoint result; +@@ -95,22 +85,4 @@ public void process(Exchange exchange) throws Exception { + assertNotNull(exchange.getOut().getHeader(SqsConstants.MESSAGE_ID)); + assertEquals(""6a1559560f67c5e7a7d5d838bf0272ee"", exchange.getOut().getHeader(SqsConstants.MD5_OF_BODY)); + } +- +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java +index 1247a68cd05c6..9a8c5086f6f49 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsSqsTest.java +@@ -22,23 +22,14 @@ + import org.apache.camel.Processor; + import org.apache.camel.component.aws.sqs.SqsConstants; + import org.apache.camel.component.mock.MockEndpoint; +-import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; +-import org.ops4j.pax.exam.Option; +-import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.OptionUtils.combine; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) +-public class AwsSqsTest extends OSGiIntegrationSpringTestSupport { ++public class AwsSqsTest extends AwsTestSupport { + + @EndpointInject(uri = ""mock:result"") + private MockEndpoint result; +@@ -94,21 +85,5 @@ public void process(Exchange exchange) throws Exception { + assertEquals(""6a1559560f67c5e7a7d5d838bf0272ee"", exchange.getOut().getHeader(SqsConstants.MD5_OF_BODY)); + } + +- @Configuration +- public static Option[] configure() { +- Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-aws""), +- workingDirectory(""target/paxrunner/""), +- equinox(), +- felix()); +- +- return options; +- } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java +new file mode 100644 +index 0000000000000..629f41db6d05f +--- /dev/null ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/aws/AwsTestSupport.java +@@ -0,0 +1,42 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++ ++package org.apache.camel.itest.osgi.aws; ++ ++import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; ++import org.ops4j.pax.exam.Option; ++import org.ops4j.pax.exam.junit.Configuration; ++import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; ++ ++import static org.ops4j.pax.exam.OptionUtils.combine; ++import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; ++ ++ ++public abstract class AwsTestSupport extends OSGiIntegrationSpringTestSupport { ++ ++ ++ @Configuration ++ public static Option[] configure() { ++ Option[] options = combine( ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-aws"")); ++ ++ return options; ++ } ++ ++} +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java +index bb50885b4eafd..4f90ea4175f3a 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/bean/validator/BeanValidatorTest.java +@@ -20,21 +20,16 @@ + import org.apache.camel.Exchange; + import org.apache.camel.Processor; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; +-import org.ops4j.pax.swissbox.tinybundles.dp.Constants; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; ++ + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; +-import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle; +-import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.withBnd; ++ + + @RunWith(JUnit4TestRunner.class) + public class BeanValidatorTest extends OSGiIntegrationTestSupport { +@@ -64,23 +59,13 @@ public void process(Exchange exchange) throws Exception { + Car createCar(String manufacturer, String licencePlate) { + return new CarWithAnnotations(manufacturer, licencePlate); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-bean-validator""), +- +- workingDirectory(""target/paxrunner/""), +- +- equinox(), +- felix()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-bean-validator"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java +index 9b4e4d4e74242..75a20aa3bb782 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintExplicitPropertiesRouteTest.java +@@ -91,6 +91,9 @@ public static Option[] configure() throws Exception { + .set(Constants.BUNDLE_SYMBOLICNAME, BlueprintExplicitPropertiesRouteTest.class.getName()) + .build()).noStart(), + ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), ++ + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-blueprint"", ""camel-test""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java +index f2f7dfc9722ca..378875caa6467 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/BlueprintPropertiesRouteTest.java +@@ -90,6 +90,8 @@ public static Option[] configure() throws Exception { + // install blueprint requirements + mavenBundle(""org.apache.felix"", ""org.apache.felix.configadmin""), + ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-blueprint"", ""camel-test""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java +index 6287094266775..b557b1f666b04 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint2Test.java +@@ -188,6 +188,8 @@ public static Option[] configure() throws Exception { + .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") + .build()).noStart(), + ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""jetty""), + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-blueprint"", ""camel-test"", ""camel-mail"", ""camel-jaxb"", ""camel-jms""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java +index 0e6799657cfcf..1f6a27908d399 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint3Test.java +@@ -112,6 +112,9 @@ public static Option[] configure() throws Exception { + .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle9"") + .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") + .build()).noStart(), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java +index dacff6254d5d7..ba5d36c80c1c6 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprint4Test.java +@@ -91,6 +91,9 @@ public static Option[] configure() throws Exception { + .add(""org/apache/camel/itest/osgi/blueprint/example.vm"", OSGiBlueprintTestSupport.class.getResource(""example.vm"")) + .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle20"") + .build()).noStart(), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java +index a2e39070aa0f3..1600985f58966 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/CamelBlueprintTest.java +@@ -146,6 +146,9 @@ public static Option[] configure() throws Exception { + .set(Constants.BUNDLE_SYMBOLICNAME, ""CamelBlueprintTestBundle5"") + .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") + .build()).noStart(), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java +index d1def0e19acf9..c1961004d98ee 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/blueprint/OSGiBlueprintHelloWorldTest.java +@@ -86,6 +86,9 @@ public static Option[] configure() throws Exception { + .add(""OSGI-INF/blueprint/test.xml"", OSGiBlueprintTestSupport.class.getResource(""blueprint-13.xml"")) + .set(Constants.BUNDLE_SYMBOLICNAME, OSGiBlueprintHelloWorldTest.class.getName()) + .build()).noStart(), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java +index ddcd5c1a6d2f3..47b6e9539b32e 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheManagerFactoryRefTest.java +@@ -26,18 +26,14 @@ + import org.apache.camel.component.cache.CacheEndpoint; + import org.apache.camel.component.cache.CacheManagerFactory; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class CacheManagerFactoryRefTest extends OSGiIntegrationTestSupport { +@@ -78,25 +74,16 @@ public void configure() { + } + }; + } +- ++ ++ ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax +- // logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures( +- getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); ++ + return options; + } + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java +index 12a06c702fe40..4a82d52ffa909 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheRoutesManagementTest.java +@@ -26,18 +26,15 @@ + import org.apache.camel.component.cache.CacheConstants; + import org.apache.camel.component.cache.CacheManagerFactory; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; ++ + + @RunWith(JUnit4TestRunner.class) + public class CacheRoutesManagementTest extends OSGiIntegrationTestSupport { +@@ -100,24 +97,14 @@ public void configure() { + }; + } + ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax +- // logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures( +- getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); ++ + return options; + } + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java +index 240ea6204226a..aef41d4f7bbdf 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/CacheTest.java +@@ -19,18 +19,14 @@ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.cache.CacheConstants; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class CacheTest extends OSGiIntegrationTestSupport { +@@ -66,19 +62,11 @@ public void configure() { + + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cache""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-cache"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java +index 8fac6b558cee8..ef3df9dfef17a 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cache/replication/CacheReplicationTest.java +@@ -20,6 +20,7 @@ + import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; ++ + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; +@@ -70,6 +71,9 @@ public static Option[] configure() throws Exception { + // this is how you set the default log level when using pax + // logging (logProfile) + Helper.setLogLevel(""WARN"")), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + + // using the features to install AMQ + scanFeatures(""mvn:org.apache.activemq/activemq-karaf/5.5.0/xml/features"", +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java +index 98a749a79f76d..69f41bca0b920 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/cxf/CxfProxyExampleTest.java +@@ -88,6 +88,9 @@ public static Option[] configure() throws Exception { + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java +index 5f2c37a493f26..14e805cf3f88d 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/dozer/DozerTest.java +@@ -27,11 +27,10 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; ++ + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; ++ + + /** + * @version +@@ -66,23 +65,14 @@ public void testDozer() throws Exception { + + assertMockEndpointsSatisfied(); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-dozer""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-dozer"")); ++ + return options; + } + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java +index 7f22127e58a67..bd6bcbbb8bac1 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/exec/ExecTest.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -26,11 +25,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + @Ignore(""We need a test which runs on all platforms"") +@@ -52,23 +48,15 @@ public void configure() { + }; + } + +- + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-exec""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-exec"")); + + return options; + } + ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java +index d14d06ed1b218..bde59afb9f502 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/freemarker/FreemarkerTest.java +@@ -22,18 +22,14 @@ + import org.apache.camel.Processor; + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class FreemarkerTest extends OSGiIntegrationTestSupport { +@@ -64,20 +60,14 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-freemarker""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-freemarker"")); + + return options; + } ++ ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java +index b4f48c1400b36..7a5a1b460e19f 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/ftp/FtpTest.java +@@ -62,6 +62,9 @@ public static Option[] configure() throws Exception { + mavenBundle().groupId(""org.apache.ftpserver"").artifactId(""ftpserver-core"").version(""1.0.5""), + mavenBundle().groupId(""org.apache.ftpserver"").artifactId(""ftplet-api"").version(""1.0.5""), + ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), ++ + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-ftp""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java +index d575d3771b278..39e9346b42a16 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/groovy/GroovyTest.java +@@ -19,18 +19,15 @@ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; ++ + + @RunWith(JUnit4TestRunner.class) + public class GroovyTest extends OSGiIntegrationTestSupport { +@@ -52,19 +49,11 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-groovy""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-groovy"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java +index 8d25c4e8825c6..ff151bc9c603c 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hawtdb/HawtDBAggregateRouteTest.java +@@ -24,18 +24,14 @@ + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; + import org.apache.camel.processor.aggregate.AggregationStrategy; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class HawtDBAggregateRouteTest extends OSGiIntegrationTestSupport { +@@ -91,21 +87,13 @@ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { + return oldExchange; + } + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-hawtdb""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-hawtdb"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java +index afe4473efd4bd..2c110c8a0a09d 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7DataFormatTest.java +@@ -29,11 +29,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class HL7DataFormatTest extends OSGiIntegrationTestSupport { +@@ -105,22 +102,15 @@ private static String createHL7AsString() { + body.append(line8); + return body.toString(); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-hl7""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-hl7"")); ++ + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java +index 61ba7e7c9dc94..a799df9982bdd 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/hl7/HL7MLLPCodecTest.java +@@ -19,7 +19,6 @@ + import org.apache.camel.Exchange; + import org.apache.camel.Processor; + import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; +@@ -27,12 +26,8 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.CoreOptions.mavenBundle; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class HL7MLLPCodecTest extends OSGiIntegrationSpringTestSupport implements Processor { +@@ -63,25 +58,15 @@ public void process(Exchange exchange) throws Exception { + String out = ""MSH|^~\\&|MYSENDER||||200701011539||ADR^A19||||123\rMSA|AA|123\n""; + exchange.getOut().setBody(out); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-mina"", ""camel-hl7""), +- +- // add hl7 osgi bundle +- mavenBundle().groupId(""http://hl7api.sourceforge.net/m2/!ca.uhn.hapi"").artifactId(""hapi-osgi-base"").version(""1.0.1""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-hl7"", ""camel-mina"")); ++ + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java +index 988592314a132..49fa76f9a6daf 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http/HttpTest.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -26,11 +25,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * +@@ -66,22 +62,14 @@ public void configure() { + } + }; + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-http""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jetty"", ""camel-http"")); ++ + return options; + } + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java +index 9cb2dd9fb2d02..42c9835650bb1 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/http4/Http4Test.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -26,11 +25,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * +@@ -66,23 +62,16 @@ public void configure() { + } + }; + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-jetty"", ""camel-http4""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-http4"", ""camel-jetty"")); ++ + return options; + } + ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java +index 9eec49769c45c..e6b5e38cd6fea 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jasypt/JasyptTest.java +@@ -20,18 +20,14 @@ + import org.apache.camel.component.jasypt.JasyptPropertiesParser; + import org.apache.camel.component.properties.PropertiesComponent; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class JasyptTest extends OSGiIntegrationTestSupport { +@@ -68,20 +64,13 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-jasypt""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jasypt"")); + + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java +index 75285698d0c89..2fc3cf5adfa1c 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbDataFormatTest.java +@@ -20,18 +20,14 @@ + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.converter.jaxb.JaxbDataFormat; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class JaxbDataFormatTest extends OSGiIntegrationTestSupport { +@@ -58,24 +54,16 @@ public void testSendMessage() throws Exception { + template.sendBodyAndHeader(""direct:start"", ""FOOBAR"", + ""foo"", ""bar""); + assertMockEndpointsSatisfied(); +- } ++ } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); + + return options; + } ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java +index be157a54c4ddf..d5d2f6bed1551 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterSpringTest.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; +@@ -26,11 +25,8 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class JaxbFallbackConverterSpringTest extends OSGiIntegrationSpringTestSupport { +@@ -56,19 +52,11 @@ public void testSendMessage() throws Exception { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java +index e6157f1946603..60886b780cc7e 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jaxb/JaxbFallbackConverterTest.java +@@ -19,18 +19,14 @@ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class JaxbFallbackConverterTest extends OSGiIntegrationTestSupport { +@@ -59,19 +55,11 @@ public void testSendMessage() throws Exception { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jaxb""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jaxb"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java +index 5bfca0fb5b968..9a34c5aae2197 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jetty/OSGiMulitJettyCamelContextsTest.java +@@ -27,17 +27,13 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.ops4j.pax.swissbox.tinybundles.dp.Constants; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +- + import static org.ops4j.pax.exam.CoreOptions.provision; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + import static org.ops4j.pax.swissbox.tinybundles.core.TinyBundles.newBundle; + + @RunWith(JUnit4TestRunner.class) +-@Ignore(""TODO: fix me"") ++//@Ignore(""TODO: fix me"") + public class OSGiMulitJettyCamelContextsTest extends OSGiIntegrationTestSupport { + + @Test +@@ -66,16 +62,13 @@ public void testStoppingJettyContext() throws Exception { + response = template.requestBody(endpointURI, ""Hello World"", String.class); + assertEquals(""response is "" , ""camelContext2"", response); + } ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jetty""), ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jetty""), + //set up the camel context bundle1 + provision(newBundle().add(""META-INF/spring/CamelContext1.xml"", OSGiMulitJettyCamelContextsTest.class.getResource(""CamelContext1.xml"")) + .add(JettyProcessor.class) +@@ -89,15 +82,11 @@ public static Option[] configure() throws Exception { + .add(JettyProcessor.class) + .set(Constants.BUNDLE_SYMBOLICNAME, ""org.apache.camel.itest.osgi.CamelContextBundle2"") + .set(Constants.DYNAMICIMPORT_PACKAGE, ""*"") +- .set(Constants.BUNDLE_NAME, ""CamelContext2"").build()), +- +- +- workingDirectory(""target/paxrunner/""), +- +- equinox(), +- felix()); ++ .set(Constants.BUNDLE_NAME, ""CamelContext2"").build()) ++ ); + + return options; + } ++ + + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java +index c36dc687a6401..b3070effcfdc9 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jms/JmsTest.java +@@ -17,7 +17,6 @@ + package org.apache.camel.itest.osgi.jms; + + import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; +@@ -25,11 +24,8 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * @version +@@ -54,21 +50,13 @@ public void testJms() throws Exception { + @Configuration + public static Option[] configure() throws Exception { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), ++ getDefaultCamelKarafOptions(), + + // using the features to install AMQ + scanFeatures(""mvn:org.apache.activemq/activemq-karaf/5.4.0/xml/features"", ""activemq""), + + // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jms""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-jms"")); + + return options; + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java +index 52ba5be5d7497..a5028c5f24538 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/jpa/JpaRouteTest.java +@@ -132,7 +132,10 @@ public static Option[] configure() throws Exception { + // Default karaf environment + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), ++ Helper.setLogLevel(""WARN"")), ++ ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-jpa""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java +index 5827694cc4d3d..e8d8e68cd7e9a 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mail/MailRouteTest.java +@@ -125,6 +125,9 @@ public static Option[] configure() throws Exception { + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), ++ + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-spring"", ""camel-test""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java +index f6cb5d14ddd2d..4d1464b1db44d 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mina/MinaTest.java +@@ -18,18 +18,14 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class MinaTest extends OSGiIntegrationTestSupport { +@@ -55,20 +51,13 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-mina""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-mina"")); + + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java +index 12f93145e98fc..25c3a510f2426 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/mybatis/MyBatisTest.java +@@ -112,6 +112,9 @@ public static Option[] configure() throws Exception { + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), + ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), ++ + mavenBundle().groupId(""org.apache.derby"").artifactId(""derby"").version(""10.4.2.0""), + + // using the features to install the camel components +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java +index 4eb4133756299..c4ef7e8d7216f 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/netty/NettyTest.java +@@ -18,18 +18,14 @@ + + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class NettyTest extends OSGiIntegrationTestSupport { +@@ -55,20 +51,13 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-netty""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-netty"")); + + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java +index 865657568af06..fb4ca25bd4fd6 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/protobuf/ProtobufRouteTest.java +@@ -23,18 +23,14 @@ + import org.apache.camel.dataformat.protobuf.ProtobufDataFormat; + import org.apache.camel.dataformat.protobuf.generated.AddressBookProtos; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class ProtobufRouteTest extends OSGiIntegrationTestSupport { +@@ -109,21 +105,13 @@ public void configure() throws Exception { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-protobuf""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-protobuf"")); + + return options; + } +- ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java +index 365f09f602046..bb6ac7568670b 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/quartz/QuartzCronRouteTest.java +@@ -60,6 +60,9 @@ public static Option[] configure() throws Exception { + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), ++ // install the spring, http features first ++ scanFeatures(getKarafFeatureUrl(), ""spring"", ""spring-dm"", ""jetty""), ++ + // using the features to install the camel components + scanFeatures(getCamelKarafFeatureUrl(), + ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-quartz""), +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java +index 463deb5d5e4ce..1988b7174b60c 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/RestletTest.java +@@ -23,18 +23,14 @@ + import org.apache.camel.Processor; + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class RestletTest extends OSGiIntegrationTestSupport { +@@ -63,22 +59,15 @@ public void process(Exchange exchange) throws Exception { + } + }; + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-restlet""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-restlet"")); ++ + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java +index ebb5f917f0211..0812124f2576c 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/restlet/example/RestletDomainServiceTest.java +@@ -18,7 +18,6 @@ + + import org.apache.camel.Exchange; + import org.apache.camel.itest.osgi.OSGiIntegrationSpringTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; +@@ -27,11 +26,8 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * @version +@@ -65,23 +61,16 @@ public void testGetDomain() throws Exception { + + assertEquals(""{www.google.com}"", response); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-cxf"", ""camel-restlet""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-cxf"", ""camel-restlet"")); ++ + return options; + } ++ + + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java +index 264c3fcb86604..2dec9d10e880e 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/rss/RssPollingConsumerTest.java +@@ -26,18 +26,14 @@ + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.component.rss.RssConstants; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class RssPollingConsumerTest extends OSGiIntegrationTestSupport { +@@ -76,21 +72,13 @@ public void configure() throws Exception { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-rss""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-rss"")); + + return options; + } +- ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java +index 4349a469e4053..1a32b6c6b38e1 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/GroovyScriptOsgiTest.java +@@ -19,19 +19,16 @@ + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; ++ + import org.junit.Ignore; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; +-import static org.ops4j.pax.exam.CoreOptions.mavenBundle; ++ + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + /** + * Test camel-script for groovy expressions in OSGi +@@ -54,25 +51,14 @@ public void testLanguage() throws Exception { + + assertMockEndpointsSatisfied(); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-script""), +- +- mavenBundle().groupId(""org.apache.servicemix.bundles"").artifactId(""org.apache.servicemix.bundles.ant"").version(""1.7.0_3""), +- mavenBundle().groupId(""org.codehaus.groovy"").artifactId(""groovy-all"").version(""1.7.9""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-script"", ""camel-groovy"")); + return options; + } ++ ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java +index 052c8164f91cc..0e856e31b84d3 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/script/RubyOsgiTest.java +@@ -55,22 +55,15 @@ public void testSendMessage() throws Exception { + template.sendBody(""direct:start"", ""Hello""); + assertMockEndpointsSatisfied(); + } +- ++ + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-script"", ""camel-ruby""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-script"", ""camel-ruby"")); ++ + return options; + } ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java +index 0c0a49ecb7b63..73767cb58d478 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletComponentTest.java +@@ -50,7 +50,7 @@ public static Option[] configure() throws Exception { + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), +- Helper.loadKarafStandardFeatures(""http"", ""war""), ++ Helper.loadKarafStandardFeatures(""spring"", ""jetty"", ""http"", ""war""), + // set the system property for pax web + org.ops4j.pax.exam.CoreOptions.systemProperty(""org.osgi.service.http.port"").value(""9080""), + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java +index 715323449bb3e..2013ffb86662b 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/servlet/ServletServicesTest.java +@@ -49,7 +49,7 @@ public static Option[] configure() throws Exception { + Helper.getDefaultOptions( + // this is how you set the default log level when using pax logging (logProfile) + Helper.setLogLevel(""WARN"")), +- Helper.loadKarafStandardFeatures(""http"", ""war""), ++ Helper.loadKarafStandardFeatures(""spring"", ""http"", ""war""), + // set the system property for pax web + org.ops4j.pax.exam.CoreOptions.systemProperty(""org.osgi.service.http.port"").value(""9080""), + +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java +index 020c74a637375..e4ecf73b5e514 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/shiro/ShiroAuthenticationTest.java +@@ -26,7 +26,6 @@ + import org.apache.camel.component.shiro.security.ShiroSecurityToken; + import org.apache.camel.component.shiro.security.ShiroSecurityTokenInjector; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.apache.shiro.authc.IncorrectCredentialsException; + import org.apache.shiro.authc.LockedAccountException; + import org.apache.shiro.authc.UnknownAccountException; +@@ -36,11 +35,8 @@ + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class ShiroAuthenticationTest extends OSGiIntegrationTestSupport { +@@ -88,24 +84,15 @@ public void testSuccessfulShiroAuthenticationWithNoAuthorization() throws Except + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-shiro""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-shiro"")); + + return options; + } +- +- ++ + protected RouteBuilder createRouteBuilder() throws Exception { + return new RouteBuilder() { + public void configure() { +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java +index 526a968165717..d3e312eea7295 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/stream/StreamTest.java +@@ -52,22 +52,14 @@ public void configure() { + } + }; + } +- + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-test"", ""camel-stream""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-stream"")); + + return options; + } ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java +index 03e12ab9f1998..e1f3cf4f5cfd4 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/syslog/SyslogTest.java +@@ -30,7 +30,6 @@ + import org.apache.camel.component.syslog.SyslogMessage; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; + import org.apache.camel.spi.DataFormat; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; +@@ -38,11 +37,9 @@ + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; ++ + + @RunWith(JUnit4TestRunner.class) + public class SyslogTest extends OSGiIntegrationTestSupport { +@@ -100,19 +97,13 @@ public void process(Exchange ex) { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), ""camel-core"", ""camel-test"", ""camel-mina"", ""camel-syslog""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); +- ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-mina"", ""camel-syslog"")); ++ + return options; + } ++ + } +diff --git a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java +index 2300a3d7c3fb2..7ba634af94c9b 100644 +--- a/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java ++++ b/tests/camel-itest-osgi/src/test/java/org/apache/camel/itest/osgi/velocity/VelocityTest.java +@@ -22,18 +22,14 @@ + import org.apache.camel.Processor; + import org.apache.camel.builder.RouteBuilder; + import org.apache.camel.itest.osgi.OSGiIntegrationTestSupport; +-import org.apache.karaf.testing.Helper; + import org.junit.Test; + import org.junit.runner.RunWith; + import org.ops4j.pax.exam.Option; + import org.ops4j.pax.exam.junit.Configuration; + import org.ops4j.pax.exam.junit.JUnit4TestRunner; + +-import static org.ops4j.pax.exam.CoreOptions.equinox; +-import static org.ops4j.pax.exam.CoreOptions.felix; + import static org.ops4j.pax.exam.OptionUtils.combine; + import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.scanFeatures; +-import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.workingDirectory; + + @RunWith(JUnit4TestRunner.class) + public class VelocityTest extends OSGiIntegrationTestSupport { +@@ -65,20 +61,14 @@ public void configure() { + } + + @Configuration +- public static Option[] configure() throws Exception { ++ public static Option[] configure() { + Option[] options = combine( +- // Default karaf environment +- Helper.getDefaultOptions( +- // this is how you set the default log level when using pax logging (logProfile) +- Helper.setLogLevel(""WARN"")), +- // using the features to install the camel components +- scanFeatures(getCamelKarafFeatureUrl(), +- ""camel-core"", ""camel-spring"", ""camel-test"", ""camel-velocity""), +- +- workingDirectory(""target/paxrunner/""), +- +- felix(), equinox()); ++ getDefaultCamelKarafOptions(), ++ // using the features to install the other camel components ++ scanFeatures(getCamelKarafFeatureUrl(), ""camel-velocity"")); + + return options; + } ++ ++ + } +\ No newline at end of file +diff --git a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml +index f47d175222b5e..49e4097ef3525 100644 +--- a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml ++++ b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext1.xml +@@ -29,7 +29,7 @@ + + + +- ++ + + + +diff --git a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml +index de47fc04df34c..f8c0387eb636f 100644 +--- a/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml ++++ b/tests/camel-itest-osgi/src/test/resources/org/apache/camel/itest/osgi/jetty/CamelContext2.xml +@@ -29,7 +29,7 @@ + + + +- ++ + + + " +ccd24b5c3ce471428531e12737591b94c91db8bf,ReactiveX-RxJava,Add doOnSubscribe for Single--,a,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java +index 20b983c063..a8a10bafb9 100644 +--- a/src/main/java/rx/Single.java ++++ b/src/main/java/rx/Single.java +@@ -2250,6 +2250,28 @@ public void onNext(T t) { + return lift(new OperatorDoOnEach(observer)); + } + ++ /** ++ * Modifies the source {@code Single} so that it invokes the given action when it is subscribed from ++ * its subscribers. Each subscription will result in an invocation of the given action except when the ++ * source {@code Single} is reference counted, in which case the source {@code Single} will invoke ++ * the given action for the first subscription. ++ *

++ * ++ *

++ *
Scheduler:
++ *
{@code doOnSubscribe} does not operate by default on a particular {@link Scheduler}.
++ *
++ * ++ * @param subscribe ++ * the action that gets called when an observer subscribes to this {@code Single} ++ * @return the source {@code Single} modified so as to call this Action when appropriate ++ * @see ReactiveX operators documentation: Do ++ */ ++ @Experimental ++ public final Single doOnSubscribe(final Action0 subscribe) { ++ return lift(new OperatorDoOnSubscribe(subscribe)); ++ } ++ + /** + * Returns an Single that emits the items emitted by the source Single shifted forward in time by a + * specified delay. Error notifications from the source Single are not delayed. +diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java +index 3ce86e9772..17794e4dbb 100644 +--- a/src/test/java/rx/SingleTest.java ++++ b/src/test/java/rx/SingleTest.java +@@ -878,6 +878,43 @@ public void doOnSuccessShouldNotSwallowExceptionThrownByAction() { + verify(action).call(eq(""value"")); + } + ++ @Test ++ public void doOnSubscribeShouldInvokeAction() { ++ Action0 action = mock(Action0.class); ++ Single single = Single.just(1).doOnSubscribe(action); ++ ++ verifyZeroInteractions(action); ++ ++ single.subscribe(); ++ single.subscribe(); ++ ++ verify(action, times(2)).call(); ++ } ++ ++ @Test ++ public void doOnSubscribeShouldInvokeActionBeforeSubscriberSubscribes() { ++ final List callSequence = new ArrayList(2); ++ ++ Single single = Single.create(new OnSubscribe() { ++ @Override ++ public void call(SingleSubscriber singleSubscriber) { ++ callSequence.add(""onSubscribe""); ++ singleSubscriber.onSuccess(1); ++ } ++ }).doOnSubscribe(new Action0() { ++ @Override ++ public void call() { ++ callSequence.add(""doOnSubscribe""); ++ } ++ }); ++ ++ single.subscribe(); ++ ++ assertEquals(2, callSequence.size()); ++ assertEquals(""doOnSubscribe"", callSequence.get(0)); ++ assertEquals(""onSubscribe"", callSequence.get(1)); ++ } ++ + @Test + public void delayWithSchedulerShouldDelayCompletion() { + TestScheduler scheduler = new TestScheduler();" +e6a03e2fc037b48f3989ef899310e007bb3d16a9,hadoop,Merge r1601491 from trunk. YARN-2030. Augmented- RMStateStore with state machine. Contributed by Binglin Chang--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1601492 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 553f378ceee6e..29add5e139352 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -134,6 +134,8 @@ Release 2.5.0 - UNRELEASED + YARN-2132. ZKRMStateStore.ZKAction#runWithRetries doesn't log the exception + it encounters. (Vamsee Yarlagadda via kasha) + ++ YARN-2030. Augmented RMStateStore with state machine. (Binglin Chang via jianhe) ++ + OPTIMIZATIONS + + BUG FIXES +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java +index 1f6e175ced108..7f4dad83fe92a 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/FileSystemRMStateStore.java +@@ -47,6 +47,8 @@ + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMStateVersionProto; + import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; +@@ -314,7 +316,7 @@ private void loadRMDTSecretManagerState(RMState rmState) throws Exception { + + @Override + public synchronized void storeApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateDataPB) throws Exception { ++ ApplicationStateData appStateDataPB) throws Exception { + String appIdStr = appId.toString(); + Path appDirPath = getAppDir(rmAppRoot, appIdStr); + fs.mkdirs(appDirPath); +@@ -334,7 +336,7 @@ public synchronized void storeApplicationStateInternal(ApplicationId appId, + + @Override + public synchronized void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateDataPB) throws Exception { ++ ApplicationStateData appStateDataPB) throws Exception { + String appIdStr = appId.toString(); + Path appDirPath = getAppDir(rmAppRoot, appIdStr); + Path nodeCreatePath = getNodePath(appDirPath, appIdStr); +@@ -354,7 +356,7 @@ public synchronized void updateApplicationStateInternal(ApplicationId appId, + @Override + public synchronized void storeApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateDataPB) ++ ApplicationAttemptStateData attemptStateDataPB) + throws Exception { + Path appDirPath = + getAppDir(rmAppRoot, appAttemptId.getApplicationId().toString()); +@@ -375,7 +377,7 @@ public synchronized void storeApplicationAttemptStateInternal( + @Override + public synchronized void updateApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateDataPB) ++ ApplicationAttemptStateData attemptStateDataPB) + throws Exception { + Path appDirPath = + getAppDir(rmAppRoot, appAttemptId.getApplicationId().toString()); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java +index c9f3541f53542..a43b20da39256 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/MemoryRMStateStore.java +@@ -32,9 +32,9 @@ + import org.apache.hadoop.yarn.api.records.ApplicationId; + import org.apache.hadoop.yarn.exceptions.YarnRuntimeException; + import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; + + import com.google.common.annotations.VisibleForTesting; + +@@ -80,7 +80,7 @@ protected synchronized void closeInternal() throws Exception { + + @Override + public void storeApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) ++ ApplicationStateData appStateData) + throws Exception { + ApplicationState appState = + new ApplicationState(appStateData.getSubmitTime(), +@@ -92,7 +92,7 @@ public void storeApplicationStateInternal(ApplicationId appId, + + @Override + public void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception { ++ ApplicationStateData appStateData) throws Exception { + ApplicationState updatedAppState = + new ApplicationState(appStateData.getSubmitTime(), + appStateData.getStartTime(), +@@ -112,7 +112,7 @@ public void updateApplicationStateInternal(ApplicationId appId, + @Override + public synchronized void storeApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) ++ ApplicationAttemptStateData attemptStateData) + throws Exception { + Credentials credentials = null; + if(attemptStateData.getAppAttemptTokens() != null){ +@@ -137,7 +137,7 @@ public synchronized void storeApplicationAttemptStateInternal( + @Override + public synchronized void updateApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) ++ ApplicationAttemptStateData attemptStateData) + throws Exception { + Credentials credentials = null; + if (attemptStateData.getAppAttemptTokens() != null) { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java +index a12099f46f3e2..6a0426c0e8ca2 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/NullRMStateStore.java +@@ -25,9 +25,9 @@ + import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; + import org.apache.hadoop.yarn.api.records.ApplicationId; + import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; + + @Unstable + public class NullRMStateStore extends RMStateStore { +@@ -54,13 +54,13 @@ public RMState loadState() throws Exception { + + @Override + protected void storeApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception { ++ ApplicationStateData appStateData) throws Exception { + // Do nothing + } + + @Override + protected void storeApplicationAttemptStateInternal(ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception { ++ ApplicationAttemptStateData attemptStateData) throws Exception { + // Do nothing + } + +@@ -102,13 +102,13 @@ public void removeRMDTMasterKeyState(DelegationKey delegationKey) throws Excepti + + @Override + protected void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception { ++ ApplicationStateData appStateData) throws Exception { + // Do nothing + } + + @Override + protected void updateApplicationAttemptStateInternal(ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception { ++ ApplicationAttemptStateData attemptStateData) throws Exception { + } + + @Override +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java +index fc4537c793f71..affc6f9d86567 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/RMStateStore.java +@@ -18,7 +18,6 @@ + + package org.apache.hadoop.yarn.server.resourcemanager.recovery; + +-import java.nio.ByteBuffer; + import java.util.HashMap; + import java.util.HashSet; + import java.util.Map; +@@ -31,7 +30,6 @@ + import org.apache.hadoop.classification.InterfaceAudience.Private; + import org.apache.hadoop.classification.InterfaceStability.Unstable; + import org.apache.hadoop.conf.Configuration; +-import org.apache.hadoop.io.DataOutputBuffer; + import org.apache.hadoop.io.Text; + import org.apache.hadoop.security.Credentials; + import org.apache.hadoop.security.token.Token; +@@ -50,6 +48,8 @@ + import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; + import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEvent; + import org.apache.hadoop.yarn.server.resourcemanager.RMFatalEventType; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; +@@ -61,6 +61,10 @@ + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptNewSavedEvent; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.event.RMAppAttemptUpdateSavedEvent; ++import org.apache.hadoop.yarn.state.InvalidStateTransitonException; ++import org.apache.hadoop.yarn.state.SingleArcTransition; ++import org.apache.hadoop.yarn.state.StateMachine; ++import org.apache.hadoop.yarn.state.StateMachineFactory; + + @Private + @Unstable +@@ -83,8 +87,163 @@ public abstract class RMStateStore extends AbstractService { + + public static final Log LOG = LogFactory.getLog(RMStateStore.class); + ++ private enum RMStateStoreState { ++ DEFAULT ++ }; ++ ++ private static final StateMachineFactory ++ stateMachineFactory = new StateMachineFactory( ++ RMStateStoreState.DEFAULT) ++ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT, ++ RMStateStoreEventType.STORE_APP, new StoreAppTransition()) ++ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT, ++ RMStateStoreEventType.UPDATE_APP, new UpdateAppTransition()) ++ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT, ++ RMStateStoreEventType.REMOVE_APP, new RemoveAppTransition()) ++ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT, ++ RMStateStoreEventType.STORE_APP_ATTEMPT, new StoreAppAttemptTransition()) ++ .addTransition(RMStateStoreState.DEFAULT, RMStateStoreState.DEFAULT, ++ RMStateStoreEventType.UPDATE_APP_ATTEMPT, new UpdateAppAttemptTransition()); ++ ++ private final StateMachine stateMachine; ++ ++ private static class StoreAppTransition ++ implements SingleArcTransition { ++ @Override ++ public void transition(RMStateStore store, RMStateStoreEvent event) { ++ if (!(event instanceof RMStateStoreAppEvent)) { ++ // should never happen ++ LOG.error(""Illegal event type: "" + event.getClass()); ++ return; ++ } ++ ApplicationState appState = ((RMStateStoreAppEvent) event).getAppState(); ++ ApplicationId appId = appState.getAppId(); ++ ApplicationStateData appStateData = ApplicationStateData ++ .newInstance(appState); ++ LOG.info(""Storing info for app: "" + appId); ++ try { ++ store.storeApplicationStateInternal(appId, appStateData); ++ store.notifyDoneStoringApplication(appId, null); ++ } catch (Exception e) { ++ LOG.error(""Error storing app: "" + appId, e); ++ store.notifyStoreOperationFailed(e); ++ } ++ }; ++ } ++ ++ private static class UpdateAppTransition implements ++ SingleArcTransition { ++ @Override ++ public void transition(RMStateStore store, RMStateStoreEvent event) { ++ if (!(event instanceof RMStateUpdateAppEvent)) { ++ // should never happen ++ LOG.error(""Illegal event type: "" + event.getClass()); ++ return; ++ } ++ ApplicationState appState = ((RMStateUpdateAppEvent) event).getAppState(); ++ ApplicationId appId = appState.getAppId(); ++ ApplicationStateData appStateData = ApplicationStateData ++ .newInstance(appState); ++ LOG.info(""Updating info for app: "" + appId); ++ try { ++ store.updateApplicationStateInternal(appId, appStateData); ++ store.notifyDoneUpdatingApplication(appId, null); ++ } catch (Exception e) { ++ LOG.error(""Error updating app: "" + appId, e); ++ store.notifyStoreOperationFailed(e); ++ } ++ }; ++ } ++ ++ private static class RemoveAppTransition implements ++ SingleArcTransition { ++ @Override ++ public void transition(RMStateStore store, RMStateStoreEvent event) { ++ if (!(event instanceof RMStateStoreRemoveAppEvent)) { ++ // should never happen ++ LOG.error(""Illegal event type: "" + event.getClass()); ++ return; ++ } ++ ApplicationState appState = ((RMStateStoreRemoveAppEvent) event) ++ .getAppState(); ++ ApplicationId appId = appState.getAppId(); ++ LOG.info(""Removing info for app: "" + appId); ++ try { ++ store.removeApplicationStateInternal(appState); ++ } catch (Exception e) { ++ LOG.error(""Error removing app: "" + appId, e); ++ store.notifyStoreOperationFailed(e); ++ } ++ }; ++ } ++ ++ private static class StoreAppAttemptTransition implements ++ SingleArcTransition { ++ @Override ++ public void transition(RMStateStore store, RMStateStoreEvent event) { ++ if (!(event instanceof RMStateStoreAppAttemptEvent)) { ++ // should never happen ++ LOG.error(""Illegal event type: "" + event.getClass()); ++ return; ++ } ++ ApplicationAttemptState attemptState = ++ ((RMStateStoreAppAttemptEvent) event).getAppAttemptState(); ++ try { ++ ApplicationAttemptStateData attemptStateData = ++ ApplicationAttemptStateData.newInstance(attemptState); ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Storing info for attempt: "" + attemptState.getAttemptId()); ++ } ++ store.storeApplicationAttemptStateInternal(attemptState.getAttemptId(), ++ attemptStateData); ++ store.notifyDoneStoringApplicationAttempt(attemptState.getAttemptId(), ++ null); ++ } catch (Exception e) { ++ LOG.error(""Error storing appAttempt: "" + attemptState.getAttemptId(), e); ++ store.notifyStoreOperationFailed(e); ++ } ++ }; ++ } ++ ++ private static class UpdateAppAttemptTransition implements ++ SingleArcTransition { ++ @Override ++ public void transition(RMStateStore store, RMStateStoreEvent event) { ++ if (!(event instanceof RMStateUpdateAppAttemptEvent)) { ++ // should never happen ++ LOG.error(""Illegal event type: "" + event.getClass()); ++ return; ++ } ++ ApplicationAttemptState attemptState = ++ ((RMStateUpdateAppAttemptEvent) event).getAppAttemptState(); ++ try { ++ ApplicationAttemptStateData attemptStateData = ApplicationAttemptStateData ++ .newInstance(attemptState); ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Updating info for attempt: "" + attemptState.getAttemptId()); ++ } ++ store.updateApplicationAttemptStateInternal(attemptState.getAttemptId(), ++ attemptStateData); ++ store.notifyDoneUpdatingApplicationAttempt(attemptState.getAttemptId(), ++ null); ++ } catch (Exception e) { ++ LOG.error(""Error updating appAttempt: "" + attemptState.getAttemptId(), e); ++ store.notifyStoreOperationFailed(e); ++ } ++ }; ++ } ++ + public RMStateStore() { + super(RMStateStore.class.getName()); ++ stateMachine = stateMachineFactory.make(this); + } + + /** +@@ -390,10 +549,10 @@ public synchronized void updateApplicationState(ApplicationState appState) { + * application. + */ + protected abstract void storeApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception; ++ ApplicationStateData appStateData) throws Exception; + + protected abstract void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception; ++ ApplicationStateData appStateData) throws Exception; + + @SuppressWarnings(""unchecked"") + /** +@@ -428,11 +587,11 @@ public synchronized void updateApplicationAttemptState( + */ + protected abstract void storeApplicationAttemptStateInternal( + ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception; ++ ApplicationAttemptStateData attemptStateData) throws Exception; + + protected abstract void updateApplicationAttemptStateInternal( + ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception; ++ ApplicationAttemptStateData attemptStateData) throws Exception; + + /** + * RMDTSecretManager call this to store the state of a delegation token +@@ -596,105 +755,10 @@ public Credentials getCredentialsFromAppAttempt(RMAppAttempt appAttempt) { + + // Dispatcher related code + protected void handleStoreEvent(RMStateStoreEvent event) { +- if (event.getType().equals(RMStateStoreEventType.STORE_APP) +- || event.getType().equals(RMStateStoreEventType.UPDATE_APP)) { +- ApplicationState appState = null; +- if (event.getType().equals(RMStateStoreEventType.STORE_APP)) { +- appState = ((RMStateStoreAppEvent) event).getAppState(); +- } else { +- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP); +- appState = ((RMStateUpdateAppEvent) event).getAppState(); +- } +- +- Exception storedException = null; +- ApplicationStateDataPBImpl appStateData = +- (ApplicationStateDataPBImpl) ApplicationStateDataPBImpl +- .newApplicationStateData(appState.getSubmitTime(), +- appState.getStartTime(), appState.getUser(), +- appState.getApplicationSubmissionContext(), appState.getState(), +- appState.getDiagnostics(), appState.getFinishTime()); +- +- ApplicationId appId = +- appState.getApplicationSubmissionContext().getApplicationId(); +- +- LOG.info(""Storing info for app: "" + appId); +- try { +- if (event.getType().equals(RMStateStoreEventType.STORE_APP)) { +- storeApplicationStateInternal(appId, appStateData); +- notifyDoneStoringApplication(appId, storedException); +- } else { +- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP); +- updateApplicationStateInternal(appId, appStateData); +- notifyDoneUpdatingApplication(appId, storedException); +- } +- } catch (Exception e) { +- LOG.error(""Error storing/updating app: "" + appId, e); +- notifyStoreOperationFailed(e); +- } +- } else if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT) +- || event.getType().equals(RMStateStoreEventType.UPDATE_APP_ATTEMPT)) { +- +- ApplicationAttemptState attemptState = null; +- if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT)) { +- attemptState = +- ((RMStateStoreAppAttemptEvent) event).getAppAttemptState(); +- } else { +- assert event.getType().equals(RMStateStoreEventType.UPDATE_APP_ATTEMPT); +- attemptState = +- ((RMStateUpdateAppAttemptEvent) event).getAppAttemptState(); +- } +- +- Exception storedException = null; +- Credentials credentials = attemptState.getAppAttemptCredentials(); +- ByteBuffer appAttemptTokens = null; +- try { +- if (credentials != null) { +- DataOutputBuffer dob = new DataOutputBuffer(); +- credentials.writeTokenStorageToStream(dob); +- appAttemptTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); +- } +- ApplicationAttemptStateDataPBImpl attemptStateData = +- (ApplicationAttemptStateDataPBImpl) ApplicationAttemptStateDataPBImpl +- .newApplicationAttemptStateData(attemptState.getAttemptId(), +- attemptState.getMasterContainer(), appAttemptTokens, +- attemptState.getStartTime(), attemptState.getState(), +- attemptState.getFinalTrackingUrl(), +- attemptState.getDiagnostics(), +- attemptState.getFinalApplicationStatus()); +- if (LOG.isDebugEnabled()) { +- LOG.debug(""Storing info for attempt: "" + attemptState.getAttemptId()); +- } +- if (event.getType().equals(RMStateStoreEventType.STORE_APP_ATTEMPT)) { +- storeApplicationAttemptStateInternal(attemptState.getAttemptId(), +- attemptStateData); +- notifyDoneStoringApplicationAttempt(attemptState.getAttemptId(), +- storedException); +- } else { +- assert event.getType().equals( +- RMStateStoreEventType.UPDATE_APP_ATTEMPT); +- updateApplicationAttemptStateInternal(attemptState.getAttemptId(), +- attemptStateData); +- notifyDoneUpdatingApplicationAttempt(attemptState.getAttemptId(), +- storedException); +- } +- } catch (Exception e) { +- LOG.error( +- ""Error storing/updating appAttempt: "" + attemptState.getAttemptId(), e); +- notifyStoreOperationFailed(e); +- } +- } else if (event.getType().equals(RMStateStoreEventType.REMOVE_APP)) { +- ApplicationState appState = +- ((RMStateStoreRemoveAppEvent) event).getAppState(); +- ApplicationId appId = appState.getAppId(); +- LOG.info(""Removing info for app: "" + appId); +- try { +- removeApplicationStateInternal(appState); +- } catch (Exception e) { +- LOG.error(""Error removing app: "" + appId, e); +- notifyStoreOperationFailed(e); +- } +- } else { +- LOG.error(""Unknown RMStateStoreEvent type: "" + event.getType()); ++ try { ++ this.stateMachine.doTransition(event.getType(), event); ++ } catch (InvalidStateTransitonException e) { ++ LOG.error(""Can't handle this event at current state"", e); + } + } + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java +index 31c8885d4f2c9..63ae990732c24 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/ZKRMStateStore.java +@@ -49,6 +49,8 @@ + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMStateVersionProto; + import org.apache.hadoop.yarn.security.client.RMDelegationTokenIdentifier; + import org.apache.hadoop.yarn.server.resourcemanager.RMZKUtils; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; +@@ -551,7 +553,7 @@ private void loadApplicationAttemptState(ApplicationState appState, + + @Override + public synchronized void storeApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateDataPB) throws Exception { ++ ApplicationStateData appStateDataPB) throws Exception { + String nodeCreatePath = getNodePath(rmAppRoot, appId.toString()); + + if (LOG.isDebugEnabled()) { +@@ -565,7 +567,7 @@ public synchronized void storeApplicationStateInternal(ApplicationId appId, + + @Override + public synchronized void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateDataPB) throws Exception { ++ ApplicationStateData appStateDataPB) throws Exception { + String nodeUpdatePath = getNodePath(rmAppRoot, appId.toString()); + + if (LOG.isDebugEnabled()) { +@@ -587,7 +589,7 @@ public synchronized void updateApplicationStateInternal(ApplicationId appId, + @Override + public synchronized void storeApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateDataPB) ++ ApplicationAttemptStateData attemptStateDataPB) + throws Exception { + String appDirPath = getNodePath(rmAppRoot, + appAttemptId.getApplicationId().toString()); +@@ -605,7 +607,7 @@ public synchronized void storeApplicationAttemptStateInternal( + @Override + public synchronized void updateApplicationAttemptStateInternal( + ApplicationAttemptId appAttemptId, +- ApplicationAttemptStateDataPBImpl attemptStateDataPB) ++ ApplicationAttemptStateData attemptStateDataPB) + throws Exception { + String appIdStr = appAttemptId.getApplicationId().toString(); + String appAttemptIdStr = appAttemptId.toString(); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java +index 255800e86b2d9..6af048b2e3d2a 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationAttemptStateData.java +@@ -18,31 +18,73 @@ + + package org.apache.hadoop.yarn.server.resourcemanager.recovery.records; + ++import java.io.IOException; + import java.nio.ByteBuffer; + + import org.apache.hadoop.classification.InterfaceAudience.Public; + import org.apache.hadoop.classification.InterfaceStability.Unstable; ++import org.apache.hadoop.io.DataOutputBuffer; ++import org.apache.hadoop.security.Credentials; + import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; + import org.apache.hadoop.yarn.api.records.Container; + import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; ++import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProto; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationAttemptState; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; ++import org.apache.hadoop.yarn.util.Records; + + /* + * Contains the state data that needs to be persisted for an ApplicationAttempt + */ + @Public + @Unstable +-public interface ApplicationAttemptStateData { +- ++public abstract class ApplicationAttemptStateData { ++ public static ApplicationAttemptStateData newInstance( ++ ApplicationAttemptId attemptId, Container container, ++ ByteBuffer attemptTokens, long startTime, RMAppAttemptState finalState, ++ String finalTrackingUrl, String diagnostics, ++ FinalApplicationStatus amUnregisteredFinalStatus) { ++ ApplicationAttemptStateData attemptStateData = ++ Records.newRecord(ApplicationAttemptStateData.class); ++ attemptStateData.setAttemptId(attemptId); ++ attemptStateData.setMasterContainer(container); ++ attemptStateData.setAppAttemptTokens(attemptTokens); ++ attemptStateData.setState(finalState); ++ attemptStateData.setFinalTrackingUrl(finalTrackingUrl); ++ attemptStateData.setDiagnostics(diagnostics); ++ attemptStateData.setStartTime(startTime); ++ attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus); ++ return attemptStateData; ++ } ++ ++ public static ApplicationAttemptStateData newInstance( ++ ApplicationAttemptState attemptState) throws IOException { ++ Credentials credentials = attemptState.getAppAttemptCredentials(); ++ ByteBuffer appAttemptTokens = null; ++ if (credentials != null) { ++ DataOutputBuffer dob = new DataOutputBuffer(); ++ credentials.writeTokenStorageToStream(dob); ++ appAttemptTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength()); ++ } ++ return newInstance(attemptState.getAttemptId(), ++ attemptState.getMasterContainer(), appAttemptTokens, ++ attemptState.getStartTime(), attemptState.getState(), ++ attemptState.getFinalTrackingUrl(), ++ attemptState.getDiagnostics(), ++ attemptState.getFinalApplicationStatus()); ++ } ++ ++ public abstract ApplicationAttemptStateDataProto getProto(); ++ + /** + * The ApplicationAttemptId for the application attempt + * @return ApplicationAttemptId for the application attempt + */ + @Public + @Unstable +- public ApplicationAttemptId getAttemptId(); ++ public abstract ApplicationAttemptId getAttemptId(); + +- public void setAttemptId(ApplicationAttemptId attemptId); ++ public abstract void setAttemptId(ApplicationAttemptId attemptId); + + /* + * The master container running the application attempt +@@ -50,9 +92,9 @@ public interface ApplicationAttemptStateData { + */ + @Public + @Unstable +- public Container getMasterContainer(); ++ public abstract Container getMasterContainer(); + +- public void setMasterContainer(Container container); ++ public abstract void setMasterContainer(Container container); + + /** + * The application attempt tokens that belong to this attempt +@@ -60,17 +102,17 @@ public interface ApplicationAttemptStateData { + */ + @Public + @Unstable +- public ByteBuffer getAppAttemptTokens(); ++ public abstract ByteBuffer getAppAttemptTokens(); + +- public void setAppAttemptTokens(ByteBuffer attemptTokens); ++ public abstract void setAppAttemptTokens(ByteBuffer attemptTokens); + + /** + * Get the final state of the application attempt. + * @return the final state of the application attempt. + */ +- public RMAppAttemptState getState(); ++ public abstract RMAppAttemptState getState(); + +- public void setState(RMAppAttemptState state); ++ public abstract void setState(RMAppAttemptState state); + + /** + * Get the original not-proxied final tracking url for the +@@ -79,34 +121,34 @@ public interface ApplicationAttemptStateData { + * @return the original not-proxied final tracking url for the + * application + */ +- public String getFinalTrackingUrl(); ++ public abstract String getFinalTrackingUrl(); + + /** + * Set the final tracking Url of the AM. + * @param url + */ +- public void setFinalTrackingUrl(String url); ++ public abstract void setFinalTrackingUrl(String url); + /** + * Get the diagnositic information of the attempt + * @return diagnositic information of the attempt + */ +- public String getDiagnostics(); ++ public abstract String getDiagnostics(); + +- public void setDiagnostics(String diagnostics); ++ public abstract void setDiagnostics(String diagnostics); + + /** + * Get the start time of the application. + * @return start time of the application + */ +- public long getStartTime(); ++ public abstract long getStartTime(); + +- public void setStartTime(long startTime); ++ public abstract void setStartTime(long startTime); + + /** + * Get the final finish status of the application. + * @return final finish status of the application + */ +- public FinalApplicationStatus getFinalApplicationStatus(); ++ public abstract FinalApplicationStatus getFinalApplicationStatus(); + +- public void setFinalApplicationStatus(FinalApplicationStatus finishState); ++ public abstract void setFinalApplicationStatus(FinalApplicationStatus finishState); + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java +index 9fce6cf12d068..55b726ffd0da8 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/ApplicationStateData.java +@@ -24,7 +24,10 @@ + import org.apache.hadoop.classification.InterfaceStability.Unstable; + import org.apache.hadoop.yarn.api.records.ApplicationId; + import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; ++import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationState; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; ++import org.apache.hadoop.yarn.util.Records; + + /** + * Contains all the state data that needs to be stored persistently +@@ -32,19 +35,43 @@ + */ + @Public + @Unstable +-public interface ApplicationStateData { +- ++public abstract class ApplicationStateData { ++ public static ApplicationStateData newInstance(long submitTime, ++ long startTime, String user, ++ ApplicationSubmissionContext submissionContext, ++ RMAppState state, String diagnostics, long finishTime) { ++ ApplicationStateData appState = Records.newRecord(ApplicationStateData.class); ++ appState.setSubmitTime(submitTime); ++ appState.setStartTime(startTime); ++ appState.setUser(user); ++ appState.setApplicationSubmissionContext(submissionContext); ++ appState.setState(state); ++ appState.setDiagnostics(diagnostics); ++ appState.setFinishTime(finishTime); ++ return appState; ++ } ++ ++ public static ApplicationStateData newInstance( ++ ApplicationState appState) { ++ return newInstance(appState.getSubmitTime(), appState.getStartTime(), ++ appState.getUser(), appState.getApplicationSubmissionContext(), ++ appState.getState(), appState.getDiagnostics(), ++ appState.getFinishTime()); ++ } ++ ++ public abstract ApplicationStateDataProto getProto(); ++ + /** + * The time at which the application was received by the Resource Manager + * @return submitTime + */ + @Public + @Unstable +- public long getSubmitTime(); ++ public abstract long getSubmitTime(); + + @Public + @Unstable +- public void setSubmitTime(long submitTime); ++ public abstract void setSubmitTime(long submitTime); + + /** + * Get the start time of the application. +@@ -63,11 +90,11 @@ public interface ApplicationStateData { + */ + @Public + @Unstable +- public void setUser(String user); ++ public abstract void setUser(String user); + + @Public + @Unstable +- public String getUser(); ++ public abstract String getUser(); + + /** + * The {@link ApplicationSubmissionContext} for the application +@@ -76,34 +103,34 @@ public interface ApplicationStateData { + */ + @Public + @Unstable +- public ApplicationSubmissionContext getApplicationSubmissionContext(); ++ public abstract ApplicationSubmissionContext getApplicationSubmissionContext(); + + @Public + @Unstable +- public void setApplicationSubmissionContext( ++ public abstract void setApplicationSubmissionContext( + ApplicationSubmissionContext context); + + /** + * Get the final state of the application. + * @return the final state of the application. + */ +- public RMAppState getState(); ++ public abstract RMAppState getState(); + +- public void setState(RMAppState state); ++ public abstract void setState(RMAppState state); + + /** + * Get the diagnostics information for the application master. + * @return the diagnostics information for the application master. + */ +- public String getDiagnostics(); ++ public abstract String getDiagnostics(); + +- public void setDiagnostics(String diagnostics); ++ public abstract void setDiagnostics(String diagnostics); + + /** + * The finish time of the application. + * @return the finish time of the application., + */ +- public long getFinishTime(); ++ public abstract long getFinishTime(); + +- public void setFinishTime(long finishTime); ++ public abstract void setFinishTime(long finishTime); + } +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java +index 75ac2eef9a737..e3ebe5e08936c 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationAttemptStateDataPBImpl.java +@@ -25,10 +25,7 @@ + import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; + import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationAttemptIdPBImpl; + import org.apache.hadoop.yarn.api.records.impl.pb.ContainerPBImpl; +-import org.apache.hadoop.yarn.api.records.impl.pb.ProtoBase; + import org.apache.hadoop.yarn.api.records.impl.pb.ProtoUtils; +-import org.apache.hadoop.yarn.factories.RecordFactory; +-import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; + import org.apache.hadoop.yarn.proto.YarnProtos.FinalApplicationStatusProto; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProto; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationAttemptStateDataProtoOrBuilder; +@@ -36,12 +33,10 @@ + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState; + +-public class ApplicationAttemptStateDataPBImpl +-extends ProtoBase +-implements ApplicationAttemptStateData { +- private static final RecordFactory recordFactory = RecordFactoryProvider +- .getRecordFactory(null); ++import com.google.protobuf.TextFormat; + ++public class ApplicationAttemptStateDataPBImpl extends ++ ApplicationAttemptStateData { + ApplicationAttemptStateDataProto proto = + ApplicationAttemptStateDataProto.getDefaultInstance(); + ApplicationAttemptStateDataProto.Builder builder = null; +@@ -60,7 +55,8 @@ public ApplicationAttemptStateDataPBImpl( + this.proto = proto; + viaProto = true; + } +- ++ ++ @Override + public ApplicationAttemptStateDataProto getProto() { + mergeLocalToProto(); + proto = viaProto ? proto : builder.build(); +@@ -76,7 +72,8 @@ private void mergeLocalToBuilder() { + builder.setMasterContainer(((ContainerPBImpl)masterContainer).getProto()); + } + if(this.appAttemptTokens != null) { +- builder.setAppAttemptTokens(convertToProtoFormat(this.appAttemptTokens)); ++ builder.setAppAttemptTokens(ProtoUtils.convertToProtoFormat( ++ this.appAttemptTokens)); + } + } + +@@ -148,7 +145,8 @@ public ByteBuffer getAppAttemptTokens() { + if(!p.hasAppAttemptTokens()) { + return null; + } +- this.appAttemptTokens = convertFromProtoFormat(p.getAppAttemptTokens()); ++ this.appAttemptTokens = ProtoUtils.convertFromProtoFormat( ++ p.getAppAttemptTokens()); + return appAttemptTokens; + } + +@@ -249,24 +247,26 @@ public void setFinalApplicationStatus(FinalApplicationStatus finishState) { + builder.setFinalApplicationStatus(convertToProtoFormat(finishState)); + } + +- public static ApplicationAttemptStateData newApplicationAttemptStateData( +- ApplicationAttemptId attemptId, Container container, +- ByteBuffer attemptTokens, long startTime, RMAppAttemptState finalState, +- String finalTrackingUrl, String diagnostics, +- FinalApplicationStatus amUnregisteredFinalStatus) { +- ApplicationAttemptStateData attemptStateData = +- recordFactory.newRecordInstance(ApplicationAttemptStateData.class); +- attemptStateData.setAttemptId(attemptId); +- attemptStateData.setMasterContainer(container); +- attemptStateData.setAppAttemptTokens(attemptTokens); +- attemptStateData.setState(finalState); +- attemptStateData.setFinalTrackingUrl(finalTrackingUrl); +- attemptStateData.setDiagnostics(diagnostics); +- attemptStateData.setStartTime(startTime); +- attemptStateData.setFinalApplicationStatus(amUnregisteredFinalStatus); +- return attemptStateData; ++ @Override ++ public int hashCode() { ++ return getProto().hashCode(); + } + ++ @Override ++ public boolean equals(Object other) { ++ if (other == null) ++ return false; ++ if (other.getClass().isAssignableFrom(this.getClass())) { ++ return this.getProto().equals(this.getClass().cast(other).getProto()); ++ } ++ return false; ++ } ++ ++ @Override ++ public String toString() { ++ return TextFormat.shortDebugString(getProto()); ++ } ++ + private static String RM_APP_ATTEMPT_PREFIX = ""RMATTEMPT_""; + public static RMAppAttemptStateProto convertToProtoFormat(RMAppAttemptState e) { + return RMAppAttemptStateProto.valueOf(RM_APP_ATTEMPT_PREFIX + e.name()); +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java +index ede8ca7c46155..8aaf1a4a7caf6 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/records/impl/pb/ApplicationStateDataPBImpl.java +@@ -20,21 +20,15 @@ + + import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; + import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl; +-import org.apache.hadoop.yarn.api.records.impl.pb.ProtoBase; +-import org.apache.hadoop.yarn.factories.RecordFactory; +-import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProto; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.ApplicationStateDataProtoOrBuilder; + import org.apache.hadoop.yarn.proto.YarnServerResourceManagerServiceProtos.RMAppStateProto; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; + +-public class ApplicationStateDataPBImpl +-extends ProtoBase +-implements ApplicationStateData { +- private static final RecordFactory recordFactory = RecordFactoryProvider +- .getRecordFactory(null); ++import com.google.protobuf.TextFormat; + ++public class ApplicationStateDataPBImpl extends ApplicationStateData { + ApplicationStateDataProto proto = + ApplicationStateDataProto.getDefaultInstance(); + ApplicationStateDataProto.Builder builder = null; +@@ -51,7 +45,8 @@ public ApplicationStateDataPBImpl( + this.proto = proto; + viaProto = true; + } +- ++ ++ @Override + public ApplicationStateDataProto getProto() { + mergeLocalToProto(); + proto = viaProto ? proto : builder.build(); +@@ -136,7 +131,7 @@ public ApplicationSubmissionContext getApplicationSubmissionContext() { + } + applicationSubmissionContext = + new ApplicationSubmissionContextPBImpl( +- p.getApplicationSubmissionContext()); ++ p.getApplicationSubmissionContext()); + return applicationSubmissionContext; + } + +@@ -200,21 +195,24 @@ public void setFinishTime(long finishTime) { + builder.setFinishTime(finishTime); + } + +- public static ApplicationStateData newApplicationStateData(long submitTime, +- long startTime, String user, +- ApplicationSubmissionContext submissionContext, RMAppState state, +- String diagnostics, long finishTime) { +- +- ApplicationStateData appState = +- recordFactory.newRecordInstance(ApplicationStateData.class); +- appState.setSubmitTime(submitTime); +- appState.setStartTime(startTime); +- appState.setUser(user); +- appState.setApplicationSubmissionContext(submissionContext); +- appState.setState(state); +- appState.setDiagnostics(diagnostics); +- appState.setFinishTime(finishTime); +- return appState; ++ @Override ++ public int hashCode() { ++ return getProto().hashCode(); ++ } ++ ++ @Override ++ public boolean equals(Object other) { ++ if (other == null) ++ return false; ++ if (other.getClass().isAssignableFrom(this.getClass())) { ++ return this.getProto().equals(this.getClass().cast(other).getProto()); ++ } ++ return false; ++ } ++ ++ @Override ++ public String toString() { ++ return TextFormat.shortDebugString(getProto()); + } + + private static String RM_APP_PREFIX = ""RMAPP_""; +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java +index 3bdb66c4b407c..9c2d87e444250 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMRestart.java +@@ -84,8 +84,8 @@ + import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.ApplicationState; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStoreEvent; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationAttemptStateDataPBImpl; +-import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationAttemptStateData; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState; + import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt; +@@ -612,7 +612,7 @@ public void testRMRestartWaitForPreviousSucceededAttempt() throws Exception { + + @Override + public void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception { ++ ApplicationStateData appStateData) throws Exception { + if (count == 0) { + // do nothing; simulate app final state is not saved. + LOG.info(appId + "" final state is not saved.""); +@@ -760,14 +760,14 @@ public void testRMRestartKilledAppWithNoAttempts() throws Exception { + @Override + public synchronized void storeApplicationAttemptStateInternal( + ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception { ++ ApplicationAttemptStateData attemptStateData) throws Exception { + // ignore attempt saving request. + } + + @Override + public synchronized void updateApplicationAttemptStateInternal( + ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) throws Exception { ++ ApplicationAttemptStateData attemptStateData) throws Exception { + // ignore attempt saving request. + } + }; +@@ -1862,7 +1862,7 @@ public class TestMemoryRMStateStore extends MemoryRMStateStore { + + @Override + public void updateApplicationStateInternal(ApplicationId appId, +- ApplicationStateDataPBImpl appStateData) throws Exception { ++ ApplicationStateData appStateData) throws Exception { + updateApp = ++count; + super.updateApplicationStateInternal(appId, appStateData); + } +@@ -1871,7 +1871,7 @@ public void updateApplicationStateInternal(ApplicationId appId, + public synchronized void + updateApplicationAttemptStateInternal( + ApplicationAttemptId attemptId, +- ApplicationAttemptStateDataPBImpl attemptStateData) ++ ApplicationAttemptStateData attemptStateData) + throws Exception { + updateAttempt = ++count; + super.updateApplicationAttemptStateInternal(attemptId, +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java +index 792b73e5a6648..da25c5beda6ad 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestFSRMStateStore.java +@@ -24,7 +24,6 @@ + import java.util.concurrent.atomic.AtomicBoolean; + + import org.junit.Assert; +- + import org.apache.commons.logging.Log; + import org.apache.commons.logging.LogFactory; + import org.apache.hadoop.conf.Configuration; +@@ -37,6 +36,7 @@ + import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; + import org.apache.hadoop.yarn.api.records.ApplicationId; + import org.apache.hadoop.yarn.conf.YarnConfiguration; ++import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.ApplicationStateData; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.RMStateVersion; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.ApplicationStateDataPBImpl; + import org.apache.hadoop.yarn.server.resourcemanager.recovery.records.impl.pb.RMStateVersionPBImpl; +@@ -213,9 +213,8 @@ public void run() { + try { + store.storeApplicationStateInternal( + ApplicationId.newInstance(100L, 1), +- (ApplicationStateDataPBImpl) ApplicationStateDataPBImpl +- .newApplicationStateData(111, 111, ""user"", null, +- RMAppState.ACCEPTED, ""diagnostics"", 333)); ++ ApplicationStateData.newInstance(111, 111, ""user"", null, ++ RMAppState.ACCEPTED, ""diagnostics"", 333)); + } catch (Exception e) { + // TODO 0 datanode exception will not be retried by dfs client, fix + // that separately." +5cea1f83748ed49c4cf9d2612c55ab7101599186,fozziethebeat$s-space,"Changes based on Keith's review. A few tweaks to EdgeSet to help tracking edge +removal +modified: src/edu/ucla/sspace/common/Similarity.java +- Updated to use VectorMath.dotProduct for the Tanimoto coefficient +deleted: src/edu/ucla/sspace/common/WordComparator.java +- Moved to SimpleNearestNeighborFinder +modified: src/edu/ucla/sspace/dependency/SimpleDependencyPath.java +- Removed println +modified: src/edu/ucla/sspace/graph/AbstractGraph.java +- Added missing implementation to Subgraph class so now all the unit tests pass +modified: src/edu/ucla/sspace/graph/DirectedMultigraph.java +- Added missing implementation to Subgraph class so now all the unit tests pass +- Fixed bug for reporting the correct edge types after removal +- Removed dead code +modified: src/edu/ucla/sspace/graph/EdgeSet.java +- Updated so that disconnect() now returns the number of edges that were removed +modified: src/edu/ucla/sspace/graph/GenericEdgeSet.java +modified: src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java +modified: src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java +modified: src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java +modified: src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java +modified: src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java +- Updated to support EdgeSet interface change +deleted: src/edu/ucla/sspace/graph/GraphRandomizer.java +- Removed dead class (functionality is in Graphs.java) +modified: src/edu/ucla/sspace/graph/SimpleWeightedEdge.java +- Fixed hashCode() +deleted: src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java +- Removed dead class +modified: src/edu/ucla/sspace/graph/UndirectedMultigraph.java +- Added missing implementation to Subgraph class so now all the unit tests pass +- Fixed bug for reporting the correct edge types after removal +- Removed dead code +modified: src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java +- Updated to replace WordComparator with SimpleNearestNeighborFinder +modified: src/edu/ucla/sspace/mains/LexSubWordsiMain.java +- Updated to replace WordComparator with SimpleNearestNeighborFinder +modified: src/edu/ucla/sspace/text/LabeledParsedStringDocument.java +- Updated for new ParsedDocument interface +modified: src/edu/ucla/sspace/text/ParsedDocument.java +- Updated to specify the format of text() as the tokens with white space delimiters. +- Added a new prettyPrintText() which is the attempt to nicely format the tokens +as they would have been originally. +modified: src/edu/ucla/sspace/text/PukWaCDocumentIterator.java +- Fixed javadoc +modified: src/edu/ucla/sspace/text/UkWaCDocumentIterator.java +- Added more class javadoc +modified: src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java +- Updated to use the class instances instead of the interface +modified: src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java +- Updated to replace WordComparator with PartitioningNearestNeighborFinder +modified: src/edu/ucla/sspace/tools/SimilarityListGenerator.java +- Updated to replace WordComparator with PartitioningNearestNeighborFinder +modified: src/edu/ucla/sspace/util/HashIndexer.java +- Fixed javadoc +modified: src/edu/ucla/sspace/util/PairCounter.java +- Fixed javadoc +renamed: src/edu/ucla/sspace/util/NearestNeighborFinder.java -> src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java +- Moved so that NearestNeighborFinder can be an interface +modified: src/edu/ucla/sspace/util/ReflectionUtil.java +- Removed dead code +modified: src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java +- Added javadoc +modified: src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java +- Added javadoc +modified: test/edu/ucla/sspace/graph/DirectedMultigraphTests.java +- Uncommented out unit tests +modified: test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java +modified: test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java +modified: test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java +modified: test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java +modified: test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java +modified: test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java +modified: test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java +modified: test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java +modified: test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java +modified: test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java +- Fixed unit tests to support proper tab-delimiting of the CoNLL format +",p,https://github.com/fozziethebeat/s-space,"diff --git a/src/edu/ucla/sspace/common/Similarity.java b/src/edu/ucla/sspace/common/Similarity.java +index d56934dd..8a46db3b 100644 +--- a/src/edu/ucla/sspace/common/Similarity.java ++++ b/src/edu/ucla/sspace/common/Similarity.java +@@ -41,6 +41,7 @@ + import edu.ucla.sspace.vector.IntegerVector; + import edu.ucla.sspace.vector.SparseVector; + import edu.ucla.sspace.vector.Vector; ++import edu.ucla.sspace.vector.VectorMath; + import edu.ucla.sspace.vector.Vectors; + import edu.ucla.sspace.vector.SparseIntegerVector; + +@@ -2187,7 +2188,7 @@ public static double tanimotoCoefficient(Vector a, Vector b) { + public static double tanimotoCoefficient(DoubleVector a, DoubleVector b) { + check(a,b); + +- // IMPLEMENTATION NOTE: The Tanimoto coefficient uses the squart of the ++ // IMPLEMENTATION NOTE: The Tanimoto coefficient uses the square of the + // vector magnitudes, which we could compute by just summing the square + // of the vector values. This would save a .sqrt() call from the + // .magnitude() call. However, we expect that this method might be +@@ -2195,83 +2196,13 @@ public static double tanimotoCoefficient(DoubleVector a, DoubleVector b) { + // should only be two multiplications instaned of |nz| multiplications + // on the second call (assuming the vector instances cache their + // magnitude, which almost all do). +- double dotProduct = 0.0; + double aMagnitude = a.magnitude(); + double bMagnitude = b.magnitude(); +- +- // Check whether both vectors support fast iteration over their non-zero +- // values. If so, use only the non-zero indices to speed up the +- // computation by avoiding zero multiplications +- if (a instanceof Iterable && b instanceof Iterable) { +- // Check whether we can easily determine how many non-zero values +- // are in each vector. This value is used to select the iteration +- // order, which affects the number of get(value) calls. +- boolean useA = +- (a instanceof SparseVector && b instanceof SparseVector) +- && ((SparseVector)a).getNonZeroIndices().length < +- ((SparseVector)b).getNonZeroIndices().length; +- +- // Choose the smaller of the two to use in computing the dot +- // product. Because it would be more expensive to compute the +- // intersection of the two sets, we assume that any potential +- // misses would be less of a performance hit. +- if (useA) { +- for (DoubleEntry e : ((Iterable)a)) { +- int index = e.index(); +- double aValue = e.value(); +- double bValue = b.get(index); +- dotProduct += aValue * bValue; +- } +- } +- else { +- for (DoubleEntry e : ((Iterable)b)) { +- int index = e.index(); +- double aValue = a.get(index); +- double bValue = e.value(); +- dotProduct += aValue * bValue; +- } +- } +- } +- +- // Check whether both vectors are sparse. If so, use only the non-zero +- // indices to speed up the computation by avoiding zero multiplications +- else if (a instanceof SparseVector && b instanceof SparseVector) { +- SparseVector svA = (SparseVector)a; +- SparseVector svB = (SparseVector)b; +- int[] nzA = svA.getNonZeroIndices(); +- int[] nzB = svB.getNonZeroIndices(); +- // Choose the smaller of the two to use in computing the dot +- // product. Because it would be more expensive to compute the +- // intersection of the two sets, we assume that any potential +- // misses would be less of a performance hit. +- if (nzA.length < nzB.length) { +- for (int nz : nzA) { +- double aValue = a.get(nz); +- double bValue = b.get(nz); +- dotProduct += aValue * bValue; +- } +- } +- else { +- for (int nz : nzB) { +- double aValue = a.get(nz); +- double bValue = b.get(nz); +- dotProduct += aValue * bValue; +- } +- } +- } +- +- // Otherwise, just assume both are dense and compute the full amount +- else { +- for (int i = 0; i < b.length(); i++) { +- double aValue = a.get(i); +- double bValue = b.get(i); +- dotProduct += aValue * bValue; +- } +- } +- ++ + if (aMagnitude == 0 || bMagnitude == 0) + return 0; +- ++ ++ double dotProduct = VectorMath.dotProduct(a, b); + double aMagSq = aMagnitude * aMagnitude; + double bMagSq = bMagnitude * bMagnitude; + +@@ -2297,82 +2228,13 @@ public static double tanimotoCoefficient(IntegerVector a, IntegerVector b) { + // should only be two multiplications instaned of |nz| multiplications + // on the second call (assuming the vector instances cache their + // magnitude, which almost all do). +- int dotProduct = 0; + double aMagnitude = a.magnitude(); + double bMagnitude = b.magnitude(); + +- // Check whether both vectors support fast iteration over their non-zero +- // values. If so, use only the non-zero indices to speed up the +- // computation by avoiding zero multiplications +- if (a instanceof Iterable && b instanceof Iterable) { +- // Check whether we can easily determine how many non-zero values +- // are in each vector. This value is used to select the iteration +- // order, which affects the number of get(value) calls. +- boolean useA = +- (a instanceof SparseVector && b instanceof SparseVector) +- && ((SparseVector)a).getNonZeroIndices().length < +- ((SparseVector)b).getNonZeroIndices().length; +- // Choose the smaller of the two to use in computing the dot +- // product. Because it would be more expensive to compute the +- // intersection of the two sets, we assume that any potential +- // misses would be less of a performance hit. +- if (useA) { +- for (IntegerEntry e : ((Iterable)a)) { +- int index = e.index(); +- int aValue = e.value(); +- int bValue = b.get(index); +- dotProduct += aValue * bValue; +- } +- } +- else { +- for (IntegerEntry e : ((Iterable)b)) { +- int index = e.index(); +- int aValue = a.get(index); +- int bValue = e.value(); +- dotProduct += aValue * bValue; +- } +- } +- } +- +- // Check whether both vectors are sparse. If so, use only the non-zero +- // indices to speed up the computation by avoiding zero multiplications +- else if (a instanceof SparseVector && b instanceof SparseVector) { +- SparseVector svA = (SparseVector)a; +- SparseVector svB = (SparseVector)b; +- int[] nzA = svA.getNonZeroIndices(); +- int[] nzB = svB.getNonZeroIndices(); +- // Choose the smaller of the two to use in computing the dot +- // product. Because it would be more expensive to compute the +- // intersection of the two sets, we assume that any potential +- // misses would be less of a performance hit. +- if (nzA.length < nzB.length) { +- for (int nz : nzA) { +- int aValue = a.get(nz); +- int bValue = b.get(nz); +- dotProduct += aValue * bValue; +- } +- } +- else { +- for (int nz : nzB) { +- int aValue = a.get(nz); +- int bValue = b.get(nz); +- dotProduct += aValue * bValue; +- } +- } +- } +- +- // Otherwise, just assume both are dense and compute the full amount +- else { +- for (int i = 0; i < b.length(); i++) { +- int aValue = a.get(i); +- int bValue = b.get(i); +- dotProduct += aValue * bValue; +- } +- } +- + if (aMagnitude == 0 || bMagnitude == 0) + return 0; +- ++ ++ int dotProduct = VectorMath.dotProduct(a, b); + double aMagSq = aMagnitude * aMagnitude; + double bMagSq = bMagnitude * bMagnitude; + +diff --git a/src/edu/ucla/sspace/common/WordComparator.java b/src/edu/ucla/sspace/common/WordComparator.java +deleted file mode 100644 +index f6b76303..00000000 +--- a/src/edu/ucla/sspace/common/WordComparator.java ++++ /dev/null +@@ -1,126 +0,0 @@ +-/* +- * Copyright 2009 David Jurgens +- * +- * This file is part of the S-Space package and is covered under the terms and +- * conditions therein. +- * +- * The S-Space package is free software: you can redistribute it and/or modify +- * it under the terms of the GNU General Public License version 2 as published +- * by the Free Software Foundation and distributed hereunder to you. +- * +- * THIS SOFTWARE IS PROVIDED ""AS IS"" AND NO REPRESENTATIONS OR WARRANTIES, +- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE +- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY +- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION +- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER +- * RIGHTS. +- * +- * You should have received a copy of the GNU General Public License +- * along with this program. If not, see . +- */ +- +-package edu.ucla.sspace.common; +- +-import edu.ucla.sspace.util.BoundedSortedMultiMap; +-import edu.ucla.sspace.util.MultiMap; +-import edu.ucla.sspace.util.SortedMultiMap; +-import edu.ucla.sspace.util.WorkQueue; +- +-import edu.ucla.sspace.vector.Vector; +- +-import java.util.Map; +-import java.util.Set; +-import java.util.SortedMap; +- +- +-/** +- * A utility class for finding the {@code k} most-similar words to a provided +- * word in a {@link SemanticSpace}. The comparisons required for generating the +- * list maybe be run in parallel by configuring an instance of this class to use +- * multiple threads.

+- * +- * All instances of this class are thread-safe. +- * +- * @author David Jurgens +- */ +-public class WordComparator { +- +- /** +- * The {@link WorkQueue} from which worker threads run word-word comparisons +- */ +- private final WorkQueue workQueue; +- +- /** +- * Creates this {@code WordComparator} with as many threads as processors. +- */ +- public WordComparator() { +- this(Runtime.getRuntime().availableProcessors()); +- } +- +- /** +- * Creates this {@code WordComparator} with the specified number of threads. +- */ +- public WordComparator(int numThreads) { +- workQueue = WorkQueue.getWorkQueue(numThreads); +- } +- +- /** +- * Compares the provided word to all other words in the provided {@link +- * SemanticSpace} and return the specified number of words that were most +- * similar according to the specified similarity measure. +- * +- * @return the most similar words, or {@code null} if the provided word was +- * not in the semantic space. +- */ +- public SortedMultiMap getMostSimilar( +- final String word, final SemanticSpace sspace, +- int numberOfSimilarWords, final Similarity.SimType similarityType) { +- +- Vector v = sspace.getVector(word); +- +- // if the semantic space did not have the word, then return null +- if (v == null) { +- return null; +- } +- +- final Vector vector = v; +- return getMostSimilar(v, sspace, numberOfSimilarWords, similarityType); +- } +- +- public SortedMultiMap getMostSimilar( +- final Vector vector, final SemanticSpace sspace, +- int numberOfSimilarWords, final Similarity.SimType similarityType) { +- Set words = sspace.getWords(); +- +- // the most-similar set will automatically retain only a fixed number +- // of elements +- final SortedMultiMap mostSimilar = +- new BoundedSortedMultiMap(numberOfSimilarWords, +- false); +- +- Object key = workQueue.registerTaskGroup(words.size()); +- +- // loop through all the other words computing their similarity +- for (final String other : words) { +- workQueue.add(key, new Runnable() { +- public void run() { +- Vector otherV = sspace.getVector(other); +- // Skip the comparison if the vectors are actually the same. +- if (otherV == vector) +- return; +- +- Double similarity = Similarity.getSimilarity( +- similarityType, vector, otherV); +- +- // lock on the Map, as it is not thread-safe +- synchronized(mostSimilar) { +- mostSimilar.put(similarity, other); +- } +- } +- }); +- } +- +- workQueue.await(key); +- return mostSimilar; +- } +-} +diff --git a/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java b/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java +index 576caa6f..51343ad8 100644 +--- a/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java ++++ b/src/edu/ucla/sspace/dependency/SimpleDependencyPath.java +@@ -73,7 +73,6 @@ public SimpleDependencyPath(List path, + nodes.add(next); + cur = next; + } +- System.out.printf(""path: %s,%nnodes: %s%n"", path, nodes); + } + + /** +diff --git a/src/edu/ucla/sspace/graph/AbstractGraph.java b/src/edu/ucla/sspace/graph/AbstractGraph.java +index 2ffa38fe..d9189a42 100755 +--- a/src/edu/ucla/sspace/graph/AbstractGraph.java ++++ b/src/edu/ucla/sspace/graph/AbstractGraph.java +@@ -967,8 +967,10 @@ public Set getAdjacencyList(int vertex) { + * {@inheritDoc} + */ + public IntSet getNeighbors(int vertex) { +- if (!vertexSubset.contains(vertex)) +- return PrimitiveCollections.emptyIntSet(); ++ return (!vertexSubset.contains(vertex)) ++ ? PrimitiveCollections.emptyIntSet() ++ : new SubgraphNeighborsView(vertex); ++ /* + // REMINDER: make this a view, rather than a created set + IntSet neighbors = new TroveIntSet(); + IntIterator it = +@@ -979,6 +981,7 @@ public IntSet getNeighbors(int vertex) { + neighbors.add(v); + } + return neighbors; ++ */ + } + + /** +@@ -1084,7 +1087,7 @@ public IntSet vertices() { + * subgraph. This class monitors for changes to edge set to update the + * state of this graph + */ +- private class SubgraphAdjacencyListView extends AbstractSet { ++ private class SubgraphAdjacencyListView extends AbstractSet { + + private final int root; + +@@ -1275,7 +1278,7 @@ public void remove() { + * subview. This view monitors for additions and removals to the set in + * order to update the state of this {@code Subgraph}. + */ +- private class SubgraphNeighborsView extends AbstractSet { ++ private class SubgraphNeighborsView extends AbstractIntSet { + + private int root; + +@@ -1285,15 +1288,20 @@ private class SubgraphNeighborsView extends AbstractSet { + public SubgraphNeighborsView(int root) { + this.root = root; + } ++ ++ public boolean add(int vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot add vertices to subgraph""); ++ } + +- /** +- * Adds an edge to this vertex and adds the vertex to the graph if it +- * was not present before. +- */ + public boolean add(Integer vertex) { + throw new UnsupportedOperationException( + ""Cannot add vertices to subgraph""); + } ++ ++ public boolean contains(int vertex) { ++ return vertexSubset.contains(vertex) && checkVertex(vertex); ++ } + + public boolean contains(Object o) { + if (!(o instanceof Integer)) +@@ -1309,12 +1317,18 @@ private boolean checkVertex(int i) { + return AbstractGraph.this.contains(i, root); + } + +- public Iterator iterator() { ++ public IntIterator iterator() { + return new SubgraphNeighborsIterator(); + } + +- public boolean remove(Object o) { +- throw new UnsupportedOperationException(); ++ public boolean remove(int vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot remove vertices from subgraph""); ++ } ++ ++ public boolean remove(Object vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot remove vertices from subgraph""); + } + + public int size() { +@@ -1333,7 +1347,7 @@ public int size() { + * vertices set, which keeps track of which neighboring vertices are + * actually in this subview. + */ +- private class SubgraphNeighborsIterator implements Iterator { ++ private class SubgraphNeighborsIterator implements IntIterator { + + private final IntIterator iter; + +@@ -1368,6 +1382,10 @@ public Integer next() { + return cur; + } + ++ public int nextInt() { ++ return next(); ++ } ++ + /** + * Throws an {@link UnsupportedOperationException} if called. + */ +diff --git a/src/edu/ucla/sspace/graph/DirectedMultigraph.java b/src/edu/ucla/sspace/graph/DirectedMultigraph.java +index 9a2b60c5..0792e9d1 100644 +--- a/src/edu/ucla/sspace/graph/DirectedMultigraph.java ++++ b/src/edu/ucla/sspace/graph/DirectedMultigraph.java +@@ -43,6 +43,8 @@ + import edu.ucla.sspace.util.DisjointSets; + import edu.ucla.sspace.util.SetDecorator; + ++import edu.ucla.sspace.util.primitive.AbstractIntSet; ++import edu.ucla.sspace.util.primitive.IntIterator; + import edu.ucla.sspace.util.primitive.IntSet; + import edu.ucla.sspace.util.primitive.PrimitiveCollections; + import edu.ucla.sspace.util.primitive.TroveIntSet; +@@ -51,8 +53,9 @@ + import gnu.trove.iterator.TIntIterator; + import gnu.trove.iterator.TIntObjectIterator; + import gnu.trove.map.TIntObjectMap; ++import gnu.trove.map.TObjectIntMap; + import gnu.trove.map.hash.TIntObjectHashMap; +-import gnu.trove.procedure.TObjectProcedure; ++import gnu.trove.map.hash.TObjectIntHashMap; + import gnu.trove.set.TIntSet; + import gnu.trove.set.hash.TIntHashSet; + +@@ -72,9 +75,9 @@ public class DirectedMultigraph + private static final long serialVersionUID = 1L; + + /** +- * The set of types contained in this graph. ++ * The count of the type distribution for all edges in the graph. + */ +- private final Set types; ++ private final TObjectIntMap typeCounts; + + /** + * The set of vertices in this mutligraph. This set is maintained +@@ -104,7 +107,7 @@ public class DirectedMultigraph + * Creates an empty graph with node edges + */ + public DirectedMultigraph() { +- types = new HashSet(); ++ typeCounts = new TObjectIntHashMap(); + vertexToEdges = new TIntObjectHashMap>(); + subgraphs = new ArrayList>(); + size = 0; +@@ -143,7 +146,7 @@ public boolean add(DirectedTypedEdge e) { + vertexToEdges.put(e.from(), from); + } + if (from.add(e)) { +- types.add(e.edgeType()); ++ updateTypeCounts(e.edgeType(), 1); + SparseDirectedTypedEdgeSet to = vertexToEdges.get(e.to()); + if (to == null) { + to = new SparseDirectedTypedEdgeSet(e.to()); +@@ -161,7 +164,7 @@ public boolean add(DirectedTypedEdge e) { + */ + public void clear() { + vertexToEdges.clear(); +- types.clear(); ++ typeCounts.clear(); + size = 0; + } + +@@ -225,14 +228,10 @@ public DirectedMultigraph copy(Set toCopy) { + return new DirectedMultigraph(this); + + DirectedMultigraph g = new DirectedMultigraph(); +- //long s = System.currentTimeMillis(); + for (int v : toCopy) { + if (!vertexToEdges.containsKey(v)) + throw new IllegalArgumentException( + ""Request copy of non-present vertex: "" + v); +-// SparseDirectedTypedEdgeSet edges = vertexToEdges.get(v); +-// g.vertexToEdges.put(v, edges.copy(toCopy)); +- + g.add(v); + SparseDirectedTypedEdgeSet edges = vertexToEdges.get(v); + if (edges == null) +@@ -245,8 +244,6 @@ public DirectedMultigraph copy(Set toCopy) { + g.add(e); + } + } +-// if (toCopy.size() > 0) +-// System.out.printf(""Copy %d vertices (%d), %d edges%n"", g.order(), toCopy.size(), g.size()); + return g; + } + +@@ -284,7 +281,7 @@ public Set> edges(T t) { + * Returns the set of edge types currently present in this graph. + */ + public Set edgeTypes() { +- return Collections.unmodifiableSet(types); ++ return Collections.unmodifiableSet(typeCounts.keySet()); + } + + /** +@@ -293,7 +290,7 @@ public Set edgeTypes() { + @Override public boolean equals(Object o) { + if (o instanceof DirectedMultigraph) { + DirectedMultigraph dm = (DirectedMultigraph)(o); +- if (dm.types.equals(types)) { ++ if (dm.typeCounts.equals(typeCounts)) { + return vertexToEdges.equals(dm.vertexToEdges); + } + return false; +@@ -301,7 +298,7 @@ public Set edgeTypes() { + else if (o instanceof Multigraph) { + @SuppressWarnings(""unchecked"") + Multigraph> m = (Multigraph>)o; +- if (m.edgeTypes().equals(types)) { ++ if (m.edgeTypes().equals(typeCounts.keySet())) { + return m.order() == order() + && m.size() == size() + && m.vertices().equals(vertices()) +@@ -372,7 +369,7 @@ public boolean hasCycles() { + * {@inheritDoc} + */ + public int hashCode() { +- return vertexToEdges.keySet().hashCode() ^ (types.hashCode() * size); ++ return vertexToEdges.keySet().hashCode() ^ (typeCounts.hashCode() * size); + } + + /** +@@ -448,6 +445,8 @@ public boolean remove(int vertex) { + // Check whether removing this vertex has caused us to remove + // the last edge for this type in the graph. If so, the graph + // no longer has this type and we need to update the state. ++ for (DirectedTypedEdge e : edges) ++ updateTypeCounts(e.edgeType(), -1); + + // Update any of the subgraphs that had this vertex to notify them + // that it was removed +@@ -467,7 +466,7 @@ public boolean remove(int vertex) { + if (s.vertexSubset.remove(vertex)) { + Iterator subgraphTypesIter = s.validTypes.iterator(); + while (subgraphTypesIter.hasNext()) { +- if (!types.contains(subgraphTypesIter.next())) ++ if (!typeCounts.containsKey(subgraphTypesIter.next())) + subgraphTypesIter.remove(); + } + } +@@ -488,25 +487,24 @@ public boolean remove(DirectedTypedEdge edge) { + // Check whether we've just removed the last edge for this type + // in the graph. If so, the graph no longer has this type and + // we need to update the state. +- +- // TODO !! +- +- +- // Remove this edge type from all the subgraphs as well +- Iterator> sIt = subgraphs.iterator(); +- while (sIt.hasNext()) { +- WeakReference ref = sIt.next(); +- Subgraph s = ref.get(); +- // Check whether this subgraph was already gc'd (the +- // subgraph was no longer in use) and if so, remove the +- // ref from the list to avoid iterating over it again +- if (s == null) { +- sIt.remove(); +- continue; ++ updateTypeCounts(edge.edgeType(), -1); ++ ++ if (!typeCounts.containsKey(edge.edgeType())) { ++ // Remove this edge type from all the subgraphs as well ++ Iterator> sIt = subgraphs.iterator(); ++ while (sIt.hasNext()) { ++ WeakReference ref = sIt.next(); ++ Subgraph s = ref.get(); ++ // Check whether this subgraph was already gc'd (the ++ // subgraph was no longer in use) and if so, remove the ++ // ref from the list to avoid iterating over it again ++ if (s == null) { ++ sIt.remove(); ++ continue; ++ } ++ s.validTypes.remove(edge.edgeType()); + } +- // FILL IN... + } +- + return true; + } + return false; +@@ -517,19 +515,6 @@ public boolean remove(DirectedTypedEdge edge) { + */ + public int size() { + return size; +-// CountingProcedure count = new CountingProcedure(); +-// vertexToEdges.forEachValue(count); +-// return count.count / 2; +- } +- +- private class CountingProcedure +- implements TObjectProcedure> { +- +- int count = 0; +- public boolean execute(SparseDirectedTypedEdgeSet edges) { +- count += edges.size(); +- return true; +- } + } + + /** +@@ -546,7 +531,7 @@ public IntSet successors(int vertex) { + * {@inheritDoc} + */ + public DirectedMultigraph subgraph(Set subset) { +- Subgraph sub = new Subgraph(types, subset); ++ Subgraph sub = new Subgraph(typeCounts.keySet(), subset); + subgraphs.add(new WeakReference(sub)); + return sub; + } +@@ -557,7 +542,7 @@ public DirectedMultigraph subgraph(Set subset) { + public DirectedMultigraph subgraph(Set subset, Set edgeTypes) { + if (edgeTypes.isEmpty()) + throw new IllegalArgumentException(""Must specify at least one type""); +- if (!types.containsAll(edgeTypes)) { ++ if (!typeCounts.keySet().containsAll(edgeTypes)) { + throw new IllegalArgumentException( + ""Cannot create subgraph with more types than exist""); + } +@@ -574,12 +559,33 @@ public String toString() { + return ""{ vertices: "" + vertices() + "", edges: "" + edges() + ""}""; + } + ++ /** ++ * Updates how many edges have this type in the graph ++ */ ++ private void updateTypeCounts(T type, int delta) { ++ if (!typeCounts.containsKey(type)) { ++ assert delta > 0 ++ : ""removing edge type that was not originally present""; ++ typeCounts.put(type, delta); ++ } ++ else { ++ int curCount = typeCounts.get(type); ++ int newCount = curCount + delta; ++ assert newCount >= 0 ++ : ""removing edge type that was not originally present""; ++ if (newCount == 0) ++ typeCounts.remove(type); ++ else ++ typeCounts.put(type, newCount); ++ } ++ } ++ + /** + * {@inheritDoc} + */ + public IntSet vertices() { +- // TODO: make this unmodifiable +- return TroveIntSet.wrap(vertexToEdges.keySet()); ++ return PrimitiveCollections.unmodifiableSet( ++ TroveIntSet.wrap(vertexToEdges.keySet())); + } + + /** +@@ -611,8 +617,8 @@ public Iterator> iterator() { + public boolean remove(Object o) { + if (o instanceof DirectedTypedEdge) { + DirectedTypedEdge e = (DirectedTypedEdge)o; +- return DirectedMultigraph.this.types. +- contains(e.edgeType()) ++ return DirectedMultigraph.this.typeCounts. ++ containsKey(e.edgeType()) + && DirectedMultigraph.this.remove((DirectedTypedEdge)o); + } + return false; +@@ -933,7 +939,7 @@ public IntSet getNeighbors(int vertex) { + SparseDirectedTypedEdgeSet edges = vertexToEdges.get(vertex); + return (edges == null) + ? PrimitiveCollections.emptyIntSet() +- : PrimitiveCollections.unmodifiableSet(edges.connected()); ++ : new SubgraphNeighborsView(vertex); + } + + /** +@@ -947,7 +953,7 @@ public boolean hasCycles() { + * {@inheritDoc} + */ + public int hashCode() { +- return vertices().hashCode() ^ (types.hashCode() * size()); ++ return vertices().hashCode() ^ (validTypes.hashCode() * size()); + } + + /** +@@ -1118,7 +1124,6 @@ public DirectedMultigraph subgraph(Set verts, Set edgeTypes) { + * {@inheritDoc} + */ + public IntSet vertices() { +- // Check that the vertices are up to date with the backing graph + return PrimitiveCollections.unmodifiableSet(vertexSubset); + } + +@@ -1323,7 +1328,7 @@ public void remove() { + * subview. This view monitors for additions and removals to the set in + * order to update the state of this {@code Subgraph}. + */ +- private class SubgraphNeighborsView extends AbstractSet { ++ private class SubgraphNeighborsView extends AbstractIntSet { + + private int root; + +@@ -1333,15 +1338,21 @@ private class SubgraphNeighborsView extends AbstractSet { + public SubgraphNeighborsView(int root) { + this.root = root; + } ++ ++ public boolean add(int vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot add vertices to subgraph""); ++ } + +- /** +- * Adds an edge to this vertex and adds the vertex to the graph if it +- * was not present before. +- */ + public boolean add(Integer vertex) { + throw new UnsupportedOperationException( + ""Cannot add vertices to subgraph""); + } ++ ++ public boolean contains(int vertex) { ++ return vertexSubset.contains(vertex) ++ && isNeighboringVertex(vertex); ++ } + + public boolean contains(Object o) { + if (!(o instanceof Integer)) +@@ -1354,12 +1365,18 @@ private boolean isNeighboringVertex(Integer i) { + return Subgraph.this.contains(root, i); + } + +- public Iterator iterator() { ++ public IntIterator iterator() { + return new SubgraphNeighborsIterator(); + } + +- public boolean remove(Object o) { +- throw new UnsupportedOperationException(); ++ public boolean remove(int vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot remove vertices from subgraph""); ++ } ++ ++ public boolean remove(Object vertex) { ++ throw new UnsupportedOperationException( ++ ""Cannot remove vertices from subgraph""); + } + + public int size() { +@@ -1376,7 +1393,7 @@ public int size() { + * vertices set, which keeps track of which neighboring vertices are + * actually in this subview. + */ +- private class SubgraphNeighborsIterator implements Iterator { ++ private class SubgraphNeighborsIterator implements IntIterator { + + private final Iterator iter; + +@@ -1411,6 +1428,10 @@ public Integer next() { + return cur; + } + ++ public int nextInt() { ++ return next(); ++ } ++ + /** + * Throws an {@link UnsupportedOperationException} if called. + */ +diff --git a/src/edu/ucla/sspace/graph/EdgeSet.java b/src/edu/ucla/sspace/graph/EdgeSet.java +index 49facf17..eec197e7 100755 +--- a/src/edu/ucla/sspace/graph/EdgeSet.java ++++ b/src/edu/ucla/sspace/graph/EdgeSet.java +@@ -64,9 +64,10 @@ public interface EdgeSet extends Set { + EdgeSet copy(IntSet vertices); + + /** +- * Removes all edges instances that connect to the specified vertex. ++ * Removes all edges instances that connect to the specified vertex, ++ * returning the number of edges that were removed, if any. + */ +- boolean disconnect(int vertex); ++ int disconnect(int vertex); + + /** + * Returns the set of {@link Edge} instances that connect the root vertex +diff --git a/src/edu/ucla/sspace/graph/GenericEdgeSet.java b/src/edu/ucla/sspace/graph/GenericEdgeSet.java +index 97ca6fe0..1674aee2 100644 +--- a/src/edu/ucla/sspace/graph/GenericEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/GenericEdgeSet.java +@@ -40,46 +40,34 @@ + * edges that may be contained within. This class keeps track of which vertices + * are in the set as well, allowing for efficient vertex-based operations. + * +- *

Due not knowing the {@link Edge} type, this class prevents modification via +- * adding or removing vertices. +- * + * @author David Jurgens + * + * @param T the type of edge to be stored in the set + */ + public class GenericEdgeSet extends AbstractSet +- implements EdgeSet { ++ implements EdgeSet, java.io.Serializable { + ++ private static final long serialVersionUID = 1L; ++ ++ /** ++ * The vertex to which all edges in the set are connected ++ */ + private final int rootVertex; + +-// private final BitSet vertices; +- +-// private final Set edges; +- ++ /** ++ * A mapping from connected vertices to the edges that connect to them ++ */ + private final MultiMap vertexToEdges ; + + public GenericEdgeSet(int rootVertex) { + this.rootVertex = rootVertex; +-// edges = new HashSet(); +-// vertices = new BitSet(); + vertexToEdges = new HashMultiMap(); + } + + /** +- * Adds the edge to this set if one of the vertices is the root vertex and +- * if the non-root vertex has a greater index that this vertex. ++ * {@inheritDoc} + */ + public boolean add(T e) { +-// if (e.from() == rootVertex && edges.add(e)) { +-// connected.set(e.to()); +-// return true; +-// } +-// else if (e.to() == rootVertex && edges.add(e)) { +-// connected.add(e.from()); +-// return true; +-// } +-// return false; +- + return (e.from() == rootVertex && vertexToEdges.put(e.to(), e)) + || (e.to() == rootVertex && vertexToEdges.put(e.from(), e)); + } +@@ -96,15 +84,16 @@ public IntSet connected() { + * {@inheritDoc} + */ + public boolean connects(int vertex) { +- return vertexToEdges.containsKey(vertex); //vertices.get(vertex); ++ return vertexToEdges.containsKey(vertex); + } + + + /** + * {@inheritDoc} + */ +- public boolean disconnect(int vertex) { +- return vertexToEdges.remove(vertex) != null; ++ public int disconnect(int vertex) { ++ Set edges = vertexToEdges.remove(vertex); ++ return (edges == null) ? 0 : edges.size(); + } + + /** +diff --git a/src/edu/ucla/sspace/graph/GraphRandomizer.java b/src/edu/ucla/sspace/graph/GraphRandomizer.java +deleted file mode 100644 +index cb1f2f4a..00000000 +--- a/src/edu/ucla/sspace/graph/GraphRandomizer.java ++++ /dev/null +@@ -1,126 +0,0 @@ +-/* +- * Copyright 2011 David Jurgens +- * +- * This file is part of the S-Space package and is covered under the terms and +- * conditions therein. +- * +- * The S-Space package is free software: you can redistribute it and/or modify +- * it under the terms of the GNU General Public License version 2 as published +- * by the Free Software Foundation and distributed hereunder to you. +- * +- * THIS SOFTWARE IS PROVIDED ""AS IS"" AND NO REPRESENTATIONS OR WARRANTIES, +- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE +- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY +- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION +- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER +- * RIGHTS. +- * +- * You should have received a copy of the GNU General Public License +- * along with this program. If not, see . +- */ +- +-package edu.ucla.sspace.graph; +- +-import java.util.ArrayList; +-import java.util.Iterator; +-import java.util.List; +-import java.util.Set; +- +- +-public class GraphRandomizer { +- +- public static void shufflePreserveDegreeInMemory(Graph g) { +- +- List edges = new ArrayList(g.edges()); +- +- // Decide on number of iterations +- int swapIterations = 3 * g.size(); +- for (int s = 0; s < swapIterations; ++s) { +- +- // Pick two vertices from which the edges will be selected +- int i = (int)(Math.random() * edges.size()); +- int j = i; +- // Pick another vertex that is not v1 +- while (i == j) +- j = (int)(Math.random() * edges.size()); +- +- T e1 = edges.get(i); +- T e2 = edges.get(j); +- +- // Swap their end points +- T swapped1 = e1.clone(e1.from(), e2.to()); +- T swapped2 = e2.clone(e2.from(), e1.to()); +- +- // Check that the new edges do not already exist in the graph +- if (g.contains(swapped1) +- || g.contains(swapped2)) +- continue; +- +- // Remove the old edges +- g.remove(e1); +- g.remove(e2); +- +- // Put in the swapped-end-point edges +- g.add(swapped1); +- g.add(swapped2); +- +- // Update the in-memory edges set so that if these edges are drawn +- // again, they don't point to old edges +- edges.set(i, swapped1); +- edges.set(j, swapped2); +- } +- } +- +- public static void shufflePreserveDegree(Graph g) { +- +- // Copy the vertices to a list to support random access +- List vertices = new ArrayList(g.vertices()); +- +- // Decide on number of iterations +- int swapIterations = 3 * g.size(); +- for (int i = 0; i < swapIterations; ++i) { +- +- // Pick two vertices from which the edges will be selected +- int v1 = vertices.get((int)(Math.random() * vertices.size())); +- int v2 = v1; +- // Pick another vertex that is not v1 +- while (v1 == v2) +- v2 = vertices.get((int)(Math.random() * vertices.size())); +- +- // From the two vertices, select an edge from each of their adjacency +- // lists. +- T e1 = getRandomEdge(g.getAdjacencyList(v1)); +- T e2 = getRandomEdge(g.getAdjacencyList(v2)); +- +- // Swap their end points +- T swapped1 = e1.clone(e1.from(), e2.to()); +- T swapped2 = e2.clone(e2.from(), e1.to()); +- +- // Check that the new edges do not already exist in the graph +- if (g.contains(swapped1) +- || g.contains(swapped2)) +- continue; +- +- // Remove the old edges +- g.remove(e1); +- g.remove(e2); +- +- // Put in the swapped-end-point edges +- g.add(swapped1); +- g.add(swapped2); +- } +- } +- +- private static T getRandomEdge(Set edges) { +- int edgeToSelect = (int)(edges.size() * Math.random()); +- Iterator it = edges.iterator(); +- int i = 0; +- while (it.hasNext()) { +- T edge = it.next(); +- if (i == edgeToSelect) +- return edge; +- i++; +- } +- throw new AssertionError(""Random edge selection logic is incorrect""); +- } +-} +\ No newline at end of file +diff --git a/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java b/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java +index eae597ea..c45988e2 100644 +--- a/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java ++++ b/src/edu/ucla/sspace/graph/SimpleWeightedEdge.java +@@ -70,8 +70,7 @@ public boolean equals(Object o) { + * {@inheritDoc} + */ + public int hashCode() { +- long bits = Double.doubleToLongBits(weight); +- return from ^ to ^ (int)(bits ^ (bits >>> 32)); ++ return from ^ to; + } + + /** +diff --git a/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java +index a0dd1768..5b3ba736 100644 +--- a/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java +@@ -43,7 +43,9 @@ + * @author David Jurgens + */ + public class SparseDirectedEdgeSet extends AbstractSet +- implements EdgeSet { ++ implements EdgeSet, java.io.Serializable { ++ ++ private static final long serialVersionUID = 1L; + + /** + * The vertex to which all edges in the set are connected +@@ -149,8 +151,13 @@ public SparseDirectedEdgeSet copy(IntSet vertices) { + /** + * {@inheritDoc} + */ +- public boolean disconnect(int vertex) { +- return inEdges.remove(vertex) | outEdges.remove(vertex); ++ public int disconnect(int vertex) { ++ int removed = 0; ++ if (inEdges.remove(vertex)) ++ removed++; ++ if (outEdges.remove(vertex)) ++ removed++; ++ return removed; + } + + /** +diff --git a/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java +index 2c6828a1..e267bddb 100644 +--- a/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/SparseDirectedTypedEdgeSet.java +@@ -59,9 +59,10 @@ + + + /** +- * An {@link EdgeSet} implementation that stores {@link TypedEdge} instances for +- * a vertex. This class provides additional methods beyond the {@code EdgeSet} +- * interface for interacting with edges on the basis of their type. ++ * An {@link EdgeSet} implementation that stores {@link DirectedTypedEdge} ++ * instances for a vertex. This class provides additional methods beyond the ++ * {@code EdgeSet} interface for interacting with edges on the basis of their ++ * type and their orientation. + */ + public class SparseDirectedTypedEdgeSet + extends AbstractSet> +@@ -305,6 +306,8 @@ public SparseDirectedTypedEdgeSet copy(IntSet vertices) { + * reasons. I was hoping the DirectedMultigraph.copy() could be sped up by + * copying the raw data faster than the Edge-based data, but this + * implementation actually slows down DirectedMultigraph.copy() by 100X. ++ * It's being left in as a future study on how to fix it to speed up the ++ * copy operation. + */ + + // public SparseDirectedTypedEdgeSet copy(Set vertices) { +@@ -340,19 +343,28 @@ public SparseDirectedTypedEdgeSet copy(IntSet vertices) { + // } + + /** +- * Removes all edges to {@code v}. ++ * {@inheritDoc} + */ +- public boolean disconnect(int v) { ++ public int disconnect(int v) { + if (connected.remove(v)) { ++ int removed = 0; + BitSet b = inEdges.remove(v); +- if (b != null) +- size -= b.cardinality(); ++ if (b != null) { ++ int edges = b.cardinality(); ++ size -= edges; ++ removed += edges; ++ } + b = outEdges.remove(v); +- if (b != null) +- size -= b.cardinality(); +- return true; ++ if (b != null) { ++ int edges = b.cardinality(); ++ size -= edges; ++ removed += edges; ++ } ++ assert removed > 0 : ++ ""connected removed an edge that wasn't listed elsewhere""; ++ return removed; + } +- return false; ++ return 0; + } + + /** +diff --git a/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java b/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java +deleted file mode 100755 +index 82a5e461..00000000 +--- a/src/edu/ucla/sspace/graph/SparseSymmetricEdgeSet.java ++++ /dev/null +@@ -1,175 +0,0 @@ +-/* +- * Copyright 2011 David Jurgens +- * +- * This file is part of the S-Space package and is covered under the terms and +- * conditions therein. +- * +- * The S-Space package is free software: you can redistribute it and/or modify +- * it under the terms of the GNU General Public License version 2 as published +- * by the Free Software Foundation and distributed hereunder to you. +- * +- * THIS SOFTWARE IS PROVIDED ""AS IS"" AND NO REPRESENTATIONS OR WARRANTIES, +- * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE +- * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY +- * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION +- * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER +- * RIGHTS. +- * +- * You should have received a copy of the GNU General Public License +- * along with this program. If not, see . +- */ +- +-package edu.ucla.sspace.graph; +- +-import java.util.AbstractSet; +-import java.util.Collections; +-import java.util.Iterator; +-import java.util.Set; +- +-import edu.ucla.sspace.util.OpenIntSet; +- +- +-/** +- * +- */ +-public class SparseSymmetricEdgeSet { +- +- private final int rootVertex; +- +- private final OpenIntSet edges; +- +- public SparseSymmetricEdgeSet(int rootVertex) { +- this.rootVertex = rootVertex; +- edges = new OpenIntSet(); +- } +- +- /** +- * Adds the edge to this set if one of the vertices is the root vertex and +- * if the non-root vertex has a greater index that this vertex. +- */ +- public boolean add(Edge e) { +- int toAdd = -1; +- if (e.from() == rootVertex) { +- toAdd = e.to(); +- } +- else { +- if (e.to() != rootVertex) +- return false; +- // else e.to() == rootVertex +- toAdd = e.from(); +- } +- +- // Only add the vertex if the index for it is greated than this vertex. +- // In a set of EdgeSets, this ensure that for two indices i,j only one +- // edge is ever present +- if (rootVertex < toAdd) +- return edges.add(toAdd); +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- public Set connected() { +- // REMINDER: wrap to prevent adding self edges? +- return edges; +- } +- +- /** +- * {@inheritDoc} +- */ +- public boolean connects(int vertex) { +- return edges.contains(vertex); +- } +- +- /** +- * {@inheritDoc} +- */ +- public boolean contains(Object o) { +- if (o instanceof Edge) { +- Edge e = (Edge)o; +- if (e.to() == rootVertex) +- return e.from() > rootVertex && edges.contains(e.from()); +- else +- return e.from() == rootVertex && edges.contains(e.to()); +- } +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- public boolean disconnect(int vertex) { +- return edges.remove(vertex); +- } +- +- /** +- * {@inheritDoc} +- */ +- public Set getEdges(int vertex) { +- return (edges.contains(vertex)) +- ? Collections.singleton(new SimpleEdge(rootVertex, vertex)) +- : null; +- } +- +- /** +- * {@inheritDoc} +- */ +- public int getRoot() { +- return rootVertex; +- } +- +- /** +- * {@inheritDoc} +- */ +- public Iterator iterator() { +- return new EdgeIterator(); +- } +- +- /** +- * {@inheritDoc} +- */ +- public boolean remove(Object o) { +- if (o instanceof Edge) { +- Edge e = (Edge)o; +- if (e.to() == rootVertex) +- return e.from() > rootVertex && edges.remove(e.from()); +- else +- return e.from() == rootVertex && edges.remove(e.to()); +- } +- return false; +- } +- +- /** +- * {@inheritDoc} +- */ +- public int size() { +- return edges.size(); +- } +- +- /** +- * An iterator over the edges in this set that constructs {@link Edge} +- * instances as it traverses through the set of connected vertices. +- */ +- private class EdgeIterator implements Iterator { +- +- private Iterator otherVertices; +- +- public EdgeIterator() { +- otherVertices = edges.iterator(); +- } +- +- public boolean hasNext() { +- return otherVertices.hasNext(); +- } +- +- public Edge next() { +- Integer i = otherVertices.next(); +- return new SimpleEdge(rootVertex, i); +- } +- +- public void remove() { +- otherVertices.remove(); +- } +- } +-} +\ No newline at end of file +diff --git a/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java +index 56fc0271..1dffc854 100644 +--- a/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/SparseTypedEdgeSet.java +@@ -278,15 +278,16 @@ public SparseTypedEdgeSet copy(IntSet vertices) { + } + + /** +- * Removes all edges to {@code v}. ++ * {@inheritDoc} + */ +- public boolean disconnect(int v) { ++ public int disconnect(int v) { + BitSet b = edges.remove(v); + if (b != null) { +- size -= b.cardinality(); +- return true; ++ int edges = b.cardinality(); ++ size -= edges; ++ return edges; + } +- return false; ++ return 0; + } + + /** +@@ -518,7 +519,10 @@ else if (curIndex != oldIndex) { + } + } + +- ++ /** ++ * A utility class for exposing the objects for types of the edges in this ++ * set, which are otherwise represented as bits. ++ */ + private class Types extends AbstractSet { + + public boolean contains(Object o) { +diff --git a/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java +index 67c991c6..705fc71f 100644 +--- a/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/SparseUndirectedEdgeSet.java +@@ -41,7 +41,9 @@ + * A {@link EdgeSet} implementation for holding {@link Edge} instances. + */ + public class SparseUndirectedEdgeSet extends AbstractSet +- implements EdgeSet { ++ implements EdgeSet, java.io.Serializable { ++ ++ private static final long serialVersionUID = 1L; + + /** + * The vertex that is connected to all the edges in this set +@@ -135,8 +137,8 @@ public SparseUndirectedEdgeSet copy(IntSet vertices) { + /** + * {@inheritDoc} + */ +- public boolean disconnect(int vertex) { +- return edges.remove(vertex); ++ public int disconnect(int vertex) { ++ return (edges.remove(vertex)) ? 1 : 0; + } + + /** +diff --git a/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java b/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java +index 448a0cec..bb022d0c 100644 +--- a/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java ++++ b/src/edu/ucla/sspace/graph/SparseWeightedEdgeSet.java +@@ -49,7 +49,7 @@ + * two vertices will only have at most one edge between them. If an edge exists + * for vertices {@code i} and {@code j} with weight {@code w}1, then + * adding a new edge to the same vertices with weight {@code w}2 will +- * not add a parallel edge and increase the set of this set, even though the ++ * not add a parallel edge and increase the size of this set, even though the + * edges are not equal. Rather, the weight on the edge between the two vertices + * is changed to {@code w}2. Similarly, any contains or removal + * operation will return its value based on the {@code WeightedEdge}'s vertices +@@ -176,12 +176,12 @@ public SparseWeightedEdgeSet copy(IntSet vertices) { + /** + * {@inheritDoc} + */ +- public boolean disconnect(int vertex) { ++ public int disconnect(int vertex) { + if (edges.containsKey(vertex)) { + edges.remove(vertex); +- return true; ++ return 1; + } +- return false; ++ return 0; + } + + /** +diff --git a/src/edu/ucla/sspace/graph/UndirectedMultigraph.java b/src/edu/ucla/sspace/graph/UndirectedMultigraph.java +index 90983a6c..f74e9b63 100644 +--- a/src/edu/ucla/sspace/graph/UndirectedMultigraph.java ++++ b/src/edu/ucla/sspace/graph/UndirectedMultigraph.java +@@ -53,8 +53,9 @@ + import gnu.trove.iterator.TIntIterator; + import gnu.trove.iterator.TIntObjectIterator; + import gnu.trove.map.TIntObjectMap; ++import gnu.trove.map.TObjectIntMap; + import gnu.trove.map.hash.TIntObjectHashMap; +-import gnu.trove.procedure.TObjectProcedure; ++import gnu.trove.map.hash.TObjectIntHashMap; + import gnu.trove.set.TIntSet; + import gnu.trove.set.hash.TIntHashSet; + +@@ -73,9 +74,9 @@ public class UndirectedMultigraph + private static final long serialVersionUID = 1L; + + /** +- * The set of types contained in this graph. ++ * The count of the type distribution for all edges in the graph. + */ +- private final Set types; ++ private final TObjectIntMap typeCounts; + + /** + * The set of vertices in this mutligraph. This set is maintained +@@ -105,7 +106,7 @@ public class UndirectedMultigraph + * Creates an empty graph with node edges + */ + public UndirectedMultigraph() { +- types = new HashSet(); ++ typeCounts = new TObjectIntHashMap(); + vertexToEdges = new TIntObjectHashMap>(); + subgraphs = new ArrayList>(); + size = 0; +@@ -144,7 +145,7 @@ public boolean add(TypedEdge e) { + vertexToEdges.put(e.from(), from); + } + if (from.add(e)) { +- types.add(e.edgeType()); ++ updateTypeCounts(e.edgeType(), 1); + SparseTypedEdgeSet to = vertexToEdges.get(e.to()); + if (to == null) { + to = new SparseTypedEdgeSet(e.to()); +@@ -162,7 +163,7 @@ public boolean add(TypedEdge e) { + */ + public void clear() { + vertexToEdges.clear(); +- types.clear(); ++ typeCounts.clear(); + size = 0; + } + +@@ -231,8 +232,6 @@ public UndirectedMultigraph copy(Set toCopy) { + if (!vertexToEdges.containsKey(v)) + throw new IllegalArgumentException( + ""Request copy of non-present vertex: "" + v); +-// SparseTypedEdgeSet edges = vertexToEdges.get(v); +-// g.vertexToEdges.put(v, edges.copy(toCopy)); + + g.add(v); + SparseTypedEdgeSet edges = vertexToEdges.get(v); +@@ -246,8 +245,6 @@ public UndirectedMultigraph copy(Set toCopy) { + g.add(e); + } + } +-// if (toCopy.size() > 0) +-// System.out.printf(""Copy %d vertices (%d), %d edges%n"", g.order(), toCopy.size(), g.size()); + return g; + } + +@@ -283,7 +280,7 @@ public Set> edges(T t) { + * Returns the set of edge types currently present in this graph. + */ + public Set edgeTypes() { +- return Collections.unmodifiableSet(types); ++ return Collections.unmodifiableSet(typeCounts.keySet()); + } + + /** +@@ -292,7 +289,7 @@ public Set edgeTypes() { + @Override public boolean equals(Object o) { + if (o instanceof UndirectedMultigraph) { + UndirectedMultigraph dm = (UndirectedMultigraph)(o); +- if (dm.types.equals(types)) { ++ if (dm.typeCounts.equals(typeCounts)) { + return vertexToEdges.equals(dm.vertexToEdges); + } + return false; +@@ -300,7 +297,7 @@ public Set edgeTypes() { + else if (o instanceof Multigraph) { + @SuppressWarnings(""unchecked"") + Multigraph> m = (Multigraph>)o; +- if (m.edgeTypes().equals(types)) { ++ if (m.edgeTypes().equals(typeCounts.keySet())) { + return m.order() == order() + && m.size() == size() + && m.vertices().equals(vertices()) +@@ -371,7 +368,8 @@ public boolean hasCycles() { + * {@inheritDoc} + */ + public int hashCode() { +- return vertexToEdges.keySet().hashCode() ^ (types.hashCode() * size); ++ return vertexToEdges.keySet().hashCode() ^ ++ (typeCounts.keySet().hashCode() * size); + } + + /** +@@ -397,6 +395,8 @@ public boolean remove(int vertex) { + // Check whether removing this vertex has caused us to remove + // the last edge for this type in the graph. If so, the graph + // no longer has this type and we need to update the state. ++ for (TypedEdge e : edges) ++ updateTypeCounts(e.edgeType(), -1); + + // Update any of the subgraphs that had this vertex to notify them + // that it was removed +@@ -416,7 +416,7 @@ public boolean remove(int vertex) { + if (s.vertexSubset.remove(vertex)) { + Iterator subgraphTypesIter = s.validTypes.iterator(); + while (subgraphTypesIter.hasNext()) { +- if (!types.contains(subgraphTypesIter.next())) ++ if (!typeCounts.containsKey(subgraphTypesIter.next())) + subgraphTypesIter.remove(); + } + } +@@ -434,26 +434,27 @@ public boolean remove(TypedEdge edge) { + if (edges != null && edges.remove(edge)) { + vertexToEdges.get(edge.from()).remove(edge); + size--; ++ + // Check whether we've just removed the last edge for this type + // in the graph. If so, the graph no longer has this type and + // we need to update the state. +- +- // TODO !! +- +- +- // Remove this edge type from all the subgraphs as well +- Iterator> sIt = subgraphs.iterator(); +- while (sIt.hasNext()) { +- WeakReference ref = sIt.next(); +- Subgraph s = ref.get(); +- // Check whether this subgraph was already gc'd (the +- // subgraph was no longer in use) and if so, remove the +- // ref from the list to avoid iterating over it again +- if (s == null) { +- sIt.remove(); +- continue; ++ updateTypeCounts(edge.edgeType(), -1); ++ ++ if (!typeCounts.containsKey(edge.edgeType())) { ++ // Remove this edge type from all the subgraphs as well ++ Iterator> sIt = subgraphs.iterator(); ++ while (sIt.hasNext()) { ++ WeakReference ref = sIt.next(); ++ Subgraph s = ref.get(); ++ // Check whether this subgraph was already gc'd (the ++ // subgraph was no longer in use) and if so, remove the ++ // ref from the list to avoid iterating over it again ++ if (s == null) { ++ sIt.remove(); ++ continue; ++ } ++ s.validTypes.remove(edge.edgeType()); + } +- // FILL IN... + } + + return true; +@@ -466,26 +467,13 @@ public boolean remove(TypedEdge edge) { + */ + public int size() { + return size; +-// CountingProcedure count = new CountingProcedure(); +-// vertexToEdges.forEachValue(count); +-// return count.count / 2; +- } +- +- private class CountingProcedure +- implements TObjectProcedure> { +- +- int count = 0; +- public boolean execute(SparseTypedEdgeSet edges) { +- count += edges.size(); +- return true; +- } + } + + /** + * {@inheritDoc} + */ + public UndirectedMultigraph subgraph(Set subset) { +- Subgraph sub = new Subgraph(types, subset); ++ Subgraph sub = new Subgraph(typeCounts.keySet(), subset); + subgraphs.add(new WeakReference(sub)); + return sub; + } +@@ -496,7 +484,7 @@ public UndirectedMultigraph subgraph(Set subset) { + public UndirectedMultigraph subgraph(Set subset, Set edgeTypes) { + if (edgeTypes.isEmpty()) + throw new IllegalArgumentException(""Must specify at least one type""); +- if (!types.containsAll(edgeTypes)) { ++ if (!typeCounts.keySet().containsAll(edgeTypes)) { + throw new IllegalArgumentException( + ""Cannot create subgraph with more types than exist""); + } +@@ -513,11 +501,31 @@ public String toString() { + return ""{ vertices: "" + vertices() + "", edges: "" + edges() + ""}""; + } + ++ /** ++ * Updates how many edges have this type in the graph ++ */ ++ private void updateTypeCounts(T type, int delta) { ++ if (!typeCounts.containsKey(type)) { ++ assert delta > 0 ++ : ""removing edge type that was not originally present""; ++ typeCounts.put(type, delta); ++ } ++ else { ++ int curCount = typeCounts.get(type); ++ int newCount = curCount + delta; ++ assert newCount >= 0 ++ : ""removing edge type that was not originally present""; ++ if (newCount == 0) ++ typeCounts.remove(type); ++ else ++ typeCounts.put(type, newCount); ++ } ++ } ++ + /** + * {@inheritDoc} + */ + public IntSet vertices() { +- // TODO: make this unmodifiable + return PrimitiveCollections.unmodifiableSet( + TroveIntSet.wrap(vertexToEdges.keySet())); + } +@@ -551,8 +559,8 @@ public Iterator> iterator() { + public boolean remove(Object o) { + if (o instanceof TypedEdge) { + TypedEdge e = (TypedEdge)o; +- return UndirectedMultigraph.this.types. +- contains(e.edgeType()) ++ return UndirectedMultigraph.this.typeCounts. ++ containsKey(e.edgeType()) + && UndirectedMultigraph.this.remove((TypedEdge)o); + } + return false; +@@ -886,7 +894,8 @@ public boolean hasCycles() { + * {@inheritDoc} + */ + public int hashCode() { +- return vertices().hashCode() ^ (types.hashCode() * size()); ++ return vertices().hashCode() ^ ++ (validTypes.hashCode() * size()); + } + + /** +diff --git a/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java b/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java +index 53a3bf3e..8466e9a5 100644 +--- a/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java ++++ b/src/edu/ucla/sspace/mains/FixedDurationTemporalRandomIndexingMain.java +@@ -27,7 +27,6 @@ + import edu.ucla.sspace.common.SemanticSpaceIO.SSpaceFormat; + import edu.ucla.sspace.common.Similarity; + import edu.ucla.sspace.common.Similarity.SimType; +-import edu.ucla.sspace.common.WordComparator; + + import edu.ucla.sspace.ri.IndexVectorUtil; + +@@ -43,6 +42,8 @@ + + import edu.ucla.sspace.util.CombinedIterator; + import edu.ucla.sspace.util.MultiMap; ++import edu.ucla.sspace.util.NearestNeighborFinder; ++import edu.ucla.sspace.util.SimpleNearestNeighborFinder; + import edu.ucla.sspace.util.SortedMultiMap; + import edu.ucla.sspace.util.TimeSpan; + import edu.ucla.sspace.util.TreeMultiMap; +@@ -172,12 +173,6 @@ public class FixedDurationTemporalRandomIndexingMain { + */ + private boolean printShiftRankings; + +- /** +- * The word comparator used for computing similarity scores when calculating +- * the semantic shift. +- */ +- private WordComparator wordComparator; +- + /** + * A mapping from each word to the vectors that account for its temporal + * semantics according to the specified time span +@@ -368,9 +363,6 @@ public void run(String[] args) throws Exception { + numThreads = argOptions.getIntOption(""threads""); + } + +- // initialize the word comparator based on the number of threads +- wordComparator = new WordComparator(numThreads); +- + overwrite = true; + if (argOptions.hasOption(""overwrite"")) { + overwrite = argOptions.getBooleanOption(""overwrite""); +@@ -680,12 +672,13 @@ private void printWordNeighbors(String dateString, + LOGGER.info(""printing the most similar words for the semantic partition"" + + "" starting at: "" + dateString); + ++ NearestNeighborFinder nnf = ++ new SimpleNearestNeighborFinder(semanticPartition); ++ + // generate the similarity lists + for (String toExamine : interestingWords) { + SortedMultiMap mostSimilar = +- wordComparator.getMostSimilar(toExamine, semanticPartition, +- interestingWordNeighbors, +- Similarity.SimType.COSINE); ++ nnf.getMostSimilar(toExamine, interestingWordNeighbors); + + if (mostSimilar != null) { + File neighborFile = +diff --git a/src/edu/ucla/sspace/mains/LexSubWordsiMain.java b/src/edu/ucla/sspace/mains/LexSubWordsiMain.java +index 262ac826..62d0a3a0 100644 +--- a/src/edu/ucla/sspace/mains/LexSubWordsiMain.java ++++ b/src/edu/ucla/sspace/mains/LexSubWordsiMain.java +@@ -6,7 +6,6 @@ + import edu.ucla.sspace.common.Similarity; + import edu.ucla.sspace.common.Similarity.SimType; + import edu.ucla.sspace.common.StaticSemanticSpace; +-import edu.ucla.sspace.common.WordComparator; + + import edu.ucla.sspace.hal.LinearWeighting; + +@@ -15,7 +14,9 @@ + import edu.ucla.sspace.text.corpora.SemEvalLexSubReader; + + import edu.ucla.sspace.util.MultiMap; ++import edu.ucla.sspace.util.NearestNeighborFinder; + import edu.ucla.sspace.util.SerializableUtil; ++import edu.ucla.sspace.util.SimpleNearestNeighborFinder; + + import edu.ucla.sspace.vector.SparseDoubleVector; + import edu.ucla.sspace.vector.Vector; +@@ -59,7 +60,7 @@ public static void main(String[] args) { + } + + public static class LexSubWordsi implements Wordsi { +- private final WordComparator comparator; ++ private final NearestNeighborFinder comparator; + + private final PrintWriter output; + +@@ -67,9 +68,9 @@ public static class LexSubWordsi implements Wordsi { + + public LexSubWordsi(String outFile, String sspaceFile) { + try { +- comparator = new WordComparator(); + output = new PrintWriter(outFile); + wordsiSpace = new StaticSemanticSpace(sspaceFile); ++ comparator = new SimpleNearestNeighborFinder(wordsiSpace); + } catch (IOException ioe) { + throw new IOError(ioe); + } +@@ -86,10 +87,9 @@ public void handleContextVector(String focus, + System.err.printf(""Processing %s\n"", secondary); + String bestSense = getBaseSense(focus, vector); + if (bestSense == null) +- return; +- ++ return; + MultiMap topWords = comparator.getMostSimilar( +- bestSense, wordsiSpace, 10, SimType.COSINE); ++ bestSense, 10); + output.printf(""%s ::"", secondary); + for (String term : topWords.values()) + output.printf("" %s"", term); +diff --git a/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java b/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java +index 2fe2ac90..acd25992 100644 +--- a/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java ++++ b/src/edu/ucla/sspace/text/LabeledParsedStringDocument.java +@@ -64,6 +64,21 @@ public DependencyTreeNode[] parsedDocument() { + * {@inheritDoc} + */ + public String text() { ++ DependencyTreeNode[] nodes = parsedDocument(); ++ StringBuilder sb = new StringBuilder(nodes.length * 8); ++ for (int i = 0; i < nodes.length; ++i) { ++ String token = nodes[i].word(); ++ sb.append(token); ++ if (i+1 < nodes.length) ++ sb.append(' '); ++ } ++ return sb.toString(); ++ } ++ ++ /** ++ * {@inheritDoc} ++ */ ++ public String prettyPrintText() { + Pattern punctuation = Pattern.compile(""[!,-.:;?`]""); + DependencyTreeNode[] nodes = parsedDocument(); + StringBuilder sb = new StringBuilder(nodes.length * 8); +diff --git a/src/edu/ucla/sspace/text/ParsedDocument.java b/src/edu/ucla/sspace/text/ParsedDocument.java +index e5406df0..fcc9b566 100644 +--- a/src/edu/ucla/sspace/text/ParsedDocument.java ++++ b/src/edu/ucla/sspace/text/ParsedDocument.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2011 David Jurgens ++ * Copyright 2012 David Jurgens + * + * This file is part of the S-Space package and is covered under the terms and + * conditions therein. +@@ -40,7 +40,18 @@ public interface ParsedDocument extends Document { + + /** + * Returns the text of the parsed document without any of the +- * parsing-related annotation. ++ * parsing-related annotation, with each parsed token separated by ++ * whitespace. + */ + String text(); ++ ++ /** ++ * Returns a pretty-printed version of the document's text without any of ++ * the parsing-related annotation and using heuristics to appropriately ++ * space punctuation, quotes, and contractions. This methods is intended as ++ * only a useful way to displaying the document's text in a more readable ++ * format than {@link #text()}, but makes no claims as to reproducing the ++ * original surface form of the document prior to parsing. ++ */ ++ String prettyPrintText(); + } +diff --git a/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java b/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java +index 34e37664..7037e315 100644 +--- a/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java ++++ b/src/edu/ucla/sspace/text/PukWaCDocumentIterator.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2011 David Jurgens ++ * Copyright 2012 David Jurgens + * + * This file is part of the S-Space package and is covered under the terms and + * conditions therein. +@@ -36,12 +36,14 @@ + * An iterator implementation that returns {@link Document} containg a single + * dependency parsed sentence given a file in the CoNLL Format which +- * is contained in the XML format provided in the WaCkypedia corpus. ++ * is contained in the XML format provided in the WaCkypedia corpus. See the WaCky group's ++ * website for more information on the PukWaC. + */ + public class PukWaCDocumentIterator implements Iterator { + + /** +- * The extractor used to build trees from the pukWaC documents ++ * The extractor used to build trees from the PukWaC documents + */ + private static final DependencyExtractor extractor = + new WaCKyDependencyExtractor(); +@@ -65,7 +67,7 @@ public class PukWaCDocumentIterator implements Iterator { + * Creates an {@code Iterator} over the file where each document returned + * contains the sequence of dependency parsed words composing a sentence.. + * +- * @param documentsFile the name of the pukWaC file containing dependency ++ * @param documentsFile the name of the PukWaC file containing dependency + * parsed sentences in the CoNLL + * Format separated by XML tags for the sentences and articles +@@ -100,7 +102,7 @@ else if (line.equals("""")) { + while ((line = documentsReader.readLine()) != null + && !line.equals("""")) { + +- // Unfortunately, the XML of the pukWaC is broken and some ++ // Unfortunately, the XML of the PukWaC is broken and some + // elements are inside the elements, so this code + // is needed to avoid putting those inside the CONLL data + if (line.contains(""CoNLL Format +- * +- *

+- * +- * This class is thread-safe. ++ * An iterator implementation that returns {@link Document} instances labled ++ * with the source URL from which its text was obtained, as specified in the ++ * ukWaC. See the WaCky group's ++ * website for more information on the ukWaC. + */ + public class UkWaCDocumentIterator implements Iterator { + +diff --git a/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java b/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java +index 756b24d2..cb48efa0 100644 +--- a/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java ++++ b/src/edu/ucla/sspace/tools/NearestNeighborFinderTool.java +@@ -28,6 +28,7 @@ + import edu.ucla.sspace.util.LoggerUtil; + import edu.ucla.sspace.util.MultiMap; + import edu.ucla.sspace.util.NearestNeighborFinder; ++import edu.ucla.sspace.util.PartitioningNearestNeighborFinder; + import edu.ucla.sspace.util.SerializableUtil; + + import java.io.File; +@@ -93,27 +94,29 @@ public static void main(String[] args) { + SemanticSpaceIO.load(options.getStringOption('C')); + int numWords = sspace.getWords().size(); + // See how many principle vectors to create +- int principleVectors = -1; ++ int numPrincipleVectors = -1; + if (options.hasOption('p')) { +- principleVectors = options.getIntOption('p'); +- if (principleVectors > numWords) { ++ numPrincipleVectors = options.getIntOption('p'); ++ if (numPrincipleVectors > numWords) { + throw new IllegalArgumentException( + ""Cannot have more principle vectors than "" + +- ""word vectors: "" + principleVectors); ++ ""word vectors: "" + numPrincipleVectors); + } +- else if (principleVectors < 1) { ++ else if (numPrincipleVectors < 1) { + throw new IllegalArgumentException( + ""Must have at least one principle vector""); + } + + } + else { +- principleVectors = ++ numPrincipleVectors = + Math.min((int)(Math.ceil(Math.log(numWords))), 1000); + System.err.printf(""Choosing a heuristically selected %d "" + +- ""principle vectors%n"", principleVectors); ++ ""principle vectors%n"", ++ numPrincipleVectors); + } +- nnf = new NearestNeighborFinder(sspace, principleVectors); ++ nnf = new PartitioningNearestNeighborFinder( ++ sspace, numPrincipleVectors); + } catch (IOException ioe) { + throw new IOError(ioe); + } +diff --git a/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java b/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java +index b22050f1..c7f697f1 100644 +--- a/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java ++++ b/src/edu/ucla/sspace/tools/SemanticSpaceExplorer.java +@@ -26,10 +26,12 @@ + import edu.ucla.sspace.common.SemanticSpace; + import edu.ucla.sspace.common.SemanticSpaceIO; + import edu.ucla.sspace.common.Similarity; +-import edu.ucla.sspace.common.WordComparator; + + import edu.ucla.sspace.text.WordIterator; + ++import edu.ucla.sspace.util.NearestNeighborFinder; ++import edu.ucla.sspace.util.PartitioningNearestNeighborFinder; ++ + import edu.ucla.sspace.vector.SparseVector; + import edu.ucla.sspace.vector.Vector; + import edu.ucla.sspace.vector.VectorIO; +@@ -102,12 +104,6 @@ private enum Command { + } + } + +- /** +- * The comparator to be used when identifying the nearest neighbors to words +- * in a semantic space. +- */ +- private final WordComparator wordComparator; +- + /** + * The mapping from file name to the {@code SemanticSpace} that was loaded + * from that file. +@@ -125,11 +121,16 @@ private enum Command { + */ + private SemanticSpace current; + ++ /** ++ * The {@code NearestNeighborFinder} for the current {@code SemanticSpace} ++ * or {@code null} if the nearest terms have yet to be searched for. ++ */ ++ private NearestNeighborFinder currentNnf; ++ + /** + * Constructs an instance of {@code SemanticSpaceExplorer}. + */ +- private SemanticSpaceExplorer() { +- this.wordComparator = new WordComparator(); ++ private SemanticSpaceExplorer() { + fileNameToSSpace = new LinkedHashMap(); + aliasToFileName = new HashMap(); + current = null; +@@ -240,6 +241,7 @@ private boolean execute(Iterator commandTokens, PrintStream out) { + } + fileNameToSSpace.put(sspaceFileName, sspace); + current = sspace; ++ currentNnf = null; + break; + } + +@@ -319,31 +321,16 @@ private boolean execute(Iterator commandTokens, PrintStream out) { + return false; + } + } +- Similarity.SimType simType = Similarity.SimType.COSINE; +- if (commandTokens.hasNext()) { +- // Upper case since it's an enum +- String simTypeStr = commandTokens.next().toUpperCase(); +- try { +- simType = Similarity.SimType.valueOf(simTypeStr); +- } catch (IllegalArgumentException iae) { +- // See if the user provided a prefix of the similarity +- // measure's name +- for (Similarity.SimType t : Similarity.SimType.values()) +- if (t.name().startsWith(simTypeStr)) +- simType = t; +- // If no prefix was found, report an error +- if (simType == null) { +- out.println(""invalid similarity measure: "" +simTypeStr); +- return false; +- } +- } +- } + ++ // If this is the first time the nearest neighbors have been ++ // searched for, construct a new NNF ++ if (currentNnf == null) ++ currentNnf = new PartitioningNearestNeighborFinder(current); ++ + // Using the provided or default arguments find the closest + // neighbors to the target word in the current semantic space + SortedMultiMap mostSimilar = +- wordComparator.getMostSimilar(focusWord, current, neighbors, +- simType); ++ currentNnf.getMostSimilar(focusWord, neighbors); + + if (mostSimilar == null) { + out.println(focusWord + +@@ -375,7 +362,7 @@ private boolean execute(Iterator commandTokens, PrintStream out) { + out.println(""missing word argument""); + return false; + } +- String word2 = commandTokens.next(); ++ String word2 = commandTokens.next(); + + Similarity.SimType simType = Similarity.SimType.COSINE; + if (commandTokens.hasNext()) { +diff --git a/src/edu/ucla/sspace/tools/SimilarityListGenerator.java b/src/edu/ucla/sspace/tools/SimilarityListGenerator.java +index a0dbb5fd..9703a36b 100644 +--- a/src/edu/ucla/sspace/tools/SimilarityListGenerator.java ++++ b/src/edu/ucla/sspace/tools/SimilarityListGenerator.java +@@ -26,9 +26,10 @@ + import edu.ucla.sspace.common.Similarity.SimType; + import edu.ucla.sspace.common.SemanticSpace; + import edu.ucla.sspace.common.SemanticSpaceIO; +-import edu.ucla.sspace.common.WordComparator; + + import edu.ucla.sspace.util.BoundedSortedMap; ++import edu.ucla.sspace.util.NearestNeighborFinder; ++import edu.ucla.sspace.util.PartitioningNearestNeighborFinder; + import edu.ucla.sspace.util.Pair; + import edu.ucla.sspace.util.SortedMultiMap; + +@@ -77,9 +78,10 @@ private void addOptions() { + ""whether to print the similarity score "" + + ""(default: false)"", + false, null, ""Program Options""); +- argOptions.addOption('s', ""similarityFunction"", +- ""name of a similarity function (default: cosine)"", +- true, ""String"", ""Program Options""); ++ // dj: current unsupported; will be next release ++ // argOptions.addOption('s', ""similarityFunction"", ++ // ""name of a similarity function (default: cosine)"", ++ // true, ""String"", ""Program Options""); + argOptions.addOption('n', ""numSimilar"", ""the number of similar words "" + + ""to print (default: 10)"", true, ""String"", + ""Program Options""); +@@ -153,12 +155,13 @@ public void run(String[] args) throws Exception { + // load the behavior options + final boolean printSimilarity = argOptions.hasOption('p'); + +- String similarityTypeName = (argOptions.hasOption('s')) +- ? argOptions.getStringOption('s').toUpperCase() : ""COSINE""; ++ // dj: setting the similarity type is currently unsupported but will be ++ // in the next release + +- SimType similarityType = SimType.valueOf(similarityTypeName); +- +- LOGGER.fine(""using similarity measure: "" + similarityType); ++ // String similarityTypeName = (argOptions.hasOption('s')) ++ // ? argOptions.getStringOption('s').toUpperCase() : ""COSINE""; ++ // SimType similarityType = SimType.valueOf(similarityTypeName); ++ // LOGGER.fine(""using similarity measure: "" + similarityType); + + final int numSimilar = (argOptions.hasOption('n')) + ? argOptions.getIntOption('n') : 10; +@@ -175,14 +178,14 @@ public void run(String[] args) throws Exception { + final PrintWriter outputWriter = new PrintWriter(output); + + final Set words = sspace.getWords(); +- WordComparator comparator = new WordComparator(numThreads); ++ NearestNeighborFinder nnf = ++ new PartitioningNearestNeighborFinder(sspace); + + + for (String word : words) { + // compute the k most-similar words to this word + SortedMultiMap mostSimilar = +- comparator.getMostSimilar(word, sspace, numSimilar, +- similarityType); ++ nnf.getMostSimilar(word, numSimilar); + + // once processing has finished write the k most-similar words to + // the output file. +diff --git a/src/edu/ucla/sspace/util/HashIndexer.java b/src/edu/ucla/sspace/util/HashIndexer.java +index 28a90a79..97807ca6 100644 +--- a/src/edu/ucla/sspace/util/HashIndexer.java ++++ b/src/edu/ucla/sspace/util/HashIndexer.java +@@ -37,7 +37,7 @@ + + /** + * A utility class for mapping a set of objects to unique indices based on +- * object equality. The indices returned by this class will always being at ++ * object equality. The indices returned by this class will always begin at + * {@code 0}. + * + *

This implementation provides faster {@link #index(Object)} performance +diff --git a/src/edu/ucla/sspace/util/PairCounter.java b/src/edu/ucla/sspace/util/PairCounter.java +index 89b9f2d1..21591721 100644 +--- a/src/edu/ucla/sspace/util/PairCounter.java ++++ b/src/edu/ucla/sspace/util/PairCounter.java +@@ -253,7 +253,7 @@ public Set> items() { + } + + /** +- * Returns an interator over the pairs that have been counted thusfar and ++ * Returns an iterator over the pairs that have been counted thusfar and + * their respective counts. + */ + public Iterator,Integer>> iterator() { +diff --git a/src/edu/ucla/sspace/util/NearestNeighborFinder.java b/src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java +similarity index 90% +rename from src/edu/ucla/sspace/util/NearestNeighborFinder.java +rename to src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java +index c92c8bc4..be4db381 100644 +--- a/src/edu/ucla/sspace/util/NearestNeighborFinder.java ++++ b/src/edu/ucla/sspace/util/PartitioningNearestNeighborFinder.java +@@ -65,10 +65,12 @@ + * A class for finding the k-nearest neighbors of one or more words. The + * {@code NearestNeighborFinder} operates by generating a set of principle + * vectors that reflect average words in a {@link SemanticSpace} and then +- * identifying mapping each principle vector to the set of words to which it is +- * closest. Finding the nearest neighbor then entails finding the +- * k-closest principle vectors and comparing only their words, rather +- * than all the words in the space. This dramatically reduces the search space. ++ * mapping each principle vector to the set of words to which it is closest. ++ * Finding the nearest neighbor then entails finding the k-closest ++ * principle vectors and comparing only their words, rather than all the words ++ * in the space. This dramatically reduces the search space by partitioning the ++ * vectors of the {@code SemanticSpace} into smaller sets, not all of which need ++ * to be searched. + * + *

The number of principle vectors is typically far less than the total + * number of vectors in the {@code SemanticSpace}, but should be more than the +@@ -77,8 +79,14 @@ + * (|Sspace| / p))}, where {@code p} is the number of principle components, + * {@code k} is the number of nearest neighbors to be found, and {@code + * |Sspace|} is the size of the semantic space. ++ * ++ *

Instances of this class are also serializable. If the backing {@code ++ * SemanticSpace} is also serializable, the space will be saved. However, if ++ * the space is not serializable, its contents will be converted to a static ++ * version and saved as a copy. + */ +-public class NearestNeighborFinder implements java.io.Serializable { ++public class PartitioningNearestNeighborFinder ++ implements NearestNeighborFinder, java.io.Serializable { + + private static final long serialVersionUID = 1L; + +@@ -86,7 +94,7 @@ public class NearestNeighborFinder implements java.io.Serializable { + * The logger to which clustering status updates will be written. + */ + private static final Logger LOGGER = +- Logger.getLogger(NearestNeighborFinder.class.getName()); ++ Logger.getLogger(PartitioningNearestNeighborFinder.class.getName()); + + /** + * The semantic space from which the principle vectors are derived +@@ -104,29 +112,41 @@ public class NearestNeighborFinder implements java.io.Serializable { + */ + private transient WorkQueue workQueue; + ++ /** ++ * Creates a new {@code NearestNeighborFinder} for the {@link ++ * SemanticSpace}, using log10(|words|) principle vectors to ++ * efficiently search for neighbors. ++ * ++ * @param sspace a semantic space to search ++ */ ++ public PartitioningNearestNeighborFinder(SemanticSpace sspace) { ++ this(sspace, (int)(Math.ceil(Math.log10(sspace.getWords().size())))); ++ } ++ + /** + * Creates a new {@code NearestNeighborFinder} for the {@link + * SemanticSpace}, using the specified number of principle vectors to + * efficiently search for neighbors. + * + * @param sspace a semantic space to search +- * @param principleVectors the number of principle vectors to use in ++ * @param numPrincipleVectors the number of principle vectors to use in + * representing the content of the space. + */ +- public NearestNeighborFinder(SemanticSpace sspace, int principleVectors) { ++ public PartitioningNearestNeighborFinder(SemanticSpace sspace, ++ int numPrincipleVectors) { + if (sspace == null) + throw new NullPointerException(); +- if (principleVectors > sspace.getWords().size()) ++ if (numPrincipleVectors > sspace.getWords().size()) + throw new IllegalArgumentException( + ""Cannot have more principle vectors than "" + +- ""word vectors: "" + principleVectors); +- else if (principleVectors < 1) ++ ""word vectors: "" + numPrincipleVectors); ++ else if (numPrincipleVectors < 1) + throw new IllegalArgumentException( + ""Must have at least one principle vector""); + this.sspace = sspace; + principleVectorToNearestTerms = new HashMultiMap(); + workQueue = new WorkQueue(); +- computePrincipleVectors(principleVectors); ++ computePrincipleVectors(numPrincipleVectors); + } + + /** +@@ -193,7 +213,7 @@ public void run() { + // which it is closest + for (int i = sta; i < end; ++i) { + DoubleVector v = termVectors.get(i); +- double highestSim = Double.NEGATIVE_INFINITY; ++ double highestSim = -Double.MAX_VALUE; + int pVec = -1; + for (int j = 0; j < principles.length; ++j) { + DoubleVector principle = principles[j]; +@@ -246,12 +266,7 @@ public void run() { + } + + /** +- * Finds the k most similar words in the semantic space according to +- * the cosine similarity, returning a mapping from their similarity to the +- * word itself. +- * +- * @return the most similar words, or {@code null} if the provided word was +- * not in the semantic space. ++ * {@inheritDoc} + */ + public SortedMultiMap getMostSimilar( + final String word, int numberOfSimilarWords) { +@@ -276,12 +291,7 @@ public SortedMultiMap getMostSimilar( + } + + /** +- * Finds the k most similar words in the semantic space according to +- * the cosine similarity, returning a mapping from their similarity to the +- * word itself. +- * +- * @return the most similar words, or {@code null} if none of the provided +- * word were not in the semantic space. ++ * {@inheritDoc} + */ + public SortedMultiMap getMostSimilar( + Set terms, int numberOfSimilarWords) { +@@ -323,13 +333,8 @@ public SortedMultiMap getMostSimilar( + return mostSim; + } + +- + /** +- * Finds the k most similar words in the semantic space according to +- * the cosine similarity, returning a mapping from their similarity to the +- * word itself. +- * +- * @return the most similar words to the vector ++ * {@inheritDoc} + */ + public SortedMultiMap getMostSimilar( + final Vector v, int numberOfSimilarWords) { +@@ -434,5 +439,4 @@ private void writeObject(ObjectOutputStream out) throws IOException { + out.writeObject(copy); + } + } +- + } +\ No newline at end of file +diff --git a/src/edu/ucla/sspace/util/ReflectionUtil.java b/src/edu/ucla/sspace/util/ReflectionUtil.java +index a3d4ffb7..583f3b2b 100644 +--- a/src/edu/ucla/sspace/util/ReflectionUtil.java ++++ b/src/edu/ucla/sspace/util/ReflectionUtil.java +@@ -48,8 +48,4 @@ public static T getObjectInstance(String className) { + throw new Error(e); + } + } +- +-// public static T[] newArrayInstance(Class c, int length) { +-// return Arrays.newInstance(c, length) +-// } + } +diff --git a/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java b/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java +index bcd6e9d3..6577e230 100644 +--- a/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java ++++ b/src/edu/ucla/sspace/util/primitive/IntIntHashMultiMap.java +@@ -42,7 +42,11 @@ + import gnu.trove.procedure.TIntProcedure; + + /** +- * ++ * A {@link MultiMap} implementation for mapping {@code int} primitives as both ++ * keys and values using a hashing strategy. This class offers a noticeable ++ * performance improvement over the equivalent {@code ++ * HashMultiMap<Integer,Integer>} by operating and representing the keys ++ * and values only in their primitive state. + */ + public class IntIntHashMultiMap implements IntIntMultiMap { + +diff --git a/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java b/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java +index 499a7527..f511b3df 100644 +--- a/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java ++++ b/src/edu/ucla/sspace/util/primitive/IntIntMultiMap.java +@@ -35,7 +35,8 @@ + + + /** +- * ++ * A {@link MultiMap} subinterface for mapping {@code int} primitives as both ++ * keys and values. + */ + public interface IntIntMultiMap extends MultiMap { + +diff --git a/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java b/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java +index 2d956032..bd88c5fc 100644 +--- a/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java ++++ b/test/edu/ucla/sspace/dependency/BreadthFirstPathIteratorTest.java +@@ -38,29 +38,29 @@ + public class BreadthFirstPathIteratorTest extends PathIteratorTestBase { + + String conll = +- ""Anarchism anarchism NN 1 2 SBJ\n"" + +- ""is be VBZ 2 0 ROOT\n"" + +- ""a a DT 3 5 NMOD\n"" + +- ""political political JJ 4 5 NMOD\n"" + +- ""philosophy philosophy NN 5 2 PRD\n"" + +- ""encompassing encompass VVG 6 5 NMOD\n"" + +- ""theories theory NNS 7 6 OBJ\n"" + +- ""and and CC 8 7 CC\n"" + +- ""attitudes attitude NNS 9 7 COORD\n"" + +- ""which which WDT 10 11 SBJ\n"" + +- ""consider consider VVP 11 9 NMOD\n"" + +- ""the the DT 12 13 NMOD\n"" + +- ""state state NN 13 15 SBJ\n"" + +- ""to t TO 14 15 VMOD\n"" + +- ""be be VB 15 11 OBJ\n"" + +- ""unnecessary unnecessary JJ 16 15 PRD\n"" + +- "", , , 17 16 P\n"" + +- ""harmul harmful JJ 18 16 COORD\n"" + +- "", , , 19 16 P\n"" + +- ""and/ ad/ JJ 20 16 COORD\n"" + +- ""or or CC 21 16 CC\n"" + +- ""undesirable undesirable JJ 22 16 COORD\n"" + +- "". . SENT 23 2 P\n""; ++ ""Anarchism\tanarchism\tNN\t1\t2\tSBJ\n"" + ++ ""is\tbe\tVBZ\t2\t0\tROOT\n"" + ++ ""a\ta\tDT\t3\t5\tNMOD\n"" + ++ ""political\tpolitical\tJJ\t4\t5\tNMOD\n"" + ++ ""philosophy\tphilosophy\tNN\t5\t2\tPRD\n"" + ++ ""encompassing\tencompass\tVVG\t6\t5\tNMOD\n"" + ++ ""theories\ttheory\tNNS\t7\t6\tOBJ\n"" + ++ ""and\tand\tCC\t8\t7\tCC\n""+ ++ ""attitudes\tattitude\tNNS\t9\t7\tCOORD\n""+ ++ ""which\twhich\tWDT\t10\t11\tSBJ\n""+ ++ ""consider\tconsider\tVVP\t11\t9\tNMOD\n""+ ++ ""the\tthe\tDT\t12\t13\tNMOD\n""+ ++ ""state\tstate\tNN\t13\t15\tSBJ\n""+ ++ ""to\tt\tTO\t14\t15\tVMOD\n""+ ++ ""be\tbe\tVB\t15\t11\tOBJ\n""+ ++ ""unnecessary\tunnecessary\tJJ\t16\t15\tPRD\n""+ ++ "",\t,\t,\t17\t16\tP\n""+ ++ ""harmul\tharmful\tJJ\t18\t16\tCOORD\n""+ ++ "",\t,\t,\t19\t16\tP\n""+ ++ ""and/\tad/\tJJ\t20\t16\tCOORD\n""+ ++ ""or\tor\tCC\t21\t16\tCC\n""+ ++ ""undesirable\tundesirable\tJJ\t22\t16\tCOORD\n""+ ++ "".\t.\tSENT\t23\t2\tP\n""; + + static final Map PATH_START_COUNTS + = new TreeMap(); +diff --git a/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java b/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java +index f0667223..06e9ae30 100644 +--- a/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java ++++ b/test/edu/ucla/sspace/dependency/CoNLLDependencyExtractorTest.java +@@ -24,6 +24,8 @@ + import edu.ucla.sspace.text.StringDocument; + import edu.ucla.sspace.text.Document; + ++import java.io.BufferedReader; ++ + import java.util.Arrays; + import java.util.HashSet; + import java.util.LinkedList; +@@ -99,6 +101,8 @@ protected void evaluateRelations(DependencyTreeNode node, + // Check that all the neighbors are in the e + for (DependencyRelation rel : node.neighbors()) { + System.out.println(""relation: "" + rel); ++ if (!expectedRelations.contains(rel)) ++ System.out.printf(""FAIL: %s does not contain %s%n"", expectedRelations, rel); + assertTrue(expectedRelations.contains(rel)); + // Remove the relation from the list to double check that the + // neighbors are a list of duplicate relations. +@@ -120,7 +124,7 @@ protected void testFirstRoot(DependencyTreeNode[] relations, int index) { + DependencyRelation[] expectedRelations = new DependencyRelation[] { + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""is"", ""VBZ""), + ""SBJ"", +- new SimpleDependencyTreeNode(""holt"", ""NNP"")), ++ new SimpleDependencyTreeNode(""Holt"", ""NNP"")), + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""is"", ""VBZ""), + ""PRD"", + new SimpleDependencyTreeNode(""columnist"", ""NN"")), +@@ -145,7 +149,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + DependencyRelation[] expectedRelations = new DependencyRelation[] { + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""beskattning"", ""N""), + ""AT"", +- new SimpleDependencyTreeNode(""individuell"", ""AJ"")), ++ new SimpleDependencyTreeNode(""Individuell"", ""AJ"")), + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""beskattning"", ""N""), + ""ET"", + new SimpleDependencyTreeNode(""av"", ""PR"")) +@@ -157,29 +161,29 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + + @Test public void testSingleExtraction() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +- Document doc = new StringDocument(SINGLE_PARSE); ++ Document doc = new StringDocument(toTabs(SINGLE_PARSE)); + DependencyTreeNode[] nodes = extractor.readNextTree(doc.reader()); + + assertEquals(12, nodes.length); + + // Check the basics of the node. +- assertEquals(""review"", nodes[8].word()); ++ assertEquals(""Review"", nodes[8].word()); + assertEquals(""NNP"", nodes[8].pos()); + + // Test expected relation for each of the links for ""Review"". + DependencyRelation[] expectedRelations = new DependencyRelation[] { +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""NMOD"", + new SimpleDependencyTreeNode(""the"", ""DT"")), +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""NMOD"", +- new SimpleDependencyTreeNode(""literary"", ""NNP"")), +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyTreeNode(""Literary"", ""NNP"")), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""ADV"", + new SimpleDependencyTreeNode(""in"", ""IN"")), + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""for"", ""IN""), + ""PMOD"", +- new SimpleDependencyTreeNode(""review"", ""NNP"")) ++ new SimpleDependencyTreeNode(""Review"", ""NNP"")) + }; + + evaluateRelations(nodes[8], new LinkedList(Arrays.asList(expectedRelations))); +@@ -187,14 +191,18 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + + @Test public void testDoubleExtraction() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +- Document doc = new StringDocument(DOUBLE_PARSE); +- DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); ++ Document doc = new StringDocument(""\n\n"" + ++ toTabs(SINGLE_PARSE) + ++ ""\n"" + ++ toTabs(SECOND_PARSE)); ++ BufferedReader reader = doc.reader(); ++ DependencyTreeNode[] relations = extractor.readNextTree(reader); + assertTrue(relations != null); + assertEquals(12, relations.length); + + testFirstRoot(relations, 2); + +- relations = extractor.readNextTree(doc.reader()); ++ relations = extractor.readNextTree(reader); + assertTrue(relations != null); + assertEquals(4, relations.length); + +@@ -203,7 +211,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + + @Test public void testRootNode() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +- Document doc = new StringDocument(SINGLE_PARSE); ++ Document doc = new StringDocument(toTabs(SINGLE_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(12, relations.length); +@@ -213,7 +221,7 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + + @Test public void testConcatonatedTrees() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +- Document doc = new StringDocument(CONCATONATED_PARSE); ++ Document doc = new StringDocument(toTabs(CONCATONATED_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(16, relations.length); +@@ -223,11 +231,26 @@ protected void testSecondRoot(DependencyTreeNode[] relations, int index) { + + @Test public void testConcatonatedTreesZeroOffset() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +- Document doc = new StringDocument(DOUBLE_ZERO_OFFSET_PARSE); ++ Document doc = new StringDocument(toTabs(DOUBLE_ZERO_OFFSET_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(16, relations.length); + testFirstRoot(relations, 2); + testSecondRoot(relations, 13); + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java b/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java +index 8f466cdc..74a1ebbe 100644 +--- a/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java ++++ b/test/edu/ucla/sspace/dependency/WaCKyDependencyExtractorTest.java +@@ -24,6 +24,8 @@ + import edu.ucla.sspace.text.StringDocument; + import edu.ucla.sspace.text.Document; + ++import java.io.BufferedReader; ++ + import java.util.Arrays; + import java.util.HashSet; + import java.util.LinkedList; +@@ -90,29 +92,29 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest { + + @Test public void testSingleExtraction() throws Exception { + DependencyExtractor extractor = new WaCKyDependencyExtractor(); +- Document doc = new StringDocument(SINGLE_PARSE); ++ Document doc = new StringDocument(toTabs(SINGLE_PARSE)); + DependencyTreeNode[] nodes = extractor.readNextTree(doc.reader()); + + assertEquals(12, nodes.length); + + // Check the basics of the node. +- assertEquals(""review"", nodes[8].word()); ++ assertEquals(""Review"", nodes[8].word()); + assertEquals(""NNP"", nodes[8].pos()); + + // Test expected relation for each of the links for ""Review"". + DependencyRelation[] expectedRelations = new DependencyRelation[] { +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""NMOD"", + new SimpleDependencyTreeNode(""the"", ""DT"")), +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""NMOD"", +- new SimpleDependencyTreeNode(""literary"", ""NNP"")), +- new SimpleDependencyRelation(new SimpleDependencyTreeNode(""review"", ""NNP""), ++ new SimpleDependencyTreeNode(""Literary"", ""NNP"")), ++ new SimpleDependencyRelation(new SimpleDependencyTreeNode(""Review"", ""NNP""), + ""ADV"", + new SimpleDependencyTreeNode(""in"", ""IN"")), + new SimpleDependencyRelation(new SimpleDependencyTreeNode(""for"", ""IN""), + ""PMOD"", +- new SimpleDependencyTreeNode(""review"", ""NNP"")) ++ new SimpleDependencyTreeNode(""Review"", ""NNP"")) + }; + + evaluateRelations(nodes[8], new LinkedList(Arrays.asList(expectedRelations))); +@@ -120,14 +122,15 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest { + + @Test public void testDoubleExtraction() throws Exception { + DependencyExtractor extractor = new WaCKyDependencyExtractor(); +- Document doc = new StringDocument(DOUBLE_PARSE); +- DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); ++ Document doc = new StringDocument(toTabs(DOUBLE_PARSE)); ++ BufferedReader reader = doc.reader(); ++ DependencyTreeNode[] relations = extractor.readNextTree(reader); + assertTrue(relations != null); + assertEquals(12, relations.length); + + testFirstRoot(relations, 2); + +- relations = extractor.readNextTree(doc.reader()); ++ relations = extractor.readNextTree(reader); + assertTrue(relations != null); + assertEquals(4, relations.length); + +@@ -136,7 +139,7 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest { + + @Test public void testRootNode() throws Exception { + DependencyExtractor extractor = new WaCKyDependencyExtractor(); +- Document doc = new StringDocument(SINGLE_PARSE); ++ Document doc = new StringDocument(toTabs(SINGLE_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(12, relations.length); +@@ -146,7 +149,7 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest { + + @Test public void testConcatonatedTrees() throws Exception { + DependencyExtractor extractor = new WaCKyDependencyExtractor(); +- Document doc = new StringDocument(CONCATONATED_PARSE); ++ Document doc = new StringDocument(toTabs(CONCATONATED_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(16, relations.length); +@@ -156,11 +159,26 @@ public class WaCKyDependencyExtractorTest extends CoNLLDependencyExtractorTest { + + @Test public void testConcatonatedTreesZeroOffset() throws Exception { + DependencyExtractor extractor = new WaCKyDependencyExtractor(); +- Document doc = new StringDocument(DOUBLE_ZERO_OFFSET_PARSE); ++ Document doc = new StringDocument(toTabs(DOUBLE_ZERO_OFFSET_PARSE)); + DependencyTreeNode[] relations = extractor.readNextTree(doc.reader()); + + assertEquals(16, relations.length); + testFirstRoot(relations, 2); + testSecondRoot(relations, 13); + } +-} ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } ++} +\ No newline at end of file +diff --git a/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java b/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java +index eb6102f5..73424070 100644 +--- a/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java ++++ b/test/edu/ucla/sspace/graph/DirectedMultigraphTests.java +@@ -36,1182 +36,1182 @@ + */ + public class DirectedMultigraphTests { + +-// @Test public void testConstructor() { +-// Set vertices = new HashSet(); +-// DirectedMultigraph g = new DirectedMultigraph(); +-// assertEquals(0, g.order()); +-// assertEquals(0, g.size()); +-// } +- +-// @Test(expected=NullPointerException.class) public void testConstructor2NullArg() { +-// Graph g = new SparseUndirectedGraph((Graph>)null); +-// } +- +-// @Test public void testAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// assertTrue(g.add(0)); +-// assertEquals(1, g.order()); +-// assertTrue(g.contains(0)); +-// // second add should have no effect +-// assertFalse(g.add(0)); +-// assertEquals(1, g.order()); +-// assertTrue(g.contains(0)); +- +-// assertTrue(g.add(1)); +-// assertEquals(2, g.order()); +-// assertTrue(g.contains(1)); +-// } +- +-// @Test public void testEquals() { +-// DirectedMultigraph g1 = new DirectedMultigraph(); +-// DirectedMultigraph g2 = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// g2.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +-// } +-// assertEquals(g1, g2); +- +-// g1 = new DirectedMultigraph(); +-// g2 = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// g2.add(new SimpleDirectedTypedEdge(""type-1"",j, i)); +-// } +-// } +- +-// assertFalse(g1.equals(g2)); +-// assertFalse(g2.equals(g1)); +-// } +- +-// @Test public void testEqualGeneric() { +-// DirectedMultigraph g1 = new DirectedMultigraph(); +-// Graph> g2 = new GenericGraph>(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// g2.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +-// } +-// assertEquals(g1, g2); +-// } +- +-// @Test public void testContainsEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 100; ++i) +-// for (int j = i + 1; j < 100; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +- +-// for (int i = 0; i < 100; ++i) { +-// for (int j = i + 1; j < 100; ++j) { +-// g.contains(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// g.contains(new SimpleDirectedTypedEdge(""type-1"",j, i)); +-// g.contains(i, j); +-// g.contains(j, i); +-// } +-// } +-// } +- +-// @Test public void testAddEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// assertTrue(g.add(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// assertEquals(2, g.order()); +-// assertEquals(1, g.size()); +-// assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +- +-// g.add(new SimpleDirectedTypedEdge(""type-1"",0, 2)); +-// assertEquals(3, g.order()); +-// assertEquals(2, g.size()); +-// assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 2))); +- +-// g.add(new SimpleDirectedTypedEdge(""type-1"",3, 4)); +-// assertEquals(5, g.order()); +-// assertEquals(3, g.size()); +-// assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",3, 4))); +-// } +- +-// @Test public void testRemoveLesserVertexWithEdges() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// for (int i = 1; i < 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// } ++ @Test public void testConstructor() { ++ Set vertices = new HashSet(); ++ DirectedMultigraph g = new DirectedMultigraph(); ++ assertEquals(0, g.order()); ++ assertEquals(0, g.size()); ++ } ++ ++ @Test(expected=NullPointerException.class) public void testConstructor2NullArg() { ++ Graph g = new SparseUndirectedGraph((Graph>)null); ++ } ++ ++ @Test public void testAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ assertTrue(g.add(0)); ++ assertEquals(1, g.order()); ++ assertTrue(g.contains(0)); ++ // second add should have no effect ++ assertFalse(g.add(0)); ++ assertEquals(1, g.order()); ++ assertTrue(g.contains(0)); ++ ++ assertTrue(g.add(1)); ++ assertEquals(2, g.order()); ++ assertTrue(g.contains(1)); ++ } ++ ++ @Test public void testEquals() { ++ DirectedMultigraph g1 = new DirectedMultigraph(); ++ DirectedMultigraph g2 = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ g2.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ } ++ assertEquals(g1, g2); ++ ++ g1 = new DirectedMultigraph(); ++ g2 = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ g2.add(new SimpleDirectedTypedEdge(""type-1"",j, i)); ++ } ++ } ++ ++ assertFalse(g1.equals(g2)); ++ assertFalse(g2.equals(g1)); ++ } ++ ++ @Test public void testEqualGeneric() { ++ DirectedMultigraph g1 = new DirectedMultigraph(); ++ Graph> g2 = new GenericGraph>(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ g1.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ g2.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ } ++ assertEquals(g1, g2); ++ } ++ ++ @Test public void testContainsEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 100; ++i) ++ for (int j = i + 1; j < 100; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ ++ for (int i = 0; i < 100; ++i) { ++ for (int j = i + 1; j < 100; ++j) { ++ g.contains(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ g.contains(new SimpleDirectedTypedEdge(""type-1"",j, i)); ++ g.contains(i, j); ++ g.contains(j, i); ++ } ++ } ++ } ++ ++ @Test public void testAddEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ assertTrue(g.add(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ assertEquals(2, g.order()); ++ assertEquals(1, g.size()); ++ assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ ++ g.add(new SimpleDirectedTypedEdge(""type-1"",0, 2)); ++ assertEquals(3, g.order()); ++ assertEquals(2, g.size()); ++ assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 2))); ++ ++ g.add(new SimpleDirectedTypedEdge(""type-1"",3, 4)); ++ assertEquals(5, g.order()); ++ assertEquals(3, g.size()); ++ assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",3, 4))); ++ } ++ ++ @Test public void testRemoveLesserVertexWithEdges() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ for (int i = 1; i < 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ } + +-// assertTrue(g.contains(0)); +-// assertTrue(g.remove(0)); +-// assertEquals(99, g.order()); +-// assertEquals(0, g.size()); +-// } +- +-// @Test public void testRemoveHigherVertexWithEdges() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// for (int i = 0; i < 99; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",100, i); +-// g.add(e); +-// } ++ assertTrue(g.contains(0)); ++ assertTrue(g.remove(0)); ++ assertEquals(99, g.order()); ++ assertEquals(0, g.size()); ++ } ++ ++ @Test public void testRemoveHigherVertexWithEdges() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ for (int i = 0; i < 99; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",100, i); ++ g.add(e); ++ } + +-// assertTrue(g.contains(100)); +-// assertTrue(g.remove(100)); +-// assertEquals(99, g.order()); +-// assertEquals(0, g.size()); +-// } +- +- +-// @Test public void testRemoveVertex() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// } +- +-// for (int i = 99; i >= 0; --i) { +-// assertTrue(g.remove(i)); +-// assertEquals(i, g.order()); +-// assertFalse(g.contains(i)); +-// assertFalse(g.remove(i)); +-// } +-// } +- +-// @Test public void testRemoveEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// for (int i = 1; i < 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// } ++ assertTrue(g.contains(100)); ++ assertTrue(g.remove(100)); ++ assertEquals(99, g.order()); ++ assertEquals(0, g.size()); ++ } ++ ++ ++ @Test public void testRemoveVertex() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ } ++ ++ for (int i = 99; i >= 0; --i) { ++ assertTrue(g.remove(i)); ++ assertEquals(i, g.order()); ++ assertFalse(g.contains(i)); ++ assertFalse(g.remove(i)); ++ } ++ } ++ ++ @Test public void testRemoveEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ for (int i = 1; i < 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ } + +-// for (int i = 99; i > 0; --i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// assertTrue(g.remove(e)); +-// assertEquals(i-1, g.size()); +-// assertFalse(g.contains(e)); +-// assertFalse(g.remove(e)); +-// } +-// } +- +-// @Test public void testVertexIterator() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +-// assertEquals(control.size(), g.order()); +-// for (Integer i : g.vertices()) +-// assertTrue(control.contains(i)); +-// } +- +-// @Test public void testEdgeIterator() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// control.add(e); +-// } +- +-// assertEquals(control.size(), g.size()); +-// assertEquals(control.size(), g.edges().size()); +-// int returned = 0; +-// for (Edge e : g.edges()) { +-// assertTrue(control.remove(e)); +-// returned++; +-// } +-// assertEquals(g.size(), returned); +-// assertEquals(0, control.size()); +-// } +- +-// @Test public void testEdgeIteratorSmall() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 5; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// assertTrue(g.add(e)); +-// control.add(e); +-// } +- +-// assertEquals(control.size(), g.size()); +-// assertEquals(control.size(), g.edges().size()); +-// int returned = 0; +-// for (Edge e : g.edges()) { +-// System.out.println(e); +-// assertTrue(control.contains(e)); +-// returned++; +-// } +-// assertEquals(control.size(), returned); +-// } +- +-// @Test public void testEdgeIteratorSmallReverse() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 5; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, 0); +-// g.add(e); +-// control.add(e); +-// } +- +-// assertEquals(control.size(), g.size()); +-// assertEquals(control.size(), g.edges().size()); +-// int returned = 0; +-// for (Edge e : g.edges()) { +-// System.out.println(e); +-// assertTrue(control.contains(e)); +-// returned++; +-// } +-// assertEquals(control.size(), returned); +-// } +- +- +-// @Test public void testAdjacentEdges() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// control.add(e); +-// } ++ for (int i = 99; i > 0; --i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ assertTrue(g.remove(e)); ++ assertEquals(i-1, g.size()); ++ assertFalse(g.contains(e)); ++ assertFalse(g.remove(e)); ++ } ++ } ++ ++ @Test public void testVertexIterator() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ assertEquals(control.size(), g.order()); ++ for (Integer i : g.vertices()) ++ assertTrue(control.contains(i)); ++ } ++ ++ @Test public void testEdgeIterator() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ control.add(e); ++ } ++ ++ assertEquals(control.size(), g.size()); ++ assertEquals(control.size(), g.edges().size()); ++ int returned = 0; ++ for (Edge e : g.edges()) { ++ assertTrue(control.remove(e)); ++ returned++; ++ } ++ assertEquals(g.size(), returned); ++ assertEquals(0, control.size()); ++ } ++ ++ @Test public void testEdgeIteratorSmall() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 5; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ assertTrue(g.add(e)); ++ control.add(e); ++ } ++ ++ assertEquals(control.size(), g.size()); ++ assertEquals(control.size(), g.edges().size()); ++ int returned = 0; ++ for (Edge e : g.edges()) { ++ System.out.println(e); ++ assertTrue(control.contains(e)); ++ returned++; ++ } ++ assertEquals(control.size(), returned); ++ } ++ ++ @Test public void testEdgeIteratorSmallReverse() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 5; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, 0); ++ g.add(e); ++ control.add(e); ++ } ++ ++ assertEquals(control.size(), g.size()); ++ assertEquals(control.size(), g.edges().size()); ++ int returned = 0; ++ for (Edge e : g.edges()) { ++ System.out.println(e); ++ assertTrue(control.contains(e)); ++ returned++; ++ } ++ assertEquals(control.size(), returned); ++ } ++ ++ ++ @Test public void testAdjacentEdges() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ control.add(e); ++ } + +-// Set> test = g.getAdjacencyList(0); +-// assertEquals(control, test); +-// } +- +-// @Test public void testAdjacencyListSize() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); ++ Set> test = g.getAdjacencyList(0); ++ assertEquals(control, test); ++ } ++ ++ @Test public void testAdjacencyListSize() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); + +-// Set> adjList = g.getAdjacencyList(0); +-// assertEquals(9, adjList.size()); ++ Set> adjList = g.getAdjacencyList(0); ++ assertEquals(9, adjList.size()); + +-// adjList = g.getAdjacencyList(1); +-// assertEquals(9, adjList.size()); ++ adjList = g.getAdjacencyList(1); ++ assertEquals(9, adjList.size()); + +-// adjList = g.getAdjacencyList(2); +-// assertEquals(9, adjList.size()); ++ adjList = g.getAdjacencyList(2); ++ assertEquals(9, adjList.size()); + +-// adjList = g.getAdjacencyList(3); +-// assertEquals(9, adjList.size()); ++ adjList = g.getAdjacencyList(3); ++ assertEquals(9, adjList.size()); + +-// adjList = g.getAdjacencyList(5); +-// assertEquals(9, adjList.size()); +-// } ++ adjList = g.getAdjacencyList(5); ++ assertEquals(9, adjList.size()); ++ } + + +-// @Test public void testAdjacentEdgesRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// control.add(e); +-// } ++ @Test public void testAdjacentEdgesRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ control.add(e); ++ } + +-// Set> test = g.getAdjacencyList(0); +-// assertEquals(control, test); +- +-// Edge removed = new SimpleDirectedTypedEdge(""type-1"",0, 1); +-// assertTrue(test.remove(removed)); +-// assertTrue(control.remove(removed)); +-// assertEquals(control, test); +-// assertEquals(99, g.size()); +-// } +- +-// @Test public void testAdjacentEdgesAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> control = new HashSet>(); +-// for (int i = 1; i <= 100; ++i) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); +-// g.add(e); +-// control.add(e); +-// } ++ Set> test = g.getAdjacencyList(0); ++ assertEquals(control, test); ++ ++ Edge removed = new SimpleDirectedTypedEdge(""type-1"",0, 1); ++ assertTrue(test.remove(removed)); ++ assertTrue(control.remove(removed)); ++ assertEquals(control, test); ++ assertEquals(99, g.size()); ++ } ++ ++ @Test public void testAdjacentEdgesAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> control = new HashSet>(); ++ for (int i = 1; i <= 100; ++i) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, i); ++ g.add(e); ++ control.add(e); ++ } + +-// Set> test = g.getAdjacencyList(0); +-// assertEquals(control, test); +- +-// DirectedTypedEdge added = new SimpleDirectedTypedEdge(""type-1"",0, 101); +-// assertTrue(test.add(added)); +-// assertTrue(control.add(added)); +-// assertEquals(control, test); +-// assertEquals(101, g.size()); +-// assertTrue(g.contains(added)); +-// assertTrue(g.contains(101)); +-// assertEquals(102, g.order()); +-// } +- +-// @Test public void testClear() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// g.clear(); +-// assertEquals(0, g.size()); +-// assertEquals(0, g.order()); +-// assertEquals(0, g.vertices().size()); +-// assertEquals(0, g.edges().size()); ++ Set> test = g.getAdjacencyList(0); ++ assertEquals(control, test); ++ ++ DirectedTypedEdge added = new SimpleDirectedTypedEdge(""type-1"",0, 101); ++ assertTrue(test.add(added)); ++ assertTrue(control.add(added)); ++ assertEquals(control, test); ++ assertEquals(101, g.size()); ++ assertTrue(g.contains(added)); ++ assertTrue(g.contains(101)); ++ assertEquals(102, g.order()); ++ } ++ ++ @Test public void testClear() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ g.clear(); ++ assertEquals(0, g.size()); ++ assertEquals(0, g.order()); ++ assertEquals(0, g.vertices().size()); ++ assertEquals(0, g.edges().size()); + +-// // Error checking case for double-clear +-// g.clear(); +-// } +- +-// @Test public void testClearEdges() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// g.clearEdges(); +-// assertEquals(0, g.size()); +-// assertEquals(10, g.order()); +-// assertEquals(10, g.vertices().size()); +-// assertEquals(0, g.edges().size()); ++ // Error checking case for double-clear ++ g.clear(); ++ } ++ ++ @Test public void testClearEdges() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ g.clearEdges(); ++ assertEquals(0, g.size()); ++ assertEquals(10, g.order()); ++ assertEquals(10, g.vertices().size()); ++ assertEquals(0, g.edges().size()); + +-// // Error checking case for double-clear +-// g.clearEdges(); +-// } +- +-// @Test public void testToString() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) +-// for (int j = i + 1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// g.toString(); +- +-// // only vertices +-// g.clearEdges(); +-// g.toString(); +- +-// // empty graph +-// g.clear(); +-// g.toString(); ++ // Error checking case for double-clear ++ g.clearEdges(); ++ } ++ ++ @Test public void testToString() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) ++ for (int j = i + 1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ g.toString(); ++ ++ // only vertices ++ g.clearEdges(); ++ g.toString(); ++ ++ // empty graph ++ g.clear(); ++ g.toString(); + +-// } +- +-// /****************************************************************** +-// * +-// * +-// * VertexSet tests +-// * +-// * +-// ******************************************************************/ +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// assertEquals(control.size(), vertices.size()); +-// assertTrue(vertices.add(100)); +-// assertTrue(g.contains(100)); +-// assertEquals(101, vertices.size()); +-// assertEquals(101, g.order()); ++ } ++ ++ /****************************************************************** ++ * ++ * ++ * VertexSet tests ++ * ++ * ++ ******************************************************************/ ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ assertEquals(control.size(), vertices.size()); ++ assertTrue(vertices.add(100)); ++ assertTrue(g.contains(100)); ++ assertEquals(101, vertices.size()); ++ assertEquals(101, g.order()); + +-// // dupe +-// assertFalse(vertices.add(100)); +-// assertEquals(101, vertices.size()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// assertEquals(control.size(), vertices.size()); +-// assertTrue(g.add(100)); +-// assertTrue(g.contains(100)); +-// assertTrue(vertices.contains(100)); +-// assertEquals(101, vertices.size()); +-// assertEquals(101, g.order()); ++ // dupe ++ assertFalse(vertices.add(100)); ++ assertEquals(101, vertices.size()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ assertEquals(control.size(), vertices.size()); ++ assertTrue(g.add(100)); ++ assertTrue(g.contains(100)); ++ assertTrue(vertices.contains(100)); ++ assertEquals(101, vertices.size()); ++ assertEquals(101, g.order()); + +-// // dupe +-// assertFalse(vertices.add(100)); +-// assertEquals(101, vertices.size()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// assertEquals(control.size(), vertices.size()); +-// assertTrue(g.contains(99)); +-// assertTrue(vertices.remove(99)); +-// assertFalse(g.contains(99)); +-// assertEquals(99, vertices.size()); +-// assertEquals(99, g.order()); ++ // dupe ++ assertFalse(vertices.add(100)); ++ assertEquals(101, vertices.size()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ assertEquals(control.size(), vertices.size()); ++ assertTrue(g.contains(99)); ++ assertTrue(vertices.remove(99)); ++ assertFalse(g.contains(99)); ++ assertEquals(99, vertices.size()); ++ assertEquals(99, g.order()); + +-// // dupe +-// assertFalse(vertices.remove(99)); +-// assertEquals(99, vertices.size()); +-// } +- +-// @Test public void testVertexSetRemoveFromGraph() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// assertEquals(control.size(), vertices.size()); +-// assertTrue(g.remove(99)); +- +-// assertFalse(g.contains(99)); +-// assertFalse(vertices.contains(99)); +-// assertEquals(99, vertices.size()); +-// assertEquals(99, g.order()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// assertEquals(control.size(), vertices.size()); +-// Iterator iter = vertices.iterator(); +-// assertTrue(iter.hasNext()); +-// Integer toRemove = iter.next(); +-// assertTrue(g.contains(toRemove)); +-// assertTrue(vertices.contains(toRemove)); +-// iter.remove(); +-// assertFalse(g.contains(toRemove)); +-// assertFalse(vertices.contains(toRemove)); +-// assertEquals(g.order(), vertices.size()); +-// } +- +-// @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// Iterator iter = vertices.iterator(); +-// int i = 0; +-// while (iter.hasNext()) { +-// i++; +-// iter.next(); +-// } +-// assertEquals(vertices.size(), i); +-// iter.next(); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// Iterator iter = vertices.iterator(); +-// assertTrue(iter.hasNext()); +-// Integer toRemove = iter.next(); +-// assertTrue(g.contains(toRemove)); +-// assertTrue(vertices.contains(toRemove)); +-// iter.remove(); +-// iter.remove(); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set control = new HashSet(); +-// for (int i = 0; i < 100; ++i) { +-// g.add(i); +-// control.add(i); +-// } +- +-// Set vertices = g.vertices(); +-// Iterator iter = vertices.iterator(); +-// iter.remove(); +-// } ++ // dupe ++ assertFalse(vertices.remove(99)); ++ assertEquals(99, vertices.size()); ++ } ++ ++ @Test public void testVertexSetRemoveFromGraph() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ assertEquals(control.size(), vertices.size()); ++ assertTrue(g.remove(99)); ++ ++ assertFalse(g.contains(99)); ++ assertFalse(vertices.contains(99)); ++ assertEquals(99, vertices.size()); ++ assertEquals(99, g.order()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ assertEquals(control.size(), vertices.size()); ++ Iterator iter = vertices.iterator(); ++ assertTrue(iter.hasNext()); ++ Integer toRemove = iter.next(); ++ assertTrue(g.contains(toRemove)); ++ assertTrue(vertices.contains(toRemove)); ++ iter.remove(); ++ assertFalse(g.contains(toRemove)); ++ assertFalse(vertices.contains(toRemove)); ++ assertEquals(g.order(), vertices.size()); ++ } ++ ++ @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ Iterator iter = vertices.iterator(); ++ int i = 0; ++ while (iter.hasNext()) { ++ i++; ++ iter.next(); ++ } ++ assertEquals(vertices.size(), i); ++ iter.next(); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ Iterator iter = vertices.iterator(); ++ assertTrue(iter.hasNext()); ++ Integer toRemove = iter.next(); ++ assertTrue(g.contains(toRemove)); ++ assertTrue(vertices.contains(toRemove)); ++ iter.remove(); ++ iter.remove(); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set control = new HashSet(); ++ for (int i = 0; i < 100; ++i) { ++ g.add(i); ++ control.add(i); ++ } ++ ++ Set vertices = g.vertices(); ++ Iterator iter = vertices.iterator(); ++ iter.remove(); ++ } + + +-// /****************************************************************** +-// * +-// * +-// * EdgeView tests +-// * +-// * +-// ******************************************************************/ +- +-// @Test public void testEdgeViewAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> edges = g.edges(); +-// assertEquals(g.size(), edges.size()); +-// edges.add(new SimpleDirectedTypedEdge(""type-1"",0, 1)); +-// assertEquals(2, g.order()); +-// assertEquals(1, g.size()); +-// assertEquals(1, edges.size()); +-// assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// assertTrue(edges.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// } +- +-// @Test public void testEdgeViewRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> edges = g.edges(); +-// assertEquals(g.size(), edges.size()); +-// edges.add(new SimpleDirectedTypedEdge(""type-1"",0, 1)); +-// edges.remove(new SimpleDirectedTypedEdge(""type-1"",0, 1)); +-// assertEquals(2, g.order()); +-// assertEquals(0, g.size()); +-// assertEquals(0, edges.size()); +-// assertFalse(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// assertFalse(edges.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// } +- +-// @Test public void testEdgeViewIterator() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> edges = g.edges(); +- +-// Set> control = new HashSet>(); +-// for (int i = 0; i < 100; i += 2) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, i+1); +-// g.add(e); // all disconnected +-// control.add(e); +-// } ++ /****************************************************************** ++ * ++ * ++ * EdgeView tests ++ * ++ * ++ ******************************************************************/ ++ ++ @Test public void testEdgeViewAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> edges = g.edges(); ++ assertEquals(g.size(), edges.size()); ++ edges.add(new SimpleDirectedTypedEdge(""type-1"",0, 1)); ++ assertEquals(2, g.order()); ++ assertEquals(1, g.size()); ++ assertEquals(1, edges.size()); ++ assertTrue(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ assertTrue(edges.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ } ++ ++ @Test public void testEdgeViewRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> edges = g.edges(); ++ assertEquals(g.size(), edges.size()); ++ edges.add(new SimpleDirectedTypedEdge(""type-1"",0, 1)); ++ edges.remove(new SimpleDirectedTypedEdge(""type-1"",0, 1)); ++ assertEquals(2, g.order()); ++ assertEquals(0, g.size()); ++ assertEquals(0, edges.size()); ++ assertFalse(g.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ assertFalse(edges.contains(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ } ++ ++ @Test public void testEdgeViewIterator() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> edges = g.edges(); ++ ++ Set> control = new HashSet>(); ++ for (int i = 0; i < 100; i += 2) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, i+1); ++ g.add(e); // all disconnected ++ control.add(e); ++ } + + +-// assertEquals(100, g.order()); +-// assertEquals(50, g.size()); +-// assertEquals(50, edges.size()); ++ assertEquals(100, g.order()); ++ assertEquals(50, g.size()); ++ assertEquals(50, edges.size()); + +-// Set> test = new HashSet>(); +-// for (DirectedTypedEdge e : edges) +-// test.add(e); +-// assertEquals(control.size(), test.size()); +-// for (Edge e : test) +-// assertTrue(control.contains(e)); +-// } +- +-// @Test public void testEdgeViewIteratorRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> edges = g.edges(); +- +-// Set> control = new HashSet>(); +-// for (int i = 0; i < 10; i += 2) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, i+1); +-// g.add(e); // all disconnected +-// control.add(e); +-// } ++ Set> test = new HashSet>(); ++ for (DirectedTypedEdge e : edges) ++ test.add(e); ++ assertEquals(control.size(), test.size()); ++ for (Edge e : test) ++ assertTrue(control.contains(e)); ++ } ++ ++ @Test public void testEdgeViewIteratorRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> edges = g.edges(); ++ ++ Set> control = new HashSet>(); ++ for (int i = 0; i < 10; i += 2) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, i+1); ++ g.add(e); // all disconnected ++ control.add(e); ++ } + +-// assertEquals(10, g.order()); +-// assertEquals(5, g.size()); +-// assertEquals(5, edges.size()); ++ assertEquals(10, g.order()); ++ assertEquals(5, g.size()); ++ assertEquals(5, edges.size()); + +-// Iterator> iter = edges.iterator(); +-// while (iter.hasNext()) { +-// iter.next(); +-// iter.remove(); +-// } +-// assertEquals(0, g.size()); +-// assertFalse(g.edges().iterator().hasNext()); +-// assertEquals(0, edges.size()); +-// assertEquals(10, g.order()); +-// } +- +-// /****************************************************************** +-// * +-// * +-// * AdjacencyListView tests +-// * +-// * +-// ******************************************************************/ +- +-// @Test public void testAdjacencyList() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) +-// for (int j = i + 1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +- +-// for (int i = 0; i < 10; ++i) { +-// Set> adjacencyList = g.getAdjacencyList(i); +-// assertEquals(9, adjacencyList.size()); ++ Iterator> iter = edges.iterator(); ++ while (iter.hasNext()) { ++ iter.next(); ++ iter.remove(); ++ } ++ assertEquals(0, g.size()); ++ assertFalse(g.edges().iterator().hasNext()); ++ assertEquals(0, edges.size()); ++ assertEquals(10, g.order()); ++ } ++ ++ /****************************************************************** ++ * ++ * ++ * AdjacencyListView tests ++ * ++ * ++ ******************************************************************/ ++ ++ @Test public void testAdjacencyList() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) ++ for (int j = i + 1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ ++ for (int i = 0; i < 10; ++i) { ++ Set> adjacencyList = g.getAdjacencyList(i); ++ assertEquals(9, adjacencyList.size()); + +-// for (int j = 0; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// if (i >= j) +-// assertFalse(adjacencyList.contains(e)); +-// else +-// assertTrue(adjacencyList.contains(e)); +-// } +-// } +-// } +- +-// @Test public void testAdjacencyListRemoveEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) +-// for (int j = i + 1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +- +-// Set> adjacencyList = g.getAdjacencyList(0); +-// Edge e = new SimpleDirectedTypedEdge(""type-1"",0, 1); +-// assertTrue(adjacencyList.contains(e)); +-// assertTrue(adjacencyList.remove(e)); +-// assertEquals(8, adjacencyList.size()); +-// assertEquals( (10 * 9) / 2 - 1, g.size()); +-// } +- +-// public void testAdjacencyListAddEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) +-// for (int j = i + 2; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +- +-// assertEquals( (10 * 9) / 2 - 9, g.size()); +- +-// Set> adjacencyList = g.getAdjacencyList(0); +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, 1); +-// assertFalse(adjacencyList.contains(e)); +-// assertFalse(g.contains(e)); +- +-// assertTrue(adjacencyList.add(e)); +-// assertTrue(g.contains(e)); +- +-// assertEquals(9, adjacencyList.size()); +-// assertEquals( (10 * 9) / 2 - 8, g.size()); +-// } +- +-// @Test public void testAdjacencyListIterator() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set> test = new HashSet>(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(9, adjacencyList.size()); +- +-// Iterator> it = adjacencyList.iterator(); +-// int i = 0; +-// while (it.hasNext()) +-// assertTrue(test.add(it.next())); +-// assertEquals(9, test.size()); +-// } +- +-// @Test public void testAdjacencyListNoVertex() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(0, adjacencyList.size()); +-// } +- +-// @Test(expected=NoSuchElementException.class) +-// public void testAdjacencyListIteratorNextOffEnd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set> test = new HashSet>(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(9, adjacencyList.size()); +- +-// Iterator> it = adjacencyList.iterator(); +-// int i = 0; +-// while (it.hasNext()) +-// assertTrue(test.add(it.next())); +-// assertEquals(9, test.size()); +-// it.next(); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set> test = new HashSet>(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(9, adjacencyList.size()); +- +-// Iterator> it = adjacencyList.iterator(); +-// assertTrue(it.hasNext()); +-// Edge e = it.next(); +-// it.remove(); +-// assertFalse(adjacencyList.contains(e)); +-// assertEquals(8, adjacencyList.size()); +-// assertFalse(g.contains(e)); +-// assertEquals( (10 * 9) / 2 - 1, g.size()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) +-// public void testAdjacencyListIteratorRemoveFirst() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set> test = new HashSet>(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(9, adjacencyList.size()); +- +-// Iterator> it = adjacencyList.iterator(); +-// it.remove(); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) +-// public void testAdjacencyListIteratorRemoveTwice() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set> test = new HashSet>(); +-// Set> adjacencyList = g.getAdjacencyList(0); +-// assertEquals(9, adjacencyList.size()); +- +-// Iterator> it = adjacencyList.iterator(); +-// assertTrue(it.hasNext()); +-// it.next(); +-// it.remove(); +-// it.remove(); +-// } +- +-// /****************************************************************** +-// * +-// * +-// * AdjacentVerticesView tests +-// * +-// * +-// ******************************************************************/ +- +- +-// @Test public void testAdjacentVertices() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set test = new HashSet(); +-// Set adjacent = g.getNeighbors(0); +-// assertEquals(9, adjacent.size()); +-// for (int i = 1; i < 10; ++i) +-// assertTrue(adjacent.contains(i)); +-// assertFalse(adjacent.contains(0)); +-// assertFalse(adjacent.contains(10)); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set test = new HashSet(); +-// Set adjacent = g.getNeighbors(0); +-// adjacent.add(1); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set test = new HashSet(); +-// Set adjacent = g.getNeighbors(0); +-// adjacent.remove(1); +-// } +- +-// @Test public void testAdjacentVerticesIterator() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set test = new HashSet(); +-// Set adjacent = g.getNeighbors(0); +-// Iterator it = adjacent.iterator(); +-// while (it.hasNext()) +-// assertTrue(test.add(it.next())); +-// assertEquals(9, test.size()); +-// } +- +- +-// @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +-// for (int i = 0; i < 10; ++i) { +-// for (int j = i + 1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// g.add(e); +-// } +-// } +- +-// Set test = new HashSet(); +-// Set adjacent = g.getNeighbors(0); +-// Iterator it = adjacent.iterator(); +-// assertTrue(it.hasNext()); +-// it.next(); +-// it.remove(); +-// } +- +-// /****************************************************************** +-// * +-// * +-// * Subgraph tests +-// * +-// * +-// ******************************************************************/ +- +-// @Test public void testSubgraph() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +-// } +- +-// @Test public void testSubgraphContainsVertex() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +-// for (int i = 0; i < 5; ++i) +-// assertTrue(subgraph.contains(i)); +-// for (int i = 5; i < 10; ++i) { +-// assertTrue(g.contains(i)); +-// assertFalse(subgraph.contains(i)); +-// } +-// } +- +-// @Test public void testSubgraphContainsEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +-// for (int i = 0; i < 5; ++i) { +-// for (int j = i+1; j < 5; ++j) { +-// assertTrue(subgraph.contains(new SimpleDirectedTypedEdge(""type-1"",i, j))); +-// } +-// } +- +-// for (int i = 5; i < 10; ++i) { +-// for (int j = i+1; j < 10; ++j) { +-// DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); +-// assertTrue(g.contains(e)); +-// assertFalse(subgraph.contains(e)); +-// } +-// } +-// } +- +-// @Test public void testSubgraphAddEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < i+2 && j < 10; ++j) +-// assertTrue(g.add(new SimpleDirectedTypedEdge(""type-1"",i, j))); +-// } +- +-// assertEquals(9, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals(4, subgraph.size()); +- +-// // Add an edge to a new vertex +-// assertTrue(subgraph.add(new SimpleDirectedTypedEdge(""type-1"", 1, 0))); +-// assertEquals(5, subgraph.size()); +-// assertEquals(5, subgraph.order()); +-// assertEquals(10, g.size()); +- +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +- +-// // Add an edge to a new vertex +-// assertTrue(subgraph.add(new SimpleDirectedTypedEdge(""type-1"",0, 5))); +-// assertEquals( (5 * 4) / 2 + 1, subgraph.size()); +-// assertEquals(6, subgraph.order()); +-// assertEquals(11, g.order()); +-// assertEquals( (9*10)/2 + 1, g.size()); +-// } +- +-// @Test public void testSubgraphRemoveEdge() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +- +-// // Remove an existing edge +-// assertTrue(subgraph.remove(new SimpleDirectedTypedEdge(""type-1"",0, 1))); +-// assertEquals( (5 * 4) / 2 - 1, subgraph.size()); +-// assertEquals(5, subgraph.order()); +-// assertEquals(10, g.order()); +-// assertEquals( (9*10)/2 - 1, g.size()); +- +-// // Remove a non-existent edge, which should have no effect even though +-// // the edge is present in the backing graph +-// assertFalse(subgraph.remove(new SimpleDirectedTypedEdge(""type-1"",0, 6))); +-// assertEquals( (5 * 4) / 2 - 1, subgraph.size()); +-// assertEquals(5, subgraph.order()); +-// assertEquals(10, g.order()); +-// assertEquals( (9*10)/2 - 1, g.size()); +-// } +- +- +-// /****************************************************************** +-// * +-// * +-// * SubgraphVertexView tests +-// * +-// * +-// ******************************************************************/ +- +- +-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +- +-// Set test = subgraph.vertices(); +-// assertEquals(5, test.size()); +- +-// // Add a vertex +-// assertTrue(test.add(5)); +-// assertEquals(6, test.size()); +-// assertEquals(6, subgraph.order()); +-// assertEquals(11, g.order()); +-// assertEquals( (5*4)/2, subgraph.size()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +- +-// Set test = subgraph.vertices(); +-// assertEquals(5, test.size()); +- +-// // Add a vertex +-// assertTrue(test.remove(0)); +-// assertEquals(4, test.size()); +-// assertEquals(4, subgraph.order()); +-// assertEquals(9, g.order()); +-// assertEquals( (4*3)/2, subgraph.size()); +-// } +- +-// @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() { +-// DirectedMultigraph g = new DirectedMultigraph(); +- +-// // fully connected +-// for (int i = 0; i < 10; i++) { +-// for (int j = i+1; j < 10; ++j) +-// g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); +-// } +- +-// // (n * (n-1)) / 2 +-// assertEquals( (10 * 9) / 2, g.size()); +-// assertEquals(10, g.order()); +- +-// Set vertices = new LinkedHashSet(); +-// for (int i = 0; i < 5; ++i) +-// vertices.add(i); +- +-// DirectedMultigraph subgraph = g.subgraph(vertices); +-// assertEquals(5, subgraph.order()); +-// assertEquals( (5 * 4) / 2, subgraph.size()); +- +-// Set test = subgraph.vertices(); +-// assertEquals(5, test.size()); +-// Iterator it = test.iterator(); +-// assertTrue(it.hasNext()); +-// // Remove the first vertex returned +-// it.next(); +-// it.remove(); +- +-// assertEquals(4, test.size()); +-// assertEquals(4, subgraph.order()); +-// assertEquals(9, g.order()); +-// assertEquals( (4*3)/2, subgraph.size()); +-// } ++ for (int j = 0; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ if (i >= j) ++ assertFalse(adjacencyList.contains(e)); ++ else ++ assertTrue(adjacencyList.contains(e)); ++ } ++ } ++ } ++ ++ @Test public void testAdjacencyListRemoveEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) ++ for (int j = i + 1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ ++ Set> adjacencyList = g.getAdjacencyList(0); ++ Edge e = new SimpleDirectedTypedEdge(""type-1"",0, 1); ++ assertTrue(adjacencyList.contains(e)); ++ assertTrue(adjacencyList.remove(e)); ++ assertEquals(8, adjacencyList.size()); ++ assertEquals( (10 * 9) / 2 - 1, g.size()); ++ } ++ ++ public void testAdjacencyListAddEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) ++ for (int j = i + 2; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ ++ assertEquals( (10 * 9) / 2 - 9, g.size()); ++ ++ Set> adjacencyList = g.getAdjacencyList(0); ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",0, 1); ++ assertFalse(adjacencyList.contains(e)); ++ assertFalse(g.contains(e)); ++ ++ assertTrue(adjacencyList.add(e)); ++ assertTrue(g.contains(e)); ++ ++ assertEquals(9, adjacencyList.size()); ++ assertEquals( (10 * 9) / 2 - 8, g.size()); ++ } ++ ++ @Test public void testAdjacencyListIterator() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set> test = new HashSet>(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(9, adjacencyList.size()); ++ ++ Iterator> it = adjacencyList.iterator(); ++ int i = 0; ++ while (it.hasNext()) ++ assertTrue(test.add(it.next())); ++ assertEquals(9, test.size()); ++ } ++ ++ @Test public void testAdjacencyListNoVertex() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(0, adjacencyList.size()); ++ } ++ ++ @Test(expected=NoSuchElementException.class) ++ public void testAdjacencyListIteratorNextOffEnd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set> test = new HashSet>(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(9, adjacencyList.size()); ++ ++ Iterator> it = adjacencyList.iterator(); ++ int i = 0; ++ while (it.hasNext()) ++ assertTrue(test.add(it.next())); ++ assertEquals(9, test.size()); ++ it.next(); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set> test = new HashSet>(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(9, adjacencyList.size()); ++ ++ Iterator> it = adjacencyList.iterator(); ++ assertTrue(it.hasNext()); ++ Edge e = it.next(); ++ it.remove(); ++ assertFalse(adjacencyList.contains(e)); ++ assertEquals(8, adjacencyList.size()); ++ assertFalse(g.contains(e)); ++ assertEquals( (10 * 9) / 2 - 1, g.size()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) ++ public void testAdjacencyListIteratorRemoveFirst() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set> test = new HashSet>(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(9, adjacencyList.size()); ++ ++ Iterator> it = adjacencyList.iterator(); ++ it.remove(); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) ++ public void testAdjacencyListIteratorRemoveTwice() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set> test = new HashSet>(); ++ Set> adjacencyList = g.getAdjacencyList(0); ++ assertEquals(9, adjacencyList.size()); ++ ++ Iterator> it = adjacencyList.iterator(); ++ assertTrue(it.hasNext()); ++ it.next(); ++ it.remove(); ++ it.remove(); ++ } ++ ++ /****************************************************************** ++ * ++ * ++ * AdjacentVerticesView tests ++ * ++ * ++ ******************************************************************/ ++ ++ ++ @Test public void testAdjacentVertices() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set test = new HashSet(); ++ Set adjacent = g.getNeighbors(0); ++ assertEquals(9, adjacent.size()); ++ for (int i = 1; i < 10; ++i) ++ assertTrue(adjacent.contains(i)); ++ assertFalse(adjacent.contains(0)); ++ assertFalse(adjacent.contains(10)); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set test = new HashSet(); ++ Set adjacent = g.getNeighbors(0); ++ adjacent.add(1); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set test = new HashSet(); ++ Set adjacent = g.getNeighbors(0); ++ adjacent.remove(1); ++ } ++ ++ @Test public void testAdjacentVerticesIterator() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set test = new HashSet(); ++ Set adjacent = g.getNeighbors(0); ++ Iterator it = adjacent.iterator(); ++ while (it.hasNext()) ++ assertTrue(test.add(it.next())); ++ assertEquals(9, test.size()); ++ } ++ ++ ++ @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ for (int i = 0; i < 10; ++i) { ++ for (int j = i + 1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ g.add(e); ++ } ++ } ++ ++ Set test = new HashSet(); ++ Set adjacent = g.getNeighbors(0); ++ Iterator it = adjacent.iterator(); ++ assertTrue(it.hasNext()); ++ it.next(); ++ it.remove(); ++ } ++ ++ /****************************************************************** ++ * ++ * ++ * Subgraph tests ++ * ++ * ++ ******************************************************************/ ++ ++ @Test public void testSubgraph() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ } ++ ++ @Test public void testSubgraphContainsVertex() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ for (int i = 0; i < 5; ++i) ++ assertTrue(subgraph.contains(i)); ++ for (int i = 5; i < 10; ++i) { ++ assertTrue(g.contains(i)); ++ assertFalse(subgraph.contains(i)); ++ } ++ } ++ ++ @Test public void testSubgraphContainsEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ for (int i = 0; i < 5; ++i) { ++ for (int j = i+1; j < 5; ++j) { ++ assertTrue(subgraph.contains(new SimpleDirectedTypedEdge(""type-1"",i, j))); ++ } ++ } ++ ++ for (int i = 5; i < 10; ++i) { ++ for (int j = i+1; j < 10; ++j) { ++ DirectedTypedEdge e = new SimpleDirectedTypedEdge(""type-1"",i, j); ++ assertTrue(g.contains(e)); ++ assertFalse(subgraph.contains(e)); ++ } ++ } ++ } ++ ++ @Test public void testSubgraphAddEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < i+2 && j < 10; ++j) ++ assertTrue(g.add(new SimpleDirectedTypedEdge(""type-1"",i, j))); ++ } ++ ++ assertEquals(9, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals(4, subgraph.size()); ++ ++ // Add an edge to a new vertex ++ assertTrue(subgraph.add(new SimpleDirectedTypedEdge(""type-1"", 1, 0))); ++ assertEquals(5, subgraph.size()); ++ assertEquals(5, subgraph.order()); ++ assertEquals(10, g.size()); ++ ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ ++ // Add an edge to a new vertex ++ assertTrue(subgraph.add(new SimpleDirectedTypedEdge(""type-1"",0, 5))); ++ assertEquals( (5 * 4) / 2 + 1, subgraph.size()); ++ assertEquals(6, subgraph.order()); ++ assertEquals(11, g.order()); ++ assertEquals( (9*10)/2 + 1, g.size()); ++ } ++ ++ @Test public void testSubgraphRemoveEdge() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ ++ // Remove an existing edge ++ assertTrue(subgraph.remove(new SimpleDirectedTypedEdge(""type-1"",0, 1))); ++ assertEquals( (5 * 4) / 2 - 1, subgraph.size()); ++ assertEquals(5, subgraph.order()); ++ assertEquals(10, g.order()); ++ assertEquals( (9*10)/2 - 1, g.size()); ++ ++ // Remove a non-existent edge, which should have no effect even though ++ // the edge is present in the backing graph ++ assertFalse(subgraph.remove(new SimpleDirectedTypedEdge(""type-1"",0, 6))); ++ assertEquals( (5 * 4) / 2 - 1, subgraph.size()); ++ assertEquals(5, subgraph.order()); ++ assertEquals(10, g.order()); ++ assertEquals( (9*10)/2 - 1, g.size()); ++ } ++ ++ ++ /****************************************************************** ++ * ++ * ++ * SubgraphVertexView tests ++ * ++ * ++ ******************************************************************/ ++ ++ ++ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ ++ Set test = subgraph.vertices(); ++ assertEquals(5, test.size()); ++ ++ // Add a vertex ++ assertTrue(test.add(5)); ++ assertEquals(6, test.size()); ++ assertEquals(6, subgraph.order()); ++ assertEquals(11, g.order()); ++ assertEquals( (5*4)/2, subgraph.size()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ ++ Set test = subgraph.vertices(); ++ assertEquals(5, test.size()); ++ ++ // Add a vertex ++ assertTrue(test.remove(0)); ++ assertEquals(4, test.size()); ++ assertEquals(4, subgraph.order()); ++ assertEquals(9, g.order()); ++ assertEquals( (4*3)/2, subgraph.size()); ++ } ++ ++ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() { ++ DirectedMultigraph g = new DirectedMultigraph(); ++ ++ // fully connected ++ for (int i = 0; i < 10; i++) { ++ for (int j = i+1; j < 10; ++j) ++ g.add(new SimpleDirectedTypedEdge(""type-1"",i, j)); ++ } ++ ++ // (n * (n-1)) / 2 ++ assertEquals( (10 * 9) / 2, g.size()); ++ assertEquals(10, g.order()); ++ ++ Set vertices = new LinkedHashSet(); ++ for (int i = 0; i < 5; ++i) ++ vertices.add(i); ++ ++ DirectedMultigraph subgraph = g.subgraph(vertices); ++ assertEquals(5, subgraph.order()); ++ assertEquals( (5 * 4) / 2, subgraph.size()); ++ ++ Set test = subgraph.vertices(); ++ assertEquals(5, test.size()); ++ Iterator it = test.iterator(); ++ assertTrue(it.hasNext()); ++ // Remove the first vertex returned ++ it.next(); ++ it.remove(); ++ ++ assertEquals(4, test.size()); ++ assertEquals(4, subgraph.order()); ++ assertEquals(9, g.order()); ++ assertEquals( (4*3)/2, subgraph.size()); ++ } + + + /****************************************************************** +diff --git a/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java b/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java +index fd06a4b1..6a47fef7 100644 +--- a/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java ++++ b/test/edu/ucla/sspace/text/corpora/PukWacDependencyCorpusReaderTest.java +@@ -26,6 +26,7 @@ + import edu.ucla.sspace.text.CorpusReader; + import edu.ucla.sspace.text.Document; + ++import java.io.BufferedReader; + import java.io.StringReader; + import java.util.Iterator; + +@@ -41,22 +42,22 @@ + public class PukWacDependencyCorpusReaderTest { + + public static final String FIRST_SENTENCE = +- ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + +- ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + +- ""3 is _ VBZ VBZ _ 0 ROOT _ _\n""; ++ toTabs(""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + ++ ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + ++ ""3 is _ VBZ VBZ _ 0 ROOT _ _\n""); + + public static final String SECOND_SENTENCE = +- ""4 a _ DT DT _ 5 NMOD _ _\n"" + +- ""5 columnist _ NN NN _ 3 PRD _ _\n"" + +- ""6 for _ IN IN _ 5 NMOD _ _\n"" + +- ""7 the _ DT DT _ 9 NMOD _ _\n"" + +- ""8 Literary _ NNP NNP _ 9 NMOD _ _\n""; +- ++ toTabs(""4 a _ DT DT _ 5 NMOD _ _\n"" + ++ ""5 columnist _ NN NN _ 3 PRD _ _\n"" + ++ ""6 for _ IN IN _ 5 NMOD _ _\n"" + ++ ""7 the _ DT DT _ 9 NMOD _ _\n"" + ++ ""8 Literary _ NNP NNP _ 9 NMOD _ _\n""); ++ + public static final String THIRD_SENTENCE = +- ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + +- ""10 in _ IN IN _ 9 ADV _ _\n"" + +- ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + +- ""12 . _ . . _ 3 P _ _\n""; ++ toTabs(""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + ++ ""10 in _ IN IN _ 9 ADV _ _\n"" + ++ ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + ++ ""12 . _ . . _ 3 P _ _\n""); + + public static final String TEST_TEXT = + ""\n"" + +@@ -87,8 +88,24 @@ public class PukWacDependencyCorpusReaderTest { + + private static String readAll(Document doc) throws Exception { + StringBuilder sb = new StringBuilder(); +- for (String line = null; (line = doc.reader().readLine()) != null; ) ++ BufferedReader reader = doc.reader(); ++ for (String line = null; (line = reader.readLine()) != null; ) + sb.append(line).append(""\n""); + return sb.toString(); + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java +index 6aae6fb7..8c0e843a 100644 +--- a/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java ++++ b/test/edu/ucla/sspace/wordsi/DependencyContextExtractorTest.java +@@ -70,7 +70,7 @@ public class DependencyContextExtractorTest { + MockWordsi wordsi = new MockWordsi(null, extractor); + + extractor.processDocument( +- new BufferedReader(new StringReader(SINGLE_PARSE)), ++ new BufferedReader(new StringReader(toTabs(SINGLE_PARSE))), + wordsi); + assertTrue(wordsi.called); + } +@@ -178,4 +178,19 @@ public boolean acceptWord(String word) { + return word.equals(""cat""); + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java +index 246d2542..33b1f431 100644 +--- a/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java ++++ b/test/edu/ucla/sspace/wordsi/OccurrenceDependencyContextGeneratorTest.java +@@ -46,18 +46,18 @@ + public class OccurrenceDependencyContextGeneratorTest { + + public static final String SINGLE_PARSE = +- ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + +- ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + +- ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + +- ""4 a _ DT DT _ 5 NMOD _ _\n"" + +- ""5 columnist _ NN NN _ 3 PRD _ _\n"" + +- ""6 for _ IN IN _ 5 NMOD _ _\n"" + +- ""7 the _ DT DT _ 9 NMOD _ _\n"" + +- ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + +- ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + +- ""10 in _ IN IN _ 9 ADV _ _\n"" + +- ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + +- ""12 . _ . . _ 3 P _ _""; ++ toTabs(""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + ++ ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + ++ ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + ++ ""4 a _ DT DT _ 5 NMOD _ _\n"" + ++ ""5 columnist _ NN NN _ 3 PRD _ _\n"" + ++ ""6 for _ IN IN _ 5 NMOD _ _\n"" + ++ ""7 the _ DT DT _ 9 NMOD _ _\n"" + ++ ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + ++ ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + ++ ""10 in _ IN IN _ 9 ADV _ _\n"" + ++ ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + ++ ""12 . _ . . _ 3 P _ _""); + + @Test public void testOccurrence() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +@@ -82,22 +82,37 @@ public int getDimension(String key) { + return 0; + if (key.equals(""is"")) + return 1; +- if (key.equals(""holt"")) ++ if (key.equals(""Holt"")) + return 2; +- if (key.equals(""mr."")) ++ if (key.equals(""Mr."")) + return 3; + + if (key.equals(""for"")) + return 4; + if (key.equals(""the"")) + return 5; +- if (key.equals(""literary"")) ++ if (key.equals(""Literary"")) + return 6; +- if (key.equals(""review"")) ++ if (key.equals(""Review"")) + return 7; + if (key.equals(""in"")) + return 8; + return -1; + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java +index 9bd825fc..241e6ef3 100644 +--- a/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java ++++ b/test/edu/ucla/sspace/wordsi/OrderingDependencyContextGeneratorTest.java +@@ -49,18 +49,18 @@ + public class OrderingDependencyContextGeneratorTest { + + public static final String SINGLE_PARSE = +- ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + +- ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + +- ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + +- ""4 a _ DT DT _ 5 NMOD _ _\n"" + +- ""5 columnist _ NN NN _ 3 PRD _ _\n"" + +- ""6 for _ IN IN _ 5 NMOD _ _\n"" + +- ""7 the _ DT DT _ 9 NMOD _ _\n"" + +- ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + +- ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + +- ""10 in _ IN IN _ 9 ADV _ _\n"" + +- ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + +- ""12 . _ . . _ 3 P _ _""; ++ toTabs(""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + ++ ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + ++ ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + ++ ""4 a _ DT DT _ 5 NMOD _ _\n"" + ++ ""5 columnist _ NN NN _ 3 PRD _ _\n"" + ++ ""6 for _ IN IN _ 5 NMOD _ _\n"" + ++ ""7 the _ DT DT _ 9 NMOD _ _\n"" + ++ ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + ++ ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + ++ ""10 in _ IN IN _ 9 ADV _ _\n"" + ++ ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + ++ ""12 . _ . . _ 3 P _ _""); + + @Test public void testOrdering() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +@@ -85,22 +85,37 @@ public int getDimension(String key) { + return 0; + if (key.equals(""is--2"")) + return 1; +- if (key.equals(""holt--3"")) ++ if (key.equals(""Holt--3"")) + return 2; +- if (key.equals(""mr.--4"")) ++ if (key.equals(""Mr.--4"")) + return 3; + + if (key.equals(""for-1"")) + return 4; + if (key.equals(""the-2"")) + return 5; +- if (key.equals(""literary-3"")) ++ if (key.equals(""Literary-3"")) + return 6; +- if (key.equals(""review-4"")) ++ if (key.equals(""Review-4"")) + return 7; + if (key.equals(""in-5"")) + return 8; + return -1; + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java b/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java +index 5da76df4..6fa81d67 100644 +--- a/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java ++++ b/test/edu/ucla/sspace/wordsi/PartOfSpeechDependencyContextGeneratorTest.java +@@ -49,18 +49,18 @@ + public class PartOfSpeechDependencyContextGeneratorTest { + + public static final String SINGLE_PARSE = +- ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + +- ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + +- ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + +- ""4 a _ DT DT _ 5 NMOD _ _\n"" + +- ""5 columnist _ NN NN _ 3 PRD _ _\n"" + +- ""6 for _ IN IN _ 5 NMOD _ _\n"" + +- ""7 the _ DT DT _ 9 NMOD _ _\n"" + +- ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + +- ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + +- ""10 in _ IN IN _ 9 ADV _ _\n"" + +- ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + +- ""12 . _ . . _ 3 P _ _""; ++ toTabs(""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + ++ ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + ++ ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + ++ ""4 a _ DT DT _ 5 NMOD _ _\n"" + ++ ""5 columnist _ NN NN _ 3 PRD _ _\n"" + ++ ""6 for _ IN IN _ 5 NMOD _ _\n"" + ++ ""7 the _ DT DT _ 9 NMOD _ _\n"" + ++ ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + ++ ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + ++ ""10 in _ IN IN _ 9 ADV _ _\n"" + ++ ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + ++ ""12 . _ . . _ 3 P _ _""); + + @Test public void testGenerate() throws Exception { + DependencyExtractor extractor = new CoNLLDependencyExtractor(); +@@ -85,22 +85,37 @@ public int getDimension(String key) { + return 0; + if (key.equals(""is-VBZ"")) + return 1; +- if (key.equals(""holt-NNP"")) ++ if (key.equals(""Holt-NNP"")) + return 2; +- if (key.equals(""mr.-NNP"")) ++ if (key.equals(""Mr.-NNP"")) + return 3; + + if (key.equals(""for-IN"")) + return 4; + if (key.equals(""the-DT"")) + return 5; +- if (key.equals(""literary-NNP"")) ++ if (key.equals(""Literary-NNP"")) + return 6; +- if (key.equals(""review-NNP"")) ++ if (key.equals(""Review-NNP"")) + return 7; + if (key.equals(""in-IN"")) + return 8; + return -1; + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java +index fbbfa3ee..367ac49e 100644 +--- a/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java ++++ b/test/edu/ucla/sspace/wordsi/psd/PseudoWordDependencyContextExtractorTest.java +@@ -50,19 +50,19 @@ + public class PseudoWordDependencyContextExtractorTest { + + public static final String SINGLE_PARSE = +- ""target: cat absolute_position: 4 relative_position: 4 prior_trees: 0 after_trees: 0\n"" + +- ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + +- ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + +- ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + +- ""4 a _ DT DT _ 5 NMOD _ _\n"" + +- ""5 cat _ NN NN _ 3 PRD _ _\n"" + +- ""6 for _ IN IN _ 5 NMOD _ _\n"" + +- ""7 the _ DT DT _ 9 NMOD _ _\n"" + +- ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + +- ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + +- ""10 in _ IN IN _ 9 ADV _ _\n"" + +- ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + +- ""12 . _ . . _ 3 P _ _""; ++ toTabs(""target: cat absolute_position: 4 relative_position: 4 prior_trees: 0 after_trees: 0\n"" + ++ ""1 Mr. _ NNP NNP _ 2 NMOD _ _\n"" + ++ ""2 Holt _ NNP NNP _ 3 SBJ _ _\n"" + ++ ""3 is _ VBZ VBZ _ 0 ROOT _ _\n"" + ++ ""4 a _ DT DT _ 5 NMOD _ _\n"" + ++ ""5 cat _ NN NN _ 3 PRD _ _\n"" + ++ ""6 for _ IN IN _ 5 NMOD _ _\n"" + ++ ""7 the _ DT DT _ 9 NMOD _ _\n"" + ++ ""8 Literary _ NNP NNP _ 9 NMOD _ _\n"" + ++ ""9 Review _ NNP NNP _ 6 PMOD _ _\n"" + ++ ""10 in _ IN IN _ 9 ADV _ _\n"" + ++ ""11 London _ NNP NNP _ 10 PMOD _ _\n"" + ++ ""12 . _ . . _ 3 P _ _""); + + private SparseDoubleVector testVector; + +@@ -149,4 +149,19 @@ public boolean acceptWord(String word) { + return word.equals(""cat""); + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + } +diff --git a/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java b/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java +index 2b51f4e2..5fc4bd6d 100644 +--- a/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java ++++ b/test/edu/ucla/sspace/wordsi/semeval/SemEvalDependencyContextExtractorTest.java +@@ -74,7 +74,7 @@ public class SemEvalDependencyContextExtractorTest { + MockWordsi wordsi = new MockWordsi(null, extractor); + + extractor.processDocument( +- new BufferedReader(new StringReader(SINGLE_PARSE)), ++ new BufferedReader(new StringReader(toTabs(SINGLE_PARSE))), + wordsi); + assertTrue(wordsi.called); + } +@@ -149,4 +149,19 @@ public boolean acceptWord(String word) { + return word.equals(""cat""); + } + } ++ ++ static String toTabs(String doc) { ++ StringBuilder sb = new StringBuilder(); ++ String[] arr = doc.split(""\n""); ++ for (String line : arr) { ++ String[] cols = line.split(""\\s+""); ++ for (int i = 0; i < cols.length; ++i) { ++ sb.append(cols[i]); ++ if (i + 1 < cols.length) ++ sb.append('\t'); ++ } ++ sb.append('\n'); ++ } ++ return sb.toString(); ++ } + }" +9f923255878b7baefd89bc37af8fe3072f163322,elasticsearch,Allow additional settings for the node in- ESSingleNodeTestCase--This change adds a method that extending classes can override to provide additional settings-for the node used in a single node test case.-,a,https://github.com/elastic/elasticsearch,"diff --git a/test/framework/src/main/java/org/elasticsearch/test/ESSingleNodeTestCase.java b/test/framework/src/main/java/org/elasticsearch/test/ESSingleNodeTestCase.java +index 6e16d60eafc01..57dfc10684588 100644 +--- a/test/framework/src/main/java/org/elasticsearch/test/ESSingleNodeTestCase.java ++++ b/test/framework/src/main/java/org/elasticsearch/test/ESSingleNodeTestCase.java +@@ -32,7 +32,6 @@ + import org.elasticsearch.cluster.metadata.MetaData; + import org.elasticsearch.cluster.node.DiscoveryNode; + import org.elasticsearch.common.Priority; +-import org.elasticsearch.common.lease.Releasables; + import org.elasticsearch.common.settings.Settings; + import org.elasticsearch.common.unit.TimeValue; + import org.elasticsearch.common.util.BigArrays; +@@ -160,6 +159,11 @@ protected final Collection> pluginList(Class + + +- +- +- + + +- +- +- +- + + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF +index b9c5a365153..be8eeb326e6 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/META-INF/MANIFEST.MF +@@ -2,7 +2,7 @@ Manifest-Version: 1.0 + Bundle-ManifestVersion: 2 + Bundle-Name: %plugin.name + Bundle-SymbolicName: net.sourceforge.pmd.eclipse.plugin;singleton:=true +-Bundle-Version: 5.0.0.v20100726 ++Bundle-Version: 5.0.0.v20100826 + Bundle-Activator: net.sourceforge.pmd.eclipse.plugin.PMDPlugin + Require-Bundle: org.apache.commons.logging;bundle-version=""1.0.4"", + org.eclipse.core.resources;bundle-version=""3.5.0"", +@@ -11,7 +11,12 @@ Require-Bundle: org.apache.commons.logging;bundle-version=""1.0.4"", + org.eclipse.jface.text;bundle-version=""3.5.0"", + org.eclipse.ui;bundle-version=""3.5.0"", + org.eclipse.ui.ide;bundle-version=""3.5.0"", +- org.eclipse.ui.editors;bundle-version=""3.5.0"" ++ org.eclipse.ui.editors;bundle-version=""3.5.0"", ++ org.eclipse.team.core;bundle-version=""3.5.0"", ++ org.eclipse.search, ++ org.eclipse.help;bundle-version=""3.5.0"", ++ org.eclipse.help.ui;bundle-version=""3.5.0"", ++ org.eclipse.help.appserver;bundle-version=""3.1.400"" + Bundle-ActivationPolicy: lazy + Bundle-RequiredExecutionEnvironment: J2SE-1.5 + Bundle-Vendor: %plugin.provider +@@ -36,9 +41,10 @@ Export-Package: net.sourceforge.pmd, + net.sourceforge.pmd.eclipse.runtime.properties, + net.sourceforge.pmd.eclipse.runtime.writer, + net.sourceforge.pmd.eclipse.ui, ++ net.sourceforge.pmd.eclipse.ui.actions, + net.sourceforge.pmd.eclipse.ui.model, +- net.sourceforge.pmd.eclipse.ui.nls, + net.sourceforge.pmd.eclipse.ui.preferences.br, + net.sourceforge.pmd.eclipse.ui.views.actions, + net.sourceforge.pmd.util, ++ org.apache.log4j, + rulesets +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties +index 83143a2c913..87f3ea1111c 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/build.properties +@@ -52,7 +52,8 @@ src.includes = icons/,\ + about.ini,\ + toc.xml,\ + welcome.xml,\ +- schema/ ++ schema/,\ ++ src/ + jars.compile.order = pmd-plugin.jar + source.pmd-plugin.jar = src/ + output.pmd-plugin.jar = bin/ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png +new file mode 100755 +index 00000000000..0703aa63f7b +Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP1.png differ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png +new file mode 100755 +index 00000000000..d98b9346871 +Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP2.png differ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png +new file mode 100755 +index 00000000000..7452a0babd2 +Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP3.png differ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png +new file mode 100755 +index 00000000000..f9bdb9d02df +Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP4.png differ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png +new file mode 100755 +index 00000000000..b7a811bfb67 +Binary files /dev/null and b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/icons/markerP5.png differ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties +index 1414e7475fb..ec6a6ba1823 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/messages.properties +@@ -19,6 +19,7 @@ preference.pmd.label.addcomment = Additional text to be appended to review comme + preference.pmd.label.sample = Sample : + preference.pmd.tooltip.addcomment = Use MessageFormat substitution rules. {0} is the user name, {1} is the current date. + preference.pmd.message.incorrect_format = Incorrect message format ++preference.pmd.group.priorities = Priority levels + preference.pmd.group.review = Violations review parameters + preference.pmd.group.general = General options + preference.pmd.label.perspective_on_check = Show PMD perspective when checking code +@@ -151,14 +152,16 @@ preference.cpd.title = CPD Configuration Options + preference.cpd.tilesize = Minimum Tile Size + + # View labels ++ + view.outline.default_text = A violation outline is not available + view.outline.column_message = Error Message + view.outline.column_line = Line + view.overview.column_element = Element + view.overview.column_vio_total = # Violations +-view.overview.column_vio_loc = # Violations/LOC ++view.overview.column_vio_loc = # Violations/KLOC + view.overview.column_vio_method = # Violations/Method + view.overview.column_project = Project ++ + view.dataflow.default_text = A dataflow graph is not available + view.dataflow.choose_method = Choose a method: + view.dataflow.graph.column_line = Line +@@ -174,6 +177,9 @@ view.dataflow.table.column_type.tooltip = Specifies the type of the anomaly, tha + view.dataflow.table.column_line = Line(s) + view.dataflow.table.column_variable = Variable + view.dataflow.table.column_method = Method ++ ++view.ast.default_text = An abstract syntax tree is not available ++ + view.column.message = Message + view.column.rule = Rule + view.column.class = Class +@@ -309,3 +315,10 @@ priority.error = Error + priority.warning_high = Warning high + priority.warning = Warning + priority.information = Information ++ ++priority.column.name = Name ++priority.column.value = Value ++priority.column.size = Size ++priority.column.shape = Shape ++priority.column.color = Color ++priority.column.description = Description +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties +index e7e8ee67b9d..9936701e989 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/nl/fr/messages.properties +@@ -101,7 +101,7 @@ view.outline.column_message = Message + view.outline.column_line = Ligne + view.overview.column_element = Elément + view.overview.column_vio_total = # Violations +-view.overview.column_vio_loc = # Violations/LDC ++view.overview.column_vio_loc = # Violations/KLDC + view.overview.column_vio_method = # Violations/Méthode + view.overview.column_project = Projet + view.dataflow.default_text = Aucun graphe de flot de données n'est disponible +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml +index db789430ed6..e7da19c4309 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/plugin.xml +@@ -12,6 +12,7 @@ + + + ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ + + ++ ++ ++ ++ + + + + + ++ ++ ++ ++ The markers used by PMD to flag projects and files with violations. ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ + + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java +index 7d565a85ac0..071aa3be09b 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PMDPlugin.java +@@ -1,8 +1,12 @@ + package net.sourceforge.pmd.eclipse.plugin; + ++import java.io.File; + import java.io.IOException; ++import java.net.URL; ++import java.util.ArrayList; + import java.util.Collection; + import java.util.HashMap; ++import java.util.HashSet; + import java.util.Iterator; + + import net.sourceforge.pmd.RuleSet; +@@ -23,6 +27,7 @@ + import net.sourceforge.pmd.eclipse.runtime.writer.IAstWriter; + import net.sourceforge.pmd.eclipse.runtime.writer.IRuleSetWriter; + import net.sourceforge.pmd.eclipse.runtime.writer.impl.WriterFactoryImpl; ++import net.sourceforge.pmd.eclipse.ui.RuleLabelDecorator; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import net.sourceforge.pmd.eclipse.ui.nls.StringTable; + +@@ -32,9 +37,14 @@ + import org.apache.log4j.Logger; + import org.apache.log4j.PatternLayout; + import org.apache.log4j.RollingFileAppender; ++import org.eclipse.core.resources.IFile; ++import org.eclipse.core.resources.IFolder; + import org.eclipse.core.resources.IProject; ++import org.eclipse.core.resources.IResource; + import org.eclipse.core.runtime.CoreException; ++import org.eclipse.core.runtime.FileLocator; + import org.eclipse.core.runtime.IStatus; ++import org.eclipse.core.runtime.Platform; + import org.eclipse.core.runtime.Status; + import org.eclipse.jface.dialogs.MessageDialog; + import org.eclipse.jface.resource.ImageDescriptor; +@@ -43,6 +53,7 @@ + import org.eclipse.swt.graphics.Image; + import org.eclipse.swt.graphics.RGB; + import org.eclipse.swt.widgets.Display; ++import org.eclipse.ui.IDecoratorManager; + import org.eclipse.ui.plugin.AbstractUIPlugin; + import org.osgi.framework.Bundle; + import org.osgi.framework.BundleContext; +@@ -52,6 +63,8 @@ + */ + public class PMDPlugin extends AbstractUIPlugin { + ++ private static File pluginFolder; ++ + private HashMap coloursByRGB = new HashMap(); + + public static final String PLUGIN_ID = ""net.sourceforge.pmd.eclipse.plugin""; +@@ -93,6 +106,22 @@ public static void disposeAll(Collection colors) { + for (Color color : colors) color.dispose(); + } + ++ public static File getPluginFolder() { ++ ++ if (pluginFolder == null) { ++ URL url = Platform.getBundle(PLUGIN_ID).getEntry(""/""); ++ try { ++ url = FileLocator.resolve(url); ++ } ++ catch(IOException ex) { ++ ex.printStackTrace(); ++ } ++ pluginFolder = new File(url.getPath()); ++ } ++ ++ return pluginFolder; ++ } ++ + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) +@@ -369,5 +398,90 @@ private void registerAdditionalRuleSets() { + log(IStatus.ERROR, ""Error when processing RuleSets extensions"", e); + } + } ++ ++ public RuleLabelDecorator ruleLabelDecorator() { ++ IDecoratorManager mgr = getWorkbench().getDecoratorManager(); ++ return (RuleLabelDecorator) mgr.getBaseLabelProvider(""net.sourceforge.pmd.eclipse.plugin.RuleLabelDecorator""); ++ } ++ ++ public void changedFiles(Collection changedFiles) { ++ ++ Collection withParents = new HashSet(changedFiles.size() * 2); ++ withParents.addAll(changedFiles); ++ for (IFile file : changedFiles) { ++ IResource parent = file.getParent(); ++ while (parent != null) { ++ withParents.add(parent); ++ parent = parent.getParent(); ++ } ++ } ++ ++ changed( withParents ); ++ } ++ ++ public void changed(Collection changedResources) { ++ ruleLabelDecorator().changed(changedResources); ++ } ++ ++ private void addFilesTo(IResource resource, Collection allKids) { ++ ++ if (resource instanceof IFile) { ++ allKids.add(resource); ++ return; ++ } ++ ++ if (resource instanceof IFolder) { ++ IFolder folder = (IFolder)resource; ++ IResource[] kids = null; ++ try { ++ kids = folder.members(); ++ } catch (CoreException e) { ++ e.printStackTrace(); ++ } ++ for (IResource irc : kids) { ++ if (irc instanceof IFile) { ++ allKids.add(irc); ++ continue; ++ } ++ if (irc instanceof IFolder) { ++ addFilesTo(irc, allKids); ++ } ++ } ++ ++ allKids.add(folder); ++ return; ++ } ++ ++ if (resource instanceof IProject) { ++ IProject project = (IProject)resource; ++ IResource[] kids = null; ++ try { ++ kids = project.members(); ++ } catch (CoreException e) { ++ e.printStackTrace(); ++ } ++ for (IResource irc : kids) { ++ if (irc instanceof IFile) { ++ allKids.add(irc); ++ continue; ++ } ++ if (irc instanceof IFolder) { ++ addFilesTo(irc, allKids); ++ } ++ } ++ allKids.add(project); ++ return; ++ } ++ } ++ ++ public void removedMarkersIn(IResource resource) { ++ ++ Collection changes = new ArrayList(); ++ ++ addFilesTo(resource, changes); ++ ++ ruleLabelDecorator().changed(changes); ++ } ++ + } + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java +index 0628bb0920a..a84200e2a29 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/PriorityDescriptor.java +@@ -1,9 +1,13 @@ + package net.sourceforge.pmd.eclipse.plugin; + ++import java.util.EnumSet; ++ + import net.sourceforge.pmd.RulePriority; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ShapeDescriptor; ++import net.sourceforge.pmd.eclipse.ui.Shape; ++import net.sourceforge.pmd.eclipse.ui.ShapeDescriptor; ++import net.sourceforge.pmd.eclipse.ui.ShapePainter; + import net.sourceforge.pmd.eclipse.ui.views.actions.AbstractPMDAction; +-import net.sourceforge.pmd.eclipse.util.Util; ++import net.sourceforge.pmd.util.StringUtil; + + import org.eclipse.jface.resource.ImageDescriptor; + import org.eclipse.swt.graphics.Image; +@@ -14,35 +18,138 @@ + * + * @author Brian Remedios + */ +-public class PriorityDescriptor { ++public class PriorityDescriptor implements Cloneable { + + public final RulePriority priority; + public String label; ++ public String description; + public String filterText; + public String iconId; + public ShapeDescriptor shape; + +- private static final RGB ProtoTransparentColour = new RGB(1,1,1); // almost black ++ private static final RGB ProtoTransparentColour = new RGB(1,1,1); // almost full black, unlikely to be used ++ ++ private static final char DELIMITER = '_'; ++ ++ public static PriorityDescriptor from(String text) { ++ ++ String[] values = text.split(Character.toString(DELIMITER)); ++ if (values.length != 7) return null; ++ ++ RGB rgb = rgbFrom(values[5]); ++ if (rgb == null) return null; ++ ++ return new PriorityDescriptor( ++ RulePriority.valueOf(Integer.parseInt(values[0])), ++ values[1], ++ values[2], ++ values[3], ++ shapeFrom(values[4]), ++ rgb, ++ Integer.parseInt(values[6]) ++ ); ++ } ++ ++ private static Shape shapeFrom(String id) { ++ int num = Integer.parseInt(id); ++ for (Shape shape : EnumSet.allOf(Shape.class)) { ++ if (shape.id == num) return shape; ++ } ++ return null; ++ } ++ ++ private static RGB rgbFrom(String desc) { ++ String[] clrs = desc.split("",""); ++ if (clrs.length != 3) return null; ++ return new RGB( ++ Integer.parseInt(clrs[0]), ++ Integer.parseInt(clrs[1]), ++ Integer.parseInt(clrs[2]) ++ ); ++ } ++ ++ private static void rgbOn(StringBuilder sb, RGB rgb) { ++ sb.append(rgb.red).append(','); ++ sb.append(rgb.green).append(','); ++ sb.append(rgb.blue); ++ } + + public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, ShapeDescriptor theShape) { + priority = thePriority; + label = AbstractPMDAction.getString(theLabelKey); ++ description = ""--""; // TODO + filterText = AbstractPMDAction.getString(theFilterTextKey); + iconId = theIconId; + shape = theShape; + } + +- public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, Util.shape theShape, RGB theColor, int theSize) { ++ public PriorityDescriptor(RulePriority thePriority, String theLabelKey, String theFilterTextKey, String theIconId, Shape theShape, RGB theColor, int theSize) { + this(thePriority, theLabelKey, theFilterTextKey, theIconId, new ShapeDescriptor(theShape, theColor, theSize)); + } + ++ private PriorityDescriptor(RulePriority thePriority) { ++ priority = thePriority; ++ } ++ ++ public String storeString() { ++ StringBuilder sb = new StringBuilder(); ++ storeOn(sb); ++ return sb.toString(); ++ } ++ ++ public boolean equals(Object other) { ++ ++ if (this == other) return true; ++ if (other.getClass() != getClass()) return false; ++ ++ PriorityDescriptor otherOne = (PriorityDescriptor)other; ++ ++ return priority.equals(otherOne.priority) && ++ StringUtil.isSame(label, otherOne.label, false, false, false) && ++ shape.equals(otherOne.shape) && ++ StringUtil.isSame(description, otherOne.description, false, false, false) && ++ StringUtil.isSame(filterText, otherOne.filterText, false, false, false) && ++ StringUtil.isSame(iconId, otherOne.iconId, false, false, false); ++ } ++ ++ public int hashCode() { ++ return ++ priority.hashCode() ^ shape.hashCode() ^ ++ String.valueOf(label).hashCode() ^ ++ String.valueOf(description).hashCode() ^ ++ String.valueOf(iconId).hashCode(); ++ } ++ ++ public void storeOn(StringBuilder sb) { ++ sb.append(priority.getPriority()).append(DELIMITER); ++ sb.append(label).append(DELIMITER); ++// sb.append(description).append(DELIMITER); ++ sb.append(filterText).append(DELIMITER); ++ sb.append(iconId).append(DELIMITER); ++ sb.append(shape.shape.id).append(DELIMITER); ++ rgbOn(sb, shape.rgbColor); sb.append(DELIMITER); ++ sb.append(shape.size).append(DELIMITER); ++ } ++ + public ImageDescriptor getImageDescriptor() { + return PMDPlugin.getImageDescriptor(iconId); + } + ++ public PriorityDescriptor clone() { ++ ++ PriorityDescriptor copy = new PriorityDescriptor(priority); ++ copy.label = label; ++ copy.description = description; ++ copy.filterText = filterText; ++ copy.iconId = iconId; ++ copy.shape = shape.clone(); ++ ++ return copy; ++ } ++ + public Image getImage(Display display) { + +- return Util.newDrawnImage( ++ return ShapePainter.newDrawnImage( + display, + shape.size, + shape.size, +@@ -51,4 +158,29 @@ public Image getImage(Display display) { + shape.rgbColor //fillColour + ); + } ++ ++ public Image getImage(Display display, int maxDimension) { ++ ++ return ShapePainter.newDrawnImage( ++ display, ++ Math.min(shape.size, maxDimension), ++ Math.min(shape.size, maxDimension), ++ shape.shape, ++ ProtoTransparentColour, ++ shape.rgbColor //fillColour ++ ); ++ } ++ ++ public String toString() { ++ ++ StringBuilder sb = new StringBuilder(); ++ sb.append(""RuleDescriptor: ""); ++ sb.append(priority).append("", ""); ++ sb.append(label).append("", ""); ++ sb.append(description).append("", ""); ++ sb.append(filterText).append("", ""); ++ sb.append(iconId).append("", ""); ++ sb.append(shape); ++ return sb.toString(); ++ } + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java +index 4bf1bf9c715..b50f339b03a 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/plugin/UISettings.java +@@ -1,20 +1,31 @@ + package net.sourceforge.pmd.eclipse.plugin; + ++import java.net.MalformedURLException; ++import java.net.URL; + import java.util.ArrayList; + import java.util.Arrays; + import java.util.Comparator; ++import java.util.EnumSet; + import java.util.HashMap; + import java.util.List; + import java.util.Map; ++import java.util.Set; + + import net.sourceforge.pmd.RulePriority; +-import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; ++import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; ++import net.sourceforge.pmd.eclipse.ui.Shape; ++import net.sourceforge.pmd.eclipse.ui.ShapeDescriptor; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import net.sourceforge.pmd.eclipse.ui.nls.StringTable; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ShapeDescriptor; +-import net.sourceforge.pmd.eclipse.util.Util; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityDescriptorCache; + ++import org.eclipse.jface.resource.ImageDescriptor; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.graphics.ImageData; ++import org.eclipse.swt.graphics.ImageLoader; + import org.eclipse.swt.graphics.RGB; ++import org.eclipse.swt.widgets.Display; + + /** + * +@@ -27,19 +38,35 @@ public class UISettings { + private static Map shapesByPriority; + private static Map prioritiesByIntValue; + ++ private static final int MAX_MARKER_DIMENSION = 9; ++ + private static final Map uiDescriptorsByPriority = new HashMap(5); ++ ++ ++ public static void reloadPriorities() { ++ uiDescriptorsByPriority.clear(); ++ uiDescriptorsByPriority(); // cause a reload ++ } + +- static { +- uiDescriptorsByPriority.put(RulePriority.LOW, new PriorityDescriptor(RulePriority.LOW, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_1, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_1, PMDUiConstants.ICON_BUTTON_PRIO1, Util.shape.triangleSouthEast, new RGB( 0,0,255), 13) ); // blue +- uiDescriptorsByPriority.put(RulePriority.MEDIUM_LOW, new PriorityDescriptor(RulePriority.MEDIUM_LOW, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_2, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_2, PMDUiConstants.ICON_BUTTON_PRIO2, Util.shape.triangleDown, new RGB( 0,255,0), 13) ); // green +- uiDescriptorsByPriority.put(RulePriority.MEDIUM, new PriorityDescriptor(RulePriority.MEDIUM, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_3, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_3, PMDUiConstants.ICON_BUTTON_PRIO3, Util.shape.triangleUp, new RGB( 255,255,0), 13) ); // yellow +- uiDescriptorsByPriority.put(RulePriority.MEDIUM_HIGH, new PriorityDescriptor(RulePriority.MEDIUM_HIGH,StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_4, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_4, PMDUiConstants.ICON_BUTTON_PRIO4, Util.shape.triangleNorthEast, new RGB( 255,0,255), 13) ); // purple +- uiDescriptorsByPriority.put(RulePriority.HIGH, new PriorityDescriptor(RulePriority.HIGH, StringKeys.MSGKEY_VIEW_FILTER_PRIORITY_5, StringKeys.MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_5, PMDUiConstants.ICON_BUTTON_PRIO5, Util.shape.diamond, new RGB( 255,0,0), 13) ); // red ++ private static Map uiDescriptorsByPriority() { ++ ++ if (uiDescriptorsByPriority.isEmpty()) { ++ IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); ++ for (RulePriority rp : currentPriorities(true)) { ++ uiDescriptorsByPriority.put(rp, preferences.getPriorityDescriptor(rp)); ++ } ++ } ++ ++ return uiDescriptorsByPriority; ++ } ++ ++ public static Shape[] allShapes() { ++ return new Shape[] { Shape.circle, Shape.star, Shape.domeLeft, Shape.domeRight, Shape.diamond, Shape.square, Shape.roundedRect, Shape.minus, Shape.pipe, Shape.plus, Shape.triangleUp, Shape.triangleDown, Shape.triangleRight, Shape.triangleLeft, Shape.triangleNorthEast, Shape.triangleSouthEast, Shape.triangleSouthWest, Shape.triangleNorthWest }; + } + + public static RulePriority[] currentPriorities(boolean sortAscending) { + +- RulePriority[] priorities = uiDescriptorsByPriority.keySet().toArray(new RulePriority[uiDescriptorsByPriority.size()]); ++ RulePriority[] priorities = RulePriority.values(); + + Arrays.sort(priorities, new Comparator() { + public int compare(RulePriority rpA, RulePriority rbB) { +@@ -47,18 +74,89 @@ public int compare(RulePriority rpA, RulePriority rbB) { + } + }); + return priorities; +- } ++ } ++ ++ public static Map shapeSet(RGB color, int size) { ++ ++ Map shapes = new HashMap(); ++ ++ for(Shape shape : EnumSet.allOf(Shape.class)) { ++ shapes.put(shape, new ShapeDescriptor(shape, color, size)); ++ } ++ ++ return shapes; ++ } ++ ++ public static String markerFilenameFor(RulePriority priority) { ++ String fileDir = PMDPlugin.getPluginFolder().getAbsolutePath(); ++ return fileDir + ""/"" + relativeMarkerFilenameFor(priority); ++ } ++ ++ public static String relativeMarkerFilenameFor(RulePriority priority) { ++ return ""icons/markerP"" + priority.getPriority() + "".png""; ++ } ++ ++ private static ImageDescriptor getImageDescriptor(final String fileName) { ++ ++ URL installURL = PMDPlugin.getDefault().getBundle().getEntry(""/""); ++ try { ++ URL url = new URL(installURL, fileName); ++ return ImageDescriptor.createFromURL(url); ++ } ++ catch (MalformedURLException mue) { ++ mue.printStackTrace(); ++ return null; ++ } ++ } ++ ++ public static ImageDescriptor markerDescriptorFor(RulePriority priority) { ++ String path = relativeMarkerFilenameFor(priority); ++ return getImageDescriptor(path); ++ } ++ ++ public static Map markerImgDescriptorsByPriority() { ++ ++ RulePriority[] priorities = currentPriorities(true); ++ Map overlaysByPriority = new HashMap(priorities.length); ++ for (RulePriority priority : priorities) { ++ overlaysByPriority.put( ++ priority.getPriority(), ++ markerDescriptorFor(priority) ++ ); ++ } ++ return overlaysByPriority; ++ } ++ ++ public static void createRuleMarkerIcons(Display display) { ++ ++ ImageLoader loader = new ImageLoader(); ++ ++ PriorityDescriptorCache pdc = PriorityDescriptorCache.instance; ++ ++ for (RulePriority priority : currentPriorities(true)) { ++ Image image = pdc.descriptorFor(priority).getImage(display, MAX_MARKER_DIMENSION); ++ loader.data = new ImageData[] { image.getImageData() }; ++ String fullPath = markerFilenameFor( priority ); ++ loader.save(fullPath, SWT.IMAGE_PNG); ++ ++ image.dispose(); ++ } ++ } ++ ++ public static String descriptionFor(RulePriority priority) { ++ return descriptorFor(priority).description; ++ } + + public static PriorityDescriptor descriptorFor(RulePriority priority) { +- return uiDescriptorsByPriority.get(priority); ++ return uiDescriptorsByPriority().get(priority); + } + + public static Map shapesByPriority() { + + if (shapesByPriority != null) return shapesByPriority; + +- Map shapesByPriority = new HashMap(uiDescriptorsByPriority.size()); +- for (Map.Entry entry : uiDescriptorsByPriority.entrySet()) { ++ Map shapesByPriority = new HashMap(uiDescriptorsByPriority().size()); ++ for (Map.Entry entry : uiDescriptorsByPriority().entrySet()) { + shapesByPriority.put(entry.getKey(), entry.getValue().shape); + } + +@@ -68,8 +166,8 @@ public static Map shapesByPriority() { + public static RulePriority priorityFor(int value) { + + if (prioritiesByIntValue == null) { +- prioritiesByIntValue = new HashMap(uiDescriptorsByPriority.size()); +- for (Map.Entry entry : uiDescriptorsByPriority.entrySet()) { ++ prioritiesByIntValue = new HashMap(uiDescriptorsByPriority().size()); ++ for (Map.Entry entry : uiDescriptorsByPriority().entrySet()) { + prioritiesByIntValue.put(entry.getKey().getPriority(), entry.getKey()); + } + } +@@ -97,8 +195,8 @@ public static String[] getPriorityLabels() { + + public static List getPriorityIntValues() { + +- List values = new ArrayList(uiDescriptorsByPriority.size()); +- for (RulePriority priority : uiDescriptorsByPriority.keySet()) { ++ List values = new ArrayList(); ++ for (RulePriority priority : RulePriority.values()) { + values.add(priority.getPriority()); + } + return values; +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java +index ed3d21a0617..0ace889df05 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/PMDRuntimeConstants.java +@@ -12,10 +12,18 @@ + */ + public class PMDRuntimeConstants { + +- public static final String PMD_MARKER = PMDPlugin.PLUGIN_ID + "".pmdMarker""; ++ public static final String PMD_MARKER = PMDPlugin.PLUGIN_ID + "".pmdMarker""; // obsolete ++ ++ public static final String PMD_MARKER_1 = PMDPlugin.PLUGIN_ID + "".pmdMarker1""; ++ public static final String PMD_MARKER_2 = PMDPlugin.PLUGIN_ID + "".pmdMarker2""; ++ public static final String PMD_MARKER_3 = PMDPlugin.PLUGIN_ID + "".pmdMarker3""; ++ public static final String PMD_MARKER_4 = PMDPlugin.PLUGIN_ID + "".pmdMarker4""; ++ public static final String PMD_MARKER_5 = PMDPlugin.PLUGIN_ID + "".pmdMarker5""; ++ + public static final String PMD_DFA_MARKER = PMDPlugin.PLUGIN_ID + "".pmdDFAMarker""; + public static final String PMD_TASKMARKER = PMDPlugin.PLUGIN_ID + "".pmdTaskMarker""; +- public static final String[] ALL_MARKER_TYPES = new String[] { PMD_MARKER, PMD_DFA_MARKER, PMD_TASKMARKER }; ++ public static final String[] RULE_MARKER_TYPES = new String[] { PMD_MARKER, PMD_MARKER_1, PMD_MARKER_2, PMD_MARKER_3, PMD_MARKER_4, PMD_MARKER_5 }; ++ public static final String[] ALL_MARKER_TYPES = new String[] { PMD_MARKER, PMD_DFA_MARKER, PMD_TASKMARKER, PMD_MARKER_1, PMD_MARKER_2, PMD_MARKER_3, PMD_MARKER_4, PMD_MARKER_5 }; + + public static final IntegerProperty MAX_VIOLATIONS_DESCRIPTOR = new IntegerProperty(""maxviolations"", ""Max allowable violations"", 1, Integer.MAX_VALUE-1, 1000, 0f); + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java +index 786d37d065e..17af8e1dc48 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/builder/MarkerUtil.java +@@ -1,8 +1,10 @@ + package net.sourceforge.pmd.eclipse.runtime.builder; + + import java.util.ArrayList; ++import java.util.HashMap; + import java.util.HashSet; + import java.util.List; ++import java.util.Map; + import java.util.Set; + + import net.sourceforge.pmd.Rule; +@@ -10,12 +12,18 @@ + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; + import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; ++import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; ++import net.sourceforge.pmd.eclipse.ui.model.FileRecord; ++import net.sourceforge.pmd.eclipse.ui.model.MarkerRecord; ++import net.sourceforge.pmd.eclipse.ui.model.RootRecord; + import net.sourceforge.pmd.util.StringUtil; + + import org.eclipse.core.resources.IFile; + import org.eclipse.core.resources.IMarker; ++import org.eclipse.core.resources.IMarkerDelta; + import org.eclipse.core.resources.IProject; + import org.eclipse.core.resources.IResource; ++import org.eclipse.core.resources.IResourceChangeEvent; + import org.eclipse.core.resources.IResourceVisitor; + import org.eclipse.core.resources.IWorkspaceRoot; + import org.eclipse.core.runtime.CoreException; +@@ -28,6 +36,8 @@ public class MarkerUtil { + + public static final IMarker[] EMPTY_MARKERS = new IMarker[0]; + ++ private static Map rulesByName; ++ + private MarkerUtil() { } + + public static boolean hasAnyRuleMarkers(IResource resource) throws CoreException { +@@ -42,15 +52,17 @@ public boolean visit(IResource resource) { + + if (resource instanceof IFile) { + +- IMarker[] ruleMarkers = null; +- try { +- ruleMarkers = resource.findMarkers(PMDRuntimeConstants.PMD_MARKER, true, IResource.DEPTH_INFINITE); +- } catch (CoreException ex) { +- // what do to? +- } +- if (ruleMarkers.length > 0) { +- foundOne[0] = true; +- return false; ++ for (String markerType : PMDRuntimeConstants.RULE_MARKER_TYPES) { ++ IMarker[] ruleMarkers = null; ++ try { ++ ruleMarkers = resource.findMarkers(markerType, true, IResource.DEPTH_INFINITE); ++ } catch (CoreException ex) { ++ // what do to? ++ } ++ if (ruleMarkers.length > 0) { ++ foundOne[0] = true; ++ return false; ++ } + } + } + +@@ -92,7 +104,7 @@ public static String ruleNameFor(IMarker marker) { + } + + public static int rulePriorityFor(IMarker marker) throws CoreException { +- return ((Integer)marker.getAttribute(PMDUiConstants.KEY_MARKERATT_PRIORITY)).intValue(); ++ return (Integer)marker.getAttribute(PMDUiConstants.KEY_MARKERATT_PRIORITY); + } + + public static int deleteViolationsOf(String ruleName, IResource resource) { +@@ -120,6 +132,17 @@ public static int deleteViolationsOf(String ruleName, IResource resource) { + } + } + ++ public static List markerDeltasIn(IResourceChangeEvent event) { ++ ++ List deltas = new ArrayList(); ++ for (String markerType : PMDRuntimeConstants.RULE_MARKER_TYPES) { ++ IMarkerDelta[] deltaArray = event.findMarkerDeltas(markerType, true); ++ for (IMarkerDelta delta : deltaArray) deltas.add(delta); ++ } ++ ++ return deltas; ++ } ++ + public static List rulesFor(IMarker[] markers) { + + List rules = new ArrayList(markers.length); +@@ -165,6 +188,7 @@ public static void deleteMarkersIn(IResource resource, String[] markerTypes) thr + for (String markerType : markerTypes) { + resource.deleteMarkers(markerType, true, IResource.DEPTH_INFINITE); + } ++ PMDPlugin.getDefault().removedMarkersIn(resource); + } + + public static IMarker[] findAllMarkers(IResource resource) throws CoreException { +@@ -189,4 +213,61 @@ public static IMarker[] findMarkers(IResource resource, String[] markerTypes) th + return markerList.toArray(markerArray); + } + ++ public static Set priorityRangeOf(IResource resource, String[] markerTypes, int sizeLimit) throws CoreException { ++ ++ Set priorityLevels = new HashSet(sizeLimit); ++ ++ for (String markerType : markerTypes) { ++ for (IMarker marker : resource.findMarkers(markerType, true, IResource.DEPTH_INFINITE)) { ++ priorityLevels.add( rulePriorityFor(marker) ); ++ if (priorityLevels.size() == sizeLimit) return priorityLevels; ++ } ++ } ++ ++ return priorityLevels; ++ } ++ ++ ++ private static void gatherRuleNames() { ++ ++ rulesByName = new HashMap(); ++ Set ruleSets = PMDPlugin.getDefault().getRuleSetManager().getRegisteredRuleSets(); ++ for (RuleSet rs : ruleSets) { ++ for (Rule rule : rs.getRules()) { ++ rulesByName.put(rule.getName(), rule); ++ } ++ } ++ } ++ ++ private static Rule ruleFrom(IMarker marker) { ++ String ruleName = marker.getAttribute(PMDRuntimeConstants.KEY_MARKERATT_RULENAME, """"); ++ if (StringUtil.isEmpty(ruleName)) return null; //printValues(marker); ++ return rulesByName.get(ruleName); ++ } ++ ++ public static Set allMarkedFiles(RootRecord root) { ++ ++ gatherRuleNames(); ++ ++ Set files = new HashSet(); ++ ++ for (AbstractPMDRecord projectRecord : root.getChildren()) { ++ for (AbstractPMDRecord packageRecord : projectRecord.getChildren()) { ++ for (AbstractPMDRecord fileRecord : packageRecord.getChildren()) { ++ ((FileRecord)fileRecord).updateChildren(); ++ for (AbstractPMDRecord mRecord : fileRecord.getChildren()) { ++ MarkerRecord markerRecord = (MarkerRecord) mRecord; ++ for (IMarker marker : markerRecord.findMarkers()) { ++ Rule rule = ruleFrom(marker); ++ if (rule == null) continue; ++ files.add((IFile)fileRecord.getResource()); ++ break; ++ } ++ } ++ } ++ } ++ } ++ ++ return files; ++ } + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java +index b9c8f873f85..62bf20c54d8 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/BaseVisitor.java +@@ -230,17 +230,17 @@ public void setProjectProperties(IProjectProperties projectProperties) { + * the resource to process + */ + protected final void reviewResource(final IResource resource) { +- final IFile file = (IFile) resource.getAdapter(IFile.class); ++ IFile file = (IFile) resource.getAdapter(IFile.class); + if (file != null && file.getFileExtension() != null) { + + try { +- boolean included = this.projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived(); +- log.debug(""Derived files included: "" + this.projectProperties.isIncludeDerivedFiles()); ++ boolean included = projectProperties.isIncludeDerivedFiles() || !projectProperties.isIncludeDerivedFiles() && !file.isDerived(); ++ log.debug(""Derived files included: "" + projectProperties.isIncludeDerivedFiles()); + log.debug(""file "" + file.getName() + "" is derived: "" + file.isDerived()); + log.debug(""file checked: "" + included); + + final File sourceCodeFile = file.getRawLocation().toFile(); +- if (getPmdEngine().applies(sourceCodeFile, getRuleSet()) && isFileInWorkingSet(file) && (this.projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived())) { ++ if (getPmdEngine().applies(sourceCodeFile, getRuleSet()) && isFileInWorkingSet(file) && (projectProperties.isIncludeDerivedFiles() || !this.projectProperties.isIncludeDerivedFiles() && !file.isDerived())) { + subTask(""PMD checking: "" + file.getName()); + + Timer timer = new Timer(); +@@ -308,7 +308,7 @@ private boolean isFileInWorkingSet(final IFile file) throws PropertiesException + * Update markers list for the specified file + * + * @param file +- * the file for which markes are to be updated ++ * the file for which markers are to be updated + * @param context + * a PMD context + * @param fTask +@@ -324,6 +324,20 @@ private int maxAllowableViolationsFor(Rule rule) { + PMDRuntimeConstants.MAX_VIOLATIONS_DESCRIPTOR.defaultValue(); + } + ++ public static String markerTypeFor(RuleViolation violation) { ++ ++ int priorityId = violation.getRule().getPriority().getPriority(); ++ ++ switch (priorityId) { ++ case 1: return PMDRuntimeConstants.PMD_MARKER_1; ++ case 2: return PMDRuntimeConstants.PMD_MARKER_2; ++ case 3: return PMDRuntimeConstants.PMD_MARKER_3; ++ case 4: return PMDRuntimeConstants.PMD_MARKER_4; ++ case 5: return PMDRuntimeConstants.PMD_MARKER_5; ++ default: return PMDRuntimeConstants.PMD_MARKER; ++ } ++ } ++ + private void updateMarkers(final IFile file, final RuleContext context, final boolean fTask, final Map> accumulator) + throws CoreException, PropertiesException { + final Set markerSet = new HashSet(); +@@ -336,7 +350,7 @@ private void updateMarkers(final IFile file, final RuleContext context, final bo + + Rule rule = null; + while (iter.hasNext()) { +- final RuleViolation violation = iter.next(); ++ RuleViolation violation = iter.next(); + rule = violation.getRule(); + review.ruleName = rule.getName(); + review.lineNumber = violation.getBeginLine(); +@@ -354,8 +368,8 @@ private void updateMarkers(final IFile file, final RuleContext context, final bo + + if (count.intValue() < maxViolations) { + // Ryan Gustafson 02/16/2008 - Always use PMD_MARKER, as people get confused as to why PMD problems don't always show up on Problems view like they do when you do build. +- // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER)); +- markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_MARKER)); ++ // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER)); ++ markerSet.add(getMarkerInfo(violation, markerTypeFor(violation))); + /* + if (isDfaEnabled && violation.getRule().usesDFA()) { + markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_DFA_MARKER)); +@@ -518,8 +532,8 @@ private class Review { + public boolean equals(final Object obj) { + boolean result = false; + if (obj instanceof Review) { +- final Review reviewObj = (Review) obj; +- result = this.ruleName.equals(reviewObj.ruleName) && this.lineNumber == reviewObj.lineNumber; ++ Review reviewObj = (Review) obj; ++ result = ruleName.equals(reviewObj.ruleName) && lineNumber == reviewObj.lineNumber; + } + return result; + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java +index 17697b5bf88..c2bd1ee1cf6 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/cmd/ReviewCodeCmd.java +@@ -36,6 +36,7 @@ + package net.sourceforge.pmd.eclipse.runtime.cmd; + + import java.util.ArrayList; ++import java.util.Collection; + import java.util.HashMap; + import java.util.Iterator; + import java.util.List; +@@ -47,7 +48,6 @@ + import net.sourceforge.pmd.RuleSet; + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; +-import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; + import net.sourceforge.pmd.eclipse.runtime.properties.IProjectProperties; + import net.sourceforge.pmd.eclipse.runtime.properties.PropertiesException; +@@ -64,6 +64,7 @@ + import org.eclipse.core.resources.IResourceRuleFactory; + import org.eclipse.core.resources.IResourceVisitor; + import org.eclipse.core.resources.IWorkspace; ++import org.eclipse.core.resources.IWorkspaceRoot; + import org.eclipse.core.resources.IWorkspaceRunnable; + import org.eclipse.core.resources.ResourcesPlugin; + import org.eclipse.core.runtime.CoreException; +@@ -90,8 +91,8 @@ public class ReviewCodeCmd extends AbstractDefaultCommand { + final private List resources = new ArrayList(); + private IResourceDelta resourceDelta; + private Map> markersByFile = new HashMap>(); +- private boolean taskMarker = false; +- private boolean openPmdPerspective = false; ++ private boolean taskMarker; ++ private boolean openPmdPerspective; + private int ruleCount; + private int fileCount; + private long pmdDuration; +@@ -107,11 +108,15 @@ public class ReviewCodeCmd extends AbstractDefaultCommand { + public ReviewCodeCmd() { + super(""ReviewCode"", ""Run PMD on a list of workbench resources""); + +- this.setOutputProperties(true); +- this.setReadOnly(true); +- this.setTerminated(false); ++ setOutputProperties(true); ++ setReadOnly(true); ++ setTerminated(false); + } + ++ public Set markedFiles() { ++ return markersByFile.keySet(); ++ } ++ + /** + * @see name.herlin.command.AbstractProcessableCommand#execute() + */ +@@ -119,9 +124,9 @@ public ReviewCodeCmd() { + public void execute() throws CommandException { + log.info(""ReviewCode command starting.""); + try { +- this.fileCount = 0; +- this.ruleCount = 0; +- this.pmdDuration = 0; ++ fileCount = 0; ++ ruleCount = 0; ++ pmdDuration = 0; + + beginTask(""PMD checking..."", getStepCount()); + +@@ -133,7 +138,7 @@ public void execute() throws CommandException { + } + + // Appliquer les marqueurs +- final IWorkspaceRunnable action = new IWorkspaceRunnable() { ++ IWorkspaceRunnable action = new IWorkspaceRunnable() { + public void run(IProgressMonitor monitor) throws CoreException { + applyMarkers(); + } +@@ -143,7 +148,7 @@ public void run(IProgressMonitor monitor) throws CoreException { + workspace.run(action, getschedulingRule(), IWorkspace.AVOID_UPDATE, getMonitor()); + + // Switch to the PMD perspective if required +- if (this.openPmdPerspective) { ++ if (openPmdPerspective) { + Display.getDefault().asyncExec(new Runnable() { + public void run() { + switchToPmdPerspective(); +@@ -174,13 +179,15 @@ public void run() { + logInfo(""Review code command terminated. "" + ruleCount + "" rules were executed against "" + fileCount + "" files. PMD was not executed.""); + } + } ++ ++ PMDPlugin.getDefault().changedFiles( markedFiles() ); + } + + /** + * @return Returns the file markers + */ + public Map> getMarkers() { +- return this.markersByFile; ++ return markersByFile; + } + + /** +@@ -301,11 +308,11 @@ private void processResource(IResource resource) throws CommandException { + log.debug(""Visiting resource "" + resource.getName() + "" : "" + getStepCount()); + + final ResourceVisitor visitor = new ResourceVisitor(); +- visitor.setMonitor(this.getMonitor()); ++ visitor.setMonitor(getMonitor()); + visitor.setRuleSet(ruleSet); + visitor.setPmdEngine(pmdEngine); +- visitor.setAccumulator(this.markersByFile); +- visitor.setUseTaskMarker(this.taskMarker); ++ visitor.setAccumulator(markersByFile); ++ visitor.setUseTaskMarker(taskMarker); + visitor.setProjectProperties(properties); + resource.accept(visitor); + +@@ -337,6 +344,7 @@ private void processProject(IProject project) throws CommandException { + + final IJavaProject javaProject = JavaCore.create(project); + final IClasspathEntry[] entries = javaProject.getRawClasspath(); ++ final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); + for (IClasspathEntry entrie : entries) { + if (entrie.getEntryKind() == IClasspathEntry.CPE_SOURCE) { + +@@ -346,9 +354,9 @@ private void processProject(IProject project) throws CommandException { + // to know if the entry is a folder or a project ! + IContainer sourceContainer = null; + try { +- sourceContainer = ResourcesPlugin.getWorkspace().getRoot().getFolder(entrie.getPath()); ++ sourceContainer = root.getFolder(entrie.getPath()); + } catch (IllegalArgumentException e) { +- sourceContainer = ResourcesPlugin.getWorkspace().getRoot().getProject(entrie.getPath().toString()); ++ sourceContainer = root.getProject(entrie.getPath().toString()); + } + if (sourceContainer == null) { + log.warn(""Source container "" + entrie.getPath() + "" for project "" + project.getName() + "" is not valid""); +@@ -384,27 +392,27 @@ private RuleSet filteredRuleSet(IProjectProperties properties) throws CommandExc + */ + private void processResourceDelta() throws CommandException { + try { +- final IProject project = this.resourceDelta.getResource().getProject(); ++ final IProject project = resourceDelta.getResource().getProject(); + final IProjectProperties properties = PMDPlugin.getDefault().loadProjectProperties(project); + +- final RuleSet ruleSet = filteredRuleSet(properties); //properties.getProjectRuleSet(); ++ RuleSet ruleSet = filteredRuleSet(properties); //properties.getProjectRuleSet(); + +- final PMDEngine pmdEngine = getPmdEngineForProject(project); +- this.setStepCount(countDeltaElement(this.resourceDelta)); ++ PMDEngine pmdEngine = getPmdEngineForProject(project); ++ setStepCount(countDeltaElement(resourceDelta)); + log.debug(""Visit of resource delta : "" + getStepCount()); + +- final DeltaVisitor visitor = new DeltaVisitor(); +- visitor.setMonitor(this.getMonitor()); ++ DeltaVisitor visitor = new DeltaVisitor(); ++ visitor.setMonitor(getMonitor()); + visitor.setRuleSet(ruleSet); + visitor.setPmdEngine(pmdEngine); +- visitor.setAccumulator(this.markersByFile); +- visitor.setUseTaskMarker(this.taskMarker); ++ visitor.setAccumulator(markersByFile); ++ visitor.setUseTaskMarker(taskMarker); + visitor.setProjectProperties(properties); +- this.resourceDelta.accept(visitor); ++ resourceDelta.accept(visitor); + +- this.ruleCount = ruleSet.getRules().size(); +- this.fileCount += visitor.getProcessedFilesCount(); +- this.pmdDuration += visitor.getActualPmdDuration(); ++ ruleCount = ruleSet.getRules().size(); ++ fileCount += visitor.getProcessedFilesCount(); ++ pmdDuration += visitor.getActualPmdDuration(); + + } catch (PropertiesException e) { + throw new CommandException(e); +@@ -423,36 +431,32 @@ private void applyMarkers() { + final Timer timer = new Timer(); + + String currentFile = """"; // for logging ++ ++ beginTask(""PMD Applying markers"", markersByFile.size()); ++ + try { +- final Set fileSet = markersByFile.keySet(); +- final Iterator i = fileSet.iterator(); +- +- beginTask(""PMD Applying markers"", fileSet.size()); +- +- while (i.hasNext() && !isCanceled()) { +- final IFile file = i.next(); ++ for (IFile file : markersByFile.keySet()) { ++ if (isCanceled()) break; + currentFile = file.getName(); + +- final Set markerInfoSet = markersByFile.get(file); ++ Set markerInfoSet = markersByFile.get(file); + // MarkerUtil.deleteAllMarkersIn(file); +- final Iterator j = markerInfoSet.iterator(); +- while (j.hasNext()) { +- final MarkerInfo markerInfo = j.next(); +- final IMarker marker = file.createMarker(markerInfo.getType()); ++ for (MarkerInfo markerInfo : markerInfoSet) { ++ IMarker marker = file.createMarker(markerInfo.getType()); + marker.setAttributes(markerInfo.getAttributeNames(), markerInfo.getAttributeValues()); + violationCount++; + } + + worked(1); +- + } + } catch (CoreException e) { +- log.warn(""CoreException when setting marker info for file "" + currentFile + "" : "" + e.getMessage()); // TODO: ++ log.warn(""CoreException when setting marker for file "" + currentFile + "" : "" + e.getMessage()); // TODO: + // NLS + } finally { + timer.stop(); +- logInfo("""" + violationCount + "" markers applied on "" + markersByFile.size() + "" files in "" + timer.getDuration() + ""ms.""); +- log.info(""End of processing marker directives. "" + violationCount + "" violations for "" + markersByFile.size() + "" files.""); ++ int count = markersByFile.size(); ++ logInfo("""" + violationCount + "" markers applied on "" + count + "" files in "" + timer.getDuration() + ""ms.""); ++ log.info(""End of processing marker directives. "" + violationCount + "" violations for "" + count + "" files.""); + } + + } +@@ -463,7 +467,7 @@ private void applyMarkers() { + * @param resource a project + * @return the element count + */ +- private int countResourceElement(final IResource resource) { ++ private int countResourceElement(IResource resource) { + final CountVisitor visitor = new CountVisitor(); + + try { +@@ -481,7 +485,7 @@ private int countResourceElement(final IResource resource) { + * @param delta a resource delta + * @return the element count + */ +- private int countDeltaElement(final IResourceDelta delta) { ++ private int countDeltaElement(IResourceDelta delta) { + final CountVisitor visitor = new CountVisitor(); + + try { +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java +index 94a0f132560..48177ea3a31 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/IPreferences.java +@@ -38,7 +38,13 @@ + + import java.util.Set; + ++import net.sourceforge.pmd.RulePriority; ++import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; ++import net.sourceforge.pmd.eclipse.ui.Shape; ++import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; ++ + import org.apache.log4j.Level; ++import org.eclipse.swt.graphics.RGB; + + /** + * This interface models the PMD Plugin preferences +@@ -61,6 +67,12 @@ public interface IPreferences { + Level LOG_LEVEL = Level.WARN; + String ACTIVE_RULES = """"; + ++ PriorityDescriptor PD_1_DEFAULT = new PriorityDescriptor(RulePriority.HIGH, StringKeys.VIEW_FILTER_PRIORITY_1, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_1, null, Shape.diamond, new RGB( 255,0,0), 13); // red ++ PriorityDescriptor PD_2_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM_HIGH, StringKeys.VIEW_FILTER_PRIORITY_2, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_2, null, Shape.square, new RGB( 0,255,255), 13); // yellow ++ PriorityDescriptor PD_3_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM, StringKeys.VIEW_FILTER_PRIORITY_3, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_3, null, Shape.circle, new RGB( 0,255,0), 13); // green ++ PriorityDescriptor PD_4_DEFAULT = new PriorityDescriptor(RulePriority.MEDIUM_LOW, StringKeys.VIEW_FILTER_PRIORITY_4, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_4, null, Shape.domeRight,new RGB( 255,0,255), 13); // purple ++ PriorityDescriptor PD_5_DEFAULT = new PriorityDescriptor(RulePriority.LOW, StringKeys.VIEW_FILTER_PRIORITY_5, StringKeys.VIEW_TOOLTIP_FILTER_PRIORITY_5, null, Shape.plus, new RGB( 0,0,255), 13); // blue ++ + boolean isActive(String rulename); + + void isActive(String ruleName, boolean flag); +@@ -107,7 +119,7 @@ public interface IPreferences { + * Get the review additional comment. This comment is a text appended to the + * review comment that is inserted into the code when a violation is reviewed. + * This string follows the MessageFormat syntax and could contain 2 variable fields. +- * The 1st fied is replaced by the current used id and the second by the current date. ++ * The 1st field is replaced by the current used id and the second by the current date. + */ + String getReviewAdditionalComment(); + +@@ -119,7 +131,7 @@ public interface IPreferences { + + /** + * Does the review comment should be the PMD style (// NOPMD comment) or the +- * Plugin style (// @PMD:REVIEW...) which was implemented before. ++ * plugin style (// @PMD:REVIEW...) which was implemented before. + */ + boolean isReviewPmdStyleEnabled(); + +@@ -128,6 +140,9 @@ public interface IPreferences { + */ + void setReviewPmdStyleEnabled(boolean reviewPmdStyleEnabled); + ++ void setPriorityDescriptor(RulePriority priority, PriorityDescriptor pd); ++ ++ PriorityDescriptor getPriorityDescriptor(RulePriority priority); + + // CPD Preferences + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java +index b7a91c3074b..099d98e70d5 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesImpl.java +@@ -36,9 +36,13 @@ + + package net.sourceforge.pmd.eclipse.runtime.preferences.impl; + ++import java.util.HashMap; + import java.util.HashSet; ++import java.util.Map; + import java.util.Set; + ++import net.sourceforge.pmd.RulePriority; ++import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; + +@@ -63,6 +67,9 @@ class PreferencesImpl implements IPreferences { + private String logFileName; + private Level logLevel; + private Set activeRuleNames = new HashSet(); ++ ++ private Map uiDescriptorsByPriority = new HashMap(5); ++ + /** + * Is constructed from a preferences manager + * @param preferencesManager +@@ -211,4 +218,12 @@ public void setActiveRuleNames(Set ruleNames) { + activeRuleNames = ruleNames; + } + ++ public void setPriorityDescriptor(RulePriority priority, PriorityDescriptor pd) { ++ uiDescriptorsByPriority.put(priority, pd); ++ } ++ ++ public PriorityDescriptor getPriorityDescriptor(RulePriority priority) { ++ return uiDescriptorsByPriority.get(priority); ++ } ++ + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java +index 11ae3ff4972..bc3ac6c7d7a 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/runtime/preferences/impl/PreferencesManagerImpl.java +@@ -48,11 +48,13 @@ + import java.util.Set; + + import net.sourceforge.pmd.Rule; ++import net.sourceforge.pmd.RulePriority; + import net.sourceforge.pmd.RuleSet; + import net.sourceforge.pmd.RuleSetFactory; + import net.sourceforge.pmd.RuleSetNotFoundException; + import net.sourceforge.pmd.eclipse.core.IRuleSetManager; + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; ++import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesFactory; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; +@@ -90,7 +92,12 @@ class PreferencesManagerImpl implements IPreferencesManager { + private static final String LOG_FILENAME = PMDPlugin.PLUGIN_ID + "".log_filename""; + private static final String LOG_LEVEL = PMDPlugin.PLUGIN_ID + "".log_level""; + private static final String DISABLED_RULES = PMDPlugin.PLUGIN_ID + "".disabled_rules""; +- ++ private static final String PRIORITY_DESC_1 = PMDPlugin.PLUGIN_ID + "".priority_descriptor_1""; ++ private static final String PRIORITY_DESC_2 = PMDPlugin.PLUGIN_ID + "".priority_descriptor_2""; ++ private static final String PRIORITY_DESC_3 = PMDPlugin.PLUGIN_ID + "".priority_descriptor_3""; ++ private static final String PRIORITY_DESC_4 = PMDPlugin.PLUGIN_ID + "".priority_descriptor_4""; ++ private static final String PRIORITY_DESC_5 = PMDPlugin.PLUGIN_ID + "".priority_descriptor_5""; ++ + private static final String OLD_PREFERENCE_PREFIX = ""net.sourceforge.pmd.runtime""; + private static final String OLD_PREFERENCE_LOCATION = ""/.metadata/.plugins/org.eclipse.core.runtime/.settings/net.sourceforge.pmd.runtime.prefs""; + public static final String NEW_PREFERENCE_LOCATION = ""/.metadata/.plugins/org.eclipse.core.runtime/.settings/net.sourceforge.pmd.eclipse.plugin.prefs""; +@@ -121,6 +128,7 @@ public IPreferences loadPreferences() { + loadLogFileName(); + loadLogLevel(); + loadActiveRules(); ++ loadRulePriorityDescriptors(); + } + + return this.preferences; +@@ -179,6 +187,7 @@ public void storePreferences(IPreferences preferences) { + storeLogFileName(); + storeLogLevel(); + storeActiveRules(); ++ storePriorityDescriptors(); + } + + /** +@@ -186,10 +195,10 @@ public void storePreferences(IPreferences preferences) { + */ + public RuleSet getRuleSet() { + +- if (this.ruleSet == null) { +- this.ruleSet = getRuleSetFromStateLocation(); ++ if (ruleSet == null) { ++ ruleSet = getRuleSetFromStateLocation(); + } +- return this.ruleSet; ++ return ruleSet; + } + + /** +@@ -282,6 +291,29 @@ private void loadActiveRules() { + this.preferences.setActiveRuleNames(asStringSet(loadPreferencesStore.getString(DISABLED_RULES), "","")); + } + ++ /** ++ * Read the priority descriptors ++ * ++ */ ++ private void loadRulePriorityDescriptors() { ++ // TODO - put into a loop ++ loadPreferencesStore.setDefault(PRIORITY_DESC_1, IPreferences.PD_1_DEFAULT.storeString()); ++ preferences.setPriorityDescriptor(RulePriority.HIGH, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_1) ) ); ++ ++ loadPreferencesStore.setDefault(PRIORITY_DESC_2, IPreferences.PD_2_DEFAULT.storeString()); ++ preferences.setPriorityDescriptor(RulePriority.MEDIUM_HIGH, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_2) ) ); ++ ++ loadPreferencesStore.setDefault(PRIORITY_DESC_3, IPreferences.PD_3_DEFAULT.storeString()); ++ preferences.setPriorityDescriptor(RulePriority.MEDIUM, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_3) ) ); ++ ++ loadPreferencesStore.setDefault(PRIORITY_DESC_4, IPreferences.PD_4_DEFAULT.storeString()); ++ preferences.setPriorityDescriptor(RulePriority.MEDIUM_LOW, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_4) ) ); ++ ++ loadPreferencesStore.setDefault(PRIORITY_DESC_5, IPreferences.PD_5_DEFAULT.storeString()); ++ preferences.setPriorityDescriptor(RulePriority.LOW, PriorityDescriptor.from( loadPreferencesStore.getString(PRIORITY_DESC_5) ) ); ++ } ++ ++ + private static Set asStringSet(String delimitedString, String delimiter) { + + String[] values = delimitedString.split(delimiter); +@@ -374,6 +406,15 @@ private void storeLogLevel() { + this.storePreferencesStore.setValue(LOG_LEVEL, this.preferences.getLogLevel().toString()); + } + ++ private void storePriorityDescriptors() { ++ // TODO put into a loop ++ storePreferencesStore.setValue(PRIORITY_DESC_1, preferences.getPriorityDescriptor(RulePriority.HIGH).storeString()); ++ storePreferencesStore.setValue(PRIORITY_DESC_2, preferences.getPriorityDescriptor(RulePriority.MEDIUM_HIGH).storeString()); ++ storePreferencesStore.setValue(PRIORITY_DESC_3, preferences.getPriorityDescriptor(RulePriority.MEDIUM).storeString()); ++ storePreferencesStore.setValue(PRIORITY_DESC_4, preferences.getPriorityDescriptor(RulePriority.MEDIUM_LOW).storeString()); ++ storePreferencesStore.setValue(PRIORITY_DESC_5, preferences.getPriorityDescriptor(RulePriority.LOW).storeString()); ++ } ++ + /** + * Get rule set from state location + */ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java +new file mode 100755 +index 00000000000..3f1488e26e8 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/search/RuleSearchPage.java +@@ -0,0 +1,147 @@ ++package net.sourceforge.pmd.eclipse.search; ++ ++import java.util.List; ++ ++import net.sourceforge.pmd.lang.Language; ++ ++import org.eclipse.jface.dialogs.DialogPage; ++import org.eclipse.jface.resource.ImageDescriptor; ++import org.eclipse.jface.text.TextSelection; ++import org.eclipse.search.ui.ISearchPage; ++import org.eclipse.search.ui.ISearchPageContainer; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.layout.GridData; ++import org.eclipse.swt.layout.GridLayout; ++import org.eclipse.swt.widgets.Button; ++import org.eclipse.swt.widgets.Combo; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Group; ++import org.eclipse.swt.widgets.Label; ++import org.eclipse.swt.widgets.Text; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public class RuleSearchPage extends DialogPage implements ISearchPage { ++ ++ private Text idText; ++ private Button caseSensitive; ++ ++ private String selected; ++ ++ private Button name; ++ private Button description; ++ private Button example; ++ private Button xpath; ++ private Combo language; ++ ++ public RuleSearchPage() { ++ } ++ ++ public RuleSearchPage(String title) { ++ super(title); ++ } ++ ++ public RuleSearchPage(String title, ImageDescriptor image) { ++ super(title, image); ++ } ++ ++ public boolean performAction() { ++ // TODO Auto-generated method stub ++ return false; ++ } ++ ++ public void setContainer(ISearchPageContainer container) { ++ if (container.getSelection() instanceof TextSelection) { ++ selected = ((TextSelection) container.getSelection()).getText(); ++ } ++ } ++ ++ public void buildLanguageCombo(Composite parent) { ++ ++ final List languages = Language.findWithRuleSupport(); ++ ++ language = new Combo(parent, SWT.READ_ONLY); ++ ++ Language deflt = Language.getDefaultLanguage(); ++ int selectionIndex = -1; ++ ++ for (int i = 0; i < languages.size(); i++) { ++ if (languages.get(i) == deflt) selectionIndex = i; ++ language.add(languages.get(i).getName()); ++ } ++ ++ language.select(selectionIndex); ++ } ++ ++ private void addButtons(Composite parent, int horizSpan) { ++ ++ Group group = new Group(parent, SWT.BORDER); ++ group.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, true, true, horizSpan, 1)); ++ group.setLayout( new GridLayout(2, false)); ++ group.setText(""Scope""); ++ ++ name = new Button(group, SWT.CHECK); ++ name.setText(""Names""); ++ ++ description = new Button(group, SWT.CHECK); ++ description.setText(""Descriptions""); ++ ++ example = new Button(group, SWT.CHECK); ++ example.setText(""Examples""); ++ ++ xpath = new Button(group, SWT.CHECK); ++ xpath.setText(""XPaths""); ++ } ++ ++ public void createControl(Composite parent) { ++ ++ Composite panel = new Composite(parent, SWT.NONE); ++ panel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.FILL_VERTICAL, true, true, 2, 1)); ++ panel.setLayout( new GridLayout(3, false)); ++ ++ Composite textPanel = new Composite(panel, SWT.None); ++ textPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.BEGINNING, true, true, 3, 1)); ++ textPanel.setLayout(new GridLayout(4, false)); ++ ++ Label label = new Label(textPanel, SWT.BORDER); ++ label.setText(""Containing text:""); ++ label.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false, 4, 1)); ++ ++ idText = new Text(textPanel, SWT.BORDER); ++ // idText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL, GridData.BEGINNING, true, false, 3, 1)); ++ ++ GridData gridData2 = new GridData(); ++ gridData2.horizontalSpan=3; ++ // gridData2.grabExcessHorizontalSpace = true; ++ // gridData2.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL; ++ idText.setLayoutData(gridData2); ++ ++ ++ if (selected != null) { ++ idText.setText(selected); ++ idText.setSelection(0, selected.length()); ++ } ++ ++ caseSensitive = new Button(textPanel, SWT.CHECK); ++ caseSensitive.setText(""Case sensitive""); ++ caseSensitive.setLayoutData(new GridData(GridData.END, GridData.BEGINNING, false, false, 1, 1)); ++ ++// addButtons(panel, 4); ++// ++// Label langLabel = new Label(panel, SWT.None); ++// langLabel.setText(""Language""); ++// buildLanguageCombo(panel); ++ ++ setControl(panel); ++ } ++ ++ @Override ++ public void setVisible(boolean visible) { ++ super.setVisible(visible); ++ idText.setFocus(); ++ } ++ ++ ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java +index cf03b573868..56a8879bdf6 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/PMDUiConstants.java +@@ -130,6 +130,8 @@ public class PMDUiConstants { + public static final String MEMENTO_OVERVIEW_FILE = ""/violationOverview_memento.xml""; + public static final String MEMENTO_DATAFLOW_FILE = ""/dataflowView_memento.xml""; + ++ public static final String MEMENTO_AST_FILE = ""/astView_memento.xml""; ++ + public static final String KEY_MARKERATT_RULENAME = ""rulename""; + public static final String KEY_MARKERATT_PRIORITY = ""pmd_priority""; + public static final String KEY_MARKERATT_LINE2 = ""line2""; +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java +new file mode 100755 +index 00000000000..810a1aff4dc +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/RuleLabelDecorator.java +@@ -0,0 +1,91 @@ ++package net.sourceforge.pmd.eclipse.ui; ++ ++import java.util.Collection; ++import java.util.HashSet; ++import java.util.Map; ++import java.util.Set; ++ ++import net.sourceforge.pmd.eclipse.plugin.UISettings; ++import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; ++import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; ++ ++import org.eclipse.core.resources.IFile; ++import org.eclipse.core.resources.IResource; ++import org.eclipse.core.runtime.CoreException; ++import org.eclipse.jface.resource.ImageDescriptor; ++import org.eclipse.jface.viewers.IDecoration; ++import org.eclipse.jface.viewers.ILabelProviderListener; ++import org.eclipse.jface.viewers.ILightweightLabelDecorator; ++import org.eclipse.jface.viewers.LabelProviderChangedEvent; ++ ++public class RuleLabelDecorator implements ILightweightLabelDecorator { ++ ++ private Collection listeners; ++ ++ private Map overlaysByPriority; ++ ++ public RuleLabelDecorator() { ++ reloadDecorators(); ++ } ++ ++ public void addListener(ILabelProviderListener listener) { ++ if (listeners == null) listeners = new HashSet(); ++ listeners.add(listener); ++ } ++ ++ public void dispose() { ++ ++ } ++ ++ public void changed(Collection resources) { ++ ++ if (listeners == null) return; ++ ++ LabelProviderChangedEvent lpce = new LabelProviderChangedEvent(this, resources.toArray()); ++ ++ for (ILabelProviderListener listener : listeners) { ++ listener.labelProviderChanged(lpce); ++ } ++ ++ } ++ ++ public void reloadDecorators() { ++ overlaysByPriority = UISettings.markerImgDescriptorsByPriority(); ++ } ++ ++ public boolean isLabelProperty(Object element, String property) { return false; } ++ ++ public void removeListener(ILabelProviderListener listener) { ++ if (listeners == null) return; ++ listeners.remove(listener); ++ } ++ ++ public void decorate(Object element, IDecoration decoration) { ++ ++ if ( !(element instanceof IResource) ) return; ++ ++ IResource resource = (IResource)element; ++ ++ Set range = null; ++ try { ++ range = MarkerUtil.priorityRangeOf(resource, PMDRuntimeConstants.RULE_MARKER_TYPES, 5); ++ } catch (CoreException e1) { ++ return; ++ } ++ ++ if (range.isEmpty()) return; ++ ++ Integer first = range.iterator().next(); ++ ImageDescriptor overlay = overlaysByPriority.get(first); ++ ++ try { ++ boolean hasMarkers = MarkerUtil.hasAnyRuleMarkers(resource); ++ if (hasMarkers) decoration.addOverlay(overlay); ++ } catch (CoreException e) { ++ // TODO Auto-generated catch block ++ e.printStackTrace(); ++ } ++ ++ } ++ ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java +new file mode 100755 +index 00000000000..dc5af5c897c +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/Shape.java +@@ -0,0 +1,78 @@ ++package net.sourceforge.pmd.eclipse.ui; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public enum Shape { ++ ++ square(1, ""Square""), circle(2, ""Circle""), roundedRect(3, ""Rounded rectangle""), diamond(4, ""Diamond""), ++ ++ minus(5, ""Dash""), pipe(6, ""Pipe""), ++ ++ domeRight(7, ""Dome right""), domeLeft(8, ""Dome left""), domeUp(9,""Dome up""), domeDown(10, ""Dome down""), ++ ++ triangleUp(11,""Triangle up""), triangleDown(12,""Triangle down""), triangleRight(13,""Triangle right""), triangleLeft(14,""Triangle left""), ++ triangleNorthEast(15,""Triangle NE""), triangleSouthEast(16,""Triangle SE""), ++ triangleSouthWest(17,""Triangle SW""), triangleNorthWest(18,""Triangle NW""), ++ ++ plus(20,""Plus"", new float[] { ++ 0.333f, 0, ++ 0.666f, 0, ++ 0.666f, 0.333f, ++ 1, 0.333f, ++ 1, 0.666f, ++ 0.666f, 0.666f, ++ 0.666f, 1, ++ 0.333f, 1, ++ 0.333f, 0.666f, ++ 0, 0.666f, ++ 0, 0.333f, ++ 0.333f, 0.333f ++ }), ++ star(21, ""Star"", new float[] { ++ 0.500f, 1.000f, ++ 0.378f, 0.619f, ++ 0, 0.619f, ++ 0.303f, 0.381f, ++ 0.193f, 0, ++ 0.500f, 0.226f, ++ 0.807f, 0, ++ 0.697f, 0.381f, ++ 1.000f, 0.619f, ++ 0.622f, 0.619f ++ }); ++ ++ public final int id; ++ public final String label; ++ private final float[] polyPoints; ++ ++ private Shape(int theId, String theLabel) { ++ this(theId, theLabel, null); ++ } ++ ++ private Shape(int theId, String theLabel, float[] optionalPolygonPoints) { ++ id = theId; ++ label = theLabel; ++ polyPoints = optionalPolygonPoints; ++ } ++ ++ @Override ++ public String toString() { ++ return label; ++ } ++ ++ public int[] scaledPointsTo(int xMax, int yMax, int xOffset, int yOffset, boolean flipX, boolean flipY) { ++ ++ if (polyPoints == null) return new int[0]; ++ ++ int[] points = new int[polyPoints.length]; ++ ++ for (int i=0; i 1) { ++ gc.fillPolygon(points); ++ gc.drawPolygon(points); ++ } ++ } ++ } ++ if (optionalText != null) gc.drawString(optionalText, x, y); ++ } ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java +new file mode 100755 +index 00000000000..af220cbc1f0 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/ShapePicker.java +@@ -0,0 +1,255 @@ ++package net.sourceforge.pmd.eclipse.ui; ++ ++import java.util.HashMap; ++import java.util.Map; ++import java.util.Vector; ++ ++import org.eclipse.jface.viewers.ISelection; ++import org.eclipse.jface.viewers.ISelectionChangedListener; ++import org.eclipse.jface.viewers.ISelectionProvider; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.SelectionChangedEvent; ++import org.eclipse.jface.viewers.StructuredSelection; ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.events.FocusEvent; ++import org.eclipse.swt.events.FocusListener; ++import org.eclipse.swt.events.MouseEvent; ++import org.eclipse.swt.events.MouseListener; ++import org.eclipse.swt.events.MouseMoveListener; ++import org.eclipse.swt.events.PaintEvent; ++import org.eclipse.swt.events.PaintListener; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.graphics.GC; ++import org.eclipse.swt.graphics.Point; ++import org.eclipse.swt.graphics.RGB; ++import org.eclipse.swt.widgets.Canvas; ++import org.eclipse.swt.widgets.Composite; ++import org.eclipse.swt.widgets.Display; ++import org.eclipse.ui.ISelectionListener; ++ ++/** ++ * Renders a set of coloured shapes mapped to known set of incoming items ++ * ++ * @author Brian Remedios ++ */ ++public class ShapePicker extends Canvas implements ISelectionProvider { ++ ++ private T[] items; ++ private int itemWidth; ++ private int gap = 6; ++ private T selectedItem; ++ private T highlightItem; ++ private Color selectedItemFillColor; ++ ++ private Map shapeDescriptorsByItem; ++// private Map tooltipsByItem; ++ ++ private Vector listeners; ++ ++ private static Map coloursByRGB = new HashMap(); ++ ++ public ShapePicker(Composite parent, int style, int theItemWidth) { ++ super(parent, style); ++ ++ itemWidth = theItemWidth; ++ ++ ShapePicker.this.addPaintListener( new PaintListener() { ++ public void paintControl(PaintEvent pe) { ++ doPaint(pe); ++ } ++ } ); ++ ++ ShapePicker.this.addMouseMoveListener( new MouseMoveListener() { ++ public void mouseMove(MouseEvent e) { ++ if (!getEnabled()) return; ++ T newItem = itemAt(e.x, e.y); ++ if (newItem != highlightItem) { ++ highlightItem = newItem; ++ setToolTipText(newItem == null ? """" : newItem.toString()); ++ redraw(); ++ } ++ } ++ } ); ++ ++ ShapePicker.this.addMouseListener( new MouseListener() { ++ public void mouseDoubleClick(MouseEvent e) { } ++ public void mouseDown(MouseEvent e) { forceFocus(); } ++ public void mouseUp(MouseEvent e) { ++ if (!getEnabled()) return; ++ T newItem = itemAt(e.x, e.y); ++ if (newItem != selectedItem) { ++ selectedItem = newItem; ++ redraw(); ++ selectionChanged(); ++ } ++ } ++ } ); ++ ++ ShapePicker.this.addFocusListener( new FocusListener() { ++ public void focusGained(FocusEvent e) { redraw(); } ++ public void focusLost(FocusEvent e) { redraw(); } ++ } ); ++ ++ selectedItemFillColor = colorFor(new RGB(200,200,200)); ++ } ++ ++ private Color colourFor(int itemIndex) { ++ ++ ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); ++ if (desc == null) return Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); ++ ++ RGB rgb = desc.rgbColor; ++ ++ return colorFor(rgb); ++ } ++ ++ private Color colorFor(RGB rgb) { ++ ++ Color color = coloursByRGB.get(rgb); ++ if (color != null) return color; ++ ++ color = new Color(null, rgb.red, rgb.green, rgb.blue); ++ coloursByRGB.put( rgb, color ); ++ ++ return color; ++ } ++ ++ private void selectionChanged() { ++ if (listeners == null) return; ++ IStructuredSelection selection = new StructuredSelection( new Object[] { selectedItem } ); ++ SelectionChangedEvent event = new SelectionChangedEvent(this, selection); ++ for (ISelectionChangedListener listener : listeners) { ++ listener.selectionChanged(event); ++ } ++ } ++ ++ public boolean forceFocus() { ++ boolean state = super.forceFocus(); ++ redraw(); ++ return state; ++ } ++ ++ private Shape shapeFor(int itemIndex) { ++ ShapeDescriptor desc = shapeDescriptorsByItem.get(items[itemIndex]); ++ return desc == null ? Shape.circle : desc.shape; ++ } ++ ++ private T itemAt(int xIn, int yIn) { ++ ++ if (items == null) return null; ++ ++ int width = getSize().x; ++ int xBoundary = 3; ++ ++ for (int i=0; i theShapeMap) { ++ ++ shapeDescriptorsByItem = theShapeMap; ++ redraw(); ++ } ++ ++ public void addSelectionChangedListener(ISelectionChangedListener listener) { ++ if (listeners == null) listeners = new Vector(); ++ listeners.add(listener); ++ } ++ ++ public void removeSelectionChangedListener(ISelectionChangedListener listener) { ++ if (listeners == null) return; ++ listeners.remove(listener); ++ } ++ ++ public void setSelection(ISelection selection) { ++ ++ setSelection( (T)((StructuredSelection)selection).getFirstElement() ); ++ ++ } ++ ++// public void setTooltipMap(Map theTooltips) { ++// tooltipsByItem = theTooltips; ++// } ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java +index 27882a9a65e..c97c99b242f 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/ClearReviewsAction.java +@@ -164,7 +164,7 @@ protected void clearReviews() { + if (selection != null && selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection) selection; + if (getMonitor() != null) { +- getMonitor().beginTask(getString(StringKeys.MSGKEY_MONITOR_REMOVE_REVIEWS), IProgressMonitor.UNKNOWN); ++ getMonitor().beginTask(getString(StringKeys.MONITOR_REMOVE_REVIEWS), IProgressMonitor.UNKNOWN); + + Iterator i = structuredSelection.iterator(); + while (i.hasNext()) { +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java +index da6291fd056..691755a384f 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/actions/PMDRemoveMarkersAction.java +@@ -35,7 +35,6 @@ + + import java.util.Iterator; + +-import net.sourceforge.pmd.eclipse.runtime.PMDRuntimeConstants; + import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; + import net.sourceforge.pmd.eclipse.ui.model.AbstractPMDRecord; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +@@ -128,7 +127,7 @@ else if (isEditorPart()) { + final IEditorInput editorInput = ((IEditorPart) targetPart()).getEditorInput(); + if (editorInput instanceof IFileEditorInput) { + MarkerUtil.deleteAllMarkersIn(((IFileEditorInput) editorInput).getFile()); +- log.debug(""Remove markers "" + PMDRuntimeConstants.PMD_MARKER + "" on currently edited file "" + ((IFileEditorInput) editorInput).getFile().getName()); ++ log.debug(""Remove markers on currently edited file "" + ((IFileEditorInput) editorInput).getFile().getName()); + } else { + log.debug(""The kind of editor input is not supported. The editor input type: "" + editorInput.getClass().getName()); + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java +new file mode 100644 +index 00000000000..c7a22cd7488 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/BasicLineStyleListener.java +@@ -0,0 +1,251 @@ ++package net.sourceforge.pmd.eclipse.ui.editors; ++ ++import java.util.ArrayList; ++import java.util.LinkedList; ++import java.util.List; ++ ++import net.sourceforge.pmd.util.StringUtil; ++ ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.custom.LineStyleEvent; ++import org.eclipse.swt.custom.LineStyleListener; ++import org.eclipse.swt.custom.StyleRange; ++import org.eclipse.swt.graphics.Color; ++import org.eclipse.swt.widgets.Display; ++ ++/** ++ * This class performs the syntax highlighting and styling for Pmpe ++ */ ++public class BasicLineStyleListener implements LineStyleListener { ++ ++// FIXME take these from the Eclipse preferences instead ++ private static final Color COMMENT_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); ++ private static final Color REFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GREEN); ++ private static final Color UNREFERENCED_VAR_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW); ++ private static final Color COMMENT_BACKGROUND = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE); ++ private static final Color PUNCTUATION_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLACK); ++ private static final Color KEYWORD_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_DARK_MAGENTA); ++ private static final Color STRING_COLOR = Display.getCurrent().getSystemColor(SWT.COLOR_BLUE); ++ ++ // Holds the syntax data ++ private SyntaxData syntaxData; ++ ++ // Holds the offsets for all multiline comments ++ private List commentOffsets; ++ ++ /** ++ * PmpeLineStyleListener constructor ++ * ++ * @param syntaxData ++ * the syntax data to use ++ */ ++ public BasicLineStyleListener(SyntaxData theSyntaxData) { ++ syntaxData = theSyntaxData; ++ commentOffsets = new LinkedList(); ++ } ++ ++ /** ++ * Refreshes the offsets for all multiline comments in the parent StyledText. ++ * The parent StyledText should call this whenever its text is modified. Note ++ * that this code doesn't ignore comment markers inside strings. ++ * ++ * @param text ++ * the text from the StyledText ++ */ ++ public void refreshMultilineComments(String text) { ++ // Clear any stored offsets ++ commentOffsets.clear(); ++ ++ if (syntaxData != null) { ++ // Go through all the instances of COMMENT_START ++ for (int pos = text.indexOf(syntaxData.getMultiLineCommentStart()); pos > -1; pos = text.indexOf(syntaxData.getMultiLineCommentStart(), pos)) { ++ // offsets[0] holds the COMMENT_START offset ++ // and COMMENT_END holds the ending offset ++ int[] offsets = new int[2]; ++ offsets[0] = pos; ++ ++ // Find the corresponding end comment. ++ pos = text.indexOf(syntaxData.getMultiLineCommentEnd(), pos); ++ ++ // If no corresponding end comment, use the end of the text ++ offsets[1] = pos == -1 ? ++ text.length() - 1 : ++ pos + syntaxData.getMultiLineCommentEnd().length() - 1; ++ pos = offsets[1]; ++ // Add the offsets to the collection ++ commentOffsets.add(offsets); ++ } ++ } ++ } ++ ++ /** ++ * Checks to see if the specified section of text begins inside a multiline ++ * comment. Returns the index of the closing comment, or the end of the line ++ * if the whole line is inside the comment. Returns -1 if the line doesn't ++ * begin inside a comment. ++ * ++ * @param start ++ * the starting offset of the text ++ * @param length ++ * the length of the text ++ * @return int ++ */ ++ private int getBeginsInsideComment(int start, int length) { ++ // Assume section doesn't being inside a comment ++ int index = -1; ++ ++ // Go through the multiline comment ranges ++ for (int i = 0, n = commentOffsets.size(); i < n; i++) { ++ int[] offsets = (int[]) commentOffsets.get(i); ++ ++ // If starting offset is past range, quit ++ if (offsets[0] > start + length) ++ break; ++ // Check to see if section begins inside a comment ++ if (offsets[0] <= start && offsets[1] >= start) { ++ // It does; determine if the closing comment marker is inside this section ++ index = offsets[1] > start + length ? ++ start + length : ++ offsets[1] + syntaxData.getMultiLineCommentEnd().length() - 1; ++ } ++ } ++ return index; ++ } ++ ++ private boolean isDefinedVariable(String text) { ++ return !StringUtil.isEmpty(text); ++ } ++ ++ private boolean atMultiLineCommentStart(String text, int position) { ++ return text.indexOf(syntaxData.getMultiLineCommentStart(), position) == position; ++ } ++ ++ private boolean atStringStart(String text, int position) { ++ return text.indexOf(syntaxData.stringStart, position) == position; ++ } ++ ++ private boolean atVarnameReference(String text, int position) { ++ if (syntaxData.varnameReference == null) return false; ++ return text.indexOf(syntaxData.varnameReference, position) == position; ++ } ++ ++ private boolean atSingleLineComment(String text, int position) { ++ if (syntaxData.getComment() == null) return false; ++ return text.indexOf(syntaxData.getComment(), position) == position; ++ } ++ ++ /** ++ * Called by StyledText to get styles for a line ++ */ ++ public void lineGetStyle(LineStyleEvent event) { ++ ++ String lineText = event.lineText; ++ int lineOffset = event.lineOffset; ++ ++ List styles = new ArrayList(); ++ ++ int start = 0; ++ int length = lineText.length(); ++ ++ // Check if line begins inside a multiline comment ++ int mlIndex = getBeginsInsideComment(lineOffset, lineText.length()); ++ if (mlIndex > -1) { ++ // Line begins inside multiline comment; create the range ++ styles.add(new StyleRange(lineOffset, mlIndex - lineOffset, COMMENT_COLOR, COMMENT_BACKGROUND)); ++ start = mlIndex; ++ } ++ // Do punctuation, single-line comments, and keywords ++ while (start < length) { ++ // Check for multiline comments that begin inside this line ++ if (atMultiLineCommentStart(lineText, start)) { ++ // Determine where comment ends ++ int endComment = lineText.indexOf(syntaxData.getMultiLineCommentEnd(), start); ++ ++ // If comment doesn't end on this line, extend range to end of line ++ if (endComment == -1) ++ endComment = length; ++ else ++ endComment += syntaxData.getMultiLineCommentEnd().length(); ++ styles.add(new StyleRange(lineOffset + start, endComment - start, COMMENT_COLOR, COMMENT_BACKGROUND)); ++ ++ start = endComment; ++ } ++ ++ else if (atStringStart(lineText, start)) { ++ // Determine where comment ends ++ int endString = lineText.indexOf(syntaxData.stringEnd, start+1); ++ ++ // If string doesn't end on this line, extend range to end of line ++ if (endString == -1) ++ endString = length; ++ else ++ endString += syntaxData.stringEnd.length(); ++ styles.add(new StyleRange(lineOffset + start, endString - start, STRING_COLOR, COMMENT_BACKGROUND)); ++ ++ start = endString; ++ } ++ ++ else if (atSingleLineComment(lineText, start)) { // Check for single line comments ++ ++ styles.add(new StyleRange(lineOffset + start, length - start, COMMENT_COLOR, COMMENT_BACKGROUND)); ++ start = length; ++ } ++ ++ else if (atVarnameReference(lineText, start)) { // Check for variable references ++ ++ StringBuilder buf = new StringBuilder(); ++ int i = start + syntaxData.getVarnameReference().length(); ++ // Call any consecutive letters a word ++ for (; i < length && Character.isLetter(lineText.charAt(i)); i++) { ++ buf.append(lineText.charAt(i)); ++ } ++ ++ // See if the word is a variable ++ if (isDefinedVariable(buf.toString())) { ++ // It's a keyword; create the StyleRange ++ styles.add(new StyleRange(lineOffset + start, i - start, REFERENCED_VAR_COLOR, null, SWT.BOLD)); ++ } ++ // Move the marker to the last char (the one that wasn't a letter) ++ // so it can be retested in the next iteration through the loop ++ start = i; ++ } ++ ++ // Check for punctuation ++ else if (syntaxData.isPunctuation(lineText.charAt(start))) { ++ // Add range for punctuation ++ styles.add(new StyleRange(lineOffset + start, 1, PUNCTUATION_COLOR, null)); ++ ++start; ++ } else if (Character.isLetter(lineText.charAt(start))) { ++ ++ int kwEnd = getKeywordEnd(lineText, start); // See if the word is a keyword ++ ++ if (kwEnd > start) { // Its a keyword; create the StyleRange ++ styles.add(new StyleRange(lineOffset + start, kwEnd - start, KEYWORD_COLOR, null)); ++ } ++ ++ // Move the marker to the last char (the one that wasn't a letter) ++ // so it can be retested in the next iteration through the loop ++ start = Math.abs(kwEnd); ++ } else ++ ++start; // It's nothing we're interested in; advance the marker ++ } ++ ++ // Copy the StyleRanges back into the event ++ event.styles = (StyleRange[]) styles.toArray(new StyleRange[styles.size()]); ++ } ++ ++ private int getKeywordEnd(String lineText, int start) { ++ ++ int length = lineText.length(); ++ ++ StringBuilder buf = new StringBuilder(length); ++ int i = start; ++ ++ // Call any consecutive letters a word ++ for (; i < length && Character.isLetter(lineText.charAt(i)); i++) { ++ buf.append(lineText.charAt(i)); ++ } ++ ++ return syntaxData.isKeyword(buf.toString()) ? i : 0-i; ++ } ++} +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java +new file mode 100644 +index 00000000000..5359d21a731 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxData.java +@@ -0,0 +1,86 @@ ++package net.sourceforge.pmd.eclipse.ui.editors; ++ ++import java.util.Collection; ++ ++/** ++ * This class contains information for syntax coloring and styling for an ++ * extension ++ */ ++public class SyntaxData { ++ ++ private String extension; ++ private Collection keywords; ++ private String punctuation; ++ private String comment; ++ private String multiLineCommentStart; ++ private String multiLineCommentEnd; ++ public String varnameReference; ++ public String stringStart; ++ public String stringEnd; ++ ++ /** ++ * Constructs a SyntaxData ++ * ++ * @param extension ++ * the extension ++ */ ++ public SyntaxData(String extension) { ++ this.extension = extension; ++ } ++ ++ public boolean matches(String otherExtension) { ++ return extension.equals(otherExtension); ++ } ++ ++ public String getExtension() { ++ return extension; ++ } ++ ++ public void setVarnameReference(String refId) { ++ varnameReference = refId; ++ } ++ ++ public String getVarnameReference() { ++ return varnameReference; ++ } ++ ++ public String getComment() { ++ return comment; ++ } ++ ++ public void setComment(String comment) { ++ this.comment = comment; ++ } ++ ++ public boolean isKeyword(String word) { ++ return keywords != null && keywords.contains(word); ++ } ++ ++ public boolean isPunctuation(char ch) { ++ return punctuation != null && punctuation.indexOf(ch) >= 0; ++ } ++ ++ public void setKeywords(Collection keywords) { ++ this.keywords = keywords; ++ } ++ ++ public String getMultiLineCommentEnd() { ++ return multiLineCommentEnd; ++ } ++ ++ public void setMultiLineCommentEnd(String multiLineCommentEnd) { ++ this.multiLineCommentEnd = multiLineCommentEnd; ++ } ++ ++ public String getMultiLineCommentStart() { ++ return multiLineCommentStart; ++ } ++ ++ public void setMultiLineCommentStart(String multiLineCommentStart) { ++ this.multiLineCommentStart = multiLineCommentStart; ++ } ++ ++ public void setPunctuation(String thePunctuationChars) { ++ punctuation = thePunctuationChars; ++ } ++} +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java +new file mode 100644 +index 00000000000..1b9130f3737 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/SyntaxManager.java +@@ -0,0 +1,104 @@ ++package net.sourceforge.pmd.eclipse.ui.editors; ++ ++import java.util.Collection; ++import java.util.HashSet; ++import java.util.Hashtable; ++import java.util.Map; ++import java.util.MissingResourceException; ++import java.util.ResourceBundle; ++import java.util.StringTokenizer; ++ ++import org.eclipse.swt.custom.StyledText; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; ++ ++/** ++ * This class manages the syntax coloring and styling data ++ */ ++public class SyntaxManager { ++ ++ private static Map syntaxByExtension = new Hashtable(); ++ ++ public static ModifyListener adapt(final StyledText codeField, String languageCode, ModifyListener oldListener) { ++ ++ if (oldListener != null) { ++ codeField.removeModifyListener(oldListener); ++ } ++ ++ SyntaxData sd = SyntaxManager.getSyntaxData(languageCode); ++ if (sd == null) { ++ //codeField.set clear the existing style ranges TODO ++ return null; ++ } ++ ++ final BasicLineStyleListener blsl = new BasicLineStyleListener(sd); ++ codeField.addLineStyleListener(blsl); ++ ++ ModifyListener ml = new ModifyListener() { ++ public void modifyText(ModifyEvent event) { ++ blsl.refreshMultilineComments(codeField.getText()); ++ codeField.redraw(); ++ } ++ }; ++ codeField.addModifyListener(ml); ++ ++ return ml; ++ } ++ ++ /** ++ * Gets the syntax data for an extension ++ */ ++ public static synchronized SyntaxData getSyntaxData(String extension) { ++ // Check in cache ++ SyntaxData sd = syntaxByExtension.get(extension); ++ if (sd == null) { ++ // Not in cache; load it and put in cache ++ sd = loadSyntaxData(extension); ++ if (sd != null) ++ syntaxByExtension.put(sd.getExtension(), sd); ++ } ++ return sd; ++ } ++ ++ /** ++ * Loads the syntax data for an extension ++ * ++ * @param extension ++ * the extension to load ++ * @return SyntaxData ++ */ ++ private static SyntaxData loadSyntaxData(String filename) { ++ SyntaxData sd = null; ++ try { ++ ResourceBundle rb = ResourceBundle.getBundle(""net.sourceforge.pmd.eclipse.ui.editors."" + filename); ++ sd = new SyntaxData(filename); ++ ++ sd.stringStart = rb.getString(""stringstart""); ++ sd.stringEnd = rb.getString(""stringend""); ++ sd.setMultiLineCommentStart(rb.getString(""multilinecommentstart"")); ++ sd.setMultiLineCommentEnd(rb.getString(""multilinecommentend"")); ++ ++ // Load the keywords ++ Collection keywords = new HashSet(); ++ for (StringTokenizer st = new StringTokenizer(rb.getString(""keywords""), "" ""); st.hasMoreTokens();) { ++ keywords.add(st.nextToken()); ++ } ++ sd.setKeywords(keywords); ++ ++ // Load the punctuation ++ sd.setPunctuation(rb.getString(""punctuation"")); ++ ++ if (rb.containsKey(""comment"")) { ++ sd.setComment( rb.getString(""comment"") ); ++ } ++ ++ if (rb.containsKey(""varnamedelimiter"")) { ++ sd.varnameReference = rb.getString(""varnamedelimiter""); ++ } ++ ++ } catch (MissingResourceException e) { ++ // Ignore ++ } ++ return sd; ++ } ++} +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java +new file mode 100644 +index 00000000000..fbfc96bfd2f +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/TextChange.java +@@ -0,0 +1,55 @@ ++package net.sourceforge.pmd.eclipse.ui.editors; ++ ++class TextChange { ++ // The starting offset of the change ++ private int start; ++ ++ // The length of the change ++ private int length; ++ ++ // The replaced text ++ String replacedText; ++ ++ /** ++ * Constructs a TextChange ++ * ++ * @param start ++ * the starting offset of the change ++ * @param length ++ * the length of the change ++ * @param replacedText ++ * the text that was replaced ++ */ ++ public TextChange(int start, int length, String replacedText) { ++ this.start = start; ++ this.length = length; ++ this.replacedText = replacedText; ++ } ++ ++ /** ++ * Returns the start ++ * ++ * @return int ++ */ ++ public int getStart() { ++ return start; ++ } ++ ++ /** ++ * Returns the length ++ * ++ * @return int ++ */ ++ public int getLength() { ++ return length; ++ } ++ ++ /** ++ * Returns the replacedText ++ * ++ * @return String ++ */ ++ public String getReplacedText() { ++ return replacedText; ++ } ++} +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties +new file mode 100644 +index 00000000000..f57c859d5b5 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/c.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .c files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=auto const double float int short struct unsigned break continue else for long signed switch void case default enum goto register sizeof typedef volatile char do extern if return static union while +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties +new file mode 100644 +index 00000000000..ab31424e402 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/cpp.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .cpp files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=asm bool catch class const_cast delete dynamic_cast explicit false friend inline mutable namespace new operator private public protected reinterpret_cast static_cast template this throw true try typeid typename using virtual wchar_t +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties +new file mode 100644 +index 00000000000..ebc3c995e36 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ecmascript.properties +@@ -0,0 +1,10 @@ ++# This file contains the syntax data for .xpath files ++comment=// ++stringstart=' ++stringend=' ++varnamedelimiter=$ ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=break case catch continue default delete do else finally for function if in instanceof new return switch this throw try typeof var void undefined while with this ++ +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties +new file mode 100644 +index 00000000000..dd6ba2f146b +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/fortran77.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .for files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=access assign backspace blank block call close common continue data dimension direct do else endif enddo end entry eof equivalence err exist external file fmt form format formatted function goto if implicit include inquire intrinsic iostat logical named namelist nextrec number open opened parameter pause print program read rec recl return rewind sequential status stop subroutine then type unformatted unit write save +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties +new file mode 100644 +index 00000000000..0a842d56039 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/java.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .java files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=abstract assert boolean break byte case catch char class const continue do double else enum extends false final finally for if implements import int interface native new null package protected public private return static strictfp super switch synchronized this throws true try void volatile while +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties +new file mode 100644 +index 00000000000..01600b684ed +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/ruby.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .ruby files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=alias and BEGIN begin break case class def defined? do else elsif END end ensure false for if in module next nil not or redo rescue retry return self super then true undef unless until when while yield +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties +new file mode 100644 +index 00000000000..931f2e6d5aa +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/scala.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .scala files ++comment=// ++stringstart="" ++stringend="" ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=abstract case catch class def do else extends false final finally for forSome if implicit import lazy match new null object override package private protected requires return sealed super this throw trait try true type val var while with yield +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties +new file mode 100644 +index 00000000000..9fa3c609577 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/editors/xpath.properties +@@ -0,0 +1,8 @@ ++# This file contains the syntax data for .xpath files ++stringstart=' ++stringend=' ++varnamedelimiter=$ ++multilinecommentstart=/* ++multilinecommentend=*/ ++punctuation=(){};:?<>=+-*/&|~!%.[] ++keywords=AdditiveExpression AllocationExpression Annotation ArgumentList Arguments ArrayDimsAndInits ArrayInitializer Assignment AssignmentOperator Block BlockStatement BreakStatement BooleanLiteral CastExpression CatchStatement ClassOrInterfaceBody ClassOrInterfaceDeclaration ClassOrInterfaceBodyDeclaration ClassOrInterfaceType ConditionalExpression ConditionalAndExpression ConditionalOrExpression ConstructorDeclaration ContinueStatement DoLoop Element EmptyStatement EqualityExpression ExplicitConstructorInvocation Expression ExtendsList FieldDeclaration FinallyStatement ForLoop ForInLoop ForStatement FormalParameter FormalParameters IfStatement ImplementsList ImportDeclaration Initializer InstanceOfExpression LabeledStatement Literal LocalVariableDeclaration MarkerAnnotation MethodDeclaration MethodDeclarator Name NameList NullLiteral NumberLiteral PackageDeclaration PrimaryExpression PrimaryPrefix PrimarySuffix PrimitiveType ReferenceType RelationalExpression ResultType ReturnStatement Statement StatementExpression SwitchLabel SwitchStatement SynchronizedStatement ThrowStatement TryStatement Type TypeArgument TypeArguments TypeDeclaration TypeParameter TypeParameters VariableDeclaration VariableDeclarator VariableDeclaratorId VariableInitializer UnaryExpression UnaryExpressionNotPlusMinus WhileLoop WhileStatement +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java +index 4887b4953a8..eeaff63176a 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/model/FileRecord.java +@@ -204,7 +204,7 @@ public final IMarker[] findMarkers() { + // this is the overwritten Function from AbstractPMDRecord + // we simply call the IResource-function to find Markers + if (this.resource.isAccessible()) { +- return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.PMD_MARKER); ++ return MarkerUtil.findMarkers(resource, PMDRuntimeConstants.RULE_MARKER_TYPES); + } + } catch (CoreException ce) { + PMDPlugin.getDefault().logError(StringKeys.MSGKEY_ERROR_FIND_MARKER + this.toString(), ce); +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java +index 5429acbeb00..ec5ca57d19d 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/nls/StringKeys.java +@@ -36,6 +36,11 @@ + + package net.sourceforge.pmd.eclipse.ui.nls; + ++import net.sourceforge.pmd.eclipse.ui.preferences.PriorityColumnDescriptor; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityFieldAccessor; ++ ++import org.eclipse.swt.SWT; ++ + /** + * Convenient class to hold PMD Constants + * @author phherlin +@@ -60,6 +65,7 @@ public class StringKeys { + public static final String MSGKEY_PREF_GENERAL_TOOLTIP_ADDCOMMENT = ""preference.pmd.tooltip.addcomment""; + public static final String MSGKEY_PREF_GENERAL_MESSAGE_INCORRECT_FORMAT =""preference.pmd.message.incorrect_format""; + public static final String MSGKEY_PREF_GENERAL_GROUP_REVIEW = ""preference.pmd.group.review""; ++ public static final String MSGKEY_PREF_GENERAL_GROUP_PRIORITIES = ""preference.pmd.group.priorities""; + public static final String MSGKEY_PREF_GENERAL_GROUP_GENERAL = ""preference.pmd.group.general""; + public static final String MSGKEY_PREF_GENERAL_LABEL_SHOW_PERSPECTIVE = ""preference.pmd.label.perspective_on_check""; + public static final String MSGKEY_PREF_GENERAL_LABEL_USE_DFA = ""preference.pmd.label.use_dfa""; +@@ -177,7 +183,7 @@ public class StringKeys { + public static final String MSGKEY_VIEW_OUTLINE_COLUMN_LINE = ""view.outline.column_line""; + public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_ELEMENT = ""view.overview.column_element""; + public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_TOTAL = ""view.overview.column_vio_total""; +- public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_LOC = ""view.overview.column_vio_loc""; ++ public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_KLOC = ""view.overview.column_vio_loc""; + public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_VIO_METHOD = ""view.overview.column_vio_method""; + public static final String MSGKEY_VIEW_OVERVIEW_COLUMN_PROJECT = ""view.overview.column_project""; + public static final String MSGKEY_VIEW_DATAFLOW_DEFAULT_TEXT = ""view.dataflow.default_text""; +@@ -196,22 +202,24 @@ public class StringKeys { + public static final String MSGKEY_VIEW_DATAFLOW_TABLE_COLUMN_METHOD = ""view.dataflow.table.column_method""; + public static final String MSGKEY_VIEW_DATAFLOW_TABLE_COLUMN_TYPE_TOOLTIP = ""view.dataflow.table.column_type.tooltip""; + +- public static final String MSGKEY_VIEW_FILTER_PRIORITY_1 = ""view.filter.priority.1""; +- public static final String MSGKEY_VIEW_FILTER_PRIORITY_2 = ""view.filter.priority.2""; +- public static final String MSGKEY_VIEW_FILTER_PRIORITY_3 = ""view.filter.priority.3""; +- public static final String MSGKEY_VIEW_FILTER_PRIORITY_4 = ""view.filter.priority.4""; +- public static final String MSGKEY_VIEW_FILTER_PRIORITY_5 = ""view.filter.priority.5""; +- public static final String MSGKEY_VIEW_FILTER_PROJECT_PREFIX = ""view.filter.project_prefix""; ++ public static final String VIEW_AST_DEFAULT_TEXT = ""view.ast.default_text""; ++ ++ public static final String VIEW_FILTER_PRIORITY_1 = ""view.filter.priority.1""; ++ public static final String VIEW_FILTER_PRIORITY_2 = ""view.filter.priority.2""; ++ public static final String VIEW_FILTER_PRIORITY_3 = ""view.filter.priority.3""; ++ public static final String VIEW_FILTER_PRIORITY_4 = ""view.filter.priority.4""; ++ public static final String VIEW_FILTER_PRIORITY_5 = ""view.filter.priority.5""; ++ public static final String VIEW_FILTER_PROJECT_PREFIX = ""view.filter.project_prefix""; + + public static final String MSGKEY_VIEW_ACTION_CURRENT_PROJECT = ""view.action.current_project""; + +- public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_1 = ""view.tooltip.filter.priority.1""; +- public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_2 = ""view.tooltip.filter.priority.2""; +- public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_3 = ""view.tooltip.filter.priority.3""; +- public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_4 = ""view.tooltip.filter.priority.4""; +- public static final String MSGKEY_VIEW_TOOLTIP_FILTER_PRIORITY_5 = ""view.tooltip.filter.priority.5""; +- public static final String MSGKEY_VIEW_TOOLTIP_PACKAGES_FILES = ""view.tooltip.packages_files""; +- public static final String MSGKEY_VIEW_TOOLTIP_COLLAPSE_ALL = ""view.tooltip.collapse_all""; ++ public static final String VIEW_TOOLTIP_FILTER_PRIORITY_1 = ""view.tooltip.filter.priority.1""; ++ public static final String VIEW_TOOLTIP_FILTER_PRIORITY_2 = ""view.tooltip.filter.priority.2""; ++ public static final String VIEW_TOOLTIP_FILTER_PRIORITY_3 = ""view.tooltip.filter.priority.3""; ++ public static final String VIEW_TOOLTIP_FILTER_PRIORITY_4 = ""view.tooltip.filter.priority.4""; ++ public static final String VIEW_TOOLTIP_FILTER_PRIORITY_5 = ""view.tooltip.filter.priority.5""; ++ public static final String VIEW_TOOLTIP_PACKAGES_FILES = ""view.tooltip.packages_files""; ++ public static final String VIEW_TOOLTIP_COLLAPSE_ALL = ""view.tooltip.collapse_all""; + + public static final String MSGKEY_VIEW_COLUMN_MESSAGE = ""view.column.message""; + public static final String MSGKEY_VIEW_COLUMN_RULE = ""view.column.rule""; +@@ -320,16 +328,23 @@ public class StringKeys { + public static final String MSGKEY_PRIORITY_WARNING = ""priority.warning""; + public static final String MSGKEY_PRIORITY_INFORMATION = ""priority.information""; + +- public static final String MSGKEY_MONITOR_JOB_TITLE = ""monitor.job_title""; +- public static final String MSGKEY_MONITOR_CHECKING_FILE = ""monitor.checking_file""; +- public static final String MSGKEY_PMD_PROCESSING = ""monitor.begintask""; +- public static final String MSGKEY_MONITOR_UPDATING_PROJECTS = ""monitor.updating_projects""; +- public static final String MSGKEY_MONITOR_REVIEW = ""monitor.review""; +- public static final String MSGKEY_MONITOR_REMOVE_REVIEWS = ""monitor.remove_reviews""; +- public static final String MSGKEY_MONITOR_CALC_STATS_TASK = ""monitor.calc_stats""; +- public static final String MSGKEY_MONITOR_CALC_STATS_OF_PACKAGE = ""monitor.calc_stats.package""; ++ public static final String MONITOR_JOB_TITLE = ""monitor.job_title""; ++ public static final String MONITOR_CHECKING_FILE = ""monitor.checking_file""; ++ public static final String PMD_PROCESSING = ""monitor.begintask""; ++ public static final String MONITOR_UPDATING_PROJECTS = ""monitor.updating_projects""; ++ public static final String MONITOR_REVIEW = ""monitor.review""; ++ public static final String MONITOR_REMOVE_REVIEWS = ""monitor.remove_reviews""; ++ public static final String MONITOR_CALC_STATS_TASK = ""monitor.calc_stats""; ++ public static final String MONITOR_CALC_STATS_OF_PACKAGE = ""monitor.calc_stats.package""; + public static final String MSGKEY_MONITOR_COLLECTING_MARKERS = ""monitor.collect_markers""; + ++ public static final String PRIORITY_COLUMN_NAME = ""priority.column.name""; ++ public static final String PRIORITY_COLUMN_VALUE = ""priority.column.value""; ++ public static final String PRIORITY_COLUMN_SIZE = ""priority.column.size""; ++ public static final String PRIORITY_COLUMN_SHAPE = ""priority.column.shape""; ++ public static final String PRIORITY_COLUMN_COLOR = ""priority.column.color""; ++ public static final String PRIORITY_COLUMN_DESC = ""priority.column.description""; ++ + /** + * This class is not meant to be instanciated + * +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java +index 557d48df8f6..7dcd46f0f67 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/GeneralPreferencesPage.java +@@ -2,18 +2,40 @@ + + import java.text.MessageFormat; + import java.util.Date; ++import java.util.List; ++import java.util.Set; + ++import net.sourceforge.pmd.RulePriority; + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; ++import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; ++import net.sourceforge.pmd.eclipse.plugin.UISettings; ++import net.sourceforge.pmd.eclipse.runtime.builder.MarkerUtil; + import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; ++import net.sourceforge.pmd.eclipse.ui.Shape; ++import net.sourceforge.pmd.eclipse.ui.ShapePicker; ++import net.sourceforge.pmd.eclipse.ui.model.RootRecord; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityDescriptorCache; + + import org.apache.log4j.Level; ++import org.eclipse.core.resources.IFile; ++import org.eclipse.core.resources.ResourcesPlugin; ++import org.eclipse.jface.preference.ColorSelector; + import org.eclipse.jface.preference.PreferencePage; ++import org.eclipse.jface.util.IPropertyChangeListener; ++import org.eclipse.jface.util.PropertyChangeEvent; ++import org.eclipse.jface.viewers.ISelectionChangedListener; ++import org.eclipse.jface.viewers.IStructuredContentProvider; ++import org.eclipse.jface.viewers.IStructuredSelection; ++import org.eclipse.jface.viewers.SelectionChangedEvent; ++import org.eclipse.jface.viewers.TableViewer; ++import org.eclipse.jface.viewers.Viewer; + import org.eclipse.swt.SWT; + import org.eclipse.swt.events.ModifyEvent; + import org.eclipse.swt.events.ModifyListener; + import org.eclipse.swt.events.SelectionEvent; + import org.eclipse.swt.events.SelectionListener; ++import org.eclipse.swt.graphics.RGB; + import org.eclipse.swt.layout.GridData; + import org.eclipse.swt.layout.GridLayout; + import org.eclipse.swt.widgets.Button; +@@ -24,6 +46,8 @@ + import org.eclipse.swt.widgets.Label; + import org.eclipse.swt.widgets.Scale; + import org.eclipse.swt.widgets.Spinner; ++import org.eclipse.swt.widgets.Table; ++import org.eclipse.swt.widgets.TableColumn; + import org.eclipse.swt.widgets.Text; + import org.eclipse.ui.IWorkbench; + import org.eclipse.ui.IWorkbenchPreferencePage; +@@ -41,7 +65,8 @@ + public class GeneralPreferencesPage extends PreferencePage implements IWorkbenchPreferencePage { + + private static final String[] LOG_LEVELS = { ""OFF"", ""FATAL"", ""ERROR"", ""WARN"", ""INFO"", ""DEBUG"", ""ALL"" }; +- ++ private static final RGB SHAPE_COLOR = new RGB(255,255,255); ++ + private Text additionalCommentText; + private Label sampleLabel; + private Button showPerspectiveBox; +@@ -53,7 +78,8 @@ public class GeneralPreferencesPage extends PreferencePage implements IWorkbench + private Scale logLevelScale; + private Label logLevelValueLabel; + private Button browseButton; +- ++ private TableViewer tableViewer; ++ + /** + * Initialize the page + * +@@ -61,7 +87,7 @@ public class GeneralPreferencesPage extends PreferencePage implements IWorkbench + */ + public void init(IWorkbench arg0) { + setDescription(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TITLE)); +- this.preferences = PMDPlugin.getDefault().loadPreferences(); ++ preferences = PMDPlugin.getDefault().loadPreferences(); + } + + /** +@@ -77,13 +103,15 @@ protected Control createContents(Composite parent) { + layout.verticalSpacing = 10; + composite.setLayout(layout); + +- // Create chidls ++ // Create groups + Group generalGroup = buildGeneralGroup(composite); ++ Group priorityGroup = buildPriorityGroup(composite); + Group reviewGroup = buildReviewGroup(composite); + Group logGroup = buildLoggingGroup(composite); + + // Layout children + generalGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); ++ priorityGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + logGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + GridData data = new GridData(); +@@ -96,7 +124,7 @@ protected Control createContents(Composite parent) { + + /** + * Build the group of general preferences +- * @param parent the parent composte ++ * @param parent the parent composite + * @return the group widget + */ + private Group buildGeneralGroup(final Composite parent) { +@@ -131,11 +159,154 @@ private Group buildGeneralGroup(final Composite parent) { + data = new GridData(); + data.horizontalAlignment = GridData.FILL; + data.grabExcessHorizontalSpace = true; +- this.maxViolationsPerFilePerRule.setLayoutData(data); ++ maxViolationsPerFilePerRule.setLayoutData(data); + + return group; + } ++ ++ /** ++ * Build the group of priority preferences ++ * @param parent the parent composite ++ * @return the group widget ++ */ ++ private Group buildPriorityGroup(final Composite parent) { + ++ Group group = new Group(parent, SWT.SHADOW_IN); ++ group.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_GROUP_PRIORITIES)); ++ group.setLayout(new GridLayout(1, false)); ++ ++ IStructuredContentProvider contentProvider = new IStructuredContentProvider() { ++ public void dispose() { } ++ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } ++ public Object[] getElements(Object inputElement) { return (RulePriority[])inputElement; } ++ }; ++ PriorityTableLabelProvider labelProvider = new PriorityTableLabelProvider(PriorityColumnDescriptor.VisibleColumns); ++ ++ tableViewer = new TableViewer(group, SWT.BORDER | SWT.MULTI); ++ Table table = tableViewer.getTable(); ++ table.setLayoutData( new GridData(GridData.BEGINNING, GridData.CENTER, true, true) ); ++ ++ tableViewer.setLabelProvider(labelProvider); ++ tableViewer.setContentProvider(contentProvider); ++ table.setHeaderVisible(true); ++ labelProvider.addColumnsTo(table); ++ tableViewer.setInput( UISettings.currentPriorities(true) ); ++ ++ TableColumn[] columns = table.getColumns(); ++ for (TableColumn column : columns) column.pack(); ++ ++ GridData data = new GridData(); ++ data.horizontalAlignment = GridData.FILL; ++ data.grabExcessHorizontalSpace = true; ++ table.setLayoutData(data); ++ ++ Composite editorPanel = new Composite(group, SWT.None); ++ editorPanel.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true) ); ++ editorPanel.setLayout(new GridLayout(6, false)); ++ ++ Label shapeLabel = new Label(editorPanel, SWT.None); ++ shapeLabel.setLayoutData( new GridData()); ++ shapeLabel.setText(""Shape:""); ++ ++ final ShapePicker ssc = new ShapePicker(editorPanel, SWT.None, 14); ++ ssc.setLayoutData( new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1)); ++ ssc.setSize(280, 30); ++ ssc.setShapeMap(UISettings.shapeSet(SHAPE_COLOR, 10)); ++ ssc.setItems( UISettings.allShapes() ); ++ ++ Label colourLabel = new Label(editorPanel, SWT.None); ++ colourLabel.setLayoutData( new GridData()); ++ colourLabel.setText(""Color:""); ++ ++ final ColorSelector colorPicker = new ColorSelector(editorPanel); ++ ++ Label nameLabel = new Label(editorPanel, SWT.None); ++ nameLabel.setLayoutData( new GridData()); ++ nameLabel.setText(""Name:""); ++ ++ final Text priorityName = new Text(editorPanel, SWT.BORDER); ++ priorityName.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true) ); ++ ++ final Label descLabel = new Label(editorPanel, SWT.None); ++ descLabel.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, false, true, 1, 1)); ++ descLabel.setText(""Description:""); ++ ++ final Text priorityDesc = new Text(editorPanel, SWT.BORDER); ++ priorityDesc.setLayoutData( new GridData(GridData.FILL, GridData.CENTER, true, true, 5, 1) ); ++ ++ tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { ++ public void selectionChanged(SelectionChangedEvent event) { ++ IStructuredSelection selection = (IStructuredSelection)event.getSelection(); ++ selectedPriorities(selection.toList(), ssc, colorPicker, priorityName); ++ }} ); ++ ++ ssc.addSelectionChangedListener(new ISelectionChangedListener() { ++ public void selectionChanged(SelectionChangedEvent event) { ++ IStructuredSelection selection = (IStructuredSelection)event.getSelection(); ++ setShape((Shape)selection.getFirstElement()); ++ }} ); ++ ++ colorPicker.addListener(new IPropertyChangeListener() { ++ public void propertyChange(PropertyChangeEvent event) { ++ setColor((RGB)event.getNewValue()); ++ }} ); ++ ++ priorityName.addModifyListener(new ModifyListener() { ++ public void modifyText(ModifyEvent me) { ++ setName( priorityName.getText() ); ++ }} ); ++ ++ return group; ++ } ++ ++ private void setShape(Shape shape) { ++ ++ if (shape == null) return; // renderers can't handle this ++ ++ for (PriorityDescriptor pd : selectedDescriptors()) { ++ pd.shape.shape = shape; ++ } ++ tableViewer.refresh(); ++ } ++ ++ private void setColor(RGB clr) { ++ for (PriorityDescriptor pd : selectedDescriptors()) { ++ pd.shape.rgbColor = clr; ++ } ++ tableViewer.refresh(); ++ } ++ ++ private void setName(String newName) { ++ for (PriorityDescriptor pd : selectedDescriptors()) { ++ pd.label = newName; ++ } ++ tableViewer.refresh(); ++ } ++ ++ private PriorityDescriptor[] selectedDescriptors() { ++ ++ Object[] items = ((IStructuredSelection)tableViewer.getSelection()).toArray(); ++ PriorityDescriptor[] descs = new PriorityDescriptor[items.length]; ++ for (int i=0; i items, ShapePicker ssc, ColorSelector colorPicker, Text nameField) { ++ ++ if (items.size() != 1 ) { ++ ssc.setSelection((Shape)null); ++ nameField.setText(""""); ++ return; ++ } ++ ++ RulePriority priority = items.get(0); ++ PriorityDescriptor desc = PriorityDescriptorCache.instance.descriptorFor(priority); ++ ++ ssc.setSelection( desc.shape.shape ); ++ nameField.setText(priority.getName()); ++ colorPicker.setColorValue( desc.shape.rgbColor ); ++ } ++ + /** + * Build the group of review preferences + * @param parent the parent composite +@@ -212,14 +383,14 @@ private Group buildLoggingGroup(Composite parent) { + logFileNameLabel.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_LABEL_LOG_FILE_NAME)); + logFileNameLabel.setLayoutData(gridData); + +- this.logFileNameText = new Text(loggingGroup, SWT.BORDER); +- this.logFileNameText.setText(this.preferences.getLogFileName()); +- this.logFileNameText.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TOOLTIP_LOG_FILE_NAME)); +- this.logFileNameText.setLayoutData(gridData1); ++ logFileNameText = new Text(loggingGroup, SWT.BORDER); ++ logFileNameText.setText(this.preferences.getLogFileName()); ++ logFileNameText.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_TOOLTIP_LOG_FILE_NAME)); ++ logFileNameText.setLayoutData(gridData1); + +- this.browseButton = new Button(loggingGroup, SWT.NONE); +- this.browseButton.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_BUTTON_BROWSE)); +- this.browseButton.addSelectionListener(new SelectionListener() { ++ browseButton = new Button(loggingGroup, SWT.NONE); ++ browseButton.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_BUTTON_BROWSE)); ++ browseButton.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent event) { + browseLogFile(); + } +@@ -234,15 +405,15 @@ public void widgetDefaultSelected(SelectionEvent event) { + Label logLevelLabel = new Label(loggingGroup, SWT.NONE); + logLevelLabel.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_LABEL_LOG_LEVEL)); + +- this.logLevelValueLabel = new Label(loggingGroup, SWT.NONE); +- this.logLevelValueLabel.setText(""""); +- this.logLevelValueLabel.setLayoutData(gridData2); ++ logLevelValueLabel = new Label(loggingGroup, SWT.NONE); ++ logLevelValueLabel.setText(""""); ++ logLevelValueLabel.setLayoutData(gridData2); + +- this.logLevelScale = new Scale(loggingGroup, SWT.NONE); +- this.logLevelScale.setMaximum(6); +- this.logLevelScale.setPageIncrement(1); +- this.logLevelScale.setLayoutData(gridData3); +- this.logLevelScale.addSelectionListener(new SelectionListener() { ++ logLevelScale = new Scale(loggingGroup, SWT.NONE); ++ logLevelScale.setMaximum(6); ++ logLevelScale.setPageIncrement(1); ++ logLevelScale.setLayoutData(gridData3); ++ logLevelScale.addSelectionListener(new SelectionListener() { + public void widgetSelected(SelectionEvent event) { + updateLogLevelValueLabel(); + } +@@ -251,7 +422,7 @@ public void widgetDefaultSelected(SelectionEvent event) { + } + }); + +- this.logLevelScale.setSelection(intLogLevel(this.preferences.getLogLevel())); ++ logLevelScale.setSelection(intLogLevel(this.preferences.getLogLevel())); + updateLogLevelValueLabel(); + + return loggingGroup; +@@ -357,32 +528,32 @@ private Button buildReviewPmdStyleBoxButton(final Composite parent) { + * @see org.eclipse.jface.preference.PreferencePage#performDefaults() + */ + protected void performDefaults() { +- if (this.additionalCommentText != null) { +- this.additionalCommentText.setText(IPreferences.REVIEW_ADDITIONAL_COMMENT_DEFAULT); ++ if (additionalCommentText != null) { ++ additionalCommentText.setText(IPreferences.REVIEW_ADDITIONAL_COMMENT_DEFAULT); + } + +- if (this.showPerspectiveBox != null) { +- this.showPerspectiveBox.setSelection(IPreferences.PMD_PERSPECTIVE_ENABLED_DEFAULT); ++ if (showPerspectiveBox != null) { ++ showPerspectiveBox.setSelection(IPreferences.PMD_PERSPECTIVE_ENABLED_DEFAULT); + } + +- if (this.useProjectBuildPath != null) { +- this.useProjectBuildPath.setSelection(IPreferences.PROJECT_BUILD_PATH_ENABLED_DEFAULT); ++ if (useProjectBuildPath != null) { ++ useProjectBuildPath.setSelection(IPreferences.PROJECT_BUILD_PATH_ENABLED_DEFAULT); + } + +- if (this.maxViolationsPerFilePerRule != null) { +- this.maxViolationsPerFilePerRule.setMinimum(IPreferences.MAX_VIOLATIONS_PFPR_DEFAULT); ++ if (maxViolationsPerFilePerRule != null) { ++ maxViolationsPerFilePerRule.setMinimum(IPreferences.MAX_VIOLATIONS_PFPR_DEFAULT); + } + +- if (this.reviewPmdStyleBox !=null) { +- this.reviewPmdStyleBox.setSelection(IPreferences.REVIEW_PMD_STYLE_ENABLED_DEFAULT); ++ if (reviewPmdStyleBox !=null) { ++ reviewPmdStyleBox.setSelection(IPreferences.REVIEW_PMD_STYLE_ENABLED_DEFAULT); + } + +- if (this.logFileNameText != null) { +- this.logFileNameText.setText(IPreferences.LOG_FILENAME_DEFAULT); ++ if (logFileNameText != null) { ++ logFileNameText.setText(IPreferences.LOG_FILENAME_DEFAULT); + } + +- if (this.logLevelScale != null) { +- this.logLevelScale.setSelection(intLogLevel(IPreferences.LOG_LEVEL)); ++ if (logLevelScale != null) { ++ logLevelScale.setSelection(intLogLevel(IPreferences.LOG_LEVEL)); + updateLogLevelValueLabel(); + } + } +@@ -422,44 +593,67 @@ protected void browseLogFile() { + dialog.setText(getMessage(StringKeys.MSGKEY_PREF_GENERAL_DIALOG_BROWSE)); + String fileName = dialog.open(); + if (fileName != null) { +- this.logFileNameText.setText(fileName); ++ logFileNameText.setText(fileName); + } + } + ++ private void updateMarkerIcons() { ++ ++ if (!PriorityDescriptorCache.instance.hasChanges()) { ++ return; ++ } ++ ++ // TODO show in UI...could take a while to update ++ ++ PriorityDescriptorCache.instance.storeInPreferences(); ++ UISettings.createRuleMarkerIcons(getShell().getDisplay()); ++ UISettings.reloadPriorities(); ++ ++ // ensure that the decorator gets these new images... ++ PMDPlugin.getDefault().ruleLabelDecorator().reloadDecorators(); ++ ++ RootRecord root = new RootRecord(ResourcesPlugin.getWorkspace().getRoot()); ++ Set files = MarkerUtil.allMarkedFiles(root); ++ PMDPlugin.getDefault().changedFiles(files); ++ } ++ + /** + * @see org.eclipse.jface.preference.IPreferencePage#performOk() + */ + public boolean performOk() { +- if (this.additionalCommentText != null) { +- this.preferences.setReviewAdditionalComment(this.additionalCommentText.getText()); ++ ++ updateMarkerIcons(); ++ ++ if (additionalCommentText != null) { ++ preferences.setReviewAdditionalComment(additionalCommentText.getText()); + } + +- if (this.showPerspectiveBox != null) { +- this.preferences.setPmdPerspectiveEnabled(this.showPerspectiveBox.getSelection()); ++ if (showPerspectiveBox != null) { ++ preferences.setPmdPerspectiveEnabled(showPerspectiveBox.getSelection()); + } + +- if (this.useProjectBuildPath != null) { +- this.preferences.setProjectBuildPathEnabled(this.useProjectBuildPath.getSelection()); ++ if (useProjectBuildPath != null) { ++ preferences.setProjectBuildPathEnabled(useProjectBuildPath.getSelection()); + } + +- if (this.maxViolationsPerFilePerRule != null) { +- this.preferences.setMaxViolationsPerFilePerRule(Integer.valueOf(this.maxViolationsPerFilePerRule.getText()).intValue()); ++ if (maxViolationsPerFilePerRule != null) { ++ preferences.setMaxViolationsPerFilePerRule(Integer.valueOf(maxViolationsPerFilePerRule.getText()).intValue()); + } + +- if (this.reviewPmdStyleBox != null) { +- this.preferences.setReviewPmdStyleEnabled(this.reviewPmdStyleBox.getSelection()); ++ if (reviewPmdStyleBox != null) { ++ preferences.setReviewPmdStyleEnabled(reviewPmdStyleBox.getSelection()); + } + +- if (this.logFileNameText != null) { +- this.preferences.setLogFileName(this.logFileNameText.getText()); ++ if (logFileNameText != null) { ++ preferences.setLogFileName(logFileNameText.getText()); + } + +- if (this.logLevelScale != null) { +- this.preferences.setLogLevel(Level.toLevel(LOG_LEVELS[this.logLevelScale.getSelection()])); ++ if (logLevelScale != null) { ++ preferences.setLogLevel(Level.toLevel(LOG_LEVELS[logLevelScale.getSelection()])); + } + +- this.preferences.sync(); +- PMDPlugin.getDefault().applyLogPreferences(this.preferences); ++ preferences.sync(); ++ PMDPlugin.getDefault().applyLogPreferences(preferences); + + return true; + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java +new file mode 100755 +index 00000000000..c015b52718b +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityColumnDescriptor.java +@@ -0,0 +1,41 @@ ++package net.sourceforge.pmd.eclipse.ui.preferences; ++ ++import net.sourceforge.pmd.RulePriority; ++import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.AbstractColumnDescriptor; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.PriorityFieldAccessor; ++ ++import org.eclipse.swt.SWT; ++import org.eclipse.swt.graphics.Image; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public class PriorityColumnDescriptor extends AbstractColumnDescriptor { ++ ++ private PriorityFieldAccessor accessor; ++ ++ public PriorityColumnDescriptor(String labelKey, int theAlignment, int theWidth, boolean resizableFlag, PriorityFieldAccessor theAccessor) { ++ super(labelKey, theAlignment, theWidth, resizableFlag, null); ++ ++ accessor = theAccessor; ++ } ++ ++ protected Object valueFor(RulePriority priority) { ++ return accessor.valueFor(priority); ++ } ++ ++ protected Image imageFor(RulePriority priority) { ++ return accessor.imageFor(priority); ++ } ++ ++ public static final PriorityColumnDescriptor name = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_NAME, SWT.LEFT, 25, true, PriorityFieldAccessor.name); ++ public static final PriorityColumnDescriptor value = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_VALUE, SWT.RIGHT, 25, true, PriorityFieldAccessor.value); ++// public static final PriorityColumnDescriptor size = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_SIZE, SWT.RIGHT, 25, true, PriorityFieldAccessor.size); ++ public static final PriorityColumnDescriptor image = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_SHAPE, SWT.CENTER, 25, true, PriorityFieldAccessor.image); ++// public static final PriorityColumnDescriptor color = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_COLOR, SWT.RIGHT, 25, true, PriorityFieldAccessor.color); ++ public static final PriorityColumnDescriptor description = new PriorityColumnDescriptor(StringKeys.PRIORITY_COLUMN_DESC, SWT.LEFT, 25, true, PriorityFieldAccessor.description); ++ ++ public static final PriorityColumnDescriptor[] VisibleColumns = new PriorityColumnDescriptor[] { image, name, value, description }; ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java +new file mode 100755 +index 00000000000..aae651f48f0 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/PriorityTableLabelProvider.java +@@ -0,0 +1,42 @@ ++package net.sourceforge.pmd.eclipse.ui.preferences; ++ ++import net.sourceforge.pmd.RulePriority; ++ ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.widgets.Table; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public class PriorityTableLabelProvider extends AbstractTableLabelProvider { ++ ++ private final PriorityColumnDescriptor[] columns; ++ ++ public PriorityTableLabelProvider(PriorityColumnDescriptor[] theColumns) { ++ columns = theColumns; ++ } ++ ++ ++ public boolean isLabelProperty(Object element, String property) { ++ return false; ++ } ++ ++ public Image getColumnImage(Object element, int columnIndex) { ++ ++ return columns[columnIndex].imageFor((RulePriority)element); ++ } ++ ++ public String getColumnText(Object element, int columnIndex) { ++ ++ Object value = columns[columnIndex].valueFor((RulePriority)element); ++ return value == null ? null : value.toString(); ++ } ++ ++ public void addColumnsTo(Table table) { ++ ++ for (PriorityColumnDescriptor desc : columns) { ++ desc.buildTableColumn(table); ++ } ++ } ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java +index 44c32082021..1cf26a16bb1 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/RuleDialog.java +@@ -9,6 +9,7 @@ + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + import net.sourceforge.pmd.eclipse.plugin.UISettings; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; + import net.sourceforge.pmd.lang.rule.RuleReference; + import net.sourceforge.pmd.lang.rule.XPathRule; + import net.sourceforge.pmd.util.StringUtil; +@@ -635,16 +636,18 @@ private Text buildXPathText(Composite parent) { + } + + if (mode == MODE_EDIT) { +- if (this.editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { +- text.setText(this.editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); ++ //if (editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { ++ if (RuleUtil.isXPathRule(editedRule)) { ++ text.setText(editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); + text.setEditable(true); + } + } + + if (mode == MODE_VIEW) { + text.setEditable(false); +- if (this.editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { +- text.setText(this.editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); ++ //if (editedRule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { ++ if (RuleUtil.isXPathRule(editedRule)) { ++ text.setText(editedRule.getProperty(XPathRule.XPATH_DESCRIPTOR).trim()); + } + } + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java +index e4e5c5d8805..6e16c210083 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractColumnDescriptor.java +@@ -3,6 +3,8 @@ + import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; + import net.sourceforge.pmd.eclipse.util.ResourceManager; + ++import org.eclipse.swt.widgets.Table; ++import org.eclipse.swt.widgets.TableColumn; + import org.eclipse.swt.widgets.Tree; + import org.eclipse.swt.widgets.TreeColumn; + +@@ -41,7 +43,7 @@ public AbstractColumnDescriptor(String labelKey, int theAlignment, int theWidth, + */ + public String tooltip() { return tooltip; } + +- protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortListener) { ++ protected TreeColumn buildTreeColumn(Tree parent) { + + final TreeColumn tc = new TreeColumn(parent, alignment); + tc.setWidth(width); +@@ -51,4 +53,16 @@ protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortLis + + return tc; + } ++ ++ public TableColumn buildTableColumn(Table parent) { ++ ++ final TableColumn tc = new TableColumn(parent, alignment); ++ tc.setText(label); ++ tc.setWidth(width); ++ tc.setResizable(isResizable); ++ tc.setToolTipText(tooltip); ++ if (imagePath != null) tc.setImage(ResourceManager.imageFor(imagePath)); ++ ++ return tc; ++ } + } +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java +index 1e174f42bbe..bb2b4c7e51d 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractRuleColumnDescriptor.java +@@ -27,7 +27,7 @@ protected AbstractRuleColumnDescriptor(String labelKey, int theAlignment, int th + + protected TreeColumn buildTreeColumn(Tree parent, final RuleSortListener sortListener) { + +- TreeColumn tc = super.buildTreeColumn(parent, sortListener); ++ TreeColumn tc = super.buildTreeColumn(parent); + + tc.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event e) { +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java +index c3c2269dbfe..87978a166a8 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/AbstractTreeTableManager.java +@@ -50,7 +50,6 @@ public abstract class AbstractTreeTableManager { + + private final Set hiddenColumnNames; + +-// private Button sortByCheckedButton; + private Button selectAllButton; + private Button unSelectAllButton; + private IPreferences preferences; +@@ -307,7 +306,6 @@ protected void isActive(String item, boolean flag) { + + protected void buildCheckButtons(Composite parent) { + +- // sortByCheckedButton = buildSortByCheckedItemsButton(parent); + selectAllButton = buildSelectAllButton(parent); + unSelectAllButton = buildUnselectAllButton(parent); + } +@@ -434,7 +432,6 @@ protected void updateButtonsFor(int[] selectionRatio) { + + selectAllButton.setEnabled( selectionRatio[0] < selectionRatio[1]); + unSelectAllButton.setEnabled( selectionRatio[0] > 0); +-// sortByCheckedButton.setEnabled( (selectionRatio[0] != 0) && (selectionRatio[0] != selectionRatio[1])); + } + + protected abstract void updateCheckControls(); +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java +index e3c885994e6..e505d48fe09 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/ColumnDescriptor.java +@@ -1,9 +1,12 @@ + package net.sourceforge.pmd.eclipse.ui.preferences.br; + ++/** ++ * ++ * @author Brian Remedios ++ */ + public interface ColumnDescriptor { + +- public abstract String label(); +- +- public abstract String tooltip(); ++ String label(); + ++ String tooltip(); + } +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java +index c643ed556ce..3f0ef7cc9b8 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/IndexedString.java +@@ -26,5 +26,5 @@ public int compareTo(IndexedString other) { + deltaLength; + } + +- public static final IndexedString Empty = new IndexedString("""", Collections.EMPTY_LIST); ++ public static final IndexedString Empty = new IndexedString(""""); + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java +deleted file mode 100644 +index 44812b3ca50..00000000000 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage.java ++++ /dev/null +@@ -1,1490 +0,0 @@ +-package net.sourceforge.pmd.eclipse.ui.preferences.br; +- +-import java.io.File; +-import java.io.FileOutputStream; +-import java.io.OutputStream; +-import java.lang.reflect.InvocationTargetException; +-import java.lang.reflect.Method; +-import java.util.ArrayList; +-import java.util.HashMap; +-import java.util.HashSet; +-import java.util.Iterator; +-import java.util.List; +-import java.util.Map; +-import java.util.Set; +- +-import net.sourceforge.pmd.PropertyDescriptor; +-import net.sourceforge.pmd.Rule; +-import net.sourceforge.pmd.RulePriority; +-import net.sourceforge.pmd.RuleSet; +-import net.sourceforge.pmd.eclipse.runtime.preferences.impl.PreferenceUIStore; +-import net.sourceforge.pmd.eclipse.runtime.writer.IRuleSetWriter; +-import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; +-import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; +-import net.sourceforge.pmd.eclipse.ui.preferences.RuleDialog; +-import net.sourceforge.pmd.eclipse.ui.preferences.RuleSetSelectionDialog; +-import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.AbstractRulePanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.Configuration; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.DescriptionPanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.EditorUsageMode; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExamplePanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.ExclusionPanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.PerRulePropertyPanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.QuickFixPanelManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.RulePropertyManager; +-import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.XPathPanelManager; +-import net.sourceforge.pmd.eclipse.util.ResourceManager; +-import net.sourceforge.pmd.eclipse.util.Util; +-import net.sourceforge.pmd.util.FileUtil; +-import net.sourceforge.pmd.util.StringUtil; +-import net.sourceforge.pmd.util.designer.Designer; +- +-import org.eclipse.core.resources.IncrementalProjectBuilder; +-import org.eclipse.core.resources.ResourcesPlugin; +-import org.eclipse.core.runtime.CoreException; +-import org.eclipse.core.runtime.IProgressMonitor; +-import org.eclipse.jface.dialogs.InputDialog; +-import org.eclipse.jface.dialogs.MessageDialog; +-import org.eclipse.jface.dialogs.ProgressMonitorDialog; +-import org.eclipse.jface.operation.IRunnableWithProgress; +-import org.eclipse.jface.viewers.CheckboxTreeViewer; +-import org.eclipse.jface.viewers.ICheckStateProvider; +-import org.eclipse.jface.viewers.ISelectionChangedListener; +-import org.eclipse.jface.viewers.IStructuredSelection; +-import org.eclipse.jface.viewers.SelectionChangedEvent; +-import org.eclipse.jface.viewers.StructuredSelection; +-import org.eclipse.swt.SWT; +-import org.eclipse.swt.events.SelectionAdapter; +-import org.eclipse.swt.events.SelectionEvent; +-import org.eclipse.swt.events.SelectionListener; +-import org.eclipse.swt.graphics.Image; +-import org.eclipse.swt.graphics.Point; +-import org.eclipse.swt.graphics.Rectangle; +-import org.eclipse.swt.layout.FormAttachment; +-import org.eclipse.swt.layout.FormData; +-import org.eclipse.swt.layout.FormLayout; +-import org.eclipse.swt.layout.GridData; +-import org.eclipse.swt.layout.GridLayout; +-import org.eclipse.swt.layout.RowLayout; +-import org.eclipse.swt.widgets.Button; +-import org.eclipse.swt.widgets.Combo; +-import org.eclipse.swt.widgets.Composite; +-import org.eclipse.swt.widgets.Control; +-import org.eclipse.swt.widgets.Event; +-import org.eclipse.swt.widgets.FileDialog; +-import org.eclipse.swt.widgets.Label; +-import org.eclipse.swt.widgets.Listener; +-import org.eclipse.swt.widgets.Menu; +-import org.eclipse.swt.widgets.MenuItem; +-import org.eclipse.swt.widgets.Sash; +-import org.eclipse.swt.widgets.TabFolder; +-import org.eclipse.swt.widgets.TabItem; +-import org.eclipse.swt.widgets.Tree; +-import org.eclipse.swt.widgets.TreeColumn; +-import org.eclipse.swt.widgets.TreeItem; +-import org.eclipse.ui.IWorkbench; +-import org.eclipse.ui.IWorkbenchPreferencePage; +-import org.eclipse.ui.dialogs.ContainerCheckedTreeViewer; +- +-/** +- * This page is used to modify preferences only. They are stored in the preference store that belongs to +- * the main plug-in class. That way, preferences can be accessed directly via the preference store. +- * +- * @author Philippe Herlin +- * @author Brian Remedios +- */ +- +-public class PMDPreferencePage extends AbstractPMDPreferencePage implements ValueChangeListener, RuleSortListener { +- +- public static PMDPreferencePage activeInstance = null; +- +- // columns shown in the rule treetable in the desired order +- private static final RuleColumnDescriptor[] availableColumns = new RuleColumnDescriptor[] { +- TextColumnDescriptor.name, +- //TextColumnDescriptor.priorityName, +- IconColumnDescriptor.priority, +- TextColumnDescriptor.fixCount, +- TextColumnDescriptor.since, +- TextColumnDescriptor.ruleSetName, +- TextColumnDescriptor.ruleType, +- TextColumnDescriptor.minLangVers, +- TextColumnDescriptor.maxLangVers, +- TextColumnDescriptor.language, +- ImageColumnDescriptor.filterViolationRegex, // regex text -> compact color squares (for comparison) +- ImageColumnDescriptor.filterViolationXPath, // xpath text -> compact color circles (for comparison) +- TextColumnDescriptor.properties, +- }; +- +- // last item in this list is the grouping used at startup +- private static final Object[][] groupingChoices = new Object[][] { +- { TextColumnDescriptor.ruleSetName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULESET}, +- { TextColumnDescriptor.since, StringKeys.MSGKEY_PREF_RULESET_GROUPING_PMD_VERSION }, +- { TextColumnDescriptor.priorityName, StringKeys.MSGKEY_PREF_RULESET_COLUMN_PRIORITY }, +- { TextColumnDescriptor.ruleType, StringKeys.MSGKEY_PREF_RULESET_COLUMN_RULE_TYPE }, +- { TextColumnDescriptor.language, StringKeys.MSGKEY_PREF_RULESET_COLUMN_LANGUAGE }, +- { ImageColumnDescriptor.filterViolationRegex, StringKeys.MSGKEY_PREF_RULESET_GROUPING_REGEX }, +- { null, StringKeys.MSGKEY_PREF_RULESET_GROUPING_NONE } +- }; +- +-// private static final int RuleTableFraction = 55; // percent of screen height vs property tabs +- +- private ContainerCheckedTreeViewer ruleTreeViewer; +- private Button addRuleButton; +- private Button removeRuleButton; +- private RuleSet ruleSet; +- private TabFolder tabFolder; +-// private final Set checkedRules = new HashSet(); +- private Menu ruleListMenu; +- private Set hiddenColumnNames = new HashSet(); +- +- private RulePropertyManager[] rulePropertyManagers; +- +- private boolean sortDescending; +- private RuleFieldAccessor columnSorter = RuleFieldAccessor.name; // initial sort +- private RuleColumnDescriptor groupingColumn; +- +- private Map> paintListeners = new HashMap>(); +- +- private RuleSelection ruleSelection; // may hold rules and/or group nodes +- private Map priorityMenusByPriority; +- private Map rulesetMenusByName; +- +- private RuleFieldAccessor checkedColumnAccessor; +- +- private Button sortByCheckedButton; +- private Button selectAllButton; +- private Button unSelectAllButton; +- +- /** +- * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) +- */ +- public void init(IWorkbench workbench) { +- super.init(workbench); +- +- activeInstance = this; +- +- hiddenColumnNames = PreferenceUIStore.instance.hiddenColumnNames(); +- +- checkedColumnAccessor = createCheckedItemAccessor(); +- } +- +- private RuleFieldAccessor createCheckedItemAccessor() { +- +- return new BasicRuleFieldAccessor() { +- public Comparable valueFor(Rule rule) { +- return preferences.isActive(rule.getName()); +- } +- }; +- } +- +- private void sortByCheckedItems() { +- sortBy(checkedColumnAccessor, ruleTreeViewer.getTree().getColumn(0)); +- } +- +- +- protected String descriptionId() { +- return StringKeys.MSGKEY_PREF_RULESET_TITLE; +- } +- /** +- * @see org.eclipse.jface.preference.PreferencePage#performDefaults() +- */ +- @Override +- protected void performDefaults() { +- populateRuleTable(); +- super.performDefaults(); +- } +- +- private void storeActiveRules() { +- +- Object[] chosenRules = ruleTreeViewer.getCheckedElements(); +- for (Object item : chosenRules) { +- if (item instanceof Rule) { +- preferences.isActive(((Rule)item).getName(), true); +- } +- } +- +- System.out.println(""Active rules: "" + preferences.getActiveRuleNames()); +- } +- +- /** +- * @see org.eclipse.jface.preference.IPreferencePage#performOk() +- */ +- @Override +- public boolean performOk() { +- +- saveRuleSelections(); +- PreferenceUIStore.instance.save(); +- +- if (isModified()) { +- updateRuleSet(); +- rebuildProjects(); +- storeActiveRules(); +- } +- +- return super.performOk(); +- } +- +- @Override +- public boolean performCancel() { +- +- saveRuleSelections(); +- PreferenceUIStore.instance.save(); +- return super.performCancel(); +- } +- +- private void restoreSavedRuleSelections() { +- +- Set names = PreferenceUIStore.instance.selectedRuleNames(); +- List rules = new ArrayList(); +- for (String name : names) rules.add(ruleSet.getRuleByName(name)); +- +- IStructuredSelection selection = new StructuredSelection(rules); +- ruleTreeViewer.setSelection(selection); +- } +- +- private void saveRuleSelections() { +- +- IStructuredSelection selection = (IStructuredSelection)ruleTreeViewer.getSelection(); +- +- List ruleNames = new ArrayList(); +- for (Object item : selection.toList()) { +- if (item instanceof Rule) +- ruleNames.add(((Rule)item).getName()); +- } +- +- PreferenceUIStore.instance.selectedRuleNames(ruleNames); +- } +- +- /** +- * @see org.eclipse.jface.preference.PreferencePage#createContents(Composite) +- */ +- @Override +- protected Control createContents(Composite parent) { +- +- populateRuleset(); +- +- Composite composite = new Composite(parent, SWT.NULL); +- layoutControls(composite); +- +- restoreSavedRuleSelections(); +- updateCheckButtons(); +- +- return composite; +- } +- +- private Composite createRuleSection(Composite parent) { +- +- Composite ruleSection = new Composite(parent, SWT.NULL); +- +- // Create the controls (order is important !) +- Composite groupCombo = buildGroupCombo(ruleSection, StringKeys.MSGKEY_PREF_RULESET_RULES_GROUPED_BY); +- +- Tree ruleTree = buildRuleTreeViewer(ruleSection); +- groupBy(null); +- +- Composite ruleTableButtons = buildRuleTableButtons(ruleSection); +- Composite rulePropertiesTableButtons = buildRulePropertiesTableButtons(ruleSection); +- +- // Place controls on the layout +- GridLayout gridLayout = new GridLayout(3, false); +- ruleSection.setLayout(gridLayout); +- +- GridData data = new GridData(); +- data.horizontalSpan = 3; +- groupCombo.setLayoutData(data); +- +- data = new GridData(); +- data.heightHint = 200; data.widthHint = 350; +- data.horizontalSpan = 1; +- data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; +- data.grabExcessHorizontalSpace = true; data.grabExcessVerticalSpace = true; +- ruleTree.setLayoutData(data); +- +- data = new GridData(); +- data.horizontalSpan = 1; +- data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; +- ruleTableButtons.setLayoutData(data); +- +- data = new GridData(); +- data.horizontalSpan = 1; +- data.horizontalAlignment = GridData.FILL; data.verticalAlignment = GridData.FILL; +- rulePropertiesTableButtons.setLayoutData(data); +- +- return ruleSection; +- } +- +- private int[] selectionRatioIn(Rule[] rules) { +- +- int selectedCount = 0; +- for (Rule rule : rules) { +- if (preferences.isActive(rule.getName())) selectedCount++; +- } +- return new int[] { selectedCount , rules.length }; +- } +- +- private ICheckStateProvider createCheckStateProvider() { +- +- return new ICheckStateProvider() { +- +- public boolean isChecked(Object item) { +- if (item instanceof Rule) { +- return preferences.isActive(((Rule)item).getName()); +- } else { +- if (item instanceof RuleGroup) { +- int[] fraction = selectionRatioIn(((RuleGroup)item).rules()); +- return (fraction[0] > 0) && (fraction[0] == fraction[1]); +- } +- } +- return false; // should never get here +- } +- +- public boolean isGrayed(Object item) { +- +- if (item instanceof Rule) return false; +- if (item instanceof RuleGroup) { +- int[] fraction = selectionRatioIn(((RuleGroup)item).rules()); +- return (fraction[0] > 0) && (fraction[0] != fraction[1]); +- } +- return false; +- } +- +- }; +- } +- +- /** +- * Main layout +- * @param parent Composite +- */ +- private void layoutControls(Composite parent) { +- +- parent.setLayout(new FormLayout()); +- int ruleTableFraction = 55; //PreferenceUIStore.instance.tableFraction(); +- +- // Create the sash first, so the other controls can be attached to it. +- final Sash sash = new Sash(parent, SWT.HORIZONTAL); +- FormData data = new FormData(); +- data.left = new FormAttachment(0, 0); // attach to left +- data.right = new FormAttachment(100, 0); // attach to right +- data.top = new FormAttachment(ruleTableFraction, 0); +- sash.setLayoutData(data); +- sash.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- // Re-attach to the top edge, and we use the y value of the event to determine the offset from the top +- ((FormData)sash.getLayoutData()).top = new FormAttachment(0, event.y); +-// PreferenceUIStore.instance.tableFraction(event.y); +- sash.getParent().layout(); +- } +- }); +- +- // Create the first text box and attach its bottom edge to the sash +- Composite ruleSection = createRuleSection(parent); +- data = new FormData(); +- data.top = new FormAttachment(0, 0); +- data.bottom = new FormAttachment(sash, 0); +- data.left = new FormAttachment(0, 0); +- data.right = new FormAttachment(100, 0); +- ruleSection.setLayoutData(data); +- +- // Create the second text box and attach its top edge to the sash +- TabFolder propertySection = buildTabFolder(parent); +- data = new FormData(); +- data.top = new FormAttachment(sash, 0); +- data.bottom = new FormAttachment(100, 0); +- data.left = new FormAttachment(0, 0); +- data.right = new FormAttachment(100, 0); +- propertySection.setLayoutData(data); +- } +- +- public static String ruleSetNameFrom(Rule rule) { +- return ruleSetNameFrom( rule.getRuleSetName() ); +- } +- +- public static String ruleSetNameFrom(String rulesetName) { +- +- int pos = rulesetName.toUpperCase().indexOf(""RULES""); +- return pos < 0 ? rulesetName : rulesetName.substring(0, pos-1); +- } +- +- private TreeColumn columnFor(String tooltipText) { +- for (TreeColumn column : ruleTreeViewer.getTree().getColumns()) { +- if (column.getToolTipText().equals(tooltipText)) return column; +- } +- return null; +- } +- +- private void redrawTable() { +- redrawTable(""-"", -1); +- } +- +- private void redrawTable(String sortColumnLabel, int sortDir) { +- groupBy(groupingColumn); +- +- TreeColumn sortColumn = columnFor(sortColumnLabel); +- ruleTreeViewer.getTree().setSortColumn(sortColumn); +- ruleTreeViewer.getTree().setSortDirection(sortDir); +- } +- +- private void updateCheckButtons() { +- +- Rule[] rules = new Rule[ruleSet.size()]; +- rules = ruleSet.getRules().toArray(rules); +- int[] selectionRatio = selectionRatioIn(rules); +- +- selectAllButton.setEnabled( selectionRatio[0] < selectionRatio[1]); +- unSelectAllButton.setEnabled( selectionRatio[0] > 0); +- sortByCheckedButton.setEnabled( (selectionRatio[0] != 0) && (selectionRatio[0] != selectionRatio[1])); +- } +- +- private Composite buildGroupCombo(Composite parent, String comboLabelKey) { +- +- Composite panel = new Composite(parent, 0); +- GridLayout layout = new GridLayout(5, false); +- panel.setLayout(layout); +- +- sortByCheckedButton = buildSortByCheckedItemsButton(panel); +- selectAllButton = buildSelectAllButton(panel); +- unSelectAllButton = buildUnselectAllButton(panel); +- +- Label label = new Label(panel, 0); +- GridData data = new GridData(); +- data.horizontalAlignment = SWT.LEFT; +- data.verticalAlignment = SWT.CENTER; +- label.setLayoutData(data); +- label.setText(SWTUtil.stringFor(comboLabelKey)); +- +- final Combo combo = new Combo(panel, SWT.READ_ONLY); +- combo.setItems(SWTUtil.i18lLabelsIn(groupingChoices, 1)); +- combo.select(groupingChoices.length - 1); // picks last one by default TODO make it a persistent preference +- +- combo.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent e) { +- int selectionIdx = combo.getSelectionIndex(); +- Object[] choice = groupingChoices[selectionIdx]; +- groupingColumn = (RuleColumnDescriptor)choice[0]; +- redrawTable(); +- } +- }); +- +- return panel; +- } +- +- /** +- * Method buildTabFolder. +- * @param parent Composite +- * @return TabFolder +- */ +- private TabFolder buildTabFolder(Composite parent) { +- +- tabFolder = new TabFolder(parent, SWT.TOP); +- +- rulePropertyManagers = new RulePropertyManager[] { +- buildDescriptionTab(tabFolder, 0, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_DESCRIPTION)), +- buildPropertyTab(tabFolder, 1, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_PROPERTIES)), +- buildUsageTab(tabFolder, 2, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FILTERS)), +- buildXPathTab(tabFolder, 3, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_XPATH)), +- buildQuickFixTab(tabFolder, 4, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), +- buildExampleTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), +- }; +- +- tabFolder.pack(); +- return tabFolder; +- } +- +- /** +- * @param parent TabFolder +- * @param index int +- */ +- private RulePropertyManager buildPropertyTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- PerRulePropertyPanelManager manager = new PerRulePropertyPanelManager(title, EditorUsageMode.Editing, this); +- tab.setControl( +- manager.setupOn(parent) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * @param parent TabFolder +- * @param index int +- */ +- private RulePropertyManager buildDescriptionTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- DescriptionPanelManager manager = new DescriptionPanelManager(title, EditorUsageMode.Editing, this); +- tab.setControl( +- manager.setupOn(parent) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * @param parent TabFolder +- * @param index int +- */ +- private RulePropertyManager buildXPathTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- XPathPanelManager manager = new XPathPanelManager(title, EditorUsageMode.Editing, this); +- tab.setControl( +- manager.setupOn(parent) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * @param parent TabFolder +- * @param index int +- */ +- private RulePropertyManager buildExampleTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- ExamplePanelManager manager = new ExamplePanelManager(title, EditorUsageMode.Editing, this); +- tab.setControl( +- manager.setupOn(parent) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * @param parent TabFolder +- * @param index int +- */ +- private RulePropertyManager buildQuickFixTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- QuickFixPanelManager manager = new QuickFixPanelManager(title, EditorUsageMode.Editing, this); +- tab.setControl( +- manager.setupOn(parent) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * +- * @param parent TabFolder +- * @param index int +- * @param title String +- */ +- private RulePropertyManager buildUsageTab(TabFolder parent, int index, String title) { +- +- TabItem tab = new TabItem(parent, 0, index); +- tab.setText(title); +- +- ExclusionPanelManager manager = new ExclusionPanelManager(title, EditorUsageMode.Editing, this, true); +- tab.setControl( +- manager.setupOn( +- parent +- ) +- ); +- manager.tab(tab); +- return manager; +- } +- +- /** +- * Create buttons for rule table management +- * @param parent Composite +- * @return Composite +- */ +- private Composite buildRuleTableButtons(Composite parent) { +- Composite composite = new Composite(parent, SWT.NULL); +- GridLayout gridLayout = new GridLayout(); +- gridLayout.numColumns = 1; +- gridLayout.verticalSpacing = 3; +- composite.setLayout(gridLayout); +- +- addRuleButton = buildAddRuleButton(composite); +- removeRuleButton = buildRemoveRuleButton(composite); +- Button importRuleSetButton = buildImportRuleSetButton(composite); +- Button exportRuleSetButton = buildExportRuleSetButton(composite); +- Button ruleDesignerButton = buildRuleDesignerButton(composite); +- +- GridData data = new GridData(); +- addRuleButton.setLayoutData(data); +- +- data = new GridData(); +- importRuleSetButton.setLayoutData(data); +- +- data = new GridData(); +- exportRuleSetButton.setLayoutData(data); +- +- data = new GridData(); +- data.horizontalAlignment = GridData.FILL; +- data.grabExcessVerticalSpace = true; +- data.verticalAlignment = GridData.END; +- ruleDesignerButton.setLayoutData(data); +- +- return composite; +- } +- +- /** +- * Create buttons for rule properties table management +- * @param parent Composite +- * @return Composite +- */ +- private Composite buildRulePropertiesTableButtons(Composite parent) { +- Composite composite = new Composite(parent, SWT.NULL); +- RowLayout rowLayout = new RowLayout(); +- rowLayout.type = SWT.VERTICAL; +- rowLayout.wrap = false; +- rowLayout.pack = false; +- composite.setLayout(rowLayout); +- +- return composite; +- } +- +- /** +- * Build rule table viewer +- * @param parent Composite +- * @return Tree +- */ +- private Tree buildRuleTreeViewer(Composite parent) { +- +- int treeStyle = SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.MULTI | SWT.FULL_SELECTION | SWT.CHECK; +- ruleTreeViewer = new ContainerCheckedTreeViewer(parent, treeStyle); +- +- final Tree ruleTree = ruleTreeViewer.getTree(); +- ruleTree.setLinesVisible(true); +- ruleTree.setHeaderVisible(true); +- +- ruleTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() { +- public void selectionChanged(SelectionChangedEvent event) { +- IStructuredSelection selection = (IStructuredSelection)event.getSelection(); +- selectedItems(selection.toArray()); +- } +- }); +- +- ruleListMenu = createMenuFor(ruleTree); +- ruleTree.setMenu(ruleListMenu); +- ruleTree.addListener(SWT.MenuDetect, new Listener () { +- public void handleEvent (Event event) { +- popupRuleSelectionMenu(event); +- } +- }); +- +- ruleTree.addListener(SWT.Selection, new Listener() { +- public void handleEvent(Event event) { +- if (event.detail == SWT.CHECK) { +- TreeItem item = (TreeItem) event.item; +- boolean checked = item.getChecked(); +- checkItems(item, checked); +- checkPath(item.getParentItem(), checked, false); +- } +- // if (!checkedRules.isEmpty()) System.out.println(checkedRules.iterator().next()); +- } +- }); +- +- ruleTree.addListener(SWT.MouseMove, new Listener() { +- public void handleEvent(Event event) { +- Point point = new Point(event.x, event.y); +- TreeItem item = ruleTree.getItem(point); +- if (item != null) { +- int columnIndex = columnIndexAt(item, event.x); +- updateTooltipFor(item, columnIndex); +- } +- } +- }); +- +- ruleTreeViewer.setCheckStateProvider(createCheckStateProvider()); +- +- return ruleTree; +- } +- +- private int columnIndexAt(TreeItem item, int xPosition) { +- +- TreeColumn[] cols = ruleTreeViewer.getTree().getColumns(); +- Rectangle bounds = null; +- +- for(int i = 0; i < cols.length; i++){ +- bounds = item.getBounds(i); +- if (bounds.x < xPosition && xPosition < (bounds.x + bounds.width)) { +- return i; +- } +- } +- return -1; +- } +- +- private void updateTooltipFor(TreeItem item, int columnIndex) { +- +- RuleLabelProvider provider = (RuleLabelProvider)ruleTreeViewer.getLabelProvider(); +- String txt = provider.getDetailText(item.getData(), columnIndex); +- ruleTreeViewer.getTree().setToolTipText(txt); +- } +- +- public static Image imageFor(RulePriority priority) { +- String codePath = PMDUiConstants.buttonCodePathFor(priority, false); +- return ResourceManager.imageFor(codePath); +- } +- +- private boolean currentSelectionHasNonDefaultValues() { +- +- return ruleSelection == null ? +- false : RuleUtil.allUseDefaultValues(ruleSelection); +- } +- +- private Menu createMenuFor(Control control) { +- +- Menu menu = new Menu(control); +- +- MenuItem priorityMenu = new MenuItem (menu, SWT.CASCADE); +- priorityMenu.setText(SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_COLUMN_PRIORITY)); +- Menu subMenu = new Menu(menu); +- priorityMenu.setMenu (subMenu); +- priorityMenusByPriority = new HashMap(RulePriority.values().length); +- +- for (RulePriority priority : RulePriority.values()) { +- MenuItem priorityItem = new MenuItem (subMenu, SWT.RADIO); +- priorityMenusByPriority.put(priority, priorityItem); +- priorityItem.setText(priority.getName()); // TODO need to internationalize? +- // priorityItem.setImage(imageFor(priority)); not visible with radiobuttons +- final RulePriority pri = priority; +- priorityItem.addSelectionListener( new SelectionListener() { +- public void widgetSelected(SelectionEvent e) { +- setPriority(pri); +- } +- public void widgetDefaultSelected(SelectionEvent e) { }} +- ); +- } +- +- MenuItem removeItem = new MenuItem(menu, SWT.PUSH); +- removeItem.setText(""Remove""); +- removeItem.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- removeSelectedRules(); +- } +- }); +- +- MenuItem useDefaultsItem = new MenuItem(menu, SWT.PUSH); +- useDefaultsItem.setText(""Use defaults""); +- useDefaultsItem.setEnabled(false); +- useDefaultsItem.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- // useDefaultValues(); +- } +- }); +- +- return menu; +- } +- +- private void addColumnSelectionOptions(Menu menu) { +- +- MenuItem showMenu = new MenuItem(menu, SWT.CASCADE); +- showMenu.setText(""Show""); +- Menu columnsSubMenu = new Menu(menu); +- showMenu.setMenu(columnsSubMenu); +- +- for (String columnLabel : columnLabels()) { +- MenuItem columnItem = new MenuItem(columnsSubMenu, SWT.CHECK); +- columnItem.setSelection(!hiddenColumnNames.contains(columnLabel)); +- columnItem.setText(columnLabel); +- final String nameStr = columnLabel; +- columnItem.addSelectionListener( new SelectionAdapter() { +- public void widgetSelected(SelectionEvent e) { +- toggleColumnVisiblity(nameStr); +- } +- } +- ); +- } +- } +- +- private static String[] columnLabels() { +- String[] names = new String[availableColumns.length]; +- for (int i=0; i(); +- +- MenuItem demoItem = new MenuItem(rulesetSubMenu, SWT.PUSH); +- demoItem.setText(""---demo only---""); // NO API to re-parent rules to other rulesets (yet) +- +- for (String rulesetName : rulesetNames()) { +- MenuItem rulesetItem = new MenuItem(rulesetSubMenu, SWT.RADIO); +- rulesetMenusByName.put(rulesetName, rulesetItem); +- rulesetItem.setText(rulesetName); +- final String rulesetStr = rulesetName; +- rulesetItem.addSelectionListener( new SelectionAdapter() { +- public void widgetSelected(SelectionEvent e) { +- setRuleset(rulesetStr); +- } +- } +- ); +- } +- } +- private void popupRuleSelectionMenu(Event event) { +- +- // have to do it here or else the ruleset var is null in the menu setup - timing issue +- if (rulesetMenusByName == null) { +- addRulesetMenuOptions(ruleListMenu); +- new MenuItem(ruleListMenu, SWT.SEPARATOR); +- addColumnSelectionOptions(ruleListMenu); +- } +- +- adjustMenuPrioritySettings(); +- adjustMenuRulesetSettings(); +- adjustMenuUseDefaultsOption(); +- ruleListMenu.setLocation(event.x, event.y); +- ruleListMenu.setVisible(true); +- } +- +- private void adjustMenuUseDefaultsOption() { +- +- } +- +- // if all the selected rules/ruleGroups reference a common ruleset name +- // then check that item and disable it, do the reverse for all others. +- private void adjustMenuRulesetSettings() { +- +- String rulesetName = ruleSetNameFrom(RuleUtil.commonRuleset(ruleSelection)); +- Iterator> iter = rulesetMenusByName.entrySet().iterator(); +- +- while (iter.hasNext()) { +- Map.Entry entry = iter.next(); +- MenuItem item = entry.getValue(); +- if (rulesetName == null) { // allow all entries if none or conflicting +- item.setSelection(false); +- item.setEnabled(true); +- continue; +- } +- if (StringUtil.areSemanticEquals(entry.getKey(), rulesetName)) { +- item.setSelection(true); +- item.setEnabled(false); +- } else { +- item.setSelection(false); +- item.setEnabled(true); +- } +- } +- } +- +- private void adjustMenuPrioritySettings() { +- +- RulePriority priority = RuleUtil.commonPriority(ruleSelection); +- Iterator> iter = priorityMenusByPriority.entrySet().iterator(); +- +- while (iter.hasNext()) { +- Map.Entry entry = iter.next(); +- MenuItem item = entry.getValue(); +- if (entry.getKey() == priority) { +- item.setSelection(true); +- item.setEnabled(false); +- } else { +- item.setSelection(false); +- item.setEnabled(true); +- } +- } +- } +- +- private boolean hasPriorityGrouping() { +- return +- groupingColumn == TextColumnDescriptor.priorityName || +- groupingColumn == TextColumnDescriptor.priority; +- } +- +- private void setPriority(RulePriority priority) { +- +- ruleSelection.setPriority(priority); +- +- if (hasPriorityGrouping()) { +- redrawTable(); +- } else { +- ruleTreeViewer.update(ruleSelection.allRules().toArray(), null); +- } +- } +- +- private String[] rulesetNames() { +- +- Set names = new HashSet(); +- for (Rule rule : ruleSet.getRules()) { +- names.add(ruleSetNameFrom(rule)); // if we strip out the 'Rules' portions then we don't get matches...need to rename rulesets +- } +- return names.toArray(new String[names.size()]); +- } +- +- private void setRuleset(String rulesetName) { +- // TODO - awaiting support in PMD itself +- } +- +- /** +- * @param item Object[] +- */ +- private void selectedItems(Object[] items) { +- +- ruleSelection = new RuleSelection(items); +- for (RulePropertyManager manager : rulePropertyManagers) manager.manage(ruleSelection); +- +- removeRuleButton.setEnabled(items.length > 0); +- } +- +- /** +- * Method groupBy. +- * @param chosenColumn RuleColumnDescriptor +- */ +- private void groupBy(RuleColumnDescriptor chosenColumn) { +- +- List visibleColumns = new ArrayList(availableColumns.length); +- for (RuleColumnDescriptor desc : availableColumns) { +- if (desc == chosenColumn) continue; // redundant, don't include it +- if (hiddenColumnNames.contains(desc.label())) continue; +- visibleColumns.add(desc); +- } +- +- setupTreeColumns( +- visibleColumns.toArray(new RuleColumnDescriptor[visibleColumns.size()]), +- chosenColumn == null ? null : chosenColumn.accessor() +- ); +- } +- +- /** +- * Remove all rows, columns, and column painters in preparation +- * for new columns. +- * +- * @return Tree +- */ +- private Tree cleanupRuleTree() { +- +- Tree ruleTree = ruleTreeViewer.getTree(); +- +- ruleTree.clearAll(true); +- for(;ruleTree.getColumns().length>0;) { // TODO also dispose any heading icons? +- ruleTree.getColumns()[0].dispose(); +- } +- +- // ensure we don't have any previous per-column painters left over +- for (Map.Entry> entry : paintListeners.entrySet()) { +- int eventCode = entry.getKey().intValue(); +- List listeners = entry.getValue(); +- for (Listener listener : listeners) { +- ruleTree.removeListener(eventCode, listener); +- } +- listeners.clear(); +- } +- +- return ruleTree; +- } +- +- /** +- * Method setupTreeColumns. +- * @param columnDescs RuleColumnDescriptor[] +- * @param groupingField RuleFieldAccessor +- */ +- private void setupTreeColumns(RuleColumnDescriptor[] columnDescs, RuleFieldAccessor groupingField) { +- +- Tree ruleTree = cleanupRuleTree(); +- +- for (int i=0; i iter = selectedRuleSet.getRules().iterator(); +- while (iter.hasNext()) { +- Rule rule = iter.next(); +- rule.setRuleSetName(""pmd-eclipse""); +- ruleSet.addRule(rule); +- } +- } +- setModified(true); +- try { +- refresh(); +- } catch (Throwable t) { +- plugin.logError(""Exception when refreshing the rule table"", t); +- } +- } catch (RuntimeException e) { +- plugin.showError(getMessage(StringKeys.MSGKEY_ERROR_IMPORTING_RULESET), e); +- } +- } +- } +- }); +- +- return button; +- } +- +- /** +- * Build the export rule set button +- * @param parent Composite +- * @return Button +- */ +- private Button buildExportRuleSetButton(Composite parent) { +- Button button = new Button(parent, SWT.PUSH | SWT.LEFT); +- button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_EXPORT)); +- button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_EXPORTRULESET)); +- button.setEnabled(true); +- button.addSelectionListener(new SelectionAdapter() { +- @Override +- public void widgetSelected(SelectionEvent event) { +- FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); +- String fileName = dialog.open(); +- if (fileName != null) { +- try { +- File file = new File(fileName); +- boolean flContinue = true; +- if (file.exists()) { +- flContinue = MessageDialog.openConfirm(getShell(), +- getMessage(StringKeys.MSGKEY_CONFIRM_TITLE), +- getMessage(StringKeys.MSGKEY_CONFIRM_RULESET_EXISTS)); +- } +- +- InputDialog input = null; +- if (flContinue) { +- input = new InputDialog(getShell(), +- getMessage(StringKeys.MSGKEY_PREF_RULESET_DIALOG_TITLE), +- getMessage(StringKeys.MSGKEY_PREF_RULESET_DIALOG_RULESET_DESCRIPTION), +- ruleSet.getDescription() == null ? """" : ruleSet.getDescription().trim(), null); +- flContinue = input.open() == InputDialog.OK; +- } +- +- if (flContinue) { +- ruleSet.setName(FileUtil.getFileNameWithoutExtension(file.getName())); +- ruleSet.setDescription(input.getValue()); +- OutputStream out = new FileOutputStream(fileName); +- IRuleSetWriter writer = plugin.getRuleSetWriter(); +- writer.write(out, ruleSet); +- out.close(); +- MessageDialog.openInformation(getShell(), getMessage(StringKeys.MSGKEY_INFORMATION_TITLE), +- getMessage(StringKeys.MSGKEY_INFORMATION_RULESET_EXPORTED)); +- } +- } catch (Exception e) { +- plugin.showError(getMessage(StringKeys.MSGKEY_ERROR_EXPORTING_RULESET), e); +- } +- } +- } +- }); +- +- return button; +- } +- +- private CheckboxTreeViewer treeViewer() { return ruleTreeViewer; } +- +- private Button buildSortByCheckedItemsButton(Composite parent) { +- Button button = new Button(parent, SWT.PUSH | SWT.LEFT); +- button.setToolTipText(""Sort by checked items""); +- button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_SORT_CHECKED)); +- +- button.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- sortByCheckedItems(); +- } +- }); +- +- return button; +- } +- +- /** +- * +- * @param parent Composite +- * @return Button +- */ +- private Button buildSelectAllButton(Composite parent) { +- Button button = new Button(parent, SWT.PUSH | SWT.LEFT); +-// button.setText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_SELECT_ALL)); +- button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_CHECK_ALL)); +- +- button.setEnabled(true); +- button.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- setAllRulesActive(); +- } +- }); +- +- return button; +- } +- +- private void setAllRulesActive() { +- for (Rule rule : ruleSet.getRules()) { +- preferences.isActive(rule.getName(), true); +- } +- +- treeViewer().setCheckedElements(ruleSet.getRules().toArray()); +- setModified(true); +- updateCheckButtons(); +- } +- +- /** +- * +- * @param parent Composite +- * @return Button +- */ +- private Button buildUnselectAllButton(Composite parent) { +- Button button = new Button(parent, SWT.PUSH | SWT.LEFT); +-// button.setText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_SELECT_ALL)); +- button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_UNCHECK_ALL)); +- +- button.setEnabled(true); +- button.addSelectionListener(new SelectionAdapter() { +- public void widgetSelected(SelectionEvent event) { +- preferences.getActiveRuleNames().clear(); +- treeViewer().setCheckedElements(new Object[0]); +- setModified(true); +- updateCheckButtons(); +- } +- }); +- +- return button; +- } +- +- /** +- * Build the Rule Designer button +- * @param parent Composite +- * @return Button +- */ +- private Button buildRuleDesignerButton(Composite parent) { +- Button button = new Button(parent, SWT.PUSH | SWT.LEFT); +- button.setImage(ResourceManager.imageFor(PMDUiConstants.ICON_BUTTON_EDITOR)); +- button.setToolTipText(getMessage(StringKeys.MSGKEY_PREF_RULESET_BUTTON_RULEDESIGNER)); +- button.setEnabled(true); +- button.addSelectionListener(new SelectionAdapter() { +- @Override +- public void widgetSelected(SelectionEvent event) { +- // TODO Is this cool from Eclipse? Is there a nicer way to spawn a J2SE Application? +- new Thread(new Runnable() { +- public void run() { +- Designer.main(new String[] { ""-noexitonclose"" }); +- } +- }).start(); +- } +- }); +- +- return button; +- } +- +- private void populateRuleset() { +- +- RuleSet defaultRuleSet = plugin.getPreferencesManager().getRuleSet(); +- ruleSet = new RuleSet(); +- ruleSet.addRuleSet(defaultRuleSet); +- ruleSet.setName(defaultRuleSet.getName()); +- ruleSet.setDescription(Util.asCleanString(defaultRuleSet.getDescription())); +- ruleSet.addExcludePatterns(defaultRuleSet.getExcludePatterns()); +- ruleSet.addIncludePatterns(defaultRuleSet.getIncludePatterns()); +- } +- +- /** +- * Populate the rule table +- */ +- private void populateRuleTable() { +- ruleTreeViewer.setInput(ruleSet); +- checkSelections(); +- } +- +- private void checkSelections() { +- +-// List activeRules = new ArrayList(); +-// +-// for (Rule rule : ruleSet.getRules()) { +-// if (preferences.isActive(rule.getName())) { +-// activeRules.add(rule); +-// } +-// } +-// +-// ruleTreeViewer.setCheckedElements(activeRules.toArray()); +- } +- +- /** +- * Refresh the list +- */ +- protected void refresh() { +- try { +- ruleTreeViewer.getControl().setRedraw(false); +- ruleTreeViewer.refresh(); +- } catch (ClassCastException e) { +- plugin.logError(""Ignoring exception while refreshing table"", e); +- } finally { +- ruleTreeViewer.getControl().setRedraw(true); +- } +- } +- +- /** +- * Update the configured rule set +- * Update also all configured projects +- */ +- private void updateRuleSet() { +- try { +- ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); +- monitorDialog.run(true, true, new IRunnableWithProgress() { +- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { +- plugin.getPreferencesManager().setRuleSet(ruleSet); +- } +- }); +- } catch (Exception e) { +- plugin.logError(""Exception updating all projects after a preference change"", e); +- } +- } +- +- /** +- * If user wants to, rebuild all projects +- */ +- private void rebuildProjects() { +- if (MessageDialog.openQuestion(getShell(), getMessage(StringKeys.MSGKEY_QUESTION_TITLE), +- getMessage(StringKeys.MSGKEY_QUESTION_RULES_CHANGED))) { +- try { +- ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(getShell()); +- monitorDialog.run(true, true, new IRunnableWithProgress() { +- public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { +- try { +- ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); +- } catch (CoreException e) { +- plugin.logError(""Exception building all projects after a preference change"", e); +- } +- } +- }); +- } catch (Exception e) { +- plugin.logError(""Exception building all projects after a preference change"", e); +- } +- } +- } +- +- /** +- * Select and show a particular rule in the table +- * @param rule Rule +- */ +- protected void selectAndShowRule(Rule rule) { +- Tree tree = ruleTreeViewer.getTree(); +- TreeItem[] items = tree.getItems(); +- for (TreeItem item : items) { +- Rule itemRule = (Rule)item.getData(); +- if (itemRule.equals(rule)) { +- // tree.setSelection(tree.indexOf(items[i])); +- tree.showSelection(); +- break; +- } +- } +- } +- +- public void changed(Rule rule, PropertyDescriptor desc, Object newValue) { +- // TODO enhance to recognize default values +- ruleTreeViewer.update(rule, null); +- setModified(); +- } +- +- public void changed(RuleSelection selection, PropertyDescriptor desc, Object newValue) { +- // TODO enhance to recognize default values +- +- for (Rule rule : selection.allRules()) { +- if (newValue != null) { // non-reliable update behaviour, alternate trigger option - weird +- ruleTreeViewer.getTree().redraw(); +- // System.out.println(""doing redraw""); +- } else { +- ruleTreeViewer.update(rule, null); +- // System.out.println(""viewer update""); +- } +- } +- for (RulePropertyManager manager : rulePropertyManagers) { +- manager.validate(); +- } +- +- setModified(); +- } +- +- public void sortBy(RuleFieldAccessor accessor, Object context) { +- +- TreeColumn column = (TreeColumn)context; +- +- if (columnSorter == accessor) { +- sortDescending = !sortDescending; +- } else { +- columnSorter = accessor; +- } +- +- redrawTable(column.getToolTipText(), sortDescending ? SWT.DOWN : SWT.UP); +- } +- +- +-} +\ No newline at end of file +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java +index 7c954782571..20a0d5bcc89 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PMDPreferencePage2.java +@@ -11,6 +11,7 @@ + import net.sourceforge.pmd.RuleSet; + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + import net.sourceforge.pmd.eclipse.runtime.preferences.impl.PreferenceUIStore; ++import net.sourceforge.pmd.eclipse.ui.Shape; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; + import net.sourceforge.pmd.eclipse.ui.preferences.panelmanagers.Configuration; +@@ -55,9 +56,9 @@ public class PMDPreferencePage2 extends AbstractPMDPreferencePage implements Rul + private RulePropertyManager[] rulePropertyManagers; + private RuleTableManager tableManager; + +- public static final Util.shape PriorityShape = Util.shape.diamond; +- public static final Util.shape RegexFilterShape = Util.shape.square; +- public static final Util.shape XPathFilterShape = Util.shape.circle; ++ public static final Shape PriorityShape = Shape.diamond; ++ public static final Shape RegexFilterShape = Shape.square; ++ public static final Shape XPathFilterShape = Shape.circle; + + public static final FontBuilder blueBold11 = new FontBuilder(""Tahoma"", 11, SWT.BOLD, SWT.COLOR_BLUE); + public static final FontBuilder redBold11 = new FontBuilder(""Tahoma"", 11, SWT.BOLD, SWT.COLOR_RED); +@@ -69,7 +70,7 @@ public class PMDPreferencePage2 extends AbstractPMDPreferencePage implements Rul + //TextColumnDescriptor.priorityName, + // IconColumnDescriptor.priority, + ImageColumnDescriptor.priority, +- TextColumnDescriptor.fixCount, ++ // TextColumnDescriptor.fixCount, + TextColumnDescriptor.since, + TextColumnDescriptor.ruleSetName, + TextColumnDescriptor.ruleType, +@@ -284,8 +285,8 @@ private TabFolder buildTabFolder(Composite parent) { + buildPropertyTab(tabFolder, 2, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_PROPERTIES)), + buildUsageTab(tabFolder, 3, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FILTERS)), + buildXPathTab(tabFolder, 4, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_XPATH)), +- buildQuickFixTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), +- buildExampleTab(tabFolder, 6, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), ++// buildQuickFixTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_FIXES)), ++ buildExampleTab(tabFolder, 5, SWTUtil.stringFor(StringKeys.MSGKEY_PREF_RULESET_TAB_EXAMPLES)), + }; + + tabFolder.pack(); +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java +new file mode 100644 +index 00000000000..69ac06f3c45 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityDescriptorCache.java +@@ -0,0 +1,65 @@ ++package net.sourceforge.pmd.eclipse.ui.preferences.br; ++ ++import java.util.HashMap; ++import java.util.Map; ++ ++import net.sourceforge.pmd.RulePriority; ++import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; ++import net.sourceforge.pmd.eclipse.plugin.PriorityDescriptor; ++import net.sourceforge.pmd.eclipse.plugin.UISettings; ++import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferences; ++import net.sourceforge.pmd.eclipse.runtime.preferences.IPreferencesManager; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public class PriorityDescriptorCache { ++ ++ private Map uiDescriptorsByPriority; ++ ++ public static final PriorityDescriptorCache instance = new PriorityDescriptorCache(); ++ ++ private PriorityDescriptorCache() { ++ uiDescriptorsByPriority = new HashMap(5); ++ loadFromPreferences(); ++ } ++ ++ public void loadFromPreferences() { ++ ++ IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); ++ for (RulePriority rp : UISettings.currentPriorities(true)) { ++ uiDescriptorsByPriority.put(rp, preferences.getPriorityDescriptor(rp).clone()); ++ } ++ } ++ ++ public void storeInPreferences() { ++ ++ IPreferencesManager mgr = PMDPlugin.getDefault().getPreferencesManager(); ++ ++ IPreferences prefs = mgr.loadPreferences(); ++ ++ for (Map.Entry entry : uiDescriptorsByPriority.entrySet()) { ++ prefs.setPriorityDescriptor(entry.getKey(), entry.getValue()); ++ } ++ ++ mgr.storePreferences(prefs); ++ } ++ ++ public PriorityDescriptor descriptorFor(RulePriority priority) { ++ return uiDescriptorsByPriority.get(priority); ++ } ++ ++ public boolean hasChanges() { ++ ++ IPreferences preferences = PMDPlugin.getDefault().getPreferencesManager().loadPreferences(); ++ ++ for (RulePriority rp : UISettings.currentPriorities(true)) { ++ PriorityDescriptor newOne = uiDescriptorsByPriority.get(rp); ++ PriorityDescriptor currentOne = preferences.getPriorityDescriptor(rp); ++ if (newOne.equals(currentOne)) continue; ++ return true; ++ } ++ return false; ++ } ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java +new file mode 100755 +index 00000000000..0692ce0b1bd +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessor.java +@@ -0,0 +1,49 @@ ++package net.sourceforge.pmd.eclipse.ui.preferences.br; ++ ++import net.sourceforge.pmd.RulePriority; ++import net.sourceforge.pmd.eclipse.ui.Shape; ++ ++import org.eclipse.swt.graphics.Image; ++import org.eclipse.swt.graphics.RGB; ++import org.eclipse.swt.widgets.Display; ++ ++/** ++ * ++ * @author Brian Remedios ++ */ ++public interface PriorityFieldAccessor { ++ ++ T valueFor(RulePriority priority); ++ ++ Image imageFor(RulePriority priority); ++ ++ String labelFor(RulePriority priority); ++ ++ PriorityFieldAccessor name = new PriorityFieldAccessorAdapter() { ++ public String valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).label; } ++ }; ++ ++ PriorityFieldAccessor description = new PriorityFieldAccessorAdapter() { ++ public String valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).description; } ++ }; ++ ++ PriorityFieldAccessor shape = new PriorityFieldAccessorAdapter() { ++ public Shape valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.shape; } ++ }; ++ ++ PriorityFieldAccessor color = new PriorityFieldAccessorAdapter() { ++ public RGB valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.rgbColor; } ++ }; ++ ++ PriorityFieldAccessor size = new PriorityFieldAccessorAdapter() { ++ public Integer valueFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).shape.size; } ++ }; ++ ++ PriorityFieldAccessor value = new PriorityFieldAccessorAdapter() { ++ public Integer valueFor(RulePriority priority) { return priority.getPriority(); } ++ }; ++ ++ PriorityFieldAccessor image = new PriorityFieldAccessorAdapter() { ++ public Image imageFor(RulePriority priority) { return PriorityDescriptorCache.instance.descriptorFor(priority).getImage(Display.getCurrent()); } ++ }; ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java +new file mode 100644 +index 00000000000..5dc26d01734 +--- /dev/null ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/PriorityFieldAccessorAdapter.java +@@ -0,0 +1,12 @@ ++package net.sourceforge.pmd.eclipse.ui.preferences.br; ++ ++import net.sourceforge.pmd.RulePriority; ++ ++import org.eclipse.swt.graphics.Image; ++ ++public class PriorityFieldAccessorAdapter implements PriorityFieldAccessor { ++ ++ public T valueFor(RulePriority priority) { return null; } ++ public Image imageFor(RulePriority priority) { return null; } ++ public String labelFor(RulePriority priority) { return null; } ++} +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java +index d8bf8571aa8..eaf0d756496 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleFieldAccessor.java +@@ -119,6 +119,7 @@ public Comparable valueFor(Rule rule) { + public String labelFor(Rule rule) { + List types = new ArrayList(3); + if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) types.add(ruleTypeXPath[1]); ++ // if (if (RuleUtil.isXPathRule(rule)) TODO + if (rule.usesDFA()) types.add(ruleTypeDFlow[1]); + if (rule.usesTypeResolution()) types.add(ruleTypeTypeRes[1]); + return Util.asString(types, "", ""); +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java +index e32fea396b4..26a4f06ce26 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleTableManager.java +@@ -233,6 +233,8 @@ private void createRule(Shell shell) { + try { + CreateRuleWizard wiz = new CreateRuleWizard(); + WizardDialog dialog = new WizardDialog(shell, wiz); ++ wiz.dialog(dialog); ++ + int result = dialog.open(); + + if (result == Window.OK) { +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java +index 44403d9d9f6..3bc9214a0d2 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/RuleUtil.java +@@ -14,6 +14,7 @@ + import net.sourceforge.pmd.lang.Language; + import net.sourceforge.pmd.lang.LanguageVersion; + import net.sourceforge.pmd.lang.rule.RuleReference; ++import net.sourceforge.pmd.lang.rule.XPathRule; + import net.sourceforge.pmd.lang.rule.properties.AbstractProperty; + import net.sourceforge.pmd.util.CollectionUtil; + +@@ -33,6 +34,15 @@ public static boolean isDefaultValue(Map.Entry, Object> en + return areEqual(desc.defaultValue(), value); + } + ++ // TODO fix rule!! ++ public static boolean isXPathRule(Rule rule) { ++ ++ for (PropertyDescriptor desc : rule.getPropertyDescriptors()) { ++ if (desc.equals(XPathRule.XPATH_DESCRIPTOR)) return true; ++ } ++ return false; ++ } ++ + // TODO move elsewhere + public static boolean areEqual(Object value, Object otherValue) { + if (value == otherValue) { +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items +index 18f8a30a337..1d35cc11c1d 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TODO items +@@ -4,7 +4,6 @@ Finish remaining editors and the Add Property dialog + Enable 'Use defaults' option in popup menu (need support in properties/PMD) + Add selection column selected rules in per-project rule settings table + Rework context menu - build on-demand, not before +-Markup violations using priority icons rather than the yellow yield signs or red Xs + Work on support for fixes + Format example & description text + Need preference widgets to allow user-specified shapes for RulePriorities +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java +index 17c63399940..00bbf6da61b 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/AbstractRulePanelManager.java +@@ -6,6 +6,9 @@ + import net.sourceforge.pmd.PropertyDescriptor; + import net.sourceforge.pmd.Rule; + import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; ++import net.sourceforge.pmd.eclipse.ui.editors.BasicLineStyleListener; ++import net.sourceforge.pmd.eclipse.ui.editors.SyntaxData; ++import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; + import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSelection; + import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; + import net.sourceforge.pmd.eclipse.ui.preferences.editors.TypeText; +@@ -17,7 +20,10 @@ + import org.eclipse.jface.wizard.WizardPage; + import org.eclipse.swt.SWT; + import org.eclipse.swt.custom.CCombo; ++import org.eclipse.swt.custom.LineStyleListener; + import org.eclipse.swt.custom.StyledText; ++import org.eclipse.swt.events.ModifyEvent; ++import org.eclipse.swt.events.ModifyListener; + import org.eclipse.swt.graphics.Color; + import org.eclipse.swt.graphics.RGB; + import org.eclipse.swt.widgets.Button; +@@ -201,7 +207,16 @@ public void handleEvent(Event event) { + } + }); + } ++ ++ protected void addTextListeners(final StyledText control, final StringProperty desc) { + ++ control.addListener(SWT.FocusOut, new Listener() { ++ public void handleEvent(Event event) { ++ changed(desc, control.getText()); ++ } ++ }); ++ } ++ + protected void initializeOn(Composite parent) { + + if (errorColour != null) return; +@@ -335,4 +350,10 @@ protected Text newTextField(Composite parent) { + + return new Text(parent, SWT.BORDER | SWT.WRAP | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); + } ++ ++ protected StyledText newCodeField(Composite parent) { ++ ++ return new StyledText(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL); ++ } ++ + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java +index 7527a975672..c2dffaa3bea 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/CreateRuleWizard.java +@@ -9,6 +9,7 @@ + + import org.eclipse.jface.wizard.IWizardPage; + import org.eclipse.jface.wizard.Wizard; ++import org.eclipse.jface.wizard.WizardDialog; + + /** + * A wizard that encapsulates a succession of rule panel managers to collect the +@@ -18,18 +19,24 @@ + */ + public class CreateRuleWizard extends Wizard implements ValueChangeListener, RuleTarget { + +- private Rule rule; +- ++ private Rule rule; ++ private WizardDialog dialog; ++ + public CreateRuleWizard() { + super(); + } + ++ public void dialog(WizardDialog theDialog) { ++ dialog = theDialog; ++ } ++ + public Rule rule() { + return rule; + } + + public void rule(Rule theRule) { + rule = theRule; ++ dialog.updateButtons(); + } + + public void addPages() { +@@ -38,7 +45,7 @@ public void addPages() { + addPage(new PerRulePropertyPanelManager(""properties"", EditorUsageMode.CreateNew, this)); + addPage(new XPathPanelManager(""xpath"", EditorUsageMode.CreateNew, this)); + addPage(new ExclusionPanelManager(""exclusion"", EditorUsageMode.CreateNew, this, false)); +- addPage(new QuickFixPanelManager(""fixes"", EditorUsageMode.CreateNew, this)); ++// addPage(new QuickFixPanelManager(""fixes"", EditorUsageMode.CreateNew, this)); + addPage(new ExamplePanelManager(""examples"", EditorUsageMode.CreateNew, this)); + } + +@@ -82,7 +89,8 @@ public IWizardPage getNextPage(IWizardPage currentPage) { + getAndPrepare(ExclusionPanelManager.ID); + } + if (currentPage instanceof ExclusionPanelManager || currentPage instanceof XPathPanelManager) { +- return getAndPrepare(QuickFixPanelManager.ID); ++// return getAndPrepare(QuickFixPanelManager.ID); ++ return getAndPrepare(ExamplePanelManager.ID); + } + if (currentPage instanceof QuickFixPanelManager) { + return getAndPrepare(ExamplePanelManager.ID); +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java +index 6f24e8971f7..e661cf0ef0d 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExamplePanelManager.java +@@ -5,18 +5,20 @@ + + import net.sourceforge.pmd.PMD; + import net.sourceforge.pmd.Rule; ++import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; + import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; + import net.sourceforge.pmd.lang.rule.RuleReference; + import net.sourceforge.pmd.util.StringUtil; + + import org.eclipse.swt.SWT; ++import org.eclipse.swt.custom.StyledText; ++import org.eclipse.swt.events.ModifyListener; + import org.eclipse.swt.layout.GridData; + import org.eclipse.swt.layout.GridLayout; + import org.eclipse.swt.widgets.Composite; + import org.eclipse.swt.widgets.Control; + import org.eclipse.swt.widgets.Event; + import org.eclipse.swt.widgets.Listener; +-import org.eclipse.swt.widgets.Text; + + /** + * +@@ -24,8 +26,9 @@ + */ + public class ExamplePanelManager extends AbstractRulePanelManager { + +- private Text exampleField; +- ++ private StyledText exampleField; ++ private ModifyListener modifyListener; ++ + public static final String ID = ""example""; + + public ExamplePanelManager(String theTitle, EditorUsageMode theMode, ValueChangeListener theListener) { +@@ -61,7 +64,7 @@ public Control setupOn(Composite parent) { + GridLayout layout = new GridLayout(2, false); + panel.setLayout(layout); + +- exampleField = newTextField(panel); ++ exampleField = newCodeField(panel); + gridData = new GridData(GridData.FILL_BOTH); + gridData.grabExcessHorizontalSpace = true; + gridData.horizontalSpan = 1; +@@ -77,11 +80,11 @@ public void handleEvent(Event event) { + + if (StringUtil.areSemanticEquals(existingValue, cleanValue)) return; + +- soleRule.setDescription(cleanValue); ++ soleRule.setDescription(cleanValue); + valueChanged(null, cleanValue); + } + }); +- ++ + return panel; + } + +@@ -127,6 +130,11 @@ protected void adapt() { + shutdown(exampleField); + } else { + show(exampleField, examples(soleRule)); ++ modifyListener = SyntaxManager.adapt( ++ exampleField, ++ soleRule.getLanguage().getTerseName(), ++ modifyListener ++ ); + } + } + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java +index ffe2bbe69b4..791d79833d7 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/ExclusionPanelManager.java +@@ -4,6 +4,7 @@ + import java.util.List; + + import net.sourceforge.pmd.Rule; ++import net.sourceforge.pmd.eclipse.ui.editors.SyntaxManager; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; + import net.sourceforge.pmd.eclipse.ui.preferences.editors.SWTUtil; +@@ -11,6 +12,7 @@ + import net.sourceforge.pmd.lang.rule.properties.StringProperty; + + import org.eclipse.swt.SWT; ++import org.eclipse.swt.custom.StyledText; + import org.eclipse.swt.events.ModifyEvent; + import org.eclipse.swt.events.ModifyListener; + import org.eclipse.swt.layout.GridData; +@@ -28,7 +30,7 @@ + public class ExclusionPanelManager extends AbstractRulePanelManager { + + private Text excludeWidget; +- private Text xpathWidget; ++ private StyledText xpathWidget; + private Composite excludeColour; + private Composite xPathColour; + private ColourManager colourManager; +@@ -79,6 +81,23 @@ public void modifyText(ModifyEvent e) { + }); + } + ++ private void addListeners(final StyledText control, final StringProperty desc, final Control colourWindow) { ++ ++ addTextListeners(control, desc); ++ ++ control.addModifyListener(new ModifyListener() { ++ public void modifyText(ModifyEvent e) { ++ String newText = control.getText(); ++ if (colourWindow != null) { ++ colourWindow.setBackground( ++ colourManager.colourFor(newText) ++ ); ++ } ++ changed(desc, newText); ++ } ++ }); ++ } ++ + private Composite newColourPanel(Composite parent, String label) { + + Composite panel = new Composite(parent, SWT.None); +@@ -158,11 +177,12 @@ public Control setupOn(Composite parent) { + gridData = new GridData(GridData.FILL_BOTH); + gridData.horizontalSpan = 2; + gridData.grabExcessHorizontalSpace = true; +- xpathWidget = newTextField(panel); ++ xpathWidget = newCodeField(panel); + xpathWidget.setLayoutData(gridData); +- ++ SyntaxManager.adapt(xpathWidget, ""xpath"", null); ++ + addListeners(xpathWidget, Rule.VIOLATION_SUPPRESS_XPATH_DESCRIPTOR, xPathColour); +- ++ + panel.pack(); + + return panel; +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java +index d404cee62bb..f689655d0c0 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/FormArranger.java +@@ -10,6 +10,7 @@ + import net.sourceforge.pmd.eclipse.ui.PMDUiConstants; + import net.sourceforge.pmd.eclipse.ui.preferences.br.EditorFactory; + import net.sourceforge.pmd.eclipse.ui.preferences.br.NewPropertyDialog; ++import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleUtil; + import net.sourceforge.pmd.eclipse.ui.preferences.br.SizeChangeListener; + import net.sourceforge.pmd.eclipse.ui.preferences.br.ValueChangeListener; + import net.sourceforge.pmd.eclipse.util.ResourceManager; +@@ -200,7 +201,7 @@ public void widgetSelected(SelectionEvent e) { + */ + public List updateDeleteButtons() { + +- if (rule == null || !rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) { ++ if (rule == null || !RuleUtil.isXPathRule(rule)) { + return Collections.emptyList(); + } + +@@ -208,7 +209,7 @@ public List updateDeleteButtons() { + List refPositions = Util.referencedNamePositionsIn(source, '$'); + if (refPositions.isEmpty()) return Collections.emptyList(); + +- List unreferenced = new ArrayList(refPositions.size()); ++ List unreferencedOnes = new ArrayList(refPositions.size()); + List varNames = Util.fragmentsWithin(source, refPositions); + + for (Control[] widgetRow : widgets) { +@@ -221,9 +222,9 @@ public List updateDeleteButtons() { + ""Delete variable: $"" + buttonName : + ""Delete unreferenced variable: $"" + buttonName + ); +- if (!isReferenced) unreferenced.add((String) butt.getData()); ++ if (!isReferenced) unreferencedOnes.add((String) butt.getData()); + } + +- return unreferenced; ++ return unreferencedOnes; + }; + } +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java +index 8ab9fea8db9..4e00c5ff029 100644 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/PerRulePropertyPanelManager.java +@@ -7,6 +7,7 @@ + import java.util.List; + import java.util.Map; + ++import net.sourceforge.pmd.PropertyDescriptor; + import net.sourceforge.pmd.Rule; + import net.sourceforge.pmd.eclipse.ui.preferences.br.EditorFactory; + import net.sourceforge.pmd.eclipse.ui.preferences.br.SizeChangeListener; +@@ -78,7 +79,14 @@ public PerRulePropertyPanelManager(String theTitle, EditorUsageMode theMode, Val + protected boolean canManageMultipleRules() { return false; } + + protected boolean canWorkWith(Rule rule) { +- if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) return true; ++ ++ // TODO if (rule.hasDescriptor(XPathRule.XPATH_DESCRIPTOR)) return true; won't work, need to tweak Rule implementation as map is empty ++ ++ // alternate approach for now ++ for (PropertyDescriptor desc : rule.getPropertyDescriptors()) { ++ if (desc.equals(XPathRule.XPATH_DESCRIPTOR)) return true; ++ } ++ + return !Configuration.filteredPropertiesOf(rule).isEmpty(); + } + +diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java +index c459ffa8088..b04e8de674f 100755 +--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java ++++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/panelmanagers/RulePanelManager.java +@@ -12,6 +12,7 @@ + import net.sourceforge.pmd.RuleSet; + import net.sourceforge.pmd.eclipse.plugin.PMDPlugin; + import net.sourceforge.pmd.eclipse.plugin.UISettings; ++import net.sourceforge.pmd.eclipse.ui.ShapePicker; + import net.sourceforge.pmd.eclipse.ui.nls.StringKeys; + import net.sourceforge.pmd.eclipse.ui.preferences.br.ImplementationType; + import net.sourceforge.pmd.eclipse.ui.preferences.br.RuleFieldAccessor; +@@ -55,7 +56,7 @@ public class RulePanelManager extends AbstractRulePanelManager { + private Button ruleReferenceButton; + private Combo languageCombo; + private Combo priorityCombo; +- private ShapeSetCanvas priorityDisplay; ++ private ShapePicker priorityDisplay; + + private Label minLanguageLabel; + private Label maxLanguageLabel; +@@ -68,6 +69,8 @@ public class RulePanelManager extends AbstractRulePanelManager { + private Button usesDfaButton; + private List

++ ++ ++ ++
++ ++ ++
++ ++
++
++ ++ +diff --git a/deltaspike/modules/jsf/impl/src/test/resources/viewScopedContextTest/page.xhtml b/deltaspike/modules/jsf/impl/src/test/resources/viewScopedContextTest/page.xhtml +index ead52307f..627404016 100644 +--- a/deltaspike/modules/jsf/impl/src/test/resources/viewScopedContextTest/page.xhtml ++++ b/deltaspike/modules/jsf/impl/src/test/resources/viewScopedContextTest/page.xhtml +@@ -26,9 +26,6 @@ + xmlns:c=""http://java.sun.com/jsp/jstl/core""> + + +-
+- it works! +-
+
+ + " +f00ea151341c3b7a481ed512e124349990fa8c15,Vala,"libgnomeui-2.0: Update to 2.24.2. +",c,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +f64233fb2d9bcb77e9249d3bc497fd9d110e6a9f,ReactiveX-RxJava,Add Single.fromCallable()--,a,https://github.com/ReactiveX/RxJava,"diff --git a/src/main/java/rx/Single.java b/src/main/java/rx/Single.java +index 4324d32acf..3701d93189 100644 +--- a/src/main/java/rx/Single.java ++++ b/src/main/java/rx/Single.java +@@ -12,6 +12,7 @@ + */ + package rx; + ++import java.util.concurrent.Callable; + import java.util.concurrent.Future; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; +@@ -605,6 +606,43 @@ public final static Single from(Future future, Scheduler sch + return new Single(OnSubscribeToObservableFuture.toObservableFuture(future)).subscribeOn(scheduler); + } + ++ /** ++ * Returns a {@link Single} that invokes passed function and emits its result for each new Observer that subscribes. ++ *

++ * Allows you to defer execution of passed function until Observer subscribes to the {@link Single}. ++ * It makes passed function ""lazy"". ++ * Result of the function invocation will be emitted by the {@link Single}. ++ *

++ *
Scheduler:
++ *
{@code fromCallable} does not operate by default on a particular {@link Scheduler}.
++ *
++ * ++ * @param func ++ * function which execution should be deferred, it will be invoked when Observer will subscribe to the {@link Single}. ++ * @param ++ * the type of the item emitted by the {@link Single}. ++ * @return a {@link Single} whose {@link Observer}s' subscriptions trigger an invocation of the given function. ++ */ ++ @Experimental ++ public static Single fromCallable(final Callable func) { ++ return create(new OnSubscribe() { ++ @Override ++ public void call(SingleSubscriber singleSubscriber) { ++ final T value; ++ ++ try { ++ value = func.call(); ++ } catch (Throwable t) { ++ Exceptions.throwIfFatal(t); ++ singleSubscriber.onError(t); ++ return; ++ } ++ ++ singleSubscriber.onSuccess(value); ++ } ++ }); ++ } ++ + /** + * Returns a {@code Single} that emits a specified item. + *

+diff --git a/src/test/java/rx/SingleTest.java b/src/test/java/rx/SingleTest.java +index 7d8fe2dc22..f78151b094 100644 +--- a/src/test/java/rx/SingleTest.java ++++ b/src/test/java/rx/SingleTest.java +@@ -20,8 +20,10 @@ + import static org.mockito.Mockito.mock; + import static org.mockito.Mockito.verify; + import static org.mockito.Mockito.verifyZeroInteractions; ++import static org.mockito.Mockito.when; + + import java.util.Arrays; ++import java.util.concurrent.Callable; + import java.util.concurrent.CountDownLatch; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; +@@ -530,4 +532,42 @@ public void doOnErrorShouldThrowCompositeExceptionIfOnErrorActionThrows() { + + verify(action).call(error); + } ++ ++ @Test ++ public void shouldEmitValueFromCallable() throws Exception { ++ Callable callable = mock(Callable.class); ++ ++ when(callable.call()).thenReturn(""value""); ++ ++ TestSubscriber testSubscriber = new TestSubscriber(); ++ ++ Single ++ .fromCallable(callable) ++ .subscribe(testSubscriber); ++ ++ testSubscriber.assertValue(""value""); ++ testSubscriber.assertNoErrors(); ++ ++ verify(callable).call(); ++ } ++ ++ @Test ++ public void shouldPassErrorFromCallable() throws Exception { ++ Callable callable = mock(Callable.class); ++ ++ Throwable error = new IllegalStateException(); ++ ++ when(callable.call()).thenThrow(error); ++ ++ TestSubscriber testSubscriber = new TestSubscriber(); ++ ++ Single ++ .fromCallable(callable) ++ .subscribe(testSubscriber); ++ ++ testSubscriber.assertNoValues(); ++ testSubscriber.assertError(error); ++ ++ verify(callable).call(); ++ } + }" +7b22bc146b318790552aa8ec1ece25a3a06d1316,Valadoc,"Add support for cgraphs + +Based on patch by Richard Schwarting + +Fixes bug 703688. +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +c9a360e36059aa46d7090e879762d44d54fa2782,hbase,HBASE-7197. Add multi get to RemoteHTable- (Elliott Clark)--git-svn-id: https://svn.apache.org/repos/asf/hbase/trunk@1422143 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java +index beebe960b05b..92fe09202f61 100644 +--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java ++++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/rest/client/RemoteHTable.java +@@ -148,6 +148,29 @@ protected String buildRowSpec(final byte[] row, final Map familyMap, + return sb.toString(); + } + ++ protected String buildMultiRowSpec(final byte[][] rows, int maxVersions) { ++ StringBuilder sb = new StringBuilder(); ++ sb.append('/'); ++ sb.append(Bytes.toStringBinary(name)); ++ sb.append(""/multiget/""); ++ if (rows == null || rows.length == 0) { ++ return sb.toString(); ++ } ++ sb.append(""?""); ++ for(int i=0; i results = new ArrayList(); + for (RowModel row: model.getRows()) { +@@ -273,31 +296,66 @@ public Result get(Get get) throws IOException { + if (get.getFilter() != null) { + LOG.warn(""filters not supported on gets""); + } ++ Result[] results = getResults(spec); ++ if (results.length > 0) { ++ if (results.length > 1) { ++ LOG.warn(""too many results for get ("" + results.length + "")""); ++ } ++ return results[0]; ++ } else { ++ return new Result(); ++ } ++ } ++ ++ public Result[] get(List gets) throws IOException { ++ byte[][] rows = new byte[gets.size()][]; ++ int maxVersions = 1; ++ int count = 0; ++ ++ for(Get g:gets) { ++ ++ if ( count == 0 ) { ++ maxVersions = g.getMaxVersions(); ++ } else if (g.getMaxVersions() != maxVersions) { ++ LOG.warn(""MaxVersions on Gets do not match, using the first in the list (""+maxVersions+"")""); ++ } ++ ++ if (g.getFilter() != null) { ++ LOG.warn(""filters not supported on gets""); ++ } ++ ++ rows[count] = g.getRow(); ++ count ++; ++ } ++ ++ String spec = buildMultiRowSpec(rows, maxVersions); ++ ++ return getResults(spec); ++ } ++ ++ private Result[] getResults(String spec) throws IOException { + for (int i = 0; i < maxRetries; i++) { + Response response = client.get(spec, Constants.MIMETYPE_PROTOBUF); + int code = response.getCode(); + switch (code) { +- case 200: +- CellSetModel model = new CellSetModel(); +- model.getObjectFromMessage(response.getBody()); +- Result[] results = buildResultFromModel(model); +- if (results.length > 0) { +- if (results.length > 1) { +- LOG.warn(""too many results for get ("" + results.length + "")""); ++ case 200: ++ CellSetModel model = new CellSetModel(); ++ model.getObjectFromMessage(response.getBody()); ++ Result[] results = buildResultFromModel(model); ++ if ( results.length > 0) { ++ return results; + } +- return results[0]; +- } +- // fall through +- case 404: +- return new Result(); ++ // fall through ++ case 404: ++ return new Result[0]; + +- case 509: +- try { +- Thread.sleep(sleepTime); +- } catch (InterruptedException e) { } +- break; +- default: +- throw new IOException(""get request returned "" + code); ++ case 509: ++ try { ++ Thread.sleep(sleepTime); ++ } catch (InterruptedException e) { } ++ break; ++ default: ++ throw new IOException(""get request returned "" + code); + } + } + throw new IOException(""get request timed out""); +@@ -708,11 +766,6 @@ public Object[] batchCallback(List actions, Batch.Callback + throw new IOException(""batchCallback not supported""); + } + +- @Override +- public Result[] get(List gets) throws IOException { +- throw new IOException(""get(List) not supported""); +- } +- + @Override + public T coprocessorProxy(Class protocol, + byte[] row) { +diff --git a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java +index 01e23d99a0ed..b52a167fbbc9 100644 +--- a/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java ++++ b/hbase-server/src/test/java/org/apache/hadoop/hbase/rest/client/TestRemoteTable.java +@@ -216,6 +216,45 @@ public void testGet() throws IOException { + assertEquals(2, count); + } + ++ @Test ++ public void testMultiGet() throws Exception { ++ ArrayList gets = new ArrayList(); ++ gets.add(new Get(ROW_1)); ++ gets.add(new Get(ROW_2)); ++ Result[] results = remoteTable.get(gets); ++ assertNotNull(results); ++ assertEquals(2, results.length); ++ assertEquals(1, results[0].size()); ++ assertEquals(2, results[1].size()); ++ ++ //Test Versions ++ gets = new ArrayList(); ++ Get g = new Get(ROW_1); ++ g.setMaxVersions(3); ++ gets.add(g); ++ gets.add(new Get(ROW_2)); ++ results = remoteTable.get(gets); ++ assertNotNull(results); ++ assertEquals(2, results.length); ++ assertEquals(1, results[0].size()); ++ assertEquals(3, results[1].size()); ++ ++ //404 ++ gets = new ArrayList(); ++ gets.add(new Get(Bytes.toBytes(""RESALLYREALLYNOTTHERE""))); ++ results = remoteTable.get(gets); ++ assertNotNull(results); ++ assertEquals(0, results.length); ++ ++ gets = new ArrayList(); ++ gets.add(new Get(Bytes.toBytes(""RESALLYREALLYNOTTHERE""))); ++ gets.add(new Get(ROW_1)); ++ gets.add(new Get(ROW_2)); ++ results = remoteTable.get(gets); ++ assertNotNull(results); ++ assertEquals(0, results.length); ++ } ++ + @Test + public void testPut() throws IOException { + Put put = new Put(ROW_3);" +50ccd7ec86dc105c4c6030cd152423ec7b1483a2,restlet-framework-java,JAX-RS-Extension: - added javadoc to util methods.--,p,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java +index 1378510e3c..0df57b574c 100644 +--- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java ++++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/util/Util.java +@@ -41,7 +41,6 @@ + import java.util.Map; + import java.util.NoSuchElementException; + import java.util.Set; +-import java.util.TreeSet; + import java.util.logging.Logger; + + import javax.ws.rs.Path; +@@ -334,19 +333,6 @@ public static Set createSet(A... objects) { + return set; + } + +- /** +- * @param +- * @param collection +- * @param comparator +- * @return +- */ +- public static Collection createTreeSet(Collection collection, +- Comparator comparator) { +- Collection coll2 = new TreeSet(comparator); +- coll2.addAll(collection); +- return coll2; +- } +- + /** + * Check if the given objects are equal. Can deal with null references. if + * both elements are null, than the result is true. +@@ -362,7 +348,7 @@ public static boolean equals(Object object1, Object object2) { + } + + /** +- * Converte the given Date into a String. Copied from ++ * Converts the given Date into a String. Copied from + * {@link com.noelios.restlet.HttpCall}. + * + * @param date +@@ -380,16 +366,19 @@ public static String formatDate(Date date, boolean cookie) { + } + + /** ++ * Returns the first element of the given collection. Throws an exception if ++ * the collection is empty. ++ * + * @param coll + * @param + * @return Returns the first Element of the collection +- * @throws IndexOutOfBoundsException +- * If the list is empty ++ * @throws NoSuchElementException ++ * If the collection is empty. + */ + public static A getFirstElement(Collection coll) +- throws IndexOutOfBoundsException { ++ throws NoSuchElementException { + if (coll.isEmpty()) +- throw new IndexOutOfBoundsException( ++ throw new NoSuchElementException( + ""The Collection is empty; you can't get the first element of it.""); + if (coll instanceof LinkedList) + return ((LinkedList) coll).getFirst(); +@@ -399,14 +388,17 @@ public static A getFirstElement(Collection coll) + } + + /** ++ * Returns the first element of the given {@link Iterable}. Throws an ++ * exception if the {@link Iterable} is empty. ++ * + * @param coll + * @param + * @return Returns the first Element of the collection +- * @throws IndexOutOfBoundsException +- * If the list is empty ++ * @throws NoSuchElementException ++ * If the collection is empty + */ + public static A getFirstElement(Iterable coll) +- throws IndexOutOfBoundsException { ++ throws NoSuchElementException { + if (coll instanceof LinkedList) + return ((LinkedList) coll).getFirst(); + if (coll instanceof List) +@@ -415,6 +407,9 @@ public static A getFirstElement(Iterable coll) + } + + /** ++ * Returns the first element of the {@link List}. Throws an exception if ++ * the list is empty. ++ * + * @param list + * @param + * @return Returns the first Element of the collection +@@ -432,14 +427,15 @@ public static A getFirstElement(List list) + } + + /** ++ * Returns the first element of the given {@link Iterable}. Returns null, ++ * if the {@link Iterable} is empty. ++ * + * @param coll + * @param +- * @return Returns the first Element of the collection +- * @throws IndexOutOfBoundsException +- * If the list is empty ++ * @return the first element of the collection, or null if the iterable is ++ * empty. + */ +- public static A getFirstElementOrNull(Iterable coll) +- throws IndexOutOfBoundsException { ++ public static A getFirstElementOrNull(Iterable coll) { + if (coll instanceof LinkedList) { + LinkedList linkedList = ((LinkedList) coll); + if (linkedList.isEmpty()) +@@ -460,12 +456,13 @@ public static A getFirstElementOrNull(Iterable coll) + } + + /** ++ * Returns the first entry of the given {@link Map}. Throws an exception if ++ * the Map is empty. ++ * + * @param map + * @param + * @param +- * @return Returns the first element, returned by the iterator over the +- * map.entrySet() +- * ++ * @return the first entry of the given {@link Map}. + * @throws NoSuchElementException + * If the map is empty. + */ +@@ -475,12 +472,13 @@ public static Map.Entry getFirstEntry(Map map) + } + + /** +- * @return Returns the first element, returned by the iterator over the +- * map.keySet() ++ * Returns the key of the first entry of the given {@link Map}. Throws an ++ * exception if the Map is empty. + * + * @param map + * @param + * @param ++ * @return the key of the first entry of the given {@link Map}. + * @throws NoSuchElementException + * If the map is empty. + */ +@@ -490,11 +488,13 @@ public static K getFirstKey(Map map) + } + + /** +- * @return Returns the first element, returned by the iterator over the +- * map.values() ++ * Returns the value of the first entry of the given {@link Map}. Throws an ++ * exception if the Map is empty. ++ * + * @param map + * @param + * @param ++ * @return the value of the first entry of the given {@link Map}. + * @throws NoSuchElementException + * If the map is empty. + */ +@@ -504,8 +504,10 @@ public static V getFirstValue(Map map) + } + + /** ++ * Returns the HTTP headers of the Restlet {@link Request} as {@link Form}. ++ * + * @param request +- * @return Returns the HTTP-Headers-Form from the Request. ++ * @return Returns the HTTP headers of the Request. + */ + public static Form getHttpHeaders(Request request) { + Form headers = (Form) request.getAttributes().get( +@@ -518,9 +520,10 @@ public static Form getHttpHeaders(Request request) { + } + + /** ++ * Returns the HTTP headers of the Restlet {@link Response} as {@link Form}. ++ * + * @param response +- * a Restlet response +- * @return Returns the HTTP-Headers-Form from the Response. ++ * @return Returns the HTTP headers of the Response. + */ + public static Form getHttpHeaders(Response response) { + Form headers = (Form) response.getAttributes().get( +@@ -553,9 +556,12 @@ public static MultivaluedMap getJaxRsHttpHeaders( + } + + /** ++ * Returns the last element of the given {@link Iterable}. Throws an ++ * exception if the given iterable is empty. ++ * + * @param iterable + * @param +- * @return Returns the last Element of the {@link Iterable} ++ * @return Returns the last element of the {@link Iterable} + * @throws IndexOutOfBoundsException + * If the {@link Iterable} is a {@link List} and its is + * empty. +@@ -575,9 +581,12 @@ public static A getLastElement(Iterable iterable) + } + + /** ++ * Returns the last element of the given {@link Iterator}. Throws an ++ * exception if the given iterator is empty. ++ * + * @param iter + * @param +- * @return Returns the last Element of the {@link Iterator}. ++ * @return Returns the last element of the {@link Iterator}. + * @throws NoSuchElementException + * If the {@link Iterator} is empty. + */ +@@ -590,9 +599,12 @@ public static A getLastElement(Iterator iter) + } + + /** ++ * Returns the last element of the given {@link List}. Throws an exception ++ * if the given list is empty. ++ * + * @param list + * @param +- * @return Returns the last Element of the list ++ * @return Returns the last element of the list + * @throws IndexOutOfBoundsException + * If the list is empty + */ +@@ -604,7 +616,8 @@ public static A getLastElement(List list) + } + + /** +- * Returns the last element of the given Iterable, or null, if it is empty. ++ * Returns the last element of the given {@link Iterable}, or null, if the ++ * iterable is empty. Returns null, if the iterable is empty. + * + * @param iterable + * @param +@@ -632,11 +645,12 @@ public static A getLastElementOrNull(Iterable iterable) { + } + + /** ++ * Returns the last element of the given {@link Iterator}, or null, if the ++ * iterator is empty. Returns null, if the iterator is empty. ++ * + * @param iter + * @param + * @return Returns the last Element of the {@link Iterator}. +- * @throws NoSuchElementException +- * If the {@link Iterator} is empty. + */ + public static A getLastElementOrNull(Iterator iter) { + A e = null; +@@ -716,9 +730,13 @@ public static String getOnlyMetadataName(List metadatas) { + } + + /** ++ * Returns the @{@link Path} annotation of the given root resource ++ * class. ++ * + * @param jaxRsClass +- * @return the path annotation or null, if no is present and requirePath is +- * false. ++ * the root resource class. ++ * @return the @{@link Path} annotation of the given root resource ++ * class. + * @throws MissingAnnotationException + * if the path annotation is missing + * @throws IllegalArgumentException +@@ -737,9 +755,12 @@ public static Path getPathAnnotation(Class jaxRsClass) + } + + /** ++ * Returns the @{@link Path} annotation of the given sub resource ++ * locator. Throws an exception if no @{@link Path} annotation is ++ * available. ++ * + * @param method + * the java method to get the @Path from +- * @param pathRequired + * @return the @Path annotation. + * @throws IllegalArgumentException + * if null was given. +@@ -759,6 +780,9 @@ public static Path getPathAnnotation(Method method) + } + + /** ++ * Returns the @{@link Path} annotation of the given sub resource ++ * locator. Returns null if no @{@link Path} annotation is available. ++ * + * @param method + * the java method to get the @Path from + * @return the @Path annotation or null, if not present. +@@ -774,6 +798,8 @@ public static Path getPathAnnotationOrNull(Method method) + } + + /** ++ * Returns the perhaps decoded template of the path annotation. ++ * + * @param resource + * @return Returns the path template as String. Never returns null. + * @throws IllegalPathOnClassException +@@ -932,7 +958,7 @@ public Object run() throws Exception { + } + + /** +- * Checks, if the list is empty. ++ * Checks, if the list is empty or null. + * + * @param list + * @return true, if the list is empty or null, or false, if the list +@@ -944,7 +970,7 @@ public static boolean isEmpty(List list) { + } + + /** +- * Tests, if the given array is empty. Will not throw a ++ * Tests, if the given array is empty or null. Will not throw a + * NullPointerException. + * + * @param array +@@ -959,11 +985,12 @@ public static boolean isEmpty(Object[] array) { + } + + /** +- * Tests, if the given String is empty or ""/"". Will not throw a ++ * Tests, if the given String is null, empty or ""/"". Will not throw a + * NullPointerException. + * + * @param string +- * @return Returns true, if the given string ist null, empty or equals ""/"" ++ * @return Returns true, if the given string ist null, empty or equals ""/"", ++ * otherwise false. + */ + public static boolean isEmptyOrSlash(String string) { + return string == null || string.length() == 0 || string.equals(""/""); +diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java +index 7020117cc8..6fb83146e9 100644 +--- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java ++++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/IntoRrcInjector.java +@@ -179,12 +179,11 @@ protected void inject(ResourceObject resourceObject, + } + for (Field ppf : this.injectFieldsPathParam) { + PathParam headerParam = ppf.getAnnotation(PathParam.class); +- DefaultValue defaultValue = ppf.getAnnotation(DefaultValue.class); ++ // REQUEST forbid @DefaultValue on @PathParam + Class convTo = ppf.getType(); + Type paramGenericType = ppf.getGenericType(); + Object value = WrapperUtil.getPathParamValue(convTo, +- paramGenericType, headerParam, leaveEncoded, defaultValue, +- callContext); ++ paramGenericType, headerParam, leaveEncoded, callContext); + Util.inject(jaxRsResObj, ppf, value); + } + for (Field cpf : this.injectFieldsQueryParam) { +diff --git a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java +index c362ef193e..7b0e25733b 100644 +--- a/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java ++++ b/modules/org.restlet.ext.jaxrs_1.0/src/org/restlet/ext/jaxrs/internal/wrappers/WrapperUtil.java +@@ -134,6 +134,8 @@ public void remove() { + private static final Collection> VALID_ANNOTATIONS = createValidAnnotations(); + + /** ++ * Checks, if the given annotation is annotated with at least one JAX-RS ++ * related annotation. + * + * @param javaMethod + * Java method, class or something like that. +@@ -143,7 +145,7 @@ public void remove() { + static boolean checkForJaxRsAnnotations(Method javaMethod) { + for (Annotation annotation : javaMethod.getAnnotations()) { + Class annoType = annotation.annotationType(); +- if (annoType.getName().startsWith(WrapperUtil.JAX_RS_PACKAGE_PREFIX)) ++ if (annoType.getName().startsWith(JAX_RS_PACKAGE_PREFIX)) + return true; + if (annoType.isAnnotationPresent(HttpMethod.class)) + return true; +@@ -217,7 +219,7 @@ private static boolean checkParameterAnnotation( + } + + /** +- * converts the given value without any decoding. ++ * Converts the given value without any decoding. + * + * @param paramClass + * @param paramValue +@@ -419,8 +421,12 @@ static List convertToMediaTypes(String[] mimes) { + } + + /** ++ * Creates the collection for the given ++ * {@link ParameterizedType parametrized Type}.
++ * If the given type do not represent an collection, null is returned. ++ * + * @param type +- * @return ++ * @return the created collection or null. + */ + private static
Collection createColl(ParameterizedType type) { + Type rawType = type.getRawType(); +@@ -432,28 +438,37 @@ else if (rawType.equals(SortedSet.class)) + return new TreeSet(); + else if (rawType.equals(Collection.class)) { + Logger logger = Logger.getAnonymousLogger(); +- logger.config(WrapperUtil.COLL_PARAM_NOT_DEFAULT); ++ logger.config(COLL_PARAM_NOT_DEFAULT); + return new ArrayList(); + } + return null; + } + + /** ++ * Creates a concrete instance of the given {@link Representation} subtype. ++ * It must contain a constructor with one parameter of type ++ * {@link Representation}. ++ * ++ * @param representationType ++ * the class to instantiate + * @param entity ++ * the Representation to use for the constructor. ++ * @param logger ++ * the logger to use + * @return the created representation, or null, if it could not be + * converted. +- * @throws ConvertParameterException ++ * @throws ConvertRepresentationException + */ + private static Object createConcreteRepresentationInstance( +- Class paramType, Representation entity, Logger logger) ++ Class representationType, Representation entity, Logger logger) + throws ConvertRepresentationException { +- if (paramType.equals(Representation.class)) ++ if (representationType.equals(Representation.class)) + return entity; + Constructor constr; + try { +- constr = paramType.getConstructor(Representation.class); ++ constr = representationType.getConstructor(Representation.class); + } catch (SecurityException e) { +- logger.warning(""The constructor "" + paramType ++ logger.warning(""The constructor "" + representationType + + ""(Representation) is not accessable.""); + return null; + } catch (NoSuchMethodException e) { +@@ -462,7 +477,7 @@ private static Object createConcreteRepresentationInstance( + try { + return constr.newInstance(entity); + } catch (Exception e) { +- throw ConvertRepresentationException.object(paramType, ++ throw ConvertRepresentationException.object(representationType, + ""the message body"", e); + } + } +@@ -518,17 +533,14 @@ static Object createInstance(Constructor constructor, + try { + return constructor.newInstance(args); + } catch (IllegalArgumentException e) { +- throw new InstantiateException( +- ""Could not instantiate "" + constructor.getDeclaringClass(), +- e); ++ throw new InstantiateException(""Could not instantiate "" ++ + constructor.getDeclaringClass(), e); + } catch (InstantiationException e) { +- throw new InstantiateException( +- ""Could not instantiate "" + constructor.getDeclaringClass(), +- e); ++ throw new InstantiateException(""Could not instantiate "" ++ + constructor.getDeclaringClass(), e); + } catch (IllegalAccessException e) { +- throw new InstantiateException( +- ""Could not instantiate "" + constructor.getDeclaringClass(), +- e); ++ throw new InstantiateException(""Could not instantiate "" ++ + constructor.getDeclaringClass(), e); + } + } + +@@ -540,11 +552,12 @@ static Collection> createValidAnnotations() { + } + + /** ++ * Finds the constructor to use by the JAX-RS runtime. ++ * + * @param jaxRsClass + * @return Returns the constructor to use for the given root resource class +- * (See JSR-311-Spec, section 2.3). If no constructor could be +- * found, null is returned. Than try {@link Class#newInstance()} +- * @throws IllegalTypeException ++ * or provider. If no constructor could be found, null is returned. ++ * Than try {@link Class#newInstance()} + */ + static Constructor findJaxRsConstructor(Class jaxRsClass) { + Constructor constructor = null; +@@ -608,6 +621,8 @@ static javax.ws.rs.ext.ContextResolver getContextResolver(Field field, + } + + /** ++ * Creates the value of a cookie as the given type. ++ * + * @param paramClass + * the class to convert to + * @param paramGenericType +@@ -674,10 +689,10 @@ static Object getCookieParamValue(Class paramClass, + return convertParamValuesFromParam(paramClass, paramGenericType, + new ParamValueIter((Series) cookies.subList(cookieName)), + getValue(cookies.getFirst(cookieName)), defaultValue, true); ++ // leaveEncoded = true -> not change + } catch (ConvertParameterException e) { + throw new ConvertCookieParamException(e); + } +- // leaveEncoded = true -> not change + } + + /** +@@ -707,6 +722,12 @@ static Object getHeaderParamValue(Class paramClass, + } + } + ++ /** ++ * Returns the HTTP method related to the given java method. ++ * ++ * @param javaMethod ++ * @return ++ */ + static org.restlet.data.Method getHttpMethod(Method javaMethod) { + for (Annotation annotation : javaMethod.getAnnotations()) { + Class annoType = annotation.annotationType(); +@@ -812,8 +833,7 @@ else if (paramClass.equals(Conditions.class)) + } + if (annoType.equals(PathParam.class)) { + return getPathParamValue(paramClass, paramGenericType, +- (PathParam) annotation, leaveEncoded, defaultValue, +- callContext); ++ (PathParam) annotation, leaveEncoded, callContext); + } + if (annoType.equals(MatrixParam.class)) { + return getMatrixParamValue(paramClass, paramGenericType, +@@ -992,15 +1012,13 @@ private static Object getParamValueForPrimitive(Class paramClass, + * the generic type to convert to + * @param pathParam + * @param leaveEncoded +- * @param defaultValue + * @param callContext + * @param logger + * @return + * @throws ConvertPathParamException + */ + static Object getPathParamValue(Class paramClass, Type paramGenericType, +- PathParam pathParam, boolean leaveEncoded, +- DefaultValue defaultValue, CallContext callContext) ++ PathParam pathParam, boolean leaveEncoded, CallContext callContext) + throws ConvertPathParamException { + // LATER testen Path-Param: List (see PathParamTest.testGet3()) + // TODO @PathParam(""x"") PathSegment allowed. +@@ -1008,10 +1026,13 @@ static Object getPathParamValue(Class paramClass, Type paramGenericType, + String pathParamValue = callContext.getLastPathParamEnc(pathParam); + Iterator pathParamValueIter = callContext + .pathParamEncIter(pathParam); ++ // REQUEST What should happens, if no PathParam could be found? ++ // Internal Server Error? It could be that someone request a qPathParam ++ // value of a prior @Path, but this is not good IMO. ++ // perhaps add another attribute to @PathParam, which allows it. + try { + return convertParamValuesFromParam(paramClass, paramGenericType, +- pathParamValueIter, pathParamValue, defaultValue, +- leaveEncoded); ++ pathParamValueIter, pathParamValue, null, leaveEncoded); + } catch (ConvertParameterException e) { + throw new ConvertPathParamException(e); + }" +ceb5861998de2e1a07a7279d3f1d26ecfb2c2dca,Mylyn Reviews,"Simplified some column handling logic + +-avoid repetition of column handling,output,... +",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java +new file mode 100644 +index 00000000..c5400b7d +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ColumnLabelProvider.java +@@ -0,0 +1,39 @@ ++/******************************************************************************* ++ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology ++ * 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: ++ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.ui.editors; ++ ++import org.eclipse.swt.graphics.Image; ++/** ++ * @author mattk ++ * ++ * @param ++ */ ++public class ColumnLabelProvider extends TableLabelProvider { ++ ++ private IColumnSpec[] specs; ++ ++ public ColumnLabelProvider(IColumnSpec[] specs) { ++ this.specs = specs; ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ @Override ++ public Image getColumnImage(Object element, int columnIndex) { ++ return specs[columnIndex].getImage((T) element); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ @Override ++ public String getColumnText(Object element, int columnIndex) { ++ return specs[columnIndex].getText((T) element); ++ } ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java +new file mode 100644 +index 00000000..bb87f4f7 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/IColumnSpec.java +@@ -0,0 +1,28 @@ ++/******************************************************************************* ++ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology ++ * 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: ++ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.ui.editors; ++ ++import org.eclipse.swt.graphics.Image; ++ ++/** ++ * ++ * @author mattk ++ * ++ * @param ++ */ ++public interface IColumnSpec { ++ public String getTitle(); ++ ++ public String getText(T value); ++ ++ public Image getImage(T value); ++ ++} +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java +index 275a43a7..12875b04 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewSummaryTaskEditorPart.java +@@ -21,7 +21,6 @@ + import org.eclipse.jface.viewers.IStructuredSelection; + import org.eclipse.jface.viewers.ITreeContentProvider; + import org.eclipse.jface.viewers.TreeViewer; +-import org.eclipse.jface.viewers.TreeViewerColumn; + import org.eclipse.jface.viewers.Viewer; + import org.eclipse.jface.viewers.ViewerFilter; + import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; +@@ -84,13 +83,68 @@ public void createControl(final Composite parent, FormToolkit toolkit) { + summarySection.setClient(reviewResultsComposite); + setSection(toolkit, summarySection); + } ++ enum Column implements IColumnSpec { ++ TASK(""Task"") { ++ @Override ++ public String getText(ITreeNode value) { ++ return value.getTaskId(); ++ } ++ }, ++ RESULT(Messages.ReviewSummaryTaskEditorPart_Header_Result) { ++ @Override ++ public String getText(ITreeNode value) { ++ return value.getResult() != null ? value.getResult().name() ++ : """"; ++ } ++ ++ @Override ++ public Image getImage(ITreeNode value) { ++ if (value.getResult() == null) ++ return null; ++ switch (value.getResult()) { ++ case FAIL: ++ return Images.REVIEW_RESULT_FAILED.createImage(); ++ case WARNING: ++ return Images.REVIEW_RESULT_WARNING.createImage(); ++ case PASSED: ++ return Images.REVIEW_RESULT_PASSED.createImage(); ++ case TODO: ++ return Images.REVIEW_RESULT_NONE.createImage(); ++ } ++ return null; ++ } ++ }, ++ DESCRIPTION(""Description"") { ++ @Override ++ public String getText(ITreeNode value) { ++ return value.getDescription(); ++ } ++ }, ++ WHO(""Who"") { ++ @Override ++ public String getText(ITreeNode value) { ++ return value.getPerson(); ++ } ++ }; ++ ++ private String title; ++ ++ private Column(String title) { ++ this.title = title; ++ } ++ ++ public String getTitle() { ++ return title; ++ } ++ ++ public String getText(ITreeNode value) { ++ return value != null ? value.toString() : """"; ++ } ++ ++ public Image getImage(ITreeNode value) { ++ return null; ++ } + +- private TreeViewerColumn createColumn(TreeViewer tree, String columnTitle) { +- TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); +- column.getColumn().setText(columnTitle); +- column.getColumn().setWidth(100); +- column.getColumn().setResizable(true); +- return column; + } + + private TreeViewer createResultsViewer(Composite reviewResultsComposite, +@@ -105,67 +159,19 @@ private TreeViewer createResultsViewer(Composite reviewResultsComposite, + } + tree.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TREE_BORDER); + +- TreeViewer reviewResults = new TreeViewer(tree); +- createColumn(reviewResults, ""Task""); +- createColumn(reviewResults, +- Messages.ReviewSummaryTaskEditorPart_Header_Result); +- createColumn(reviewResults, ""Description""); +- createColumn(reviewResults, ""Who""); ++ TreeViewer reviewResults = createTreeWithColumns(tree); + + reviewResults.setContentProvider(new ReviewResultContentProvider()); + +- reviewResults.setLabelProvider(new TableLabelProvider() { +- private static final int COLUMN_TASK_ID = 0; +- private static final int COLUMN_RESULT = 1; +- private static final int COLUMN_DESCRIPTION = 2; +- private static final int COLUMN_WHO = 3; +- +- public Image getColumnImage(Object element, int columnIndex) { +- if (columnIndex == COLUMN_RESULT) { +- ITreeNode node = (ITreeNode) element; +- if (node.getResult() == null) +- return null; +- switch (node.getResult()) { +- case FAIL: +- return Images.REVIEW_RESULT_FAILED.createImage(); +- case WARNING: +- return Images.REVIEW_RESULT_WARNING.createImage(); +- case PASSED: +- return Images.REVIEW_RESULT_PASSED.createImage(); +- case TODO: +- return Images.REVIEW_RESULT_NONE.createImage(); +- +- } +- } +- return null; +- } +- +- public String getColumnText(Object element, int columnIndex) { +- +- ITreeNode node = (ITreeNode) element; +- switch (columnIndex) { +- case COLUMN_TASK_ID: +- return node.getTaskId(); +- case COLUMN_RESULT: +- return node.getResult() != null ? node.getResult().name() +- : """"; +- case COLUMN_DESCRIPTION: +- return node.getDescription(); +- case COLUMN_WHO: +- return node.getPerson(); +- default: +- return null; +- } +- } +- +- }); ++ reviewResults.setLabelProvider(new ColumnLabelProvider( ++ Column.values())); + reviewResults.addDoubleClickListener(new IDoubleClickListener() { + + public void doubleClick(DoubleClickEvent event) { + if (!event.getSelection().isEmpty()) { + ITreeNode treeNode = (ITreeNode) ((IStructuredSelection) event + .getSelection()).getFirstElement(); +- if(treeNode instanceof ReviewResultNode) { ++ if (treeNode instanceof ReviewResultNode) { + treeNode = treeNode.getParent(); + } + ITaskProperties task = treeNode.getTask(); +@@ -176,6 +182,13 @@ public void doubleClick(DoubleClickEvent event) { + return reviewResults; + } + ++ private TreeViewer createTreeWithColumns(Tree tree) { ++ TreeViewer reviewResults = new TreeViewer(tree); ++ return TreeHelper.createColumns(reviewResults, Column.values()); ++ } ++ ++ ++ + private final class ScopeViewerFilter extends ViewerFilter { + @Override + public boolean select(Viewer viewer, Object parentElement, +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java +index 327e148d..d8bf6cb5 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/ReviewTaskEditorPart.java +@@ -37,14 +37,13 @@ + import org.eclipse.jface.viewers.TreeNode; + import org.eclipse.jface.viewers.TreeNodeContentProvider; + import org.eclipse.jface.viewers.TreeViewer; +-import org.eclipse.jface.viewers.TreeViewerColumn; + import org.eclipse.mylyn.reviews.tasks.core.IReviewFile; + import org.eclipse.mylyn.reviews.tasks.core.IReviewMapper; ++import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem; + import org.eclipse.mylyn.reviews.tasks.core.ITaskProperties; + import org.eclipse.mylyn.reviews.tasks.core.Rating; + import org.eclipse.mylyn.reviews.tasks.core.ReviewResult; + import org.eclipse.mylyn.reviews.tasks.core.ReviewScope; +-import org.eclipse.mylyn.reviews.tasks.core.IReviewScopeItem; + import org.eclipse.mylyn.reviews.tasks.core.internal.TaskProperties; + import org.eclipse.mylyn.reviews.tasks.ui.Images; + import org.eclipse.mylyn.reviews.tasks.ui.ReviewsUiPlugin; +@@ -84,6 +83,73 @@ public ReviewTaskEditorPart() { + setExpandVertically(true); + } + ++ private enum Column implements IColumnSpec { ++ GROUP(""Group"") { ++ @Override ++ public String getText(TreeNode node) { ++ Object value = node.getValue(); ++ if (value instanceof IReviewScopeItem) { ++ return ((IReviewScopeItem) value).getDescription(); ++ } ++ return null; ++ } ++ }, ++ FILES(""Filename"") { ++ @Override ++ public String getText(TreeNode node) { ++ Object value = node.getValue(); ++ if (value instanceof IReviewFile) { ++ return ((IReviewFile) value).getFileName(); ++ } ++ return null; ++ } ++ ++ @Override ++ public Image getImage(TreeNode node) { ++ Object element = node.getValue(); ++ if (element instanceof IReviewFile) { ++ ISharedImages sharedImages = PlatformUI.getWorkbench() ++ .getSharedImages(); ++ IReviewFile file = ((IReviewFile) element); ++ if (file.isNewFile()) { ++ return new NewFile().createImage(); ++ } ++ if (!file.canReview()) { ++ return new MissingFile().createImage(); ++ } ++ ++ return sharedImages.getImage(ISharedImages.IMG_OBJ_FILE); ++ } ++ return null; ++ } ++ }; ++ ++ /* ++ * Object element = ((TreeNode) node).getValue(); if (columnIndex == ++ * COLUMN_FILE) { ++ * ++ * } } return null; ++ */ ++ private String title; ++ ++ private Column(String title) { ++ this.title = title; ++ } ++ ++ public String getTitle() { ++ return title; ++ } ++ ++ public String getText(TreeNode value) { ++ return value != null ? value.toString() : """"; ++ } ++ ++ public Image getImage(TreeNode value) { ++ return null; ++ } ++ ++ } ++ + @Override + public void createControl(Composite parent, FormToolkit toolkit) { + section = createSection(parent, toolkit, true); +@@ -93,7 +159,7 @@ public void createControl(Composite parent, FormToolkit toolkit) { + gd.horizontalSpan = 4; + section.setLayout(gl); + section.setLayoutData(gd); +-setSection(toolkit, section); ++ setSection(toolkit, section); + + composite = toolkit.createComposite(section); + +@@ -104,55 +170,12 @@ public void createControl(Composite parent, FormToolkit toolkit) { + fileList.getControl().setLayoutData( + new GridData(SWT.FILL, SWT.FILL, true, true)); + +- createColumn(fileList, ""Group"", 100); +- createColumn(fileList, ""Filename"", 100); ++ TreeHelper.createColumns(fileList, Column.values()); + fileList.getTree().setLinesVisible(true); + fileList.getTree().setHeaderVisible(true); + +- fileList.setLabelProvider(new TableLabelProvider() { +- private final int COLUMN_GROUP = 0; +- private final int COLUMN_FILE = 1; +- +- @Override +- public String getColumnText(Object node, int columnIndex) { +- Object element = ((TreeNode) node).getValue(); +- switch (columnIndex) { +- case COLUMN_GROUP: +- if (element instanceof IReviewScopeItem) { +- return ((IReviewScopeItem) element).getDescription(); +- } +- break; +- case COLUMN_FILE: +- if (element instanceof IReviewFile) { +- return ((IReviewFile) element).getFileName(); +- } +- break; +- } +- return null; +- } +- +- @Override +- public Image getColumnImage(Object node, int columnIndex) { +- Object element = ((TreeNode) node).getValue(); +- if (element instanceof IReviewFile) { +- if (columnIndex == COLUMN_FILE) { +- ISharedImages sharedImages = PlatformUI.getWorkbench() +- .getSharedImages(); +- IReviewFile file = ((IReviewFile) element); +- if (file.isNewFile()) { +- return new NewFile().createImage(); +- } +- if (!file.canReview()) { +- return new MissingFile().createImage(); +- } +- +- return sharedImages +- .getImage(ISharedImages.IMG_OBJ_FILE); +- } +- } +- return null; +- } +- }); ++ fileList.setLabelProvider(new ColumnLabelProvider(Column ++ .values())); + + fileList.setContentProvider(new TreeNodeContentProvider()); + fileList.addDoubleClickListener(new IDoubleClickListener() { +@@ -161,7 +184,8 @@ public void doubleClick(DoubleClickEvent event) { + ISelection selection = event.getSelection(); + if (selection instanceof IStructuredSelection) { + IStructuredSelection sel = (IStructuredSelection) selection; +- Object value = ((TreeNode)sel.getFirstElement()).getValue(); ++ Object value = ((TreeNode) sel.getFirstElement()) ++ .getValue(); + if (value instanceof IReviewFile) { + final IReviewFile file = (IReviewFile) value; + if (file.canReview()) { +@@ -224,7 +248,7 @@ public void run() throws Exception { + return; + } + List files = reviewScope.getItems(); +- ++ + final TreeNode[] rootNodes = new TreeNode[files.size()]; + int index = 0; + for (IReviewScopeItem item : files) { +@@ -244,8 +268,8 @@ public void run() throws Exception { + Display.getCurrent().asyncExec(new Runnable() { + @Override + public void run() { +- fileList.setInput(rootNodes); +- if(rootNodes.length==0) { ++ fileList.setInput(rootNodes); ++ if (rootNodes.length == 0) { + section.setExpanded(false); + } + } +@@ -261,15 +285,6 @@ public void handleException(Throwable exception) { + }); + } + +- private TreeViewerColumn createColumn(TreeViewer tree, String title, +- int width) { +- TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); +- column.getColumn().setText(title); +- column.getColumn().setWidth(width); +- column.getColumn().setResizable(true); +- return column; +- } +- + private void createResultFields(Composite composite, FormToolkit toolkit) { + Composite resultComposite = toolkit.createComposite(composite); + toolkit.paintBordersFor(resultComposite); +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java +new file mode 100644 +index 00000000..7d5fb386 +--- /dev/null ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/editors/TreeHelper.java +@@ -0,0 +1,38 @@ ++/******************************************************************************* ++ * Copyright (c) 2010 Research Group for Industrial Software (INSO), Vienna University of Technology ++ * 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: ++ * Kilian Matt (Research Group for Industrial Software (INSO), Vienna University of Technology) - initial API and implementation ++ *******************************************************************************/ ++package org.eclipse.mylyn.reviews.tasks.ui.editors; ++ ++import org.eclipse.jface.viewers.TreeViewer; ++import org.eclipse.jface.viewers.TreeViewerColumn; ++import org.eclipse.swt.SWT; ++/** ++ * @author mattk ++ * ++ */ ++public class TreeHelper { ++ ++ public static TreeViewer createColumns(TreeViewer tree, ++ IColumnSpec[] columns) { ++ for (IColumnSpec column : columns) { ++ createColumn(tree, column); ++ } ++ return tree; ++ } ++ ++ public static TreeViewerColumn createColumn(TreeViewer tree, ++ IColumnSpec columnSpec) { ++ TreeViewerColumn column = new TreeViewerColumn(tree, SWT.LEFT); ++ column.getColumn().setText(columnSpec.getTitle()); ++ column.getColumn().setWidth(100); ++ column.getColumn().setResizable(true); ++ return column; ++ } ++}" +56a939c3f16d0c9a90fb4f9e332838a234c08415,Vala,"Error when lambda parameter has incompatible direction with the delegate + +Fixes bug 740894 +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +fcfbdf64406ac44b771a3c1b91b95d9d9a465391,hadoop,YARN-3181. FairScheduler: Fix up outdated findbugs- issues. (kasha)--(cherry picked from commit c2b185def846f5577a130003a533b9c377b58fab)-,p,https://github.com/apache/hadoop,"diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt +index 6d27c85bf5be8..87524586bf320 100644 +--- a/hadoop-yarn-project/CHANGES.txt ++++ b/hadoop-yarn-project/CHANGES.txt +@@ -243,6 +243,8 @@ Release 2.7.0 - UNRELEASED + YARN-2079. Recover NonAggregatingLogHandler state upon nodemanager + restart. (Jason Lowe via junping_du) + ++ YARN-3181. FairScheduler: Fix up outdated findbugs issues. (kasha) ++ + YARN-3124. Fixed CS LeafQueue/ParentQueue to use QueueCapacities to track + capacities-by-label. (Wangda Tan via jianhe) + +diff --git a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml +index c45634e1be07b..70f1a71fbcb74 100644 +--- a/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml ++++ b/hadoop-yarn-project/hadoop-yarn/dev-support/findbugs-exclude.xml +@@ -142,22 +142,12 @@ + + + +- +- +- +- +- + + + + + + +- +- +- +- +- + + + +@@ -215,18 +205,6 @@ + + + +- +- +- +- +- +- +- +- +- +- +- +- + + + +@@ -426,11 +404,6 @@ + + + +- +- +- +- +- + + + +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java +index 0ea731403029e..9cb767d38a5d5 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationConfiguration.java +@@ -33,6 +33,9 @@ + + import com.google.common.annotations.VisibleForTesting; + ++import javax.annotation.concurrent.ThreadSafe; ++ ++@ThreadSafe + public class AllocationConfiguration extends ReservationSchedulerConfiguration { + private static final AccessControlList EVERYBODY_ACL = new AccessControlList(""*""); + private static final AccessControlList NOBODY_ACL = new AccessControlList("" ""); +@@ -204,12 +207,16 @@ public float getFairSharePreemptionThreshold(String queueName) { + } + + public ResourceWeights getQueueWeight(String queue) { +- ResourceWeights weight = queueWeights.get(queue); +- return (weight == null) ? ResourceWeights.NEUTRAL : weight; ++ synchronized (queueWeights) { ++ ResourceWeights weight = queueWeights.get(queue); ++ return (weight == null) ? ResourceWeights.NEUTRAL : weight; ++ } + } + + public void setQueueWeight(String queue, ResourceWeights weight) { +- queueWeights.put(queue, weight); ++ synchronized (queueWeights) { ++ queueWeights.put(queue, weight); ++ } + } + + public int getUserMaxApps(String user) { +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java +index 76fa588fc767f..c19aa513e1c1d 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/AllocationFileLoaderService.java +@@ -201,7 +201,7 @@ public synchronized void setReloadListener(Listener reloadListener) { + * @throws ParserConfigurationException if XML parser is misconfigured. + * @throws SAXException if config file is malformed. + */ +- public synchronized void reloadAllocations() throws IOException, ++ public void reloadAllocations() throws IOException, + ParserConfigurationException, SAXException, AllocationConfigurationException { + if (allocFile == null) { + return; +diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java +index c2282fdb736ca..c50f281cb6645 100644 +--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java ++++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSOpDurations.java +@@ -31,6 +31,8 @@ + import static org.apache.hadoop.metrics2.lib.Interns.info; + import org.apache.hadoop.metrics2.lib.MutableRate; + ++import javax.annotation.concurrent.ThreadSafe; ++ + /** + * Class to capture the performance metrics of FairScheduler. + * This should be a singleton. +@@ -38,6 +40,7 @@ + @InterfaceAudience.Private + @InterfaceStability.Unstable + @Metrics(context=""fairscheduler-op-durations"") ++@ThreadSafe + public class FSOpDurations implements MetricsSource { + + @Metric(""Duration for a continuous scheduling run"")" +93fbeee2b06807a7190b82edb46db3f43f9b84bb,Vala,"glib-2.0: add g_date_set_time_t binding +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +328b8d4d2ee831d64f8347072f95cf70a07e24a1,artificerrepo$artificer,"Moved the test maven projects. +Updated the s-ramp wagon's ""get"" functionality to bring it in-line with +put.",p,https://github.com/artificerrepo/artificer,"diff --git a/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java b/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java +index c0caeb408..7c3f588e8 100644 +--- a/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java ++++ b/s-ramp-wagon/src/main/java/org/overlord/sramp/wagon/SrampWagon.java +@@ -15,20 +15,13 @@ + */ + package org.overlord.sramp.wagon; + +-import java.io.ByteArrayInputStream; + import java.io.File; + import java.io.FileInputStream; + import java.io.FileNotFoundException; + import java.io.IOException; + import java.io.InputStream; +-import java.io.StringWriter; +-import java.security.MessageDigest; + + import javax.xml.bind.JAXBException; +-import javax.xml.transform.Transformer; +-import javax.xml.transform.TransformerFactory; +-import javax.xml.transform.dom.DOMSource; +-import javax.xml.transform.stream.StreamResult; + + import org.apache.commons.io.IOUtils; + import org.apache.http.conn.HttpHostConnectException; +@@ -59,9 +52,7 @@ + import org.overlord.sramp.client.SrampServerException; + import org.overlord.sramp.wagon.models.MavenGavInfo; + import org.overlord.sramp.wagon.util.DevNullOutputStream; +-import org.overlord.sramp.wagon.util.PomGenerator; + import org.s_ramp.xmlns._2010.s_ramp.BaseArtifactType; +-import org.w3c.dom.Document; + + /** + * Implements a wagon provider that uses the S-RAMP Atom API. +@@ -127,11 +118,65 @@ public void closeConnection() throws ConnectionException { + public void fillInputData(InputData inputData) throws TransferFailedException, + ResourceDoesNotExistException, AuthorizationException { + Resource resource = inputData.getResource(); +- ++ // Skip maven-metadata.xml files - they are not (yet?) supported + if (resource.getName().contains(""maven-metadata.xml"")) + throw new ResourceDoesNotExistException(""Could not find file: '"" + resource + ""'""); + + logger.debug(""Looking up resource from s-ramp repository: "" + resource); ++ ++ MavenGavInfo gavInfo = MavenGavInfo.fromResource(resource); ++ if (gavInfo.isHash()) { ++ doGetHash(gavInfo, inputData); ++ } else { ++ doGetArtifact(gavInfo, inputData); ++ } ++ ++ } ++ ++ /** ++ * Gets the hash data from the s-ramp repository and stores it in the {@link InputData} for ++ * use by Maven. ++ * @param gavInfo ++ * @param inputData ++ * @throws TransferFailedException ++ * @throws ResourceDoesNotExistException ++ * @throws AuthorizationException ++ */ ++ private void doGetHash(MavenGavInfo gavInfo, InputData inputData) throws TransferFailedException, ++ ResourceDoesNotExistException, AuthorizationException { ++ String artyPath = gavInfo.getFullName(); ++ String hashPropName; ++ if (gavInfo.getType().endsWith("".md5"")) { ++ hashPropName = ""maven.hash.md5""; ++ artyPath = artyPath.substring(0, artyPath.length() - 4); ++ } else { ++ hashPropName = ""maven.hash.sha1""; ++ artyPath = artyPath.substring(0, artyPath.length() - 5); ++ } ++ SrampArchiveEntry entry = this.archive.getEntry(artyPath); ++ if (entry == null) { ++ throw new ResourceDoesNotExistException(""Failed to find resource hash: "" + gavInfo.getName()); ++ } ++ BaseArtifactType metaData = entry.getMetaData(); ++ ++ String hashValue = SrampModelUtils.getCustomProperty(metaData, hashPropName); ++ if (hashValue == null) { ++ throw new ResourceDoesNotExistException(""Failed to find resource hash: "" + gavInfo.getName()); ++ } ++ inputData.setInputStream(IOUtils.toInputStream(hashValue)); ++ } ++ ++ /*** ++ * Gets the artifact content from the s-ramp repository and stores it in the {@link InputData} ++ * object for use by Maven. ++ * @param gavInfo ++ * @param inputData ++ * @throws TransferFailedException ++ * @throws ResourceDoesNotExistException ++ * @throws AuthorizationException ++ */ ++ private void doGetArtifact(MavenGavInfo gavInfo, InputData inputData) throws TransferFailedException, ++ ResourceDoesNotExistException, AuthorizationException { + // RESTEasy uses the current thread's context classloader to load its logger class. This + // fails in Maven because the context classloader is the wagon plugin's classloader, which + // doesn't know about any of the RESTEasy JARs. So here we're temporarily setting the +@@ -140,43 +185,19 @@ public void fillInputData(InputData inputData) throws TransferFailedException, + ClassLoader oldCtxCL = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(SrampWagon.class.getClassLoader()); + try { +- MavenGavInfo gavInfo = MavenGavInfo.fromResource(resource); + String endpoint = getSrampEndpoint(); + SrampAtomApiClient client = new SrampAtomApiClient(endpoint); + + // Query the artifact meta data using GAV info + BaseArtifactType artifact = findExistingArtifact(client, gavInfo); + if (artifact == null) +- throw new ResourceDoesNotExistException(""Artifact not found in s-ramp repository: '"" + resource + ""'""); ++ throw new ResourceDoesNotExistException(""Artifact not found in s-ramp repository: '"" + gavInfo.getName() + ""'""); ++ this.archive.addEntry(gavInfo.getFullName(), artifact, null); + ArtifactType type = ArtifactType.valueOf(artifact); + +- if (""pom"".equals(gavInfo.getType())) { +- String serializedPom = generatePom(artifact); +- inputData.setInputStream(new ByteArrayInputStream(serializedPom.getBytes(""UTF-8""))); +- return; +- } else if (""pom.sha1"".equals(gavInfo.getType())) { +- // Generate a SHA1 hash on the fly for the POM +- String serializedPom = generatePom(artifact); +- MessageDigest md = MessageDigest.getInstance(""SHA1""); +- md.update(serializedPom.getBytes(""UTF-8"")); +- byte[] mdbytes = md.digest(); +- StringBuilder sb = new StringBuilder(); +- for (int i = 0; i < mdbytes.length; i++) { +- sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); +- } +- inputData.setInputStream(new ByteArrayInputStream(sb.toString().getBytes(""UTF-8""))); +- return; +- } else if (gavInfo.getType().endsWith("".sha1"")) { +- InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); +- String sha1Hash = generateSHA1Hash(artifactContent); +- inputData.setInputStream(new ByteArrayInputStream(sha1Hash.getBytes(""UTF-8""))); +- return; +- } else { +- // Get the artifact content as an input stream +- InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); +- inputData.setInputStream(artifactContent); +- return; +- } ++ // Get the artifact content as an input stream ++ InputStream artifactContent = client.getArtifactContent(type, artifact.getUuid()); ++ inputData.setInputStream(artifactContent); + } catch (ResourceDoesNotExistException e) { + throw e; + } catch (SrampClientException e) { +@@ -189,64 +210,6 @@ public void fillInputData(InputData inputData) throws TransferFailedException, + } finally { + Thread.currentThread().setContextClassLoader(oldCtxCL); + } +- throw new ResourceDoesNotExistException(""Could not find file: '"" + resource + ""'""); +- } +- +- /** +- * Generates a SHA1 hash for the given binary content. +- * @param artifactContent an s-ramp artifact input stream +- * @return a SHA1 hash +- */ +- private String generateSHA1Hash(InputStream artifactContent) { +- try { +- MessageDigest md = MessageDigest.getInstance(""SHA1""); +- byte[] buff = new byte[2048]; +- int count = artifactContent.read(buff); +- while (count != -1) { +- md.update(buff, 0, count); +- count = artifactContent.read(buff); +- } +- byte[] mdbytes = md.digest(); +- StringBuilder sb = new StringBuilder(); +- for (int i = 0; i < mdbytes.length; i++) { +- sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); +- } +- return sb.toString(); +- } catch (Exception e) { +- throw new RuntimeException(e); +- } finally { +- IOUtils.closeQuietly(artifactContent); +- } +- } +- +- /** +- * Generates a POM for the artifact. +- * @param artifact +- * @throws Exception +- */ +- private String generatePom(BaseArtifactType artifact) throws Exception { +- ArtifactType type = ArtifactType.valueOf(artifact); +- PomGenerator pomGenerator = new PomGenerator(); +- Document pomDoc = pomGenerator.generatePom(artifact, type); +- String serializedPom = serializeDocument(pomDoc); +- return serializedPom; +- } +- +- /** +- * Serialize a document to a string. +- * @param document +- */ +- private String serializeDocument(Document document) { +- try { +- StringWriter writer = new StringWriter(); +- Transformer transformer = TransformerFactory.newInstance().newTransformer(); +- transformer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, ""no""); +- transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, ""yes""); +- transformer.transform(new DOMSource(document), new StreamResult(writer)); +- return writer.toString(); +- } catch (Exception e) { +- throw new RuntimeException(e); +- } + } + + /** +@@ -503,7 +466,8 @@ private BaseArtifactType findExistingArtifactByGAV(SrampAtomApiClient client, Ma + * @throws SrampServerException + * @throws JAXBException + */ +- private BaseArtifactType findExistingArtifactByUniversal(SrampAtomApiClient client, MavenGavInfo gavInfo) throws SrampServerException, SrampClientException, JAXBException { ++ private BaseArtifactType findExistingArtifactByUniversal(SrampAtomApiClient client, MavenGavInfo gavInfo) ++ throws SrampServerException, SrampClientException, JAXBException { + String artifactType = gavInfo.getGroupId().substring(gavInfo.getGroupId().indexOf('.') + 1); + String uuid = gavInfo.getArtifactId(); + Entry entry = null; +diff --git a/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template b/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template +deleted file mode 100644 +index f512f2053..000000000 +--- a/s-ramp-wagon/src/main/resources/org/overlord/sramp/wagon/util/pom.template ++++ /dev/null +@@ -1,18 +0,0 @@ +- +- +- +- 4.0.0 +- +- +- +- +- +- +- +- +- +- +- +\ No newline at end of file +diff --git a/s-ramp-wagon/src/test/resources/test-wagon-pull/.gitignore b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/.gitignore +similarity index 100% +rename from s-ramp-wagon/src/test/resources/test-wagon-pull/.gitignore +rename to s-ramp-wagon/src/test/maven-projects/test-wagon-pull/.gitignore +diff --git a/s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml +similarity index 92% +rename from s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml +rename to s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml +index 1f9d097bd..71ea9bf15 100644 +--- a/s-ramp-wagon/src/test/resources/test-wagon-pull/pom.xml ++++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/pom.xml +@@ -5,6 +5,7 @@ + test-wagon-pull + 0.0.1-SNAPSHOT + test-wagon-pull ++ + + + local-sramp-repo +@@ -25,7 +26,11 @@ + org.overlord.sramp.test + test-wagon-push + 0.0.1-SNAPSHOT +- xsd ++ ++ ++ junit ++ junit ++ 4.10 + + + +diff --git a/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java +new file mode 100644 +index 000000000..0aed61c75 +--- /dev/null ++++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/main/java/org/overlord/sramp/wagontest/TestPullDependency.java +@@ -0,0 +1,43 @@ ++/* ++ * Copyright 2012 JBoss Inc ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.overlord.sramp.wagontest; ++ ++import org.overlord.sramp.test.wagon.Widget; ++ ++/** ++ * Tests the ability to create a new instance of the generated class found in ++ * the test-wagon-push project. ++ * ++ * @author eric.wittmann@redhat.com ++ */ ++public class TestPullDependency { ++ ++ /** ++ * Constructor. ++ */ ++ public TestPullDependency() { ++ } ++ ++ /** ++ * Do something with a Widget. ++ */ ++ public void doit() { ++ Widget widget = new Widget(); ++ System.out.println(""It's done!""); ++ System.out.println(widget); ++ } ++ ++} +diff --git a/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java +new file mode 100644 +index 000000000..fa54b9f5f +--- /dev/null ++++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-pull/src/test/java/org/overlord/sramp/wagontest/TestPullDependencyTest.java +@@ -0,0 +1,37 @@ ++/* ++ * Copyright 2012 JBoss Inc ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.overlord.sramp.wagontest; ++ ++import org.junit.Test; ++ ++/** ++ * Unit test. ++ * ++ * @author eric.wittmann@redhat.com ++ */ ++public class TestPullDependencyTest { ++ ++ /** ++ * Test method for {@link org.overlord.sramp.wagontest.TestPullDependency#doit()}. ++ */ ++ @Test ++ public void testDoit() { ++ TestPullDependency tpd = new TestPullDependency(); ++ tpd.doit(); ++ System.out.println(""DONE: success""); ++ } ++ ++} +diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/.gitignore b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/.gitignore +similarity index 100% +rename from s-ramp-wagon/src/test/resources/test-wagon-push/.gitignore +rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/.gitignore +diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml +similarity index 97% +rename from s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml +rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml +index 595c057ff..0706da5d9 100644 +--- a/s-ramp-wagon/src/test/resources/test-wagon-push/pom.xml ++++ b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/pom.xml +@@ -10,7 +10,7 @@ + + local-sramp-repo + Local S-RAMP Repository +- sramp://localhost:9090/s-ramp-atom/s-ramp/ ++ sramp://localhost:8080/s-ramp-atom/s-ramp/ + default + + true +diff --git a/s-ramp-wagon/src/test/resources/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd b/s-ramp-wagon/src/test/maven-projects/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd +similarity index 100% +rename from s-ramp-wagon/src/test/resources/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd +rename to s-ramp-wagon/src/test/maven-projects/test-wagon-push/src/main/resources/META-INF/schemas/widget.xsd" +b07575194155e5f90e3ab514812d11dd74eef75f,abashev$vfs-s3,"Added support for Server Side Encryption +- Added S3FileSystemConfigBuilder +- Refactored S3FileSystem + Object so that FileSystem encapsulates +the various options (similar to SftpFileSystem+Object) +- Added get/setServerSideEncryption as necessary +- Added integration tests +- Fixed a bug in copy file tests where file counts were not being +tested properly. +",a,https://github.com/abashev/vfs-s3,"diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java +index 683a6dde..96572709 100644 +--- a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java ++++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileObject.java +@@ -47,18 +47,8 @@ public class S3FileObject extends AbstractFileObject { + + private static final String MIMETYPE_JETS3T_DIRECTORY = ""application/x-directory""; + +- /** Amazon S3 service */ +- private final AWSCredentials awsCredentials; +- private final AmazonS3 service; +- +- private final TransferManager transferManager; +- +- /** Amazon S3 bucket */ +- private final Bucket bucket; +- + /** Amazon S3 object */ + private ObjectMetadata objectMetadata; +- + private String objectKey; + + /** +@@ -82,16 +72,9 @@ public class S3FileObject extends AbstractFileObject { + */ + private Owner fileOwner; + +- public S3FileObject( +- AbstractFileName fileName, S3FileSystem fileSystem, AWSCredentials awsCredentials, AmazonS3 service, +- TransferManager transferManager, Bucket bucket +- ) throws FileSystemException { ++ public S3FileObject(AbstractFileName fileName, ++ S3FileSystem fileSystem) throws FileSystemException { + super(fileName, fileSystem); +- +- this.awsCredentials = awsCredentials; +- this.service = service; +- this.bucket = bucket; +- this.transferManager = transferManager; + } + + @Override +@@ -100,7 +83,7 @@ protected void doAttach() { + try { + // Do we have file with name? + String candidateKey = getS3Key(); +- objectMetadata = service.getObjectMetadata(bucket.getName(), candidateKey); ++ objectMetadata = getService().getObjectMetadata(getBucket().getName(), candidateKey); + objectKey = candidateKey; + logger.info(""Attach file to S3 Object: "" + objectKey); + +@@ -116,7 +99,7 @@ protected void doAttach() { + try { + // Do we have folder with that name? + String candidateKey = getS3Key() + FileName.SEPARATOR; +- objectMetadata = service.getObjectMetadata(bucket.getName(), candidateKey); ++ objectMetadata = getService().getObjectMetadata(getBucket().getName(), candidateKey); + objectKey = candidateKey; + logger.info(""Attach folder to S3 Object: "" + objectKey); + +@@ -156,7 +139,7 @@ protected void doDetach() throws Exception { + + @Override + protected void doDelete() throws Exception { +- service.deleteObject(bucket.getName(), objectKey); ++ getService().deleteObject(getBucket().getName(), objectKey); + } + + @Override +@@ -164,7 +147,7 @@ protected void doCreateFolder() throws Exception { + if (logger.isDebugEnabled()) { + logger.debug( + ""Create new folder in bucket ["" + +- ((bucket != null) ? bucket.getName() : ""null"") + ++ ((getBucket() != null) ? getBucket().getName() : ""null"") + + ""] with key ["" + + ((objectMetadata != null) ? objectKey : ""null"") + + ""]"" +@@ -178,7 +161,9 @@ protected void doCreateFolder() throws Exception { + InputStream input = new ByteArrayInputStream(new byte[0]); + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(0); +- service.putObject(new PutObjectRequest(bucket.getName(), objectKey + FileName.SEPARATOR, input, metadata)); ++ if (((S3FileSystem)getFileSystem()).getServerSideEncryption()) ++ metadata.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); ++ getService().putObject(new PutObjectRequest(getBucket().getName(), objectKey + FileName.SEPARATOR, input, metadata)); + } + + @Override +@@ -228,13 +213,13 @@ protected String[] doListChildren() throws Exception { + path = path + ""/""; + } + +- ObjectListing listing = service.listObjects(bucket.getName(), path); ++ ObjectListing listing = getService().listObjects(getBucket().getName(), path); + final List summaries = new ArrayList(listing.getObjectSummaries()); + while (listing.isTruncated()) { + final ListObjectsRequest loReq = new ListObjectsRequest(); +- loReq.setBucketName(bucket.getName()); ++ loReq.setBucketName(getBucket().getName()); + loReq.setMarker(listing.getNextMarker()); +- listing = service.listObjects(loReq); ++ listing = getService().listObjects(loReq); + summaries.addAll(listing.getObjectSummaries()); + } + +@@ -275,13 +260,13 @@ protected FileObject[] doListChildrenResolved() throws Exception + path = path + ""/""; + } + +- ObjectListing listing = service.listObjects(bucket.getName(), path); ++ ObjectListing listing = getService().listObjects(getBucket().getName(), path); + final List summaries = new ArrayList(listing.getObjectSummaries()); + while (listing.isTruncated()) { + final ListObjectsRequest loReq = new ListObjectsRequest(); +- loReq.setBucketName(bucket.getName()); ++ loReq.setBucketName(getBucket().getName()); + loReq.setMarker(listing.getNextMarker()); +- listing = service.listObjects(loReq); ++ listing = getService().listObjects(loReq); + summaries.addAll(listing.getObjectSummaries()); + } + +@@ -332,7 +317,7 @@ private void downloadOnce () throws FileSystemException { + final String failedMessage = ""Failed to download S3 Object %s. %s""; + final String objectPath = getName().getPath(); + try { +- S3Object obj = service.getObject(bucket.getName(), objectKey); ++ S3Object obj = getService().getObject(getBucket().getName(), objectKey); + logger.info(String.format(""Downloading S3 Object: %s"", objectPath)); + InputStream is = obj.getObjectContent(); + if (obj.getObjectMetadata().getContentLength() > 0) { +@@ -438,7 +423,7 @@ private Owner getS3Owner() { + */ + private AccessControlList getS3Acl() { + String key = getS3Key(); +- return """".equals(key) ? service.getBucketAcl(bucket.getName()) : service.getObjectAcl(bucket.getName(), key); ++ return """".equals(key) ? getService().getBucketAcl(getBucket().getName()) : getService().getObjectAcl(getBucket().getName(), key); + } + + /** +@@ -450,12 +435,12 @@ private void putS3Acl (AccessControlList s3Acl) { + String key = getS3Key(); + // Determine context. Object or Bucket + if ("""".equals(key)) { +- service.setBucketAcl(bucket.getName(), s3Acl); ++ getService().setBucketAcl(getBucket().getName(), s3Acl); + } else { + // Before any operations with object it must be attached + doAttach(); + // Put ACL to S3 +- service.setObjectAcl(bucket.getName(), objectKey, s3Acl); ++ getService().setObjectAcl(getBucket().getName(), objectKey, s3Acl); + } + } + +@@ -608,7 +593,7 @@ public void setAcl (Acl acl) throws FileSystemException { + * @return + */ + public String getHttpUrl() { +- StringBuilder sb = new StringBuilder(""http://"" + bucket.getName() + "".s3.amazonaws.com/""); ++ StringBuilder sb = new StringBuilder(""http://"" + getBucket().getName() + "".s3.amazonaws.com/""); + String key = getS3Key(); + + // Determine context. Object or Bucket +@@ -627,9 +612,9 @@ public String getHttpUrl() { + public String getPrivateUrl() { + return String.format( + ""s3://%s:%s@%s/%s"", +- awsCredentials.getAWSAccessKeyId(), +- awsCredentials.getAWSSecretKey(), +- bucket.getName(), ++ getAwsCredentials().getAWSAccessKeyId(), ++ getAwsCredentials().getAWSSecretKey(), ++ getBucket().getName(), + getS3Key() + ); + } +@@ -646,7 +631,9 @@ public String getSignedUrl(int expireInSeconds) throws FileSystemException { + cal.add(SECOND, expireInSeconds); + + try { +- return service.generatePresignedUrl(bucket.getName(), getS3Key(), cal.getTime()).toString(); ++ return getService().generatePresignedUrl( ++ getBucket().getName(), ++ getS3Key(), cal.getTime()).toString(); + } catch (AmazonServiceException e) { + throw new FileSystemException(e); + } +@@ -658,19 +645,40 @@ public String getSignedUrl(int expireInSeconds) throws FileSystemException { + * @throws FileSystemException + */ + public String getMD5Hash() throws FileSystemException { +- final String key = getS3Key(); + String hash = null; + ++ ObjectMetadata metadata = getObjectMetadata(); ++ if (metadata != null) { ++ hash = metadata.getETag(); // TODO this is something different than mentioned in methodname / javadoc ++ } ++ ++ return hash; ++ } ++ ++ public ObjectMetadata getObjectMetadata() throws FileSystemException { + try { +- ObjectMetadata metadata = service.getObjectMetadata(bucket.getName(), key); +- if (metadata != null) { +- hash = metadata.getETag(); // TODO this is something different than mentioned in methodname / javadoc +- } ++ return getService().getObjectMetadata(getBucket().getName(), getS3Key()); + } catch (AmazonServiceException e) { + throw new FileSystemException(e); + } ++ } + +- return hash; ++ /** FileSystem object containing configuration */ ++ protected AWSCredentials getAwsCredentials() { ++ return ((S3FileSystem)getFileSystem()).getAwsCredentials(); ++ } ++ ++ protected AmazonS3 getService() { ++ return ((S3FileSystem)getFileSystem()).getService(); ++ } ++ ++ protected TransferManager getTransferManager() { ++ return ((S3FileSystem)getFileSystem()).getTransferManager(); ++ } ++ ++ /** Amazon S3 bucket */ ++ protected Bucket getBucket() { ++ return ((S3FileSystem)getFileSystem()).getBucket(); + } + + /** +@@ -689,11 +697,15 @@ protected void onClose() throws IOException { + FileChannel cacheFileChannel = getCacheFileChannel(); + + objectMetadata.setContentLength(cacheFileChannel.size()); +- objectMetadata.setContentType(Mimetypes.getInstance().getMimetype(getName().getBaseName())); +- ++ objectMetadata.setContentType( ++ Mimetypes.getInstance().getMimetype(getName().getBaseName())); ++ if (((S3FileSystem)getFileSystem()).getServerSideEncryption()) ++ objectMetadata.setServerSideEncryption( ++ ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + try { +- final Upload upload = transferManager.upload( +- bucket.getName(), objectKey, newInputStream(cacheFileChannel), objectMetadata ++ final Upload upload = getTransferManager().upload( ++ getBucket().getName(), objectKey, ++ newInputStream(cacheFileChannel), objectMetadata + ); + + upload.addProgressListener(new ProgressListener() { +@@ -708,7 +720,7 @@ public void progressChanged(ProgressEvent progressEvent) { + if ((progress - lastValue) > REPORT_THRESHOLD) { + logger.info( + ""File "" + objectKey + +- "" was uploaded to "" + bucket.getName() + ++ "" was uploaded to "" + getBucket().getName() + + "" for "" + (int) progress + ""%"" + ); + +@@ -716,7 +728,7 @@ public void progressChanged(ProgressEvent progressEvent) { + } + + if (progressEvent.getEventCode() == COMPLETED_EVENT_CODE) { +- logger.info(""File "" + objectKey + "" was successfully uploaded to "" + bucket.getName()); ++ logger.info(""File "" + objectKey + "" was successfully uploaded to "" + getBucket().getName()); + } + } + }); +@@ -790,21 +802,23 @@ public void copyFrom(final FileObject file, final FileSelector selector) + // Copy across + try + { ++ String srcBucketName = ((S3FileObject)srcFile).getBucket().getName(); ++ String srcFileName = ((S3FileObject)srcFile).getS3Key(); ++ String destBucketName = ((S3FileObject)destFile).getBucket().getName(); ++ String destFileName = ((S3FileObject)destFile).getS3Key(); + if (srcFile.getType() == FileType.FOLDER) { +- service.copyObject( +- ((S3FileObject)srcFile).bucket.getName(), +- ((S3FileObject)srcFile).getS3Key() + FileName.SEPARATOR, +- ((S3FileObject)destFile).bucket.getName(), +- ((S3FileObject)destFile).getS3Key() + FileName.SEPARATOR +- ); +- } else { +- service.copyObject( +- ((S3FileObject)srcFile).bucket.getName(), +- ((S3FileObject)srcFile).getS3Key(), +- ((S3FileObject)destFile).bucket.getName(), +- ((S3FileObject)destFile).getS3Key() +- ); +- } ++ srcFileName = srcFileName + FileName.SEPARATOR; ++ destFileName = destFileName + FileName.SEPARATOR; ++ } ++ CopyObjectRequest copy = new CopyObjectRequest( ++ srcBucketName, srcFileName, destBucketName, destFileName); ++ if (srcFile.getType() == FileType.FILE ++ && ((S3FileSystem)destFile.getFileSystem()).getServerSideEncryption()) { ++ ObjectMetadata meta = ((S3FileObject)srcFile).getObjectMetadata(); ++ meta.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); ++ copy.setNewObjectMetadata(meta); ++ } ++ getService().copyObject(copy); + + destFile.close(); + } catch (AmazonServiceException e) { +diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java +index b2653f7a..74dd428a 100644 +--- a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java ++++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystem.java +@@ -33,15 +33,19 @@ public class S3FileSystem extends AbstractFileSystem { + private final Bucket bucket; + private final TransferManager transferManager; + ++ private Boolean serverSideEncryption; ++ + public S3FileSystem( +- S3FileName fileName, AWSCredentials awsCredentials, AmazonS3 service, FileSystemOptions fileSystemOptions +- ) throws FileSystemException { ++ S3FileName fileName, AWSCredentials awsCredentials, AmazonS3 service, ++ FileSystemOptions fileSystemOptions) throws FileSystemException { + super(fileName, null, fileSystemOptions); + + String bucketId = fileName.getBucketId(); + + this.awsCredentials = awsCredentials; + this.service = service; ++ this.serverSideEncryption = S3FileSystemConfigBuilder.getInstance() ++ .getServerSideEncryption(fileSystemOptions); + + try { + if (service.doesBucketExist(bucketId)) { +@@ -71,8 +75,32 @@ protected void addCapabilities(Collection caps) { + caps.addAll(S3FileProvider.capabilities); + } + ++ public Boolean getServerSideEncryption() { ++ return serverSideEncryption; ++ } ++ ++ public void setServerSideEncryption(Boolean serverSideEncryption) { ++ this.serverSideEncryption = serverSideEncryption; ++ } ++ ++ protected Bucket getBucket() { ++ return bucket; ++ } ++ ++ protected AWSCredentials getAwsCredentials() { ++ return awsCredentials; ++ } ++ ++ protected AmazonS3 getService() { ++ return service; ++ } ++ ++ protected TransferManager getTransferManager() { ++ return transferManager; ++ } ++ + @Override + protected FileObject createFile(AbstractFileName fileName) throws Exception { +- return new S3FileObject(fileName, this, awsCredentials, service, transferManager, bucket); ++ return new S3FileObject(fileName, this); + } + } +diff --git a/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java +new file mode 100644 +index 00000000..15de92fd +--- /dev/null ++++ b/src/main/java/com/intridea/io/vfs/provider/s3/S3FileSystemConfigBuilder.java +@@ -0,0 +1,47 @@ ++package com.intridea.io.vfs.provider.s3; ++ ++import org.apache.commons.vfs2.FileSystem; ++import org.apache.commons.vfs2.FileSystemConfigBuilder; ++import org.apache.commons.vfs2.FileSystemOptions; ++ ++public class S3FileSystemConfigBuilder extends FileSystemConfigBuilder { ++ private static final S3FileSystemConfigBuilder BUILDER = new S3FileSystemConfigBuilder(); ++ ++ private static final String SERVER_SIDE_ENCRYPTION = S3FileSystemConfigBuilder.class.getName() + "".SERVER_SIDE_ENCRYPTION""; ++ ++ private S3FileSystemConfigBuilder() ++ { ++ super(""s3.""); ++ } ++ ++ public static S3FileSystemConfigBuilder getInstance() ++ { ++ return BUILDER; ++ } ++ ++ @Override ++ protected Class getConfigClass() { ++ return S3FileSystem.class; ++ } ++ ++ /** ++ * use server-side encryption. ++ * ++ * @param opts The FileSystemOptions. ++ * @param serverSideEncryption true if server-side encryption should be used. ++ */ ++ public void setServerSideEncryption(FileSystemOptions opts, boolean serverSideEncryption) ++ { ++ setParam(opts, SERVER_SIDE_ENCRYPTION, serverSideEncryption ? Boolean.TRUE : Boolean.FALSE); ++ } ++ ++ /** ++ * @param opts The FileSystemOptions. ++ * @return true if server-side encryption is being used. ++ * @see #setServerSideEncryption(org.apache.commons.vfs2.FileSystemOptions, boolean) ++ */ ++ public Boolean getServerSideEncryption(FileSystemOptions opts) ++ { ++ return getBoolean(opts, SERVER_SIDE_ENCRYPTION, false); ++ } ++} +diff --git a/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java b/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java +index d60c3eab..ca911083 100644 +--- a/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java ++++ b/src/test/java/com/intridea/io/vfs/provider/s3/S3ProviderTest.java +@@ -1,5 +1,6 @@ + package com.intridea.io.vfs.provider.s3; + ++import com.amazonaws.services.s3.model.ObjectMetadata; + import com.intridea.io.vfs.TestEnvironment; + import com.intridea.io.vfs.operations.IMD5HashGetter; + import com.intridea.io.vfs.operations.IPublicUrlsGetter; +@@ -14,6 +15,7 @@ + import java.io.FileNotFoundException; + import java.security.MessageDigest; + import java.security.NoSuchAlgorithmException; ++import java.util.Arrays; + import java.util.Locale; + import java.util.Properties; + import java.util.Random; +@@ -29,8 +31,7 @@ public class S3ProviderTest { + private static final String BACKUP_ZIP = ""src/test/resources/backup.zip""; + + private FileSystemManager fsManager; +- +- private String fileName, dirName, bucketName, bigFile; ++ private String fileName, encryptedFileName, dirName, bucketName, bigFile; + private FileObject file, dir; + + private FileSystemOptions opts; +@@ -41,6 +42,7 @@ public void setUp() throws FileNotFoundException, IOException { + + fsManager = VFS.getManager(); + Random r = new Random(); ++ encryptedFileName = ""vfs-encrypted-file"" + r.nextInt(1000); + fileName = ""vfs-file"" + r.nextInt(1000); + dirName = ""vfs-dir"" + r.nextInt(1000); + bucketName = config.getProperty(""s3.testBucket"", ""vfs-s3-tests""); +@@ -54,6 +56,17 @@ public void createFileOk() throws FileSystemException { + assertTrue(file.exists()); + } + ++ @Test ++ public void createEncryptedFileOk() throws FileSystemException { ++ file = fsManager.resolveFile(""s3://"" + bucketName + ""/test-place/"" + encryptedFileName, opts); ++ ((S3FileSystem)file.getFileSystem()).setServerSideEncryption(true); ++ file.createFile(); ++ assertTrue(file.exists()); ++ assertEquals( ++ ((S3FileObject) file).getObjectMetadata().getServerSideEncryption(), ++ ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); ++ } ++ + @Test(expectedExceptions={FileSystemException.class}) + public void createFileFailed() throws FileSystemException { + FileObject tmpFile = fsManager.resolveFile(""s3://../new-mpoint/vfs-bad-file""); +@@ -130,6 +143,31 @@ public void upload() throws FileNotFoundException, IOException { + dest.copyFrom(src, Selectors.SELECT_SELF); + + assertTrue(dest.exists() && dest.getType().equals(FileType.FILE)); ++ assertEquals(((S3FileObject)dest).getObjectMetadata().getServerSideEncryption(), ++ null); ++ } ++ ++ @Test(dependsOnMethods = {""createEncryptedFileOk""}) ++ public void uploadEncrypted() throws FileNotFoundException, IOException { ++ FileObject dest = fsManager.resolveFile(""s3://"" + bucketName + ""/test-place/backup.zip""); ++ ((S3FileSystem)dest.getFileSystem()).setServerSideEncryption(true); ++ ++ // Delete file if exists ++ if (dest.exists()) { ++ dest.delete(); ++ } ++ ++ // Copy data ++ final File backupFile = new File(BACKUP_ZIP); ++ ++ assertTrue(backupFile.exists(), ""Backup file should exists""); ++ ++ FileObject src = fsManager.resolveFile(backupFile.getAbsolutePath()); ++ dest.copyFrom(src, Selectors.SELECT_SELF); ++ ++ assertTrue(dest.exists() && dest.getType().equals(FileType.FILE)); ++ assertEquals(((S3FileObject)dest).getObjectMetadata().getServerSideEncryption(), ++ ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); + } + + @Test(dependsOnMethods={""createFileOk""}) +@@ -318,7 +356,9 @@ public void getUrls() throws FileSystemException { + + final String signedUrl = urlsGetter.getSignedUrl(60); + +- assertTrue(signedUrl.startsWith(""https://"" + bucketName + "".s3.amazonaws.com/test-place%2Fbackup.zip?"")); ++ assertTrue( ++ signedUrl.startsWith(""https://s3.amazonaws.com/"" + bucketName + ""/test-place%2Fbackup.zip?""), ++ signedUrl); + assertTrue(signedUrl.indexOf(""Signature="") != (-1)); + assertTrue(signedUrl.indexOf(""Expires="") != (-1)); + assertTrue(signedUrl.indexOf(""AWSAccessKeyId="") != (-1)); +@@ -347,16 +387,40 @@ public void getMD5Hash() throws NoSuchAlgorithmException, FileNotFoundException, + + @Test(dependsOnMethods={""findFiles""}) + public void copyInsideBucket() throws FileSystemException { +- FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); +- FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-copy""); +- testsDirCopy.copyFrom(testsDir, Selectors.SELECT_SELF_AND_CHILDREN); +- +- // Should have same number of files +- FileObject[] files = testsDir.findFiles(Selectors.SELECT_ALL); +- FileObject[] filesCopy = testsDir.findFiles(Selectors.SELECT_ALL); +- assertEquals(files.length, filesCopy.length); ++ FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); ++ FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-copy""); ++ testsDirCopy.copyFrom(testsDir, Selectors.SELECT_SELF_AND_CHILDREN); ++ ++ // Should have same number of files ++ FileObject[] files = testsDir.findFiles(Selectors.SELECT_SELF_AND_CHILDREN); ++ FileObject[] filesCopy = testsDirCopy.findFiles(Selectors.SELECT_SELF_AND_CHILDREN); ++ assertEquals(files.length, filesCopy.length, ++ Arrays.deepToString(files) + "" vs. "" + Arrays.deepToString(filesCopy)); + } + ++ @Test(dependsOnMethods={""findFiles""}) ++ public void copyAllToEncryptedInsideBucket() throws FileSystemException { ++ FileObject testsDir = fsManager.resolveFile(dir, ""find-tests""); ++ FileObject testsDirCopy = testsDir.getParent().resolveFile(""find-tests-encrypted-copy""); ++ ((S3FileSystem)testsDirCopy.getFileSystem()).setServerSideEncryption(true); ++ ++ testsDirCopy.copyFrom(testsDir, Selectors.SELECT_ALL); ++ ++ // Should have same number of files ++ FileObject[] files = testsDir.findFiles(Selectors.SELECT_ALL); ++ FileObject[] filesCopy = testsDirCopy.findFiles(Selectors.SELECT_ALL); ++ assertEquals(files.length, filesCopy.length); ++ ++ for (int i = 0; i < files.length; i++) { ++ if (files[i].getType() == FileType.FILE) { ++ assertEquals(((S3FileObject)files[i]).getObjectMetadata().getServerSideEncryption(), ++ null); ++ assertEquals(((S3FileObject)filesCopy[i]).getObjectMetadata().getServerSideEncryption(), ++ ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION); ++ } ++ } ++ } ++ + @Test(dependsOnMethods={""findFiles"", ""download""}) + public void delete() throws FileSystemException { + FileObject testsDir = fsManager.resolveFile(dir, ""find-tests"");" +9521bc3d3eb5d1cc164417b9ca072393bb9cccda,hadoop,MAPREDUCE-3238. Small cleanup in SchedulerApp.- (Todd Lipcon via mahadev) - Merging r1206921 from trunk--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-0.23@1206924 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt +index 34252d944233d..c760640e179ad 100644 +--- a/hadoop-mapreduce-project/CHANGES.txt ++++ b/hadoop-mapreduce-project/CHANGES.txt +@@ -56,6 +56,8 @@ Release 0.23.1 - Unreleased + MAPREDUCE-3371. Review and improve the yarn-api javadocs. (Ravi Prakash + via mahadev) + ++ MAPREDUCE-3238. Small cleanup in SchedulerApp. (Todd Lipcon via mahadev) ++ + OPTIMIZATIONS + + BUG FIXES +diff --git a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApp.java b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApp.java +index 5ee6d46e95cbb..e3798c0defc15 100644 +--- a/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApp.java ++++ b/hadoop-mapreduce-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerApp.java +@@ -53,6 +53,14 @@ + import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerReservedEvent; + import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode; + ++import com.google.common.collect.HashMultiset; ++import com.google.common.collect.Multiset; ++ ++/** ++ * Represents an Application from the viewpoint of the scheduler. ++ * Each running Application in the RM corresponds to one instance ++ * of this class. ++ */ + public class SchedulerApp { + + private static final Log LOG = LogFactory.getLog(SchedulerApp.class); +@@ -76,11 +84,16 @@ public class SchedulerApp { + final Map> reservedContainers = + new HashMap>(); + +- Map schedulingOpportunities = +- new HashMap(); ++ /** ++ * Count how many times the application has been given an opportunity ++ * to schedule a task at each priority. Each time the scheduler ++ * asks the application for a task at this priority, it is incremented, ++ * and each time the application successfully schedules a task, it ++ * is reset to 0. ++ */ ++ Multiset schedulingOpportunities = HashMultiset.create(); + +- Map reReservations = +- new HashMap(); ++ Multiset reReservations = HashMultiset.create(); + + Resource currentReservation = recordFactory + .newRecordInstance(Resource.class); +@@ -282,49 +295,33 @@ public synchronized RMContainer getRMContainer(ContainerId id) { + } + + synchronized public void resetSchedulingOpportunities(Priority priority) { +- this.schedulingOpportunities.put(priority, Integer.valueOf(0)); ++ this.schedulingOpportunities.setCount(priority, 0); + } + + synchronized public void addSchedulingOpportunity(Priority priority) { +- Integer schedulingOpportunities = +- this.schedulingOpportunities.get(priority); +- if (schedulingOpportunities == null) { +- schedulingOpportunities = 0; +- } +- ++schedulingOpportunities; +- this.schedulingOpportunities.put(priority, schedulingOpportunities); ++ this.schedulingOpportunities.setCount(priority, ++ schedulingOpportunities.count(priority) + 1); + } + ++ /** ++ * Return the number of times the application has been given an opportunity ++ * to schedule a task at the given priority since the last time it ++ * successfully did so. ++ */ + synchronized public int getSchedulingOpportunities(Priority priority) { +- Integer schedulingOpportunities = +- this.schedulingOpportunities.get(priority); +- if (schedulingOpportunities == null) { +- schedulingOpportunities = 0; +- this.schedulingOpportunities.put(priority, schedulingOpportunities); +- } +- return schedulingOpportunities; ++ return this.schedulingOpportunities.count(priority); + } + + synchronized void resetReReservations(Priority priority) { +- this.reReservations.put(priority, Integer.valueOf(0)); ++ this.reReservations.setCount(priority, 0); + } + + synchronized void addReReservation(Priority priority) { +- Integer reReservations = this.reReservations.get(priority); +- if (reReservations == null) { +- reReservations = 0; +- } +- ++reReservations; +- this.reReservations.put(priority, reReservations); ++ this.reReservations.add(priority); + } + + synchronized public int getReReservations(Priority priority) { +- Integer reReservations = this.reReservations.get(priority); +- if (reReservations == null) { +- reReservations = 0; +- this.reReservations.put(priority, reReservations); +- } +- return reReservations; ++ return this.reReservations.count(priority); + } + + public synchronized int getNumReservedContainers(Priority priority) {" +c3b4d70410f2acd2a7d6f3ef9fbcd2a156fe9f30,coremedia$jangaroo-tools,"Submit last night's results: +* Correct handling of newlines inside generated strings (e.g. modifiers rendered inside string for the runtime to interpret). +* Support *-imports. Not recommended, since it disables automatic class loading, but good for reusing existing ActionScript 3 libraries. +* FlexUnit now compiles and runs with minimal changes: +- added some missing semicolons +- static members of super classes are not in scope +- the super class and package-scoped methods still have to be +imported explicitly +- ArrayCollection not yet implemented +- special case when subclassing native class Error +[git-p4: depot-paths = ""//coremedia/jangaroo/"": change = 146563] +",a,https://github.com/coremedia/jangaroo-tools,"diff --git a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup +index e1169a5f1..5b504c150 100644 +--- a/jooc/src/main/cup/net/jangaroo/jooc/joo.cup ++++ b/jooc/src/main/cup/net/jangaroo/jooc/joo.cup +@@ -229,6 +229,8 @@ classBody ::= + + classBodyDeclarations ::= + {: RESULT = new ArrayList(); :} ++ | classBodyDeclarations:list directive:d ++ {: RESULT = list; :} + | classBodyDeclarations:list classBodyDeclaration:decl + {: RESULT = list; list.add(decl); :} + ; +@@ -269,6 +271,8 @@ constOrVar ::= + directive ::= + IMPORT:i qualifiedIde:ide SEMICOLON:s + {: RESULT = new ImportDirective(i,new IdeType(ide), s); :} ++ | IMPORT:i qualifiedIde:ide DOT:dot MUL:all SEMICOLON:s ++ {: RESULT = new ImportDirective(i,new IdeType(new QualifiedIde(ide,dot,all)), s); :} + | LBRACK:lb ide:ide RBRACK:rb + {: RESULT = new Annotation(lb, ide, rb); :} + | LBRACK:lb ide:ide LPAREN:lb2 annotationFields:af RPAREN:rb2 RBRACK:rb +@@ -286,7 +290,7 @@ annotationField ::= + ide:name EQ:eq expr:value + {: RESULT = new ObjectField(new IdeExpr(name),eq,value); :} + | expr:value +- {: RESULT = new ObjectField(new IdeExpr(new Ide(new JooSymbol(""""))),null,value); :} ++ {: RESULT = new ObjectField(null,null,value); :} + ; + + annotationFields ::= +diff --git a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java +index 39e17a443..857549d14 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/ApplyExpr.java +@@ -22,6 +22,9 @@ + */ + class ApplyExpr extends Expr { + ++ // TODO: add a compiler option for this: ++ public static final boolean ASSUME_UNDECLARED_UPPER_CASE_FUNCTIONS_CALLS_ARE_TYPE_CASTS = Boolean.valueOf(""true""); ++ + Expr fun; + boolean isType; + JooSymbol lParen; +@@ -63,9 +66,9 @@ public void analyze(Node parentNode, AnalyzeContext context) { + // otherwise, it is most likely an imported package-namespaced function. + if (Character.isUpperCase(funIde.getName().charAt(0))) { + Scope scope = context.getScope().findScopeThatDeclares(funIde); +- if (scope!=null) { +- isType = scope.getDeclaration()==context.getScope().getPackageDeclaration(); +- } ++ isType = scope == null ++ ? ASSUME_UNDECLARED_UPPER_CASE_FUNCTIONS_CALLS_ARE_TYPE_CASTS ++ : scope.getDeclaration() == context.getScope().getPackageDeclaration(); + } + } + fun.analyze(this, context); +diff --git a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java +index 9797a8188..a2d5f048d 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/ClassDeclaration.java +@@ -28,6 +28,7 @@ public class ClassDeclaration extends IdeDeclaration { + private Map members = new LinkedHashMap(); + private Set boundMethodCandidates = new HashSet(); + private Set classInit = new HashSet(); ++ private List packageImports; + + public Extends getOptExtends() { + return optExtends; +@@ -88,15 +89,14 @@ public void setConstructor(MethodDeclaration methodDeclaration) { + } + + public void generateCode(JsWriter out) throws IOException { +- out.writeSymbolWhitespace(symClass); +- if (!writeRuntimeModifiersUnclosed(out)) { +- out.write(""\""""); +- } +- out.writeSymbolToken(symClass); ++ out.beginString(); ++ writeModifiers(out); ++ out.writeSymbol(symClass); + ide.generateCode(out); + if (optExtends != null) optExtends.generateCode(out); + if (optImplements != null) optImplements.generateCode(out); +- out.write(""\"",[""); ++ out.endString(); ++ out.write("",[""); + boolean isFirst = true; + for (MemberDeclaration memberDeclaration : members.values()) { + if (memberDeclaration.isMethod() && memberDeclaration.isPublic() && memberDeclaration.isStatic()) { +@@ -111,7 +111,12 @@ public void generateCode(JsWriter out) throws IOException { + } + } + out.write(""],""); +- out.write(""function($jooPublic,$jooPrivate){with($jooPublic)with($jooPrivate)return[""); ++ String packageName = QualifiedIde.constructQualifiedNameStr(getPackageDeclaration().getQualifiedName()); ++ out.write(""function($jooPublic,$jooPrivate){""); ++ for (String importedPackage : packageImports) { ++ out.write(""with(""+importedPackage+"")""); ++ } ++ out.write(""with(""+ packageName +"")with($jooPublic)with($jooPrivate)return[""); + if (!classInit.isEmpty()) { + out.write(""function(){joo.Class.init(""); + for (Iterator iterator = classInit.iterator(); iterator.hasNext();) { +@@ -129,6 +134,7 @@ public void generateCode(JsWriter out) throws IOException { + public void analyze(Node parentNode, AnalyzeContext context) { + // do *not* call super! + this.parentNode = parentNode; ++ packageImports = context.getCurrentPackage().getPackageImports(); + context.getScope().declareIde(getName(), this); + parentDeclaration = context.getScope().getPackageDeclaration(); + context.enterScope(this); +diff --git a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java +index e5f11d767..05e4edefb 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/Declaration.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/Declaration.java +@@ -120,28 +120,6 @@ protected void writeModifiers(JsWriter out) throws IOException { + } + } + +- protected void writeRuntimeModifiers(JsWriter out) throws IOException { +- if (writeRuntimeModifiersUnclosed(out)) { +- out.write(""\"",""); +- } +- } +- +- protected boolean writeRuntimeModifiersUnclosed(JsWriter out) throws IOException { +- if (symModifiers.length>0) { +- out.writeSymbolWhitespace(symModifiers[0]); +- out.write('""'); +- for (int i = 0; i < symModifiers.length; i++) { +- JooSymbol modifier = symModifiers[i]; +- if (i==0) +- out.writeSymbolToken(modifier); +- else +- out.writeSymbol(modifier); +- } +- return true; +- } +- return false; +- } +- + public void analyze(Node parentNode, AnalyzeContext context) { + super.analyze(parentNode, context); + parentDeclaration = context.getScope().getDeclaration(); +diff --git a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java +index d0374a329..cd92f9407 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/DotExpr.java +@@ -48,10 +48,11 @@ public void analyze(Node parentNode, AnalyzeContext context) { + if (!(parentNode instanceof ApplyExpr)) { + String[] qualifiedName = getQualifiedName(arg1); + if (qualifiedName!=null) { +- String qulifiedNameStr = QualifiedIde.constructQualifiedNameStr(qualifiedName); +- Scope declaringScope = context.getScope().findScopeThatDeclares(qulifiedNameStr); +- if (declaringScope!=null && declaringScope.getDeclaration().equals(context.getCurrentPackage())) { +- this.classDeclaration.addClassInit(qulifiedNameStr); ++ String qualifiedNameStr = QualifiedIde.constructQualifiedNameStr(qualifiedName); ++ Scope declaringScope = context.getScope().findScopeThatDeclares(qualifiedNameStr); ++ if (declaringScope==null && qualifiedNameStr.indexOf('.')==-1 && Character.isUpperCase(qualifiedNameStr.charAt(0)) ++ || declaringScope!=null && declaringScope.getDeclaration().equals(context.getCurrentPackage())) { ++ this.classDeclaration.addClassInit(qualifiedNameStr); + } + } + } +diff --git a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java +index 18d789af3..dc7db6fca 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/FieldDeclaration.java +@@ -35,13 +35,11 @@ public boolean isField() { + } + + public void generateCode(JsWriter out) throws IOException { +- out.writeSymbolWhitespace(optSymConstOrVar); +- if (!writeRuntimeModifiersUnclosed(out)) { +- out.write(""\""""); +- } +- out.writeSymbolToken(optSymConstOrVar); +- out.write(""\"",""); +- out.write('{'); ++ out.beginString(); ++ writeModifiers(out); ++ out.writeSymbol(optSymConstOrVar); ++ out.endString(); ++ out.write("",{""); + generateIdeCode(out); + if (optTypeRelation != null) + optTypeRelation.generateCode(out); +diff --git a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java +index aa142b060..b8be3237b 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/ImportDirective.java +@@ -37,9 +37,16 @@ public void analyze(Node parentNode, AnalyzeContext context) { + super.analyze(parentNode, context); + if (type instanceof IdeType) { + Ide ide = ((IdeType)type).ide; +- context.getScope().declareIde(ide.getName(), this); +- // also add the fully qualified name (might be the same string for top level imports): +- context.getScope().declareIde(QualifiedIde.constructQualifiedNameStr(ide.getQualifiedName()), this); ++ String typeName = ide.getName(); ++ if (""*"".equals(typeName)) { ++ // found *-import, do not register, but add to package import list: ++ String packageName = QualifiedIde.constructQualifiedNameStr(((QualifiedIde)ide).prefix.getQualifiedName()); ++ context.getCurrentPackage().addPackageImport(packageName); ++ } else { ++ context.getScope().declareIde(typeName, this); ++ // also add the fully qualified name (might be the same string for top level imports): ++ context.getScope().declareIde(QualifiedIde.constructQualifiedNameStr(ide.getQualifiedName()), this); ++ } + } + } + +diff --git a/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java b/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java +index 28a606519..5e99d3ffa 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/JsWriter.java +@@ -33,6 +33,8 @@ public class JsWriter extends FilterWriter { + boolean inComment = false; + int nOpenBeginComments = 0; + char lastChar = ' '; ++ boolean inString = false; ++ int nOpenStrings = 0; + + public JsWriter(Writer target) { + super(target); +@@ -152,7 +154,7 @@ public void beginComment() throws IOException { + nOpenBeginComments++; + } + +- private final boolean shouldWrite() throws IOException { ++ private boolean shouldWrite() throws IOException { + boolean result = keepSource || nOpenBeginComments == 0; + if (result) { + if (nOpenBeginComments > 0 && !inComment) { +@@ -178,10 +180,65 @@ public void beginCommentWriteSymbol(JooSymbol symbol) throws IOException { + writeSymbol(symbol); + } + ++ public void beginString() throws IOException { ++ nOpenStrings++; ++ } ++ ++ private void checkOpenString() throws IOException { ++ if (nOpenStrings > 0 && !inString) { ++ out.write('""'); ++ lastChar = '""'; ++ inString = true; ++ } ++ } ++ ++ private boolean checkCloseString() throws IOException { ++ if (inString) { ++ out.write('""'); ++ inString = false; ++ return true; ++ } ++ return false; ++ } ++ ++ public void endString() throws IOException { ++ Debug.assertTrue(nOpenStrings > 0, ""missing beginString() for endString()""); ++ nOpenStrings--; ++ if (nOpenStrings == 0) { ++ checkCloseString(); ++ } ++ } ++ ++ private void writeLinesInsideString(String ws) throws IOException { ++ String[] lines = ws.split(""\n"",-1); ++ for (int i = 0; i < lines.length-1; i++) { ++ String line = lines[i]; ++ if (line.length()>1) { ++ checkOpenString(); ++ write(line.substring(0,line.length()-1)); ++ write(""\\n""); ++ } ++ if(checkCloseString()) { ++ write(""+""); ++ } ++ write(""\n""); ++ } ++ String line = lines[lines.length - 1]; ++ if (line.length()>0) { ++ checkOpenString(); ++ write(line); ++ } ++ } ++ + public void writeSymbolWhitespace(JooSymbol symbol) throws IOException { + String ws = symbol.getWhitespace(); +- if (keepSource) +- write(ws); ++ if (keepSource) { ++ if (inString) { ++ writeLinesInsideString(ws); ++ } else { ++ write(ws); ++ } ++ } + else if (keepLines) + writeLines(ws); + } +@@ -192,8 +249,14 @@ protected void writeLines(String s) throws IOException { + + protected void writeLines(String s, int off, int len) throws IOException { + int pos = off; +- while ((pos = s.indexOf('\n', pos)+1) > 0 && pos < off+len+1) ++ while ((pos = s.indexOf('\n', pos)+1) > 0 && pos < off+len+1) { ++ if (inString) { ++ write(""\\n""); ++ checkCloseString(); ++ write('+'); ++ } + write('\n'); ++ } + } + + public void writeToken(String token) throws IOException { +@@ -204,6 +267,7 @@ public void writeToken(String token) throws IOException { + (lastChar == firstSymbolChar && ""=>= 0) || + (firstSymbolChar == '=' && ""=>= 0)) + write(' '); ++ checkOpenString(); + write(text); + } + } +diff --git a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java +index 11ecafe4a..b0f442645 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/MethodDeclaration.java +@@ -125,26 +125,27 @@ public void generateCode(JsWriter out) throws IOException { + out.writeSymbol(symFunction); + ide.generateCode(out); + } else { +- if (!writeRuntimeModifiersUnclosed(out)) +- out.write(""\""""); +- else +- out.write("" ""); ++ out.beginString(); ++ writeModifiers(out); + String methodName = ide.getName(); +- out.write(methodName); +- out.write(""\"",""); ++ if (!isConstructor && !isStatic() && classDeclaration.isBoundMethod(methodName)) { ++ out.writeToken(""bound""); ++ } ++ out.writeToken(methodName); ++ out.endString(); ++ out.write("",""); + out.writeSymbol(symFunction); + out.writeSymbolWhitespace(ide.ide); + if (out.getKeepSource()) { +- out.write("" ""); + if (isConstructor) { + // do not name the constructor initializer function like the class, or it will be called + // instead of the constructor function generated by the runtime! So we prefix it with a ""$"". + // The name is for debugging purposes only, anyway. +- out.write(""$""+methodName); ++ out.writeToken(""$""+methodName); + } else if (ide instanceof AccessorIde) { +- out.write(((AccessorIde)ide).getFunctionName()); ++ out.writeToken(((AccessorIde)ide).getFunctionName()); + } else { +- out.write(methodName); ++ out.writeToken(methodName); + } + } + } +diff --git a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java +index 3831976b5..c02ab5d6a 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/ObjectField.java +@@ -34,13 +34,17 @@ public ObjectField(Expr nameExpr, JooSymbol symColon, Expr value) { + + public void analyze(Node parentNode, AnalyzeContext context) { + super.analyze(parentNode, context); +- nameExpr.analyze(this, context); ++ if (nameExpr!=null) { ++ nameExpr.analyze(this, context); ++ } + value.analyze(this, context); + } + + public void generateCode(JsWriter out) throws IOException { +- nameExpr.generateCode(out); +- out.writeSymbol(symColon); ++ if (nameExpr!=null) { ++ nameExpr.generateCode(out); ++ out.writeSymbol(symColon); ++ } + value.generateCode(out); + } + +diff --git a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java +index f82eaaf8d..f0a343dd7 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/PackageDeclaration.java +@@ -16,6 +16,9 @@ + package net.jangaroo.jooc; + + import java.io.IOException; ++import java.util.List; ++import java.util.ArrayList; ++import java.util.Collections; + + /** + * @author Andreas Gawecki +@@ -23,6 +26,15 @@ + public class PackageDeclaration extends IdeDeclaration { + + JooSymbol symPackage; ++ private List packageImports = new ArrayList(); ++ ++ public void addPackageImport(String packageName) { ++ packageImports.add(packageName); ++ } ++ ++ public List getPackageImports() { ++ return Collections.unmodifiableList(packageImports); ++ } + + public PackageDeclaration(JooSymbol symPackage, Ide ide) { + super(new JooSymbol[0], 0, ide); +@@ -30,12 +42,12 @@ public PackageDeclaration(JooSymbol symPackage, Ide ide) { + } + + public void generateCode(JsWriter out) throws IOException { +- out.writeSymbolWhitespace(symPackage); +- out.write(""\""package ""); ++ out.beginString(); ++ out.writeSymbol(symPackage); + if (ide!=null) { + ide.generateCode(out); + } +- out.write(""\""""); ++ out.endString(); + out.write("",""); + } + +diff --git a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java +index 53a2ce32c..859ba12f0 100644 +--- a/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java ++++ b/jooc/src/main/java/net/jangaroo/jooc/TopLevelIdeExpr.java +@@ -38,7 +38,7 @@ public void analyze(Node parentNode, AnalyzeContext context) { + if (scope!=null) { + Scope declaringScope = scope.findScopeThatDeclares(ide); + if (declaringScope==null || declaringScope.getDeclaration() instanceof ClassDeclaration) { +- synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol(""this"")), new JooSymbol("".""), ide); ++ synthesizedDotExpr = new DotExpr(new ThisExpr(new JooSymbol(""this"")), new JooSymbol("".""), new Ide(ide.ide)); + synthesizedDotExpr.analyze(parentNode, context); + } + } +@@ -59,25 +59,28 @@ private boolean addThis() { + Scope declaringScope = scope.findScopeThatDeclares(ide); + if (declaringScope==null) { + // check for fully qualified ide: +- IdeExpr currentExpr = this; ++ DotExpr currentDotExpr = synthesizedDotExpr; + String ideName = ide.getName(); +- while (declaringScope==null && currentExpr.parentNode instanceof DotExpr && ((DotExpr)currentExpr.parentNode).arg2 instanceof IdeExpr) { +- currentExpr = (IdeExpr)((DotExpr)currentExpr.parentNode).arg2; +- ideName += ""."" +currentExpr.ide.getName(); ++ while (currentDotExpr.parentNode instanceof DotExpr) { ++ currentDotExpr = (DotExpr)currentDotExpr.parentNode; ++ if (!(currentDotExpr.arg2 instanceof IdeExpr)) ++ break; ++ ideName += ""."" +((IdeExpr)currentDotExpr.arg2).ide.getName(); + declaringScope = scope.findScopeThatDeclares(ideName); ++ if (declaringScope!=null) { ++ // it has been defined in the meantime or is an imported qualified identifier: ++ return false; ++ } + } +- if (declaringScope!=null) { +- return false; +- } +- boolean probablyAType = Character.isUpperCase(ide.getName().charAt(0)); ++ boolean maybeInScope = Character.isUpperCase(ide.getName().charAt(0)); + String warningMsg = ""Undeclared identifier: "" + ide.getName(); +- if (probablyAType) { +- warningMsg += "", assuming it is a top level type.""; ++ if (maybeInScope) { ++ warningMsg += "", assuming it is already in scope.""; + } else if (ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS) { + warningMsg += "", assuming it is an inherited member.""; + } + Jooc.warning(ide.getSymbol(), warningMsg); +- return !probablyAType && ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS; ++ return !maybeInScope && ASSUME_UNDECLARED_IDENTIFIERS_ARE_MEMBERS; + } else if (declaringScope.getDeclaration() instanceof ClassDeclaration) { + MemberDeclaration memberDeclaration = (MemberDeclaration)declaringScope.getIdeDeclaration(ide); + return !memberDeclaration.isStatic() && !memberDeclaration.isConstructor(); +@@ -85,4 +88,5 @@ private boolean addThis() { + } + return false; + } ++ + } +\ No newline at end of file +diff --git a/jooc/src/main/js/joo/Class.js b/jooc/src/main/js/joo/Class.js +index eca78a3ad..c97c163db 100644 +--- a/jooc/src/main/js/joo/Class.js ++++ b/jooc/src/main/js/joo/Class.js +@@ -499,7 +499,7 @@ Function.prototype.bind = function(object) { + var memberName = undefined; + var modifiers; + if (typeof members==""string"") { +- modifiers = members.split("" ""); ++ modifiers = members.split(/\s+/); + for (var j=0; j config, long nodesToCreate, final NodeStructFactory nodeStructFactory) { + this.storeDir = storeDir; +- final int minBufferBits = (int) (Math.log(nodesToCreate / 100) / Math.log(2)); ++ final int minBufferBits = 14; // (int) (Math.log(nodesToCreate / 100) / Math.log(2)); + RING_SIZE = 1 << Math.min(minBufferBits,18); ++ System.out.println(""Ring size ""+RING_SIZE); + this.config = config; + this.nodesToCreate = nodesToCreate; + this.nodeStructFactory = nodeStructFactory; +@@ -58,8 +59,8 @@ void init() { + nodeStructFactory.init(inserter); + NeoStore neoStore = inserter.getNeoStore(); + neoStore.getNodeStore().setHighId(nodesToCreate + 1); +- executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); +- //executor = Executors.newCachedThreadPool(); ++ final int processors = Runtime.getRuntime().availableProcessors(); ++ executor = processors >=4 ? Executors.newFixedThreadPool(processors) : Executors.newCachedThreadPool(); + + disruptor = new Disruptor(nodeStructFactory, executor, new SingleThreadedClaimStrategy(RING_SIZE), new YieldingWaitStrategy()); + disruptor.handleExceptionsWith(new BatchInserterExceptionHandler()); +@@ -75,7 +76,7 @@ private void createHandlers(NeoStore neoStore, NodeStructFactory nodeStructFacto + propertyMappingHandlers = PropertyEncodingHandler.createHandlers(inserter); + + propertyRecordCreatorHandler = new PropertyRecordCreatorHandler(); +- relationshipIdHandler = new RelationshipIdHandler(nodeStructFactory.getMaxRelsPerNode()); ++ relationshipIdHandler = new RelationshipIdHandler(); + + //nodeWriter = new NodeFileWriteHandler(new File(nodeStore.getStorageFileName())); + nodeWriter = new NodeWriteRecordHandler(neoStore.getNodeStore()); +diff --git a/src/main/java/org/neo4j/batchimport/ParallelImporter.java b/src/main/java/org/neo4j/batchimport/ParallelImporter.java +index 2f771d8..e8bd5c5 100644 +--- a/src/main/java/org/neo4j/batchimport/ParallelImporter.java ++++ b/src/main/java/org/neo4j/batchimport/ParallelImporter.java +@@ -204,11 +204,10 @@ private void initProperties(BatchInserterImpl inserter) { + @Override + public void fillStruct(long nodeId, NodeStruct nodeStruct) { + try { +- nodeStruct.init(); + String nodesLine = nodesReader.readLine(); + if (nodesLine == null) throw new IllegalStateException(""Less Node rows than indicated at id "" + nodeId); + +- final Object[] rowData = nodesData.updateArray(nodesLine); ++ final Object[] rowData = nodesData.updateArray(nodesLine,(Object[])null); + addProperties(nodeStruct, rowData, nodesData.getCount(), nodePropIds); + + addRelationships(nodeId, nodeStruct); +diff --git a/src/main/java/org/neo4j/batchimport/collections/CompactLongRecord.java b/src/main/java/org/neo4j/batchimport/collections/CompactLongRecord.java +new file mode 100644 +index 0000000..1d2485b +--- /dev/null ++++ b/src/main/java/org/neo4j/batchimport/collections/CompactLongRecord.java +@@ -0,0 +1,113 @@ ++package org.neo4j.batchimport.collections; ++ ++import edu.ucla.sspace.util.primitive.IntIterator; ++ ++import java.util.Arrays; ++ ++/** ++* @author mh ++* @since 03.11.12 ++*/ ++public class CompactLongRecord { ++ private final byte highbit; ++ volatile CompactLongRecord next; ++ private final IntArray values = new IntArray(); ++ private final int[] counts=new int[2]; ++ ++ CompactLongRecord(byte highbit) { ++ this.highbit=highbit; ++ } ++ ++ public void add(long id, boolean outgoing) { ++ final byte lead = (byte)(id >> 31L); ++ add(lead,id,outgoing); ++ } ++ ++ private void add(byte lead, long id, boolean outgoing) { ++ if (lead!=highbit) { ++ if (next==null) { ++ next=new CompactLongRecord((byte)(highbit+1)); ++ } ++ next.add(lead,id,outgoing); ++ } else { ++ int value = (int)(id & 0x7FFFFFFF); ++ if (!outgoing) value = ~value; ++ counts[idx(outgoing)]++; ++ values.add(value); ++ } ++ } ++ ++ public long[] getOutgoing() { ++ return get(true); ++ } ++ ++ public long[] getIncoming() { ++ return get(false); ++ } ++ ++ private long[] get(boolean outgoing) { ++ long[] result=new long[count(outgoing)]; ++ return collect(result,outgoing,0); ++ } ++ ++ private long[] collect(long[] result, boolean positive, int offset) { ++ final int max = counts[idx(positive)]; ++ int i=offset; ++ for (int j = 0; j < values.count; j++) { ++ int value = values.data[j]; ++ final boolean isPositive = value >= 0; ++ if (isPositive == positive) { ++ result[i++]= convert(value); ++ } ++ } ++ if (offset+max!=i) throw new IllegalStateException(String.format(""Max %d != array counter %d"",max,i)); ++ if (next!=null) return next.collect(result,positive,i); ++ // Arrays.sort(result); ++ return result; ++ } ++ ++ public int count(boolean outgoing) { ++ return counts[idx(outgoing)] + (next!=null ? next.count(outgoing) : 0); ++ } ++ ++ private int idx(boolean outgoing) { ++ return outgoing?0:1; ++ } ++ ++ public long first() { ++ if (values.hasData()) { ++ return convert(values.first()); ++ } ++ if (next!=null) return next.first(); ++ return -1L; ++ } ++ ++ public long firstPositive() { ++ if (values.hasPositive()) { ++ return convert(values.firstPositive()); ++ } ++ if (next!=null) return next.firstPositive(); ++ return -1L; ++ } ++ ++ public long firstNegative() { ++ if (values.hasNegative()) { ++ return convert(values.firstNegative()); ++ } ++ if (next!= null) return next.firstNegative(); ++ return -1L; ++ } ++ ++ public long last() { ++ if (next!=null) return next.first(); ++ if (values.hasData()) { ++ return convert(values.last()); ++ } ++ return -1L; ++ } ++ ++ private long convert(int value) { ++ if (value < 0) value = ~value; ++ return (long)highbit<<31 | value; ++ } ++} +diff --git a/src/main/java/org/neo4j/batchimport/collections/ConcurrentLongReverseRelationshipMap.java b/src/main/java/org/neo4j/batchimport/collections/ConcurrentLongReverseRelationshipMap.java +index 51e46d4..62a5ae0 100644 +--- a/src/main/java/org/neo4j/batchimport/collections/ConcurrentLongReverseRelationshipMap.java ++++ b/src/main/java/org/neo4j/batchimport/collections/ConcurrentLongReverseRelationshipMap.java +@@ -1,5 +1,6 @@ + package org.neo4j.batchimport.collections; + ++import edu.ucla.sspace.util.primitive.CompactIntSet; + import edu.ucla.sspace.util.primitive.IntSet; + + import java.util.Arrays; +@@ -10,30 +11,18 @@ + * @since 27.10.12 + */ + public class ConcurrentLongReverseRelationshipMap implements ReverseRelationshipMap { +- private final ConcurrentHashMap inner=new ConcurrentHashMap(); +- private final int arraySize; ++ private final ConcurrentHashMap inner=new ConcurrentHashMap(); + +- public ConcurrentLongReverseRelationshipMap(int arraySize) { +- this.arraySize = arraySize; +- } +- +- public void add(long key, long value) { +- long[] ids = inner.get(key); ++ public void add(long key, long value, boolean outgoing) { ++ CompactLongRecord ids = inner.get(key); + if (ids==null) { +- ids = new long[arraySize]; +- Arrays.fill(ids, -1); ++ ids = new CompactLongRecord((byte)0); + inner.put(key, ids); + } +- for (int i=0;i= 0) return data[i]; ++ } ++ } ++ throw new ArrayIndexOutOfBoundsException(""No data""); ++ } ++ ++ public boolean hasData() { ++ return count > 0; ++ } ++ ++ public boolean hasNegative() { ++ return negative>0; ++ } ++ ++ public boolean hasPositive() { ++ return (count-negative) > 0; ++ } ++ ++ public int last() { ++ if (hasData()) return data[count-1]; ++ throw new ArrayIndexOutOfBoundsException(""No data""); ++ } ++} +diff --git a/src/main/java/org/neo4j/batchimport/collections/ReverseRelationshipMap.java b/src/main/java/org/neo4j/batchimport/collections/ReverseRelationshipMap.java +index 4976483..f379014 100644 +--- a/src/main/java/org/neo4j/batchimport/collections/ReverseRelationshipMap.java ++++ b/src/main/java/org/neo4j/batchimport/collections/ReverseRelationshipMap.java +@@ -5,6 +5,6 @@ + * @since 27.10.12 + */ + public interface ReverseRelationshipMap { +- void add(long nodeId, long relId); +- long[] remove(long nodeId); ++ void add(long nodeId, long relId, boolean outgoing); ++ CompactLongRecord retrieve(long nodeId); + } +diff --git a/src/main/java/org/neo4j/batchimport/handlers/RelationshipIdHandler.java b/src/main/java/org/neo4j/batchimport/handlers/RelationshipIdHandler.java +index 587c8cc..9a24554 100644 +--- a/src/main/java/org/neo4j/batchimport/handlers/RelationshipIdHandler.java ++++ b/src/main/java/org/neo4j/batchimport/handlers/RelationshipIdHandler.java +@@ -1,9 +1,7 @@ + package org.neo4j.batchimport.handlers; + + import com.lmax.disruptor.EventHandler; +-import org.neo4j.batchimport.NodeStructFactory; + import org.neo4j.batchimport.collections.ConcurrentLongReverseRelationshipMap; +-import org.neo4j.batchimport.collections.PrimitiveIntReverseRelationshipMap; + import org.neo4j.batchimport.Utils; + import org.neo4j.batchimport.collections.ReverseRelationshipMap; + import org.neo4j.batchimport.structs.NodeStruct; +@@ -17,17 +15,8 @@ + public class RelationshipIdHandler implements EventHandler { + volatile long relId = 0; + // store reverse node-id to rel-id for future updates of relationship-records +- final ReverseRelationshipMap futureModeRelIdQueueOutgoing; +- final ReverseRelationshipMap futureModeRelIdQueueIncoming; +- +- public RelationshipIdHandler(int relsPerNode) { +- futureModeRelIdQueueOutgoing = new ConcurrentLongReverseRelationshipMap(relsPerNode); +- futureModeRelIdQueueIncoming = new ConcurrentLongReverseRelationshipMap(relsPerNode); +- } +-// final ReverseRelationshipMap futureModeRelIdQueueOutgoing = new PrimitiveIntReverseRelationshipMap(); +-// final ReverseRelationshipMap futureModeRelIdQueueIncoming = new PrimitiveIntReverseRelationshipMap(); +- //final ReverseRelationshipMap futureModeRelIdQueueOutgoing = new ConcurrentReverseRelationshipMap(RELS_PER_NODE); +- //final ReverseRelationshipMap futureModeRelIdQueueIncoming = new ConcurrentReverseRelationshipMap(RELS_PER_NODE); ++ // todo reuse and pool the CompactLongRecords, so we can skip IntArray creation ++ final ReverseRelationshipMap futureModeRelIdQueue = new ConcurrentLongReverseRelationshipMap(); + + public void onEvent(NodeStruct event, long nodeId, boolean endOfBatch) throws Exception { + for (int i = 0; i < event.relationshipCount; i++) { +@@ -37,8 +26,8 @@ public void onEvent(NodeStruct event, long nodeId, boolean endOfBatch) throws Ex + storeFutureRelId(nodeId, relationship,relId); + } + +- event.outgoingRelationshipsToUpdate = futureRelIds(nodeId, futureModeRelIdQueueOutgoing); +- event.incomingRelationshipsToUpdate = futureRelIds(nodeId, futureModeRelIdQueueIncoming); ++ event.relationshipsToUpdate = futureModeRelIdQueue.retrieve(nodeId); ++ + event.nextRel = firstRelationshipId(event); + event.maxRelationshipId = maxRelationshipId(event); + } +@@ -46,31 +35,24 @@ public void onEvent(NodeStruct event, long nodeId, boolean endOfBatch) throws Ex + private void storeFutureRelId(long nodeId, Relationship relationship, long relId) { + long other = relationship.other(); + if (other < nodeId) return; +- if (relationship.outgoing()) { +- futureModeRelIdQueueIncoming.add(other, relId); +- } else { +- futureModeRelIdQueueOutgoing.add(other, relId); +- } +- } +- +- private long[] futureRelIds(long nodeId, ReverseRelationshipMap futureRelIds) { +- long[] relIds = futureRelIds.remove(nodeId); +- if (relIds == null) return null; +- return relIds; ++ final boolean otherDirection = !relationship.outgoing(); ++ futureModeRelIdQueue.add(other, relId, otherDirection); + } + + private long firstRelationshipId(NodeStruct event) { + if (event.relationshipCount>0) return event.getRelationship(0).id; +- if (event.outgoingRelationshipsToUpdate!=null) return event.outgoingRelationshipsToUpdate[0]; +- if (event.incomingRelationshipsToUpdate!=null) return event.incomingRelationshipsToUpdate[0]; ++ if (event.relationshipsToUpdate !=null) { ++ long outgoingRelId = event.relationshipsToUpdate.firstPositive(); ++ if (outgoingRelId!=-1) return outgoingRelId; ++ return event.relationshipsToUpdate.firstNegative(); ++ } + return Record.NO_PREV_RELATIONSHIP.intValue(); + } + + private long maxRelationshipId(NodeStruct event) { + long result=Record.NO_NEXT_RELATIONSHIP.intValue(); + +- if (event.incomingRelationshipsToUpdate!=null) result=Math.max(event.incomingRelationshipsToUpdate[Utils.size(event.incomingRelationshipsToUpdate)-1],result); +- if (event.outgoingRelationshipsToUpdate!=null) result=Math.max(event.outgoingRelationshipsToUpdate[Utils.size(event.outgoingRelationshipsToUpdate)-1],result); ++ if (event.relationshipsToUpdate !=null) result=Math.max(event.relationshipsToUpdate.last(),result); // TODO max of both directions or just the last rel-id that was added, i.e. the biggest + if (event.relationshipCount>0) result=Math.max(event.getRelationship(event.relationshipCount-1).id,result); + return result; + } +diff --git a/src/main/java/org/neo4j/batchimport/handlers/RelationshipWriteHandler.java b/src/main/java/org/neo4j/batchimport/handlers/RelationshipWriteHandler.java +index 1127afc..ef582cb 100644 +--- a/src/main/java/org/neo4j/batchimport/handlers/RelationshipWriteHandler.java ++++ b/src/main/java/org/neo4j/batchimport/handlers/RelationshipWriteHandler.java +@@ -2,6 +2,7 @@ + + import com.lmax.disruptor.EventHandler; + import org.neo4j.batchimport.Utils; ++import org.neo4j.batchimport.collections.CompactLongRecord; + import org.neo4j.batchimport.structs.NodeStruct; + import org.neo4j.batchimport.structs.Relationship; + import org.neo4j.kernel.impl.nioneo.store.Record; +@@ -26,10 +27,12 @@ public void onEvent(NodeStruct event, long nodeId, boolean endOfBatch) throws Ex + relationshipWriter.start(event.maxRelationshipId); + + int count = event.relationshipCount; +- long followingNextRelationshipId = +- event.outgoingRelationshipsToUpdate!=null ? event.outgoingRelationshipsToUpdate[0] : +- event.incomingRelationshipsToUpdate!=null ? event.incomingRelationshipsToUpdate[0] : +- Record.NO_NEXT_RELATIONSHIP.intValue(); ++ long followingNextRelationshipId = Record.NO_NEXT_RELATIONSHIP.intValue(); ++ if (event.relationshipsToUpdate !=null) { ++ long value = event.relationshipsToUpdate.firstPositive(); ++ if (value == -1) value = event.relationshipsToUpdate.firstNegative(); ++ if (value != -1) followingNextRelationshipId = value; ++ } + + long prevId = Record.NO_PREV_RELATIONSHIP.intValue(); + for (int i = 0; i < count; i++) { +@@ -40,22 +43,22 @@ public void onEvent(NodeStruct event, long nodeId, boolean endOfBatch) throws Ex + counter++; + } + +- followingNextRelationshipId = +- event.incomingRelationshipsToUpdate!=null ? event.incomingRelationshipsToUpdate[0] : +- Record.NO_NEXT_RELATIONSHIP.intValue(); ++ if (event.relationshipsToUpdate!=null) { + +- prevId = createUpdateRecords(event.outgoingRelationshipsToUpdate, prevId, followingNextRelationshipId,true); ++ followingNextRelationshipId = event.relationshipsToUpdate.firstNegative(); + +- followingNextRelationshipId = Record.NO_NEXT_RELATIONSHIP.intValue(); ++ prevId = createUpdateRecords(event.relationshipsToUpdate.getOutgoing(), prevId, followingNextRelationshipId,true); + +- createUpdateRecords(event.incomingRelationshipsToUpdate, prevId, followingNextRelationshipId, false); ++ followingNextRelationshipId = Record.NO_NEXT_RELATIONSHIP.intValue(); + +- if (endOfBatch) relationshipWriter.flush(); ++ createUpdateRecords(event.relationshipsToUpdate.getIncoming(), prevId, followingNextRelationshipId, false); ++ } ++ if (endOfBatch) relationshipWriter.flush(); + } + + private long createUpdateRecords(long[] relIds, long prevId, long followingNextRelationshipId, boolean outgoing) throws IOException { +- if (relIds==null) return prevId; +- int count = Utils.size(relIds); ++ if (relIds==null || relIds.length==0) return prevId; ++ int count = relIds.length; + for (int i = 0; i < count; i++) { + long nextId = i+1 < count ? relIds[i + 1] : followingNextRelationshipId; + relationshipWriter.update(relIds[i], outgoing, prevId, nextId); +diff --git a/src/main/java/org/neo4j/batchimport/importer/RowData.java b/src/main/java/org/neo4j/batchimport/importer/RowData.java +index 13bab4e..7aa3503 100644 +--- a/src/main/java/org/neo4j/batchimport/importer/RowData.java ++++ b/src/main/java/org/neo4j/batchimport/importer/RowData.java +@@ -104,7 +104,7 @@ public Map updateMap(String line, Object... header) { + + public Object[] updateArray(String line, Object... header) { + process(line); +- if (header.length > 0) { ++ if (header!=null && header.length > 0) { + System.arraycopy(lineData, 0, header, 0, header.length); + } + return data; +diff --git a/src/main/java/org/neo4j/batchimport/structs/NodeStruct.java b/src/main/java/org/neo4j/batchimport/structs/NodeStruct.java +index 4378989..e1e9f35 100644 +--- a/src/main/java/org/neo4j/batchimport/structs/NodeStruct.java ++++ b/src/main/java/org/neo4j/batchimport/structs/NodeStruct.java +@@ -1,5 +1,6 @@ + package org.neo4j.batchimport.structs; + ++import org.neo4j.batchimport.collections.CompactLongRecord; + import org.neo4j.kernel.impl.nioneo.store.Record; + + import java.util.ArrayList; +@@ -20,8 +21,7 @@ public class NodeStruct extends PropertyHolder { + + public volatile long lastPropertyId; + public volatile long maxRelationshipId; +- public volatile long[] outgoingRelationshipsToUpdate; +- public volatile long[] incomingRelationshipsToUpdate; ++ public volatile CompactLongRecord relationshipsToUpdate; + private static int avgRelCount; + private static int relPropertyCount; + +diff --git a/src/test/java/org/neo4j/batchimport/DisruptorBatchInserterTest.java b/src/test/java/org/neo4j/batchimport/DisruptorBatchInserterTest.java +index 924acdb..2a8db4d 100644 +--- a/src/test/java/org/neo4j/batchimport/DisruptorBatchInserterTest.java ++++ b/src/test/java/org/neo4j/batchimport/DisruptorBatchInserterTest.java +@@ -18,7 +18,7 @@ public class DisruptorBatchInserterTest { + public void testSelfRelationship() throws Exception { + final NodeStruct struct = new NodeStruct(0); + struct.addRel(0, true, 0); +- new RelationshipIdHandler(1).onEvent(struct,0,false); ++ new RelationshipIdHandler().onEvent(struct,0,false); + //new RelationshipWriteHandler(new RelationshipRecordWriter(neoStore.getRelationshipStore())).onEvent(struct,0,false); + } + } +diff --git a/src/test/java/org/neo4j/batchimport/DisruptorTest.java b/src/test/java/org/neo4j/batchimport/DisruptorTest.java +index ef16895..acc91e1 100644 +--- a/src/test/java/org/neo4j/batchimport/DisruptorTest.java ++++ b/src/test/java/org/neo4j/batchimport/DisruptorTest.java +@@ -45,8 +45,8 @@ public class DisruptorTest { + private final static Logger log = Logger.getLogger(DisruptorBatchInserter.class); + + public static final String STORE_DIR = ""target/test-db2""; +- public static final int NODES_TO_CREATE = 1 * 1000 * 1000; +- private static final boolean RUN_CHECK = true; ++ public static final int NODES_TO_CREATE = 100 * 1000 ; ++ private static final boolean RUN_CHECK = false; + + @SuppressWarnings(""unchecked"") + public static void main(String[] args) throws Exception { +diff --git a/src/test/java/org/neo4j/batchimport/TestDataGenerator.java b/src/test/java/org/neo4j/batchimport/TestDataGenerator.java +index fc9e342..2449311 100644 +--- a/src/test/java/org/neo4j/batchimport/TestDataGenerator.java ++++ b/src/test/java/org/neo4j/batchimport/TestDataGenerator.java +@@ -14,7 +14,7 @@ + @Ignore + public class TestDataGenerator { + +- private static int NODES = 100 * 1000 * 1000; // * 1000; ++ private static int NODES = 1000 * 1000; // * 1000; + private static final int RELS_PER_NODE = 50; + private static final String[] TYPES = {""ONE"",""TWO"",""THREE"",""FOUR"",""FIVE"",""SIX"",""SEVEN"",""EIGHT"",""NINE"",""TEN""}; + public static final int NUM_TYPES = 10; +diff --git a/src/test/java/org/neo4j/batchimport/collections/CompactLongRecordTest.java b/src/test/java/org/neo4j/batchimport/collections/CompactLongRecordTest.java +new file mode 100644 +index 0000000..4bda4f9 +--- /dev/null ++++ b/src/test/java/org/neo4j/batchimport/collections/CompactLongRecordTest.java +@@ -0,0 +1,73 @@ ++package org.neo4j.batchimport.collections; ++ ++import org.junit.Test; ++ ++import java.util.Random; ++ ++import static org.junit.Assert.assertEquals; ++ ++/** ++ * @author mh ++ * @since 03.11.12 ++ */ ++public class CompactLongRecordTest { ++ ++ private static final int COUNT = 10000000; ++ private static final int LONGS = 1000; ++ private final CompactLongRecord record = new CompactLongRecord((byte)0); ++ ++ @Test ++ public void testAddIntValues() throws Exception { ++ record.add(0, true); ++ record.add(Integer.MAX_VALUE, true); ++ long[] ids = record.getOutgoing(); ++ assertEquals(2,record.count(true)); ++ assertEquals(0,ids[0]); ++ assertEquals(Integer.MAX_VALUE,ids[1]); ++ } ++ ++ @Test ++ public void testAddIncomingValues() throws Exception { ++ record.add(0, false); ++ record.add(Integer.MAX_VALUE, false); ++ assertEquals(2,record.count(false)); ++ long[] ids = record.getIncoming(); ++ assertEquals(0,ids[0]); ++ assertEquals(Integer.MAX_VALUE,ids[1]); ++ } ++ ++ @Test ++ public void testAddLongValues() throws Exception { ++ record.add(1L << 32, true); ++ record.add(1L << 33, true); ++ long[] ids = record.getOutgoing(); ++ assertEquals(2,record.count(true)); ++ assertEquals(1L << 32,ids[0]); ++ assertEquals(1L << 33,ids[1]); ++ } ++ ++ @Test ++ public void testPerformance() throws Exception { ++ long[] input = generateLongs(LONGS); ++ ++ long free = Runtime.getRuntime().freeMemory(); ++ long time = System.currentTimeMillis(); ++ ++ for (int i=0;i< COUNT;i++) { ++ record.add(input[i % LONGS],true); ++ } ++ ++ final long usedMemory = free - Runtime.getRuntime().freeMemory(); ++ System.out.println(""took ""+(System.currentTimeMillis()-time)+ "" ms, used ""+ usedMemory / 1024/1024+ "" MB""); ++ assertEquals(COUNT,record.count(true)); ++ } ++ ++ private long[] generateLongs(int count) { ++ final Random rnd = new Random(); ++ final long[] result = new long[count]; ++ for (int i = 0; i < count; i++) { ++ result[i] = rnd.nextLong() & 0x7FFFFFFFFL; ++ } ++ return result; ++ } ++} +diff --git a/src/test/java/org/neo4j/batchimport/collections/IntArrayTest.java b/src/test/java/org/neo4j/batchimport/collections/IntArrayTest.java +new file mode 100644 +index 0000000..f4a0d5c +--- /dev/null ++++ b/src/test/java/org/neo4j/batchimport/collections/IntArrayTest.java +@@ -0,0 +1,63 @@ ++package org.neo4j.batchimport.collections; ++ ++import org.junit.Test; ++ ++import static org.junit.Assert.assertEquals; ++ ++/** ++ * @author mh ++ * @since 03.11.12 ++ */ ++public class IntArrayTest { ++ ++ private final IntArray array = new IntArray(); ++ ++ @Test ++ public void testAdd() throws Exception { ++ array.add(42); ++ assertEquals(1, array.count); ++ assertEquals(42, array.data[0]); ++ } ++ ++ @Test ++ public void testEmptyArray() throws Exception { ++ assertEquals(false,array.hasData()); ++ assertEquals(false,array.hasPositive()); ++ assertEquals(false,array.hasNegative()); ++ } ++ ++ @Test ++ public void testHasPositive() throws Exception { ++ array.add(42); ++ assertEquals(true,array.hasData()); ++ assertEquals(true,array.hasPositive()); ++ assertEquals(false,array.hasNegative()); ++ } ++ @Test ++ public void testHasNegative() throws Exception { ++ array.add(-1); ++ assertEquals(true,array.hasData()); ++ assertEquals(false,array.hasPositive()); ++ assertEquals(true, array.hasNegative()); ++ } ++ ++ @Test ++ public void testPositiveLast() throws Exception { ++ array.add(-1); ++ array.add(42); ++ assertEquals(2, array.count); ++ assertEquals(true, array.hasPositive()); ++ assertEquals(true, array.hasNegative()); ++ assertEquals(42, array.firstPositive()); ++ assertEquals(-1, array.firstNegative()); ++ } ++ ++ @Test ++ public void testPositiveFirst() throws Exception { ++ array.add(42); ++ array.add(-1); ++ assertEquals(2, array.count); ++ assertEquals(42, array.firstPositive()); ++ assertEquals(-1, array.firstNegative()); ++ } ++}" +fef434b11eb3abf88fca6ac3073a5025447a646d,orientdb,Fixed issue -1521 about JSON management of- embedded lists with different types--,c,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +0b4b9f7ed12a5609c760ca93521d52879ab08413,Vala,"Add more default attributes +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +384542ccb54c28d73d9f368f2375ef60d99127ac,restlet-framework-java, - Fixed error in Conditions.getStatus()- sometimes returning 304 for methods other than HEAD and GET.- Contributed by Stephan Koops.--,c,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt +index e78b997580..783366ca6f 100644 +--- a/build/tmpl/text/changes.txt ++++ b/build/tmpl/text/changes.txt +@@ -33,6 +33,9 @@ Changes log + the parent resource has no 'id' attribute. Also supports + root resources with no leading slash. Patches contributed + by Vincent Ricard. ++ - Fixed error in Conditions.getStatus() sometimes returning ++ 304 for methods other than HEAD and GET. Contributed by ++ Stephan Koops. + - Misc + - Updated db4o to version 7.4.58. + - Updated FreeMarker to version 2.3.14. +diff --git a/modules/org.restlet/src/org/restlet/data/Conditions.java b/modules/org.restlet/src/org/restlet/data/Conditions.java +index 0c717a46ff..d862e06a5e 100644 +--- a/modules/org.restlet/src/org/restlet/data/Conditions.java ++++ b/modules/org.restlet/src/org/restlet/data/Conditions.java +@@ -233,7 +233,11 @@ public Status getStatus(Method method, Representation representation) { + .getModificationDate())); + + if (!isModifiedSince) { +- result = Status.REDIRECTION_NOT_MODIFIED; ++ if (Method.GET.equals(method) || Method.HEAD.equals(method)) { ++ result = Status.REDIRECTION_NOT_MODIFIED; ++ } else { ++ result = Status.CLIENT_ERROR_PRECONDITION_FAILED; ++ } + } + } + } +diff --git a/modules/org.restlet/src/org/restlet/data/Request.java b/modules/org.restlet/src/org/restlet/data/Request.java +index cc2e0ed6ad..9c81cbd5d5 100644 +--- a/modules/org.restlet/src/org/restlet/data/Request.java ++++ b/modules/org.restlet/src/org/restlet/data/Request.java +@@ -509,9 +509,11 @@ public void setOriginalRef(Reference originalRef) { + /** + * Sets the ranges to return from the target resource's representation. + * ++ * @param ranges ++ * The ranges. + */ +- public void setRanges(List range) { +- this.ranges = range; ++ public void setRanges(List ranges) { ++ this.ranges = ranges; + } + + /**" +21760a8b6b030233d4a82d8026bc9910e0a93ea5,spring-framework,Provide alternative message code resolver styles--Introduce new 'style' property to DefaultMessageCodesResolver allowing-for alternative message styles. Current styles are PREFIX_ERROR_CODE-and POSTFIX_ERROR_CODE. The default style retains existing behavior.--Issue: SPR-9707-,a,https://github.com/spring-projects/spring-framework,"diff --git a/spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java b/spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java +index ad282eb1d19c..44d8b65c720c 100644 +--- a/spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java ++++ b/spring-context/src/main/java/org/springframework/validation/DefaultMessageCodesResolver.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2002-2008 the original author or authors. ++ * Copyright 2002-2012 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. +@@ -18,14 +18,18 @@ + + import java.io.Serializable; + import java.util.ArrayList; ++import java.util.Collection; ++import java.util.LinkedHashSet; + import java.util.List; ++import java.util.Set; + + import org.springframework.util.StringUtils; + + /** + * Default implementation of the {@link MessageCodesResolver} interface. + * +- *

Will create two message codes for an object error, in the following order: ++ *

Will create two message codes for an object error, in the following order (when ++ * using the {@link Style#PREFIX_ERROR_CODE prefixed} {@link #setStyle(Style) style}): + *

+ * ++ *

By default the {@code errorCode}s will be placed at the beginning of constructed ++ * message strings. The {@link #setStyle(Style) style} property can be used to specify ++ * alternative {@link Style styles} of concatination. ++ * + *

In order to group all codes into a specific category within your resource bundles, + * e.g. ""validation.typeMismatch.name"" instead of the default ""typeMismatch.name"", + * consider specifying a {@link #setPrefix prefix} to be applied. + * + * @author Juergen Hoeller ++ * @author Phillip Webb + * @since 1.0.1 + */ + @SuppressWarnings(""serial"") +@@ -83,9 +92,13 @@ public class DefaultMessageCodesResolver implements MessageCodesResolver, Serial + */ + public static final String CODE_SEPARATOR = "".""; + ++ private static final Style DEFAULT_STYLE = Style.PREFIX_ERROR_CODE; ++ + + private String prefix = """"; + ++ private Style style = DEFAULT_STYLE; ++ + + /** + * Specify a prefix to be applied to any code built by this resolver. +@@ -96,6 +109,14 @@ public void setPrefix(String prefix) { + this.prefix = (prefix != null ? prefix : """"); + } + ++ /** ++ * Specify the style of message code that will be built by this resolver. ++ *

Default is {@link Style#PREFIX_ERROR_CODE}. ++ */ ++ public void setStyle(Style style) { ++ this.style = (style == null ? DEFAULT_STYLE : style); ++ } ++ + /** + * Return the prefix to be applied to any code built by this resolver. + *

Returns an empty String in case of no prefix. +@@ -106,9 +127,7 @@ protected String getPrefix() { + + + public String[] resolveMessageCodes(String errorCode, String objectName) { +- return new String[] { +- postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName), +- postProcessMessageCode(errorCode)}; ++ return resolveMessageCodes(errorCode, objectName, """", null); + } + + /** +@@ -121,26 +140,54 @@ public String[] resolveMessageCodes(String errorCode, String objectName) { + * @return the list of codes + */ + public String[] resolveMessageCodes(String errorCode, String objectName, String field, Class fieldType) { +- List codeList = new ArrayList(); ++ Set codeList = new LinkedHashSet(); + List fieldList = new ArrayList(); + buildFieldList(field, fieldList); +- for (String fieldInList : fieldList) { +- codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + objectName + CODE_SEPARATOR + fieldInList)); +- } ++ addCodes(codeList, errorCode, objectName, fieldList); + int dotIndex = field.lastIndexOf('.'); + if (dotIndex != -1) { + buildFieldList(field.substring(dotIndex + 1), fieldList); + } +- for (String fieldInList : fieldList) { +- codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldInList)); +- } ++ addCodes(codeList, errorCode, null, fieldList); + if (fieldType != null) { +- codeList.add(postProcessMessageCode(errorCode + CODE_SEPARATOR + fieldType.getName())); ++ addCode(codeList, errorCode, null, fieldType.getName()); + } +- codeList.add(postProcessMessageCode(errorCode)); ++ addCode(codeList, errorCode, null, null); + return StringUtils.toStringArray(codeList); + } + ++ private void addCodes(Collection codeList, String errorCode, String objectName, Iterable fields) { ++ for (String field : fields) { ++ addCode(codeList, errorCode, objectName, field); ++ } ++ } ++ ++ private void addCode(Collection codeList, String errorCode, String objectName, String field) { ++ String code = getCode(errorCode, objectName, field); ++ codeList.add(postProcessMessageCode(code)); ++ } ++ ++ private String getCode(String errorCode, String objectName, String field) { ++ switch (this.style) { ++ case PREFIX_ERROR_CODE: ++ return toDelimitedString(errorCode, objectName, field); ++ case POSTFIX_ERROR_CODE: ++ return toDelimitedString(objectName, field, errorCode); ++ } ++ throw new IllegalStateException(""Unknown style "" + this.style); ++ } ++ ++ private String toDelimitedString(String... elements) { ++ StringBuilder rtn = new StringBuilder(); ++ for (String element : elements) { ++ if(StringUtils.hasLength(element)) { ++ rtn.append(rtn.length() == 0 ? """" : CODE_SEPARATOR); ++ rtn.append(element); ++ } ++ } ++ return rtn.toString(); ++ } ++ + /** + * Add both keyed and non-keyed entries for the supplied field + * to the supplied field list. +@@ -173,4 +220,23 @@ protected String postProcessMessageCode(String code) { + return getPrefix() + code; + } + ++ ++ /** ++ * The various styles that can be used to construct message codes. ++ */ ++ public static enum Style { ++ ++ /** ++ * Prefix the error code at the beginning of the generated message code. eg: ++ * {@code errorCode + ""."" + object name + ""."" + field} ++ */ ++ PREFIX_ERROR_CODE, ++ ++ /** ++ * Postfix the error code at the end of the generated message code. eg: ++ * {@code object name + ""."" + field + ""."" + errorCode} ++ */ ++ POSTFIX_ERROR_CODE ++ } ++ + } +diff --git a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java +index 33083409ae6e..18bb109b5a32 100644 +--- a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java ++++ b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java +@@ -22,6 +22,7 @@ + + import org.junit.Test; + import org.springframework.beans.TestBean; ++import org.springframework.validation.DefaultMessageCodesResolver.Style; + + /** + * Tests for {@link DefaultMessageCodesResolver}. +@@ -119,5 +120,26 @@ public void shouldSupportNullFieldType() throws Exception { + ""errorCode.objectName.field"", + ""errorCode.field"", + ""errorCode"" }))); +- } ++ } ++ ++ @Test ++ public void shouldSupportPostfixStyle() throws Exception { ++ resolver.setStyle(Style.POSTFIX_ERROR_CODE); ++ String[] codes = resolver.resolveMessageCodes(""errorCode"", ""objectName""); ++ assertThat(codes, is(equalTo(new String[] { ++ ""objectName.errorCode"", ++ ""errorCode"" }))); ++ } ++ ++ @Test ++ public void shouldSupportFieldPostfixStyle() throws Exception { ++ resolver.setStyle(Style.POSTFIX_ERROR_CODE); ++ String[] codes = resolver.resolveMessageCodes(""errorCode"", ""objectName"", ""field"", ++ TestBean.class); ++ assertThat(codes, is(equalTo(new String[] { ++ ""objectName.field.errorCode"", ++ ""field.errorCode"", ++ ""org.springframework.beans.TestBean.errorCode"", ++ ""errorCode"" }))); ++ } + }" +e99464c45f8394708291498864de1c18f183434c,tapiji,"Removes the outdate plug-in 'org.apache.commons.io'. +",p,https://github.com/tapiji/tapiji,"diff --git a/org.apache.commons.io/.classpath b/org.apache.commons.io/.classpath +deleted file mode 100644 +index f2d41466..00000000 +--- a/org.apache.commons.io/.classpath ++++ /dev/null +@@ -1,7 +0,0 @@ +- +- +- +- +- +- +- +diff --git a/org.apache.commons.io/.project b/org.apache.commons.io/.project +deleted file mode 100644 +index b4ddad64..00000000 +--- a/org.apache.commons.io/.project ++++ /dev/null +@@ -1,28 +0,0 @@ +- +- +- org.apache.commons.io +- +- +- +- +- +- org.eclipse.jdt.core.javabuilder +- +- +- +- +- org.eclipse.pde.ManifestBuilder +- +- +- +- +- org.eclipse.pde.SchemaBuilder +- +- +- +- +- +- org.eclipse.pde.PluginNature +- org.eclipse.jdt.core.javanature +- +- +diff --git a/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs b/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs +deleted file mode 100644 +index 2f1261fd..00000000 +--- a/org.apache.commons.io/.settings/org.eclipse.jdt.core.prefs ++++ /dev/null +@@ -1,8 +0,0 @@ +-#Sat Apr 21 11:12:43 CEST 2012 +-eclipse.preferences.version=1 +-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +-org.eclipse.jdt.core.compiler.compliance=1.6 +-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +-org.eclipse.jdt.core.compiler.source=1.6 +diff --git a/org.apache.commons.io/META-INF/LICENSE.txt b/org.apache.commons.io/META-INF/LICENSE.txt +deleted file mode 100644 +index 43e91eb0..00000000 +--- a/org.apache.commons.io/META-INF/LICENSE.txt ++++ /dev/null +@@ -1,203 +0,0 @@ +- +- Apache License +- Version 2.0, January 2004 +- http://www.apache.org/licenses/ +- +- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +- +- 1. Definitions. +- +- ""License"" shall mean the terms and conditions for use, reproduction, +- and distribution as defined by Sections 1 through 9 of this document. +- +- ""Licensor"" shall mean the copyright owner or entity authorized by +- the copyright owner that is granting the License. +- +- ""Legal Entity"" shall mean the union of the acting entity and all +- other entities that control, are controlled by, or are under common +- control with that entity. For the purposes of this definition, +- ""control"" means (i) the power, direct or indirect, to cause the +- direction or management of such entity, whether by contract or +- otherwise, or (ii) ownership of fifty percent (50%) or more of the +- outstanding shares, or (iii) beneficial ownership of such entity. +- +- ""You"" (or ""Your"") shall mean an individual or Legal Entity +- exercising permissions granted by this License. +- +- ""Source"" form shall mean the preferred form for making modifications, +- including but not limited to software source code, documentation +- source, and configuration files. +- +- ""Object"" form shall mean any form resulting from mechanical +- transformation or translation of a Source form, including but +- not limited to compiled object code, generated documentation, +- and conversions to other media types. +- +- ""Work"" shall mean the work of authorship, whether in Source or +- Object form, made available under the License, as indicated by a +- copyright notice that is included in or attached to the work +- (an example is provided in the Appendix below). +- +- ""Derivative Works"" shall mean any work, whether in Source or Object +- form, that is based on (or derived from) the Work and for which the +- editorial revisions, annotations, elaborations, or other modifications +- represent, as a whole, an original work of authorship. For the purposes +- of this License, Derivative Works shall not include works that remain +- separable from, or merely link (or bind by name) to the interfaces of, +- the Work and Derivative Works thereof. +- +- ""Contribution"" shall mean any work of authorship, including +- the original version of the Work and any modifications or additions +- to that Work or Derivative Works thereof, that is intentionally +- submitted to Licensor for inclusion in the Work by the copyright owner +- or by an individual or Legal Entity authorized to submit on behalf of +- the copyright owner. For the purposes of this definition, ""submitted"" +- means any form of electronic, verbal, or written communication sent +- to the Licensor or its representatives, including but not limited to +- communication on electronic mailing lists, source code control systems, +- and issue tracking systems that are managed by, or on behalf of, the +- Licensor for the purpose of discussing and improving the Work, but +- excluding communication that is conspicuously marked or otherwise +- designated in writing by the copyright owner as ""Not a Contribution."" +- +- ""Contributor"" shall mean Licensor and any individual or Legal Entity +- on behalf of whom a Contribution has been received by Licensor and +- subsequently incorporated within the Work. +- +- 2. Grant of Copyright License. Subject to the terms and conditions of +- this License, each Contributor hereby grants to You a perpetual, +- worldwide, non-exclusive, no-charge, royalty-free, irrevocable +- copyright license to reproduce, prepare Derivative Works of, +- publicly display, publicly perform, sublicense, and distribute the +- Work and such Derivative Works in Source or Object form. +- +- 3. Grant of Patent License. Subject to the terms and conditions of +- this License, each Contributor hereby grants to You a perpetual, +- worldwide, non-exclusive, no-charge, royalty-free, irrevocable +- (except as stated in this section) patent license to make, have made, +- use, offer to sell, sell, import, and otherwise transfer the Work, +- where such license applies only to those patent claims licensable +- by such Contributor that are necessarily infringed by their +- Contribution(s) alone or by combination of their Contribution(s) +- with the Work to which such Contribution(s) was submitted. If You +- institute patent litigation against any entity (including a +- cross-claim or counterclaim in a lawsuit) alleging that the Work +- or a Contribution incorporated within the Work constitutes direct +- or contributory patent infringement, then any patent licenses +- granted to You under this License for that Work shall terminate +- as of the date such litigation is filed. +- +- 4. Redistribution. You may reproduce and distribute copies of the +- Work or Derivative Works thereof in any medium, with or without +- modifications, and in Source or Object form, provided that You +- meet the following conditions: +- +- (a) You must give any other recipients of the Work or +- Derivative Works a copy of this License; and +- +- (b) You must cause any modified files to carry prominent notices +- stating that You changed the files; and +- +- (c) You must retain, in the Source form of any Derivative Works +- that You distribute, all copyright, patent, trademark, and +- attribution notices from the Source form of the Work, +- excluding those notices that do not pertain to any part of +- the Derivative Works; and +- +- (d) If the Work includes a ""NOTICE"" text file as part of its +- distribution, then any Derivative Works that You distribute must +- include a readable copy of the attribution notices contained +- within such NOTICE file, excluding those notices that do not +- pertain to any part of the Derivative Works, in at least one +- of the following places: within a NOTICE text file distributed +- as part of the Derivative Works; within the Source form or +- documentation, if provided along with the Derivative Works; or, +- within a display generated by the Derivative Works, if and +- wherever such third-party notices normally appear. The contents +- of the NOTICE file are for informational purposes only and +- do not modify the License. You may add Your own attribution +- notices within Derivative Works that You distribute, alongside +- or as an addendum to the NOTICE text from the Work, provided +- that such additional attribution notices cannot be construed +- as modifying the License. +- +- You may add Your own copyright statement to Your modifications and +- may provide additional or different license terms and conditions +- for use, reproduction, or distribution of Your modifications, or +- for any such Derivative Works as a whole, provided Your use, +- reproduction, and distribution of the Work otherwise complies with +- the conditions stated in this License. +- +- 5. Submission of Contributions. Unless You explicitly state otherwise, +- any Contribution intentionally submitted for inclusion in the Work +- by You to the Licensor shall be under the terms and conditions of +- this License, without any additional terms or conditions. +- Notwithstanding the above, nothing herein shall supersede or modify +- the terms of any separate license agreement you may have executed +- with Licensor regarding such Contributions. +- +- 6. Trademarks. This License does not grant permission to use the trade +- names, trademarks, service marks, or product names of the Licensor, +- except as required for reasonable and customary use in describing the +- origin of the Work and reproducing the content of the NOTICE file. +- +- 7. Disclaimer of Warranty. Unless required by applicable law or +- agreed to in writing, Licensor provides the Work (and each +- Contributor provides its Contributions) on an ""AS IS"" BASIS, +- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +- implied, including, without limitation, any warranties or conditions +- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +- PARTICULAR PURPOSE. You are solely responsible for determining the +- appropriateness of using or redistributing the Work and assume any +- risks associated with Your exercise of permissions under this License. +- +- 8. Limitation of Liability. In no event and under no legal theory, +- whether in tort (including negligence), contract, or otherwise, +- unless required by applicable law (such as deliberate and grossly +- negligent acts) or agreed to in writing, shall any Contributor be +- liable to You for damages, including any direct, indirect, special, +- incidental, or consequential damages of any character arising as a +- result of this License or out of the use or inability to use the +- Work (including but not limited to damages for loss of goodwill, +- work stoppage, computer failure or malfunction, or any and all +- other commercial damages or losses), even if such Contributor +- has been advised of the possibility of such damages. +- +- 9. Accepting Warranty or Additional Liability. While redistributing +- the Work or Derivative Works thereof, You may choose to offer, +- and charge a fee for, acceptance of support, warranty, indemnity, +- or other liability obligations and/or rights consistent with this +- License. However, in accepting such obligations, You may act only +- on Your own behalf and on Your sole responsibility, not on behalf +- of any other Contributor, and only if You agree to indemnify, +- defend, and hold each Contributor harmless for any liability +- incurred by, or claims asserted against, such Contributor by reason +- of your accepting any such warranty or additional liability. +- +- END OF TERMS AND CONDITIONS +- +- APPENDIX: How to apply the Apache License to your work. +- +- To apply the Apache License to your work, attach the following +- boilerplate notice, with the fields enclosed by brackets ""[]"" +- replaced with your own identifying information. (Don't include +- the brackets!) The text should be enclosed in the appropriate +- comment syntax for the file format. We also recommend that a +- file or class name and description of purpose be included on the +- same ""printed page"" as the copyright notice for easier +- identification within third-party archives. +- +- Copyright [yyyy] [name of copyright owner] +- +- Licensed under the Apache License, Version 2.0 (the ""License""); +- you may not use this file except in compliance with the License. +- You may obtain a copy of the License at +- +- http://www.apache.org/licenses/LICENSE-2.0 +- +- Unless required by applicable law or agreed to in writing, software +- distributed under the License is distributed on an ""AS IS"" BASIS, +- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- See the License for the specific language governing permissions and +- limitations under the License. +- +diff --git a/org.apache.commons.io/META-INF/MANIFEST.MF b/org.apache.commons.io/META-INF/MANIFEST.MF +deleted file mode 100644 +index 79a52482..00000000 +--- a/org.apache.commons.io/META-INF/MANIFEST.MF ++++ /dev/null +@@ -1,12 +0,0 @@ +-Manifest-Version: 1.0 +-Bundle-ManifestVersion: 2 +-Bundle-Name: Apache Commons IO +-Bundle-SymbolicName: org.apache.commons.io +-Bundle-Version: 1.0.0 +-Export-Package: org.apache.commons.io, +- org.apache.commons.io.comparator, +- org.apache.commons.io.filefilter, +- org.apache.commons.io.input, +- org.apache.commons.io.monitor, +- org.apache.commons.io.output +-Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +diff --git a/org.apache.commons.io/META-INF/NOTICE.txt b/org.apache.commons.io/META-INF/NOTICE.txt +deleted file mode 100644 +index 7632eb8e..00000000 +--- a/org.apache.commons.io/META-INF/NOTICE.txt ++++ /dev/null +@@ -1,6 +0,0 @@ +-Apache Commons IO +-Copyright 2002-2012 The Apache Software Foundation +- +-This product includes software developed by +-The Apache Software Foundation (http://www.apache.org/). +- +diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties +deleted file mode 100644 +index b3e76eb3..00000000 +--- a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.properties ++++ /dev/null +@@ -1,5 +0,0 @@ +-#Generated by Maven +-#Tue Apr 10 11:00:26 EDT 2012 +-version=2.3 +-groupId=commons-io +-artifactId=commons-io +diff --git a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml b/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml +deleted file mode 100644 +index bae10d22..00000000 +--- a/org.apache.commons.io/META-INF/maven/commons-io/commons-io/pom.xml ++++ /dev/null +@@ -1,346 +0,0 @@ +- +- +- +- +- org.apache.commons +- commons-parent +- 24 +- +- 4.0.0 +- commons-io +- commons-io +- 2.3 +- Commons IO +- +- 2002 +- +-The Commons IO library contains utility classes, stream implementations, file filters, +-file comparators, endian transformation classes, and much more. +- +- +- http://commons.apache.org/io/ +- +- +- jira +- http://issues.apache.org/jira/browse/IO +- +- +- +- +- apache.website +- Apache Commons IO Site +- ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/${commons.componentid} +- +- +- +- +- scm:svn:http://svn.apache.org/repos/asf/commons/proper/io/trunk +- scm:svn:https://svn.apache.org/repos/asf/commons/proper/io/trunk +- http://svn.apache.org/viewvc/commons/proper/io/trunk +- +- +- +- +- Scott Sanders +- sanders +- sanders@apache.org +- +- +- Java Developer +- +- +- +- dIon Gillard +- dion +- dion@apache.org +- +- +- Java Developer +- +- +- +- Nicola Ken Barozzi +- nicolaken +- nicolaken@apache.org +- +- +- Java Developer +- +- +- +- Henri Yandell +- bayard +- bayard@apache.org +- +- +- Java Developer +- +- +- +- Stephen Colebourne +- scolebourne +- +- +- Java Developer +- +- 0 +- +- +- Jeremias Maerki +- jeremias +- jeremias@apache.org +- +- +- Java Developer +- +- +1 +- +- +- Matthew Hawthorne +- matth +- matth@apache.org +- +- +- Java Developer +- +- +- +- Martin Cooper +- martinc +- martinc@apache.org +- +- +- Java Developer +- +- +- +- Rob Oxspring +- roxspring +- roxspring@apache.org +- +- +- Java Developer +- +- +- +- Jochen Wiedmann +- jochen +- jochen.wiedmann@gmail.com +- +- +- Niall Pemberton +- niallp +- +- Java Developer +- +- +- +- Jukka Zitting +- jukka +- +- Java Developer +- +- +- +- Gary Gregory +- ggregory +- ggregory@apache.org +- http://www.garygregory.com +- -5 +- +- +- +- +- +- Rahul Akolkar +- +- +- Jason Anderson +- +- +- Nathan Beyer +- +- +- Emmanuel Bourg +- +- +- Chris Eldredge +- +- +- Magnus Grimsell +- +- +- Jim Harrington +- +- +- Thomas Ledoux +- +- +- Andy Lehane +- +- +- Marcelo Liberato +- +- +- Alban Peignier +- alban.peignier at free.fr +- +- +- Ian Springer +- +- +- Masato Tezuka +- +- +- James Urie +- +- +- Frank W. Zammetti +- +- +- +- +- +- junit +- junit +- 4.10 +- test +- +- +- +- +- 1.6 +- 1.6 +- io +- RC1 +- 2.3 +- (requires JDK 1.6+) +- 2.2 +- (requires JDK 1.5+) +- IO +- 12310477 +- +- 2.4 +- +- +- +- +- +- +- +- org.codehaus.mojo +- clirr-maven-plugin +- ${commons.clirr.version} +- +- ${minSeverity} +- +- +- +- +- +- +- org.apache.maven.plugins +- maven-surefire-plugin +- +- pertest +- +- -Xmx25M +- +- +- **/*Test*.class +- +- +- **/*AbstractTestCase* +- **/testtools/** +- +- +- **/*$* +- +- +- +- +- maven-assembly-plugin +- +- +- src/main/assembly/bin.xml +- src/main/assembly/src.xml +- +- gnu +- +- +- +- +- +- +- +- +- org.apache.maven.plugins +- maven-checkstyle-plugin +- 2.9.1 +- +- ${basedir}/checkstyle.xml +- false +- +- +- +- org.codehaus.mojo +- findbugs-maven-plugin +- 2.4.0 +- +- Normal +- Default +- ${basedir}/findbugs-exclude-filter.xml +- +- +- +- org.apache.maven.plugins +- maven-changes-plugin +- ${commons.changes.version} +- +- ${basedir}/src/changes/changes.xml +- Fix Version,Key,Component,Summary,Type,Resolution,Status +- +- Key DESC,Type,Fix Version DESC +- Fixed +- Resolved,Closed +- +- Bug,New Feature,Task,Improvement,Wish,Test +- 300 +- +- +- +- +- changes-report +- jira-report +- +- +- +- +- +- org.apache.rat +- apache-rat-plugin +- +- +- src/test/resources/**/*.bin +- .pmd +- +- +- +- +- +- +diff --git a/org.apache.commons.io/build.properties b/org.apache.commons.io/build.properties +deleted file mode 100644 +index 1ac73bad..00000000 +--- a/org.apache.commons.io/build.properties ++++ /dev/null +@@ -1,3 +0,0 @@ +-output.. = . +-bin.includes = META-INF/,\ +- org/ +diff --git a/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class b/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class +deleted file mode 100644 +index 8bebf2de..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/ByteOrderMark.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/Charsets.class b/org.apache.commons.io/org/apache/commons/io/Charsets.class +deleted file mode 100644 +index 88a74baf..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/Charsets.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/CopyUtils.class b/org.apache.commons.io/org/apache/commons/io/CopyUtils.class +deleted file mode 100644 +index 6de1db52..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/CopyUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class +deleted file mode 100644 +index ed333c99..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker$CancelException.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class b/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class +deleted file mode 100644 +index db7fc482..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/DirectoryWalker.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/EndianUtils.class b/org.apache.commons.io/org/apache/commons/io/EndianUtils.class +deleted file mode 100644 +index f4b0af54..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/EndianUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaner.class b/org.apache.commons.io/org/apache/commons/io/FileCleaner.class +deleted file mode 100644 +index 17ee0f8b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaner.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class +deleted file mode 100644 +index 6c0a2d53..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Reaper.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class +deleted file mode 100644 +index 063d71c0..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker$Tracker.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class b/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class +deleted file mode 100644 +index f793406b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileCleaningTracker.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class +deleted file mode 100644 +index 49b9d33c..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy$ForceFileDeleteStrategy.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class b/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class +deleted file mode 100644 +index 8731c9c9..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileDeleteStrategy.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileExistsException.class b/org.apache.commons.io/org/apache/commons/io/FileExistsException.class +deleted file mode 100644 +index 8eef129b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileExistsException.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class b/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class +deleted file mode 100644 +index 68888e3a..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileSystemUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FileUtils.class b/org.apache.commons.io/org/apache/commons/io/FileUtils.class +deleted file mode 100644 +index f2d4c17c..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FileUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class b/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class +deleted file mode 100644 +index 059b648a..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/FilenameUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/HexDump.class b/org.apache.commons.io/org/apache/commons/io/HexDump.class +deleted file mode 100644 +index c88a861e..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/HexDump.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/IOCase.class b/org.apache.commons.io/org/apache/commons/io/IOCase.class +deleted file mode 100644 +index 26f6e6da..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/IOCase.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class b/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class +deleted file mode 100644 +index e0835d50..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/IOExceptionWithCause.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/IOUtils.class b/org.apache.commons.io/org/apache/commons/io/IOUtils.class +deleted file mode 100644 +index 725d4f68..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/IOUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/LineIterator.class b/org.apache.commons.io/org/apache/commons/io/LineIterator.class +deleted file mode 100644 +index 08221a75..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/LineIterator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class b/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class +deleted file mode 100644 +index 1eddd012..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/TaggedIOException.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class b/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class +deleted file mode 100644 +index 5719a356..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/ThreadMonitor.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class +deleted file mode 100644 +index a3e8b2e2..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/AbstractFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class +deleted file mode 100644 +index b5774654..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/CompositeFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class +deleted file mode 100644 +index 19e76e80..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/DefaultFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class +deleted file mode 100644 +index 6718ac63..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/DirectoryFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class +deleted file mode 100644 +index 11a85482..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/ExtensionFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class +deleted file mode 100644 +index b12636e8..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/LastModifiedFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class +deleted file mode 100644 +index ed030680..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/NameFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class +deleted file mode 100644 +index 4effb1be..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/PathFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class +deleted file mode 100644 +index f616dc37..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/ReverseComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class b/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class +deleted file mode 100644 +index ad506044..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/comparator/SizeFileComparator.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class +deleted file mode 100644 +index f00eaae1..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AbstractFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class +deleted file mode 100644 +index f02c5716..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AgeFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class +deleted file mode 100644 +index 601b4d26..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/AndFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class +deleted file mode 100644 +index 26665156..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/CanReadFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class +deleted file mode 100644 +index 9d6a2977..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/CanWriteFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class +deleted file mode 100644 +index 903e3ab2..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/ConditionalFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class +deleted file mode 100644 +index 049d673f..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/DelegateFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class +deleted file mode 100644 +index 89f1b8a6..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/DirectoryFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class +deleted file mode 100644 +index 79377308..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/EmptyFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class +deleted file mode 100644 +index f5b36c5b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FalseFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class +deleted file mode 100644 +index ed3ca02d..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class b/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class +deleted file mode 100644 +index 9165c54b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/FileFilterUtils.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class +deleted file mode 100644 +index 4c8efb7f..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/HiddenFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class +deleted file mode 100644 +index c602e578..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/IOFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class +deleted file mode 100644 +index 406c5058..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/MagicNumberFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class +deleted file mode 100644 +index 413a5f08..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/NameFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class +deleted file mode 100644 +index e1cd2877..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/NotFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class +deleted file mode 100644 +index 74a1b5ce..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/OrFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class +deleted file mode 100644 +index 8001d9ee..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/PrefixFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class +deleted file mode 100644 +index c2fa2b41..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/RegexFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class +deleted file mode 100644 +index df634ec6..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/SizeFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class +deleted file mode 100644 +index f213e1c6..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/SuffixFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class +deleted file mode 100644 +index 2a162e39..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/TrueFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class +deleted file mode 100644 +index 75ab2b8d..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFileFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class b/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class +deleted file mode 100644 +index c6726689..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/filefilter/WildcardFilter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class +deleted file mode 100644 +index b46d8845..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/AutoCloseInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class +deleted file mode 100644 +index 3b186d4e..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/BOMInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class +deleted file mode 100644 +index 3aa01980..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/BoundedInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class +deleted file mode 100644 +index ed86c824..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/BrokenInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class +deleted file mode 100644 +index d56d99d4..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class b/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class +deleted file mode 100644 +index cba1c0fc..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/CharSequenceReader.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class +deleted file mode 100644 +index 7280e831..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ClassLoaderObjectInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class +deleted file mode 100644 +index 89c5b5d0..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/CloseShieldInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class +deleted file mode 100644 +index 77110a09..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ClosedInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class +deleted file mode 100644 +index e391e3a0..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/CountingInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class +deleted file mode 100644 +index c1c62315..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/DemuxInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class +deleted file mode 100644 +index fe780a58..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/NullInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/NullReader.class b/org.apache.commons.io/org/apache/commons/io/input/NullReader.class +deleted file mode 100644 +index f6ce8309..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/NullReader.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class +deleted file mode 100644 +index bcb63360..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ProxyInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class b/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class +deleted file mode 100644 +index 0e88acc8..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ProxyReader.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class +deleted file mode 100644 +index 33b0e11a..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReaderInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class +deleted file mode 100644 +index e7a796ca..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$1.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class +deleted file mode 100644 +index ddb4de84..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader$FilePart.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class b/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class +deleted file mode 100644 +index 2f4819a2..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/ReversedLinesFileReader.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class +deleted file mode 100644 +index 15ccb85c..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/SwappedDataInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class +deleted file mode 100644 +index 2e3c7571..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/TaggedInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/Tailer.class b/org.apache.commons.io/org/apache/commons/io/input/Tailer.class +deleted file mode 100644 +index 100e2959..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/Tailer.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class +deleted file mode 100644 +index a0f1b7d9..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/TailerListener.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class b/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class +deleted file mode 100644 +index 44b075de..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/TailerListenerAdapter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class b/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class +deleted file mode 100644 +index 534db867..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/TeeInputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class +deleted file mode 100644 +index 9a82342f..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReader.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class b/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class +deleted file mode 100644 +index d0d2cf4b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/input/XmlStreamReaderException.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class +deleted file mode 100644 +index 90ffd926..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListener.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class +deleted file mode 100644 +index e3f7f582..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class +deleted file mode 100644 +index d7694004..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationMonitor.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class +deleted file mode 100644 +index d3f0cf7a..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileAlterationObserver.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class b/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class +deleted file mode 100644 +index eb8bd5de..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/monitor/FileEntry.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class +deleted file mode 100644 +index 06c9873e..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/BrokenOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class +deleted file mode 100644 +index e0279aaa..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/ByteArrayOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class +deleted file mode 100644 +index 734579ba..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/CloseShieldOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class +deleted file mode 100644 +index c8dd34de..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/ClosedOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class +deleted file mode 100644 +index 65d60dd8..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/CountingOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class +deleted file mode 100644 +index a27ea22b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/DeferredFileOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class +deleted file mode 100644 +index 64eb167b..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/DemuxOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class b/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class +deleted file mode 100644 +index c40975b5..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/FileWriterWithEncoding.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class b/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class +deleted file mode 100644 +index 92f1a8f6..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/LockableFileWriter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class +deleted file mode 100644 +index c9a9e1d9..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/NullOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class b/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class +deleted file mode 100644 +index 7794b638..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/NullWriter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class +deleted file mode 100644 +index e0619cc9..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/ProxyOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class b/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class +deleted file mode 100644 +index 93a958c3..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/ProxyWriter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class b/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class +deleted file mode 100644 +index 190828ef..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/StringBuilderWriter.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class +deleted file mode 100644 +index 52b5a498..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/TaggedOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class +deleted file mode 100644 +index 7de3c99f..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/TeeOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class +deleted file mode 100644 +index 370a0322..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/ThresholdingOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class b/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class +deleted file mode 100644 +index ec9e6770..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/WriterOutputStream.class and /dev/null differ +diff --git a/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class b/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class +deleted file mode 100644 +index c2b8e394..00000000 +Binary files a/org.apache.commons.io/org/apache/commons/io/output/XmlStreamWriter.class and /dev/null differ" +95ba62f83dfa05990d2165484330cdd0792064d8,elasticsearch,Translog: Implement a file system based translog- and make it the default,a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java +index 61977707465c0..02c378097c250 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/translog/TranslogModule.java +@@ -22,7 +22,7 @@ + import org.elasticsearch.common.inject.AbstractModule; + import org.elasticsearch.common.inject.Scopes; + import org.elasticsearch.common.settings.Settings; +-import org.elasticsearch.index.translog.memory.MemoryTranslog; ++import org.elasticsearch.index.translog.fs.FsTranslog; + + /** + * @author kimchy (shay.banon) +@@ -41,7 +41,7 @@ public TranslogModule(Settings settings) { + + @Override protected void configure() { + bind(Translog.class) +- .to(settings.getAsClass(TranslogSettings.TYPE, MemoryTranslog.class)) ++ .to(settings.getAsClass(TranslogSettings.TYPE, FsTranslog.class)) + .in(Scopes.SINGLETON); + } + }" +f1d1b3440b46c48146fde6b3b1c2cd65b51bdbfe,apache$mina,"Modified IoAcceptor and IoConnector to accept IoServiceConfig as a configuration parameter for more flexibility +git-svn-id: https://svn.apache.org/repos/asf/directory/sandbox/trustin/dirmina-158@372453 13f79535-47bb-0310-9956-ffa450edef68 +",p,https://github.com/apache/mina,"diff --git a/core/src/main/java/org/apache/mina/common/IoAcceptor.java b/core/src/main/java/org/apache/mina/common/IoAcceptor.java +index 05d0d1403..5a9179bec 100644 +--- a/core/src/main/java/org/apache/mina/common/IoAcceptor.java ++++ b/core/src/main/java/org/apache/mina/common/IoAcceptor.java +@@ -57,7 +57,7 @@ public interface IoAcceptor extends IoService + * @param config the configuration + * @throws IOException if failed to bind + */ +- void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException; ++ void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException; + + /** + * Unbinds from the specified address and disconnects all clients +diff --git a/core/src/main/java/org/apache/mina/common/IoConnector.java b/core/src/main/java/org/apache/mina/common/IoConnector.java +index fc74e9faa..715b66384 100644 +--- a/core/src/main/java/org/apache/mina/common/IoConnector.java ++++ b/core/src/main/java/org/apache/mina/common/IoConnector.java +@@ -59,7 +59,7 @@ public interface IoConnector extends IoService + * @return {@link ConnectFuture} that will tell the result of the connection attempt + */ + ConnectFuture connect( SocketAddress address, IoHandler handler, +- IoConnectorConfig config ); ++ IoServiceConfig config ); + + /** + * Connects to the specified address. If communication starts +@@ -81,5 +81,5 @@ ConnectFuture connect( SocketAddress address, SocketAddress localAddress, + * @return {@link ConnectFuture} that will tell the result of the connection attempt + */ + ConnectFuture connect( SocketAddress address, SocketAddress localAddress, +- IoHandler handler, IoConnectorConfig config ); ++ IoHandler handler, IoServiceConfig config ); + } +\ No newline at end of file +diff --git a/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java b/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java +index 73718dbfe..40510603f 100644 +--- a/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java ++++ b/core/src/main/java/org/apache/mina/common/support/BaseIoAcceptor.java +@@ -22,7 +22,6 @@ + import java.net.SocketAddress; + + import org.apache.mina.common.IoAcceptor; +-import org.apache.mina.common.IoAcceptorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoSession; + +@@ -40,7 +39,7 @@ protected BaseIoAcceptor() + + public void bind( SocketAddress address, IoHandler handler ) throws IOException + { +- this.bind( address, handler, ( IoAcceptorConfig ) getDefaultConfig() ); ++ this.bind( address, handler, getDefaultConfig() ); + } + + public IoSession newSession( SocketAddress remoteAddress, SocketAddress localAddress ) +diff --git a/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java b/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java +index b4927f2ea..721a6bd7a 100644 +--- a/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java ++++ b/core/src/main/java/org/apache/mina/common/support/BaseIoConnector.java +@@ -22,7 +22,6 @@ + + import org.apache.mina.common.ConnectFuture; + import org.apache.mina.common.IoConnector; +-import org.apache.mina.common.IoConnectorConfig; + import org.apache.mina.common.IoHandler; + + /** +@@ -39,11 +38,11 @@ protected BaseIoConnector() + + public ConnectFuture connect( SocketAddress address, IoHandler handler ) + { +- return connect( address, handler, ( IoConnectorConfig ) getDefaultConfig() ); ++ return connect( address, handler, getDefaultConfig() ); + } + + public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler ) + { +- return connect( address, localAddress, handler, ( IoConnectorConfig ) getDefaultConfig() ); ++ return connect( address, localAddress, handler, getDefaultConfig() ); + } + } +diff --git a/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java b/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java +index 46e974f86..194bfbf48 100644 +--- a/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java ++++ b/core/src/main/java/org/apache/mina/common/support/DelegatedIoAcceptor.java +@@ -23,7 +23,6 @@ + import java.util.Set; + + import org.apache.mina.common.IoAcceptor; +-import org.apache.mina.common.IoAcceptorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.common.IoSession; +@@ -59,7 +58,7 @@ public void bind( SocketAddress address, IoHandler handler ) throws IOException + delegate.bind( address, handler ); + } + +- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException ++ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException + { + delegate.bind( address, handler, config ); + } +diff --git a/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java b/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java +index 3b78ba962..74ac8d362 100644 +--- a/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java ++++ b/core/src/main/java/org/apache/mina/common/support/DelegatedIoConnector.java +@@ -23,7 +23,6 @@ + + import org.apache.mina.common.ConnectFuture; + import org.apache.mina.common.IoConnector; +-import org.apache.mina.common.IoConnectorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoServiceConfig; + +@@ -58,7 +57,7 @@ public ConnectFuture connect( SocketAddress address, IoHandler handler ) + return delegate.connect( address, handler ); + } + +- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config ) ++ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + return delegate.connect( address, handler, config ); + } +@@ -70,7 +69,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, + } + + public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, +- IoHandler handler, IoConnectorConfig config ) ++ IoHandler handler, IoServiceConfig config ) + { + return delegate.connect( address, localAddress, handler, config ); + } +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java +index be095e240..900b0ef4d 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramAcceptorDelegate.java +@@ -32,7 +32,6 @@ + import org.apache.mina.common.ByteBuffer; + import org.apache.mina.common.ExceptionMonitor; + import org.apache.mina.common.IoAcceptor; +-import org.apache.mina.common.IoAcceptorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.common.IoSession; +@@ -70,7 +69,7 @@ public DatagramAcceptorDelegate( IoAcceptor wrapper ) + this.wrapper = wrapper; + } + +- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) ++ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) + throws IOException + { + if( address == null ) +@@ -79,7 +78,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con + throw new NullPointerException( ""handler"" ); + if( config == null ) + { +- config = ( IoAcceptorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + if( !( address instanceof InetSocketAddress ) ) +@@ -195,7 +194,7 @@ public IoSession newSession( SocketAddress remoteAddress, SocketAddress localAdd + RegistrationRequest req = ( RegistrationRequest ) key.attachment(); + DatagramSessionImpl s = new DatagramSessionImpl( + wrapper, this, +- ( DatagramSessionConfig ) req.config, ch, req.handler ); ++ req.config.getSessionConfig(), ch, req.handler ); + s.setRemoteAddress( remoteAddress ); + s.setSelectionKey( key ); + +@@ -329,7 +328,7 @@ private void processReadySessions( Set keys ) + RegistrationRequest req = ( RegistrationRequest ) key.attachment(); + DatagramSessionImpl session = new DatagramSessionImpl( + wrapper, this, +- ( DatagramSessionConfig ) req.config.getSessionConfig(), ++ req.config.getSessionConfig(), + ch, req.handler ); + session.setSelectionKey( key ); + +@@ -615,12 +614,12 @@ private static class RegistrationRequest + { + private final SocketAddress address; + private final IoHandler handler; +- private final IoAcceptorConfig config; ++ private final IoServiceConfig config; + + private Throwable exception; + private boolean done; + +- private RegistrationRequest( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) ++ private RegistrationRequest( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + this.address = address; + this.handler = handler; +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java +index 5e59c2139..ee7babad4 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramConnectorDelegate.java +@@ -31,7 +31,6 @@ + import org.apache.mina.common.ConnectFuture; + import org.apache.mina.common.ExceptionMonitor; + import org.apache.mina.common.IoConnector; +-import org.apache.mina.common.IoConnectorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.common.IoFilter.WriteRequest; +@@ -68,13 +67,13 @@ public DatagramConnectorDelegate( IoConnector wrapper ) + this.wrapper = wrapper; + } + +- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config ) ++ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + return connect( address, null, handler, config ); + } + + public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, +- IoHandler handler, IoConnectorConfig config ) ++ IoHandler handler, IoServiceConfig config ) + { + if( address == null ) + throw new NullPointerException( ""address"" ); +@@ -93,7 +92,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, + + if( config == null ) + { +- config = ( IoConnectorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + DatagramChannel ch = null; +@@ -540,7 +539,7 @@ private void registerNew() + + DatagramSessionImpl session = new DatagramSessionImpl( + wrapper, this, +- ( DatagramSessionConfig ) req.config.getSessionConfig(), ++ req.config.getSessionConfig(), + req.channel, req.handler ); + + boolean success = false; +@@ -618,11 +617,11 @@ private static class RegistrationRequest extends ConnectFuture + { + private final DatagramChannel channel; + private final IoHandler handler; +- private final IoConnectorConfig config; ++ private final IoServiceConfig config; + + private RegistrationRequest( DatagramChannel channel, + IoHandler handler, +- IoConnectorConfig config ) ++ IoServiceConfig config ) + { + this.channel = channel; + this.handler = handler; +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java +index 443f1f02f..19fa11cea 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/DatagramSessionImpl.java +@@ -61,7 +61,7 @@ class DatagramSessionImpl extends BaseIoSession + */ + DatagramSessionImpl( IoService wrapperManager, + DatagramService managerDelegate, +- DatagramSessionConfig config, ++ IoSessionConfig config, + DatagramChannel ch, IoHandler defaultHandler ) + { + this.wrapperManager = wrapperManager; +@@ -74,12 +74,16 @@ class DatagramSessionImpl extends BaseIoSession + this.localAddress = ch.socket().getLocalSocketAddress(); + + // Apply the initial session settings +- this.config.setBroadcast( config.isBroadcast() ); +- this.config.setReceiveBufferSize( config.getReceiveBufferSize() ); +- this.readBufferSize = config.getReceiveBufferSize(); +- this.config.setReuseAddress( config.isReuseAddress() ); +- this.config.setSendBufferSize( config.getSendBufferSize() ); +- this.config.setTrafficClass( config.getTrafficClass() ); ++ if( config instanceof DatagramSessionConfig ) ++ { ++ DatagramSessionConfig cfg = ( DatagramSessionConfig ) config; ++ this.config.setBroadcast( cfg.isBroadcast() ); ++ this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() ); ++ this.readBufferSize = cfg.getReceiveBufferSize(); ++ this.config.setReuseAddress( cfg.isReuseAddress() ); ++ this.config.setSendBufferSize( cfg.getSendBufferSize() ); ++ this.config.setTrafficClass( cfg.getTrafficClass() ); ++ } + } + + public IoService getService() +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java +index 45083b8af..6ff5f8f8b 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketAcceptorDelegate.java +@@ -85,7 +85,7 @@ public SocketAcceptorDelegate( IoAcceptor wrapper ) + * + * @throws IOException if failed to bind + */ +- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException ++ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException + { + if( address == null ) + { +@@ -109,7 +109,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con + + if( config == null ) + { +- config = ( IoAcceptorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + RegistrationRequest request = new RegistrationRequest( address, handler, config ); +@@ -230,8 +230,18 @@ public void unbind( SocketAddress address ) + + + // Disconnect all clients +- if( request.registrationRequest.config.isDisconnectOnUnbind() && +- managedSessions != null ) ++ IoServiceConfig cfg = request.registrationRequest.config; ++ boolean disconnectOnUnbind; ++ if( cfg instanceof IoAcceptorConfig ) ++ { ++ disconnectOnUnbind = ( ( IoAcceptorConfig ) cfg ).isDisconnectOnUnbind(); ++ } ++ else ++ { ++ disconnectOnUnbind = ( ( IoAcceptorConfig ) getDefaultConfig() ).isDisconnectOnUnbind(); ++ } ++ ++ if( disconnectOnUnbind && managedSessions != null ) + { + IoSession[] tempSessions = ( IoSession[] ) + managedSessions.toArray( new IoSession[ 0 ] ); +@@ -543,11 +553,11 @@ private static class RegistrationRequest + { + private final SocketAddress address; + private final IoHandler handler; +- private final IoAcceptorConfig config; ++ private final IoServiceConfig config; + private IOException exception; + private boolean done; + +- private RegistrationRequest( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) ++ private RegistrationRequest( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + this.address = address; + this.handler = handler; +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java +index e354329da..c680a0ce1 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketConnectorDelegate.java +@@ -38,7 +38,6 @@ + import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.common.support.BaseIoConnector; + import org.apache.mina.transport.socket.nio.SocketConnectorConfig; +-import org.apache.mina.transport.socket.nio.SocketSessionConfig; + import org.apache.mina.util.Queue; + + /** +@@ -68,13 +67,13 @@ public SocketConnectorDelegate( IoConnector wrapper ) + this.wrapper = wrapper; + } + +- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config ) ++ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + return connect( address, null, handler, config ); + } + + public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, +- IoHandler handler, IoConnectorConfig config ) ++ IoHandler handler, IoServiceConfig config ) + { + if( address == null ) + throw new NullPointerException( ""address"" ); +@@ -91,7 +90,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, + + if( config == null ) + { +- config = ( IoConnectorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + SocketChannel ch = null; +@@ -278,11 +277,11 @@ private void processTimedOutSessions( Set keys ) + } + } + +- private SocketSessionImpl newSession( SocketChannel ch, IoHandler handler, IoConnectorConfig config ) throws IOException ++ private SocketSessionImpl newSession( SocketChannel ch, IoHandler handler, IoServiceConfig config ) throws IOException + { + SocketSessionImpl session = new SocketSessionImpl( + wrapper, managedSessions, +- ( SocketSessionConfig ) config.getSessionConfig(), ++ config.getSessionConfig(), + ch, handler ); + try + { +@@ -363,17 +362,26 @@ public void run() + } + } + +- private static class ConnectionRequest extends ConnectFuture ++ private class ConnectionRequest extends ConnectFuture + { + private final SocketChannel channel; + private final long deadline; + private final IoHandler handler; +- private final IoConnectorConfig config; ++ private final IoServiceConfig config; + +- private ConnectionRequest( SocketChannel channel, IoHandler handler, IoConnectorConfig config ) ++ private ConnectionRequest( SocketChannel channel, IoHandler handler, IoServiceConfig config ) + { + this.channel = channel; +- this.deadline = System.currentTimeMillis() + config.getConnectTimeoutMillis(); ++ long timeout; ++ if( config instanceof IoConnectorConfig ) ++ { ++ timeout = ( ( IoConnectorConfig ) config ).getConnectTimeoutMillis(); ++ } ++ else ++ { ++ timeout = ( ( IoConnectorConfig ) getDefaultConfig() ).getConnectTimeoutMillis(); ++ } ++ this.deadline = System.currentTimeMillis() + timeout; + this.handler = handler; + this.config = config; + } +diff --git a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java +index d0544b318..56cacfcec 100644 +--- a/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java ++++ b/core/src/main/java/org/apache/mina/transport/socket/nio/support/SocketSessionImpl.java +@@ -63,7 +63,7 @@ class SocketSessionImpl extends BaseIoSession + */ + public SocketSessionImpl( + IoService manager, Set managedSessions, +- SocketSessionConfig config, ++ IoSessionConfig config, + SocketChannel ch, IoHandler defaultHandler ) + { + this.manager = manager; +@@ -77,15 +77,19 @@ public SocketSessionImpl( + this.localAddress = ch.socket().getLocalSocketAddress(); + + // Apply the initial session settings +- this.config.setKeepAlive( config.isKeepAlive() ); +- this.config.setOobInline( config.isOobInline() ); +- this.config.setReceiveBufferSize( config.getReceiveBufferSize() ); +- this.readBufferSize = config.getReceiveBufferSize(); +- this.config.setReuseAddress( config.isReuseAddress() ); +- this.config.setSendBufferSize( config.getSendBufferSize() ); +- this.config.setSoLinger( config.getSoLinger() ); +- this.config.setTcpNoDelay( config.isTcpNoDelay() ); +- this.config.setTrafficClass( config.getTrafficClass() ); ++ if( config instanceof SocketSessionConfig ) ++ { ++ SocketSessionConfig cfg = ( SocketSessionConfig ) config; ++ this.config.setKeepAlive( cfg.isKeepAlive() ); ++ this.config.setOobInline( cfg.isOobInline() ); ++ this.config.setReceiveBufferSize( cfg.getReceiveBufferSize() ); ++ this.readBufferSize = cfg.getReceiveBufferSize(); ++ this.config.setReuseAddress( cfg.isReuseAddress() ); ++ this.config.setSendBufferSize( cfg.getSendBufferSize() ); ++ this.config.setSoLinger( cfg.getSoLinger() ); ++ this.config.setTcpNoDelay( cfg.isTcpNoDelay() ); ++ this.config.setTrafficClass( cfg.getTrafficClass() ); ++ } + } + + public IoService getService() +diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java +index 7d1378d7a..3ecb2cc9e 100644 +--- a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java ++++ b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java +@@ -42,7 +42,7 @@ public IoSessionConfig getSessionConfig() + } + }; + +- public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig config ) throws IOException ++ public void bind( SocketAddress address, IoHandler handler, IoServiceConfig config ) throws IOException + { + if( address == null ) + throw new NullPointerException( ""address"" ); +@@ -54,7 +54,7 @@ public void bind( SocketAddress address, IoHandler handler, IoAcceptorConfig con + + if( config == null ) + { +- config = ( IoAcceptorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + synchronized( boundHandlers ) +@@ -109,7 +109,17 @@ public void unbind( SocketAddress address ) + + Set managedSessions = pipe.getManagedServerSessions(); + +- if( pipe.getConfig().isDisconnectOnUnbind() && managedSessions != null ) ++ IoServiceConfig cfg = pipe.getConfig(); ++ boolean disconnectOnUnbind; ++ if( cfg instanceof IoAcceptorConfig ) ++ { ++ disconnectOnUnbind = ( ( IoAcceptorConfig ) cfg ).isDisconnectOnUnbind(); ++ } ++ else ++ { ++ disconnectOnUnbind = ( ( IoAcceptorConfig ) getDefaultConfig() ).isDisconnectOnUnbind(); ++ } ++ if( disconnectOnUnbind && managedSessions != null ) + { + IoSession[] tempSessions = ( IoSession[] ) + managedSessions.toArray( new IoSession[ 0 ] ); +diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java +index 3151fc3b7..d9a304d75 100644 +--- a/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java ++++ b/core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeConnector.java +@@ -7,7 +7,6 @@ + import java.net.SocketAddress; + + import org.apache.mina.common.ConnectFuture; +-import org.apache.mina.common.IoConnectorConfig; + import org.apache.mina.common.IoHandler; + import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.common.IoSessionConfig; +@@ -35,12 +34,12 @@ public IoSessionConfig getSessionConfig() + } + }; + +- public ConnectFuture connect( SocketAddress address, IoHandler handler, IoConnectorConfig config ) ++ public ConnectFuture connect( SocketAddress address, IoHandler handler, IoServiceConfig config ) + { + return connect( address, null, handler, config ); + } + +- public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler, IoConnectorConfig config ) ++ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, IoHandler handler, IoServiceConfig config ) + { + if( address == null ) + throw new NullPointerException( ""address"" ); +@@ -52,7 +51,7 @@ public ConnectFuture connect( SocketAddress address, SocketAddress localAddress, + + if( config == null ) + { +- config = ( IoConnectorConfig ) getDefaultConfig(); ++ config = getDefaultConfig(); + } + + VmPipe entry = ( VmPipe ) VmPipeAcceptor.boundHandlers.get( address ); +diff --git a/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java b/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java +index 7f9c57516..f767155f9 100644 +--- a/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java ++++ b/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipe.java +@@ -7,8 +7,8 @@ + import java.util.HashSet; + import java.util.Set; + +-import org.apache.mina.common.IoAcceptorConfig; + import org.apache.mina.common.IoHandler; ++import org.apache.mina.common.IoServiceConfig; + import org.apache.mina.transport.vmpipe.VmPipeAcceptor; + import org.apache.mina.transport.vmpipe.VmPipeAddress; + +@@ -17,14 +17,14 @@ public class VmPipe + private final VmPipeAcceptor acceptor; + private final VmPipeAddress address; + private final IoHandler handler; +- private final IoAcceptorConfig config; ++ private final IoServiceConfig config; + private final Set managedClientSessions = Collections.synchronizedSet( new HashSet() ); + private final Set managedServerSessions = Collections.synchronizedSet( new HashSet() ); + + public VmPipe( VmPipeAcceptor acceptor, + VmPipeAddress address, + IoHandler handler, +- IoAcceptorConfig config ) ++ IoServiceConfig config ) + { + this.acceptor = acceptor; + this.address = address; +@@ -47,7 +47,7 @@ public IoHandler getHandler() + return handler; + } + +- public IoAcceptorConfig getConfig() ++ public IoServiceConfig getConfig() + { + return config; + }" +190aabbbe8d382b9b960198d8d895ab98c117893,camel,CAMEL-3689: AdviceWith can now manipulate routes.- This allows you for example to replace parts of routes during testing.--git-svn-id: https://svn.apache.org/repos/asf/camel/trunk@1072545 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/camel,"diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithBuilder.java +new file mode 100644 +index 0000000000000..1a62f43fbb1a8 +--- /dev/null ++++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithBuilder.java +@@ -0,0 +1,97 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.builder; ++ ++import org.apache.camel.model.PipelineDefinition; ++import org.apache.camel.model.ProcessorDefinition; ++ ++/** ++ * A builder when using the advice with feature. ++ */ ++public class AdviceWithBuilder { ++ ++ private final AdviceWithRouteBuilder builder; ++ private final String id; ++ private final String toString; ++ ++ public AdviceWithBuilder(AdviceWithRouteBuilder builder, String id, String toString) { ++ this.builder = builder; ++ this.id = id; ++ this.toString = toString; ++ ++ if (id == null && toString == null) { ++ throw new IllegalArgumentException(""Either id or toString must be specified""); ++ } ++ } ++ ++ /** ++ * Replaces the matched node(s) with the following nodes. ++ * ++ * @return the builder to build the nodes. ++ */ ++ public ProcessorDefinition replace() { ++ PipelineDefinition answer = new PipelineDefinition(); ++ if (id != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.replaceById(builder.getOriginalRoute(), id, answer)); ++ } else if (toString != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.replaceByToString(builder.getOriginalRoute(), toString, answer)); ++ } ++ return answer; ++ } ++ ++ /** ++ * Removes the matched node(s) ++ */ ++ public void remove() { ++ if (id != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.removeById(builder.getOriginalRoute(), id)); ++ } else if (toString != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.removeByToString(builder.getOriginalRoute(), toString)); ++ } ++ } ++ ++ /** ++ * Insert the following node(s) before the matched node(s) ++ * ++ * @return the builder to build the nodes. ++ */ ++ public ProcessorDefinition before() { ++ PipelineDefinition answer = new PipelineDefinition(); ++ if (id != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.beforeById(builder.getOriginalRoute(), id, answer)); ++ } else if (toString != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.beforeByToString(builder.getOriginalRoute(), toString, answer)); ++ } ++ return answer; ++ } ++ ++ /** ++ * Insert the following node(s) after the matched node(s) ++ * ++ * @return the builder to build the nodes. ++ */ ++ public ProcessorDefinition after() { ++ PipelineDefinition answer = new PipelineDefinition(); ++ if (id != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.afterById(builder.getOriginalRoute(), id, answer)); ++ } else if (toString != null) { ++ builder.getAdviceWithTasks().add(AdviceWithTasks.afterByToString(builder.getOriginalRoute(), toString, answer)); ++ } ++ return answer; ++ } ++ ++} +diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java +index 7d77bbb81bdb8..04d78d2267912 100644 +--- a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java ++++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithRouteBuilder.java +@@ -16,18 +16,56 @@ + */ + package org.apache.camel.builder; + ++import java.util.ArrayList; ++import java.util.List; ++ + import org.apache.camel.impl.InterceptSendToMockEndpointStrategy; ++import org.apache.camel.model.RouteDefinition; ++import org.apache.camel.util.ObjectHelper; + + /** +- * A {@link RouteBuilder} which has extended features when using +- * {@link org.apache.camel.model.RouteDefinition#adviceWith(org.apache.camel.CamelContext, RouteBuilder) adviceWith}. ++ * A {@link RouteBuilder} which has extended capabilities when using ++ * the advice with feature. + * +- * @version ++ * @see org.apache.camel.model.RouteDefinition#adviceWith(org.apache.camel.CamelContext, RouteBuilder) + */ + public abstract class AdviceWithRouteBuilder extends RouteBuilder { + ++ private RouteDefinition originalRoute; ++ private final List adviceWithTasks = new ArrayList(); ++ ++ /** ++ * Sets the original route which we advice. ++ * ++ * @param originalRoute the original route we advice. ++ */ ++ public void setOriginalRoute(RouteDefinition originalRoute) { ++ this.originalRoute = originalRoute; ++ } ++ ++ /** ++ * Gets the original route we advice. ++ * ++ * @return the original route. ++ */ ++ public RouteDefinition getOriginalRoute() { ++ return originalRoute; ++ } ++ ++ /** ++ * Gets a list of additional tasks to execute after the {@link #configure()} method has been executed ++ * during the advice process. ++ * ++ * @return a list of additional {@link AdviceWithTask} tasks to be executed during the advice process. ++ */ ++ public List getAdviceWithTasks() { ++ return adviceWithTasks; ++ } ++ + /** + * Mock all endpoints in the route. ++ * ++ * @throws Exception can be thrown if error occurred + */ + public void mockEndpoints() throws Exception { + getContext().removeEndpoints(""*""); +@@ -37,7 +75,8 @@ public void mockEndpoints() throws Exception { + /** + * Mock all endpoints matching the given pattern. + * +- * @param pattern the pattern. ++ * @param pattern the pattern. ++ * @throws Exception can be thrown if error occurred + * @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String) + */ + public void mockEndpoints(String pattern) throws Exception { +@@ -45,4 +84,34 @@ public void mockEndpoints(String pattern) throws Exception { + getContext().addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern)); + } + ++ /** ++ * Advices by matching id of the nodes in the route. ++ *

++ * Uses the {@link org.apache.camel.util.EndpointHelper#matchPattern(String, String)} matching algorithm. ++ * ++ * @param pattern the pattern ++ * @return the builder ++ * @see org.apache.camel.util.EndpointHelper#matchPattern(String, String) ++ */ ++ public AdviceWithBuilder adviceById(String pattern) { ++ ObjectHelper.notNull(originalRoute, ""originalRoute"", this); ++ ++ return new AdviceWithBuilder(this, pattern, null); ++ } ++ ++ /** ++ * Advices by matching the to string representation of the nodes in the route. ++ *

++ * Uses the {@link org.apache.camel.util.EndpointHelper#matchPattern(String, String)} matching algorithm. ++ * ++ * @param pattern the pattern ++ * @return the builder ++ * @see org.apache.camel.util.EndpointHelper#matchPattern(String, String) ++ */ ++ public AdviceWithBuilder adviceByToString(String pattern) { ++ ObjectHelper.notNull(originalRoute, ""originalRoute"", this); ++ ++ return new AdviceWithBuilder(this, null, pattern); ++ } ++ + } +diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTask.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTask.java +new file mode 100644 +index 0000000000000..7c29422d8ac6c +--- /dev/null ++++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTask.java +@@ -0,0 +1,31 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.builder; ++ ++/** ++ * Task or command being executed when using the advice with feature. ++ */ ++public interface AdviceWithTask { ++ ++ /** ++ * The task to execute ++ * ++ * @throws Exception is thrown if error during executing the task, or invalid input. ++ */ ++ void task() throws Exception; ++ ++} +diff --git a/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java +new file mode 100644 +index 0000000000000..4a568d1dbf5b1 +--- /dev/null ++++ b/camel-core/src/main/java/org/apache/camel/builder/AdviceWithTasks.java +@@ -0,0 +1,238 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.builder; ++ ++import java.util.Iterator; ++ ++import org.apache.camel.model.ProcessorDefinition; ++import org.apache.camel.model.ProcessorDefinitionHelper; ++import org.apache.camel.model.RouteDefinition; ++import org.apache.camel.util.EndpointHelper; ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; ++ ++/** ++ * {@link AdviceWithTask} tasks which are used by the {@link AdviceWithRouteBuilder}. ++ */ ++public final class AdviceWithTasks { ++ ++ private static final Logger LOG = LoggerFactory.getLogger(AdviceWithTasks.class); ++ ++ private AdviceWithTasks() { ++ // utility class ++ } ++ ++ /** ++ * Match by is used for pluggable match by logic. ++ */ ++ private interface MatchBy { ++ ++ String getId(); ++ ++ boolean match(ProcessorDefinition processor); ++ } ++ ++ /** ++ * Will match by id of the processor. ++ */ ++ private static final class MatchById implements MatchBy { ++ ++ private final String id; ++ ++ private MatchById(String id) { ++ this.id = id; ++ } ++ ++ public String getId() { ++ return id; ++ } ++ ++ public boolean match(ProcessorDefinition processor) { ++ return EndpointHelper.matchPattern(processor.getId(), id); ++ } ++ } ++ ++ /** ++ * Will match by the to string representation of the processor. ++ */ ++ private static final class MatchByToString implements MatchBy { ++ ++ private final String toString; ++ ++ private MatchByToString(String toString) { ++ this.toString = toString; ++ } ++ ++ public String getId() { ++ return toString; ++ } ++ ++ public boolean match(ProcessorDefinition processor) { ++ return EndpointHelper.matchPattern(processor.toString(), toString); ++ } ++ } ++ ++ ++ public static AdviceWithTask replaceByToString(final RouteDefinition route, final String toString, final ProcessorDefinition replace) { ++ return doReplace(route, new MatchByToString(toString), replace); ++ } ++ ++ public static AdviceWithTask replaceById(final RouteDefinition route, final String id, final ProcessorDefinition replace) { ++ return doReplace(route, new MatchById(id), replace); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ private static AdviceWithTask doReplace(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition replace) { ++ return new AdviceWithTask() { ++ public void task() throws Exception { ++ boolean match = false; ++ Iterator it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class); ++ while (it.hasNext()) { ++ ProcessorDefinition output = it.next(); ++ if (matchBy.match(output)) { ++ ProcessorDefinition parent = output.getParent(); ++ if (parent != null) { ++ int index = parent.getOutputs().indexOf(output); ++ if (index != -1) { ++ match = true; ++ parent.getOutputs().add(index + 1, replace); ++ Object old = parent.getOutputs().remove(index); ++ LOG.info(""AdviceWith ("" + matchBy.getId() + "") : ["" + old + ""] --> replace ["" + replace + ""]""); ++ } ++ } ++ } ++ } ++ ++ if (!match) { ++ throw new IllegalArgumentException(""There are no outputs which matches: "" + matchBy.getId() + "" in the route: "" + route); ++ } ++ } ++ }; ++ } ++ ++ public static AdviceWithTask removeByToString(final RouteDefinition route, final String toString) { ++ return doRemove(route, new MatchByToString(toString)); ++ } ++ ++ public static AdviceWithTask removeById(final RouteDefinition route, final String id) { ++ return doRemove(route, new MatchById(id)); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ private static AdviceWithTask doRemove(final RouteDefinition route, final MatchBy matchBy) { ++ return new AdviceWithTask() { ++ public void task() throws Exception { ++ boolean match = false; ++ Iterator it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class); ++ while (it.hasNext()) { ++ ProcessorDefinition output = it.next(); ++ if (matchBy.match(output)) { ++ ProcessorDefinition parent = output.getParent(); ++ if (parent != null) { ++ int index = parent.getOutputs().indexOf(output); ++ if (index != -1) { ++ match = true; ++ Object old = parent.getOutputs().remove(index); ++ LOG.info(""AdviceWith ("" + matchBy.getId() + "") : ["" + old + ""] --> remove""); ++ } ++ } ++ } ++ } ++ ++ if (!match) { ++ throw new IllegalArgumentException(""There are no outputs which matches: "" + matchBy.getId() + "" in the route: "" + route); ++ } ++ } ++ }; ++ } ++ ++ public static AdviceWithTask beforeByToString(final RouteDefinition route, final String toString, final ProcessorDefinition before) { ++ return doBefore(route, new MatchByToString(toString), before); ++ } ++ ++ public static AdviceWithTask beforeById(final RouteDefinition route, final String id, final ProcessorDefinition before) { ++ return doBefore(route, new MatchById(id), before); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ private static AdviceWithTask doBefore(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition before) { ++ return new AdviceWithTask() { ++ public void task() throws Exception { ++ boolean match = false; ++ Iterator it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class); ++ while (it.hasNext()) { ++ ProcessorDefinition output = it.next(); ++ if (matchBy.match(output)) { ++ ProcessorDefinition parent = output.getParent(); ++ if (parent != null) { ++ int index = parent.getOutputs().indexOf(output); ++ if (index != -1) { ++ match = true; ++ Object existing = parent.getOutputs().get(index); ++ parent.getOutputs().add(index, before); ++ LOG.info(""AdviceWith ("" + matchBy.getId() + "") : ["" + existing + ""] --> before ["" + before + ""]""); ++ } ++ } ++ } ++ } ++ ++ if (!match) { ++ throw new IllegalArgumentException(""There are no outputs which matches: "" + matchBy.getId() + "" in the route: "" + route); ++ } ++ } ++ }; ++ } ++ ++ public static AdviceWithTask afterByToString(final RouteDefinition route, final String toString, final ProcessorDefinition after) { ++ return doAfter(route, new MatchByToString(toString), after); ++ } ++ ++ public static AdviceWithTask afterById(final RouteDefinition route, final String id, final ProcessorDefinition after) { ++ return doAfter(route, new MatchById(id), after); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ private static AdviceWithTask doAfter(final RouteDefinition route, final MatchBy matchBy, final ProcessorDefinition after) { ++ return new AdviceWithTask() { ++ public void task() throws Exception { ++ boolean match = false; ++ Iterator it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class); ++ while (it.hasNext()) { ++ ProcessorDefinition output = it.next(); ++ if (matchBy.match(output)) { ++ ++ ProcessorDefinition parent = output.getParent(); ++ if (parent != null) { ++ int index = parent.getOutputs().indexOf(output); ++ if (index != -1) { ++ match = true; ++ Object existing = parent.getOutputs().get(index); ++ parent.getOutputs().add(index + 1, after); ++ LOG.info(""AdviceWith ("" + matchBy.getId() + "") : ["" + existing + ""] --> after ["" + after + ""]""); ++ } ++ } ++ } ++ } ++ ++ if (!match) { ++ throw new IllegalArgumentException(""There are no outputs which matches: "" + matchBy.getId() + "" in the route: "" + route); ++ } ++ } ++ }; ++ } ++ ++} +diff --git a/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java b/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java +index dba8330ba815a..b34bb6570d046 100644 +--- a/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java ++++ b/camel-core/src/main/java/org/apache/camel/builder/RouteBuilder.java +@@ -30,6 +30,9 @@ + import org.apache.camel.model.RouteDefinition; + import org.apache.camel.model.RoutesDefinition; + ++import org.slf4j.Logger; ++import org.slf4j.LoggerFactory; ++ + /** + * A Java DSL which is + * used to build {@link org.apache.camel.impl.DefaultRoute} instances in a {@link CamelContext} for smart routing. +@@ -37,6 +40,7 @@ + * @version + */ + public abstract class RouteBuilder extends BuilderSupport implements RoutesBuilder { ++ protected Logger log = LoggerFactory.getLogger(getClass()); + private AtomicBoolean initialized = new AtomicBoolean(false); + private RoutesDefinition routeCollection = new RoutesDefinition(); + +@@ -343,6 +347,7 @@ public RoutesDefinition getRouteCollection() { + + /** + * Factory method ++ * + * @return the CamelContext + */ + protected CamelContext createContainer() { +@@ -356,7 +361,7 @@ protected void configureRoute(RouteDefinition route) { + /** + * Adds a collection of routes to this context + * +- * @param routes ++ * @param routes the routes + * @throws Exception if the routes could not be created for whatever reason + * @deprecated use {@link #includeRoutes(org.apache.camel.RoutesBuilder) includeRoutes} instead. + */ +diff --git a/camel-core/src/main/java/org/apache/camel/model/OutputDefinition.java b/camel-core/src/main/java/org/apache/camel/model/OutputDefinition.java +index 0c8184ae0d1a6..d6aca7071a371 100644 +--- a/camel-core/src/main/java/org/apache/camel/model/OutputDefinition.java ++++ b/camel-core/src/main/java/org/apache/camel/model/OutputDefinition.java +@@ -47,4 +47,14 @@ public void setOutputs(List outputs) { + } + } + } ++ ++ @Override ++ public String getShortName() { ++ return ""output""; ++ } ++ ++ @Override ++ public String toString() { ++ return getShortName() + "" -> ["" + outputs + ""]""; ++ } + } +diff --git a/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java b/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java +index 879552b7ce04e..ed995399f601e 100644 +--- a/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java ++++ b/camel-core/src/main/java/org/apache/camel/model/RouteDefinition.java +@@ -37,6 +37,8 @@ + import org.apache.camel.ServiceStatus; + import org.apache.camel.ShutdownRoute; + import org.apache.camel.ShutdownRunningTask; ++import org.apache.camel.builder.AdviceWithRouteBuilder; ++import org.apache.camel.builder.AdviceWithTask; + import org.apache.camel.builder.ErrorHandlerBuilder; + import org.apache.camel.builder.ErrorHandlerBuilderRef; + import org.apache.camel.builder.RouteBuilder; +@@ -179,6 +181,10 @@ public Endpoint resolveEndpoint(CamelContext camelContext, String uri) throws No + /** + * Advices this route with the route builder. + *

++ * You can use a regular {@link RouteBuilder} but the specialized {@link org.apache.camel.builder.AdviceWithRouteBuilder} ++ * has additional features when using the advice with feature. ++ * We therefore suggest you to use the {@link org.apache.camel.builder.AdviceWithRouteBuilder}. ++ *

+ * The advice process will add the interceptors, on exceptions, on completions etc. configured + * from the route builder to this route. + *

+@@ -190,14 +196,29 @@ public Endpoint resolveEndpoint(CamelContext camelContext, String uri) throws No + * @param builder the route builder + * @return a new route which is this route merged with the route builder + * @throws Exception can be thrown from the route builder ++ * @see AdviceWithRouteBuilder + */ + public RouteDefinition adviceWith(CamelContext camelContext, RouteBuilder builder) throws Exception { + ObjectHelper.notNull(camelContext, ""CamelContext""); + ObjectHelper.notNull(builder, ""RouteBuilder""); + ++ if (log.isDebugEnabled()) { ++ log.debug(""AdviceWith route before: "" + this); ++ } ++ ++ // inject this route into the advice route builder so it can access this route ++ // and offer features to manipulate the route directly ++ if (builder instanceof AdviceWithRouteBuilder) { ++ ((AdviceWithRouteBuilder) builder).setOriginalRoute(this); ++ } ++ + // configure and prepare the routes from the builder + RoutesDefinition routes = builder.configureRoutes(camelContext); + ++ if (log.isDebugEnabled()) { ++ log.debug(""AdviceWith routes: "" + routes); ++ } ++ + // we can only advice with a route builder without any routes + if (!routes.getRoutes().isEmpty()) { + throw new IllegalArgumentException(""You can only advice from a RouteBuilder which has no existing routes."" +@@ -211,12 +232,23 @@ public RouteDefinition adviceWith(CamelContext camelContext, RouteBuilder builde + // stop and remove this existing route + camelContext.removeRouteDefinition(this); + ++ // any advice with tasks we should execute first? ++ if (builder instanceof AdviceWithRouteBuilder) { ++ List tasks = ((AdviceWithRouteBuilder) builder).getAdviceWithTasks(); ++ for (AdviceWithTask task : tasks) { ++ task.task(); ++ } ++ } ++ + // now merge which also ensures that interceptors and the likes get mixed in correctly as well + RouteDefinition merged = routes.route(this); + + // add the new merged route + camelContext.getRouteDefinitions().add(0, merged); + ++ // log the merged route at info level to make it easier to end users to spot any mistakes they may have made ++ log.info(""AdviceWith route after: "" + merged); ++ + // and start it + camelContext.startRoute(merged); + return merged; +diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksMatchTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksMatchTest.java +new file mode 100644 +index 0000000000000..5cb4fe212267f +--- /dev/null ++++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksMatchTest.java +@@ -0,0 +1,61 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.processor.interceptor; ++ ++import org.apache.camel.ContextTestSupport; ++import org.apache.camel.builder.AdviceWithRouteBuilder; ++import org.apache.camel.builder.RouteBuilder; ++ ++/** ++ * Advice with match multiple ids test ++ */ ++public class AdviceWithTasksMatchTest extends ContextTestSupport { ++ ++ public void testReplaceMultipleIds() throws Exception { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // replace all gold id's with the following route path ++ adviceById(""gold*"").replace().multicast().to(""mock:a"").to(""mock:b""); ++ } ++ }); ++ ++ getMockEndpoint(""mock:foo"").expectedMessageCount(0); ++ getMockEndpoint(""mock:bar"").expectedMessageCount(0); ++ getMockEndpoint(""mock:a"").expectedMessageCount(2); ++ getMockEndpoint(""mock:b"").expectedMessageCount(2); ++ getMockEndpoint(""mock:result"").expectedMessageCount(1); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ ++ @Override ++ protected RouteBuilder createRouteBuilder() throws Exception { ++ return new RouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ from(""direct:start"") ++ .to(""mock:foo"").id(""gold-1"") ++ .to(""mock:bar"").id(""gold-2"") ++ .to(""mock:result"").id(""silver-1""); ++ } ++ }; ++ } ++} +\ No newline at end of file +diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksTest.java +new file mode 100644 +index 0000000000000..7545742d743f3 +--- /dev/null ++++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksTest.java +@@ -0,0 +1,142 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.processor.interceptor; ++ ++import org.apache.camel.ContextTestSupport; ++import org.apache.camel.builder.AdviceWithRouteBuilder; ++import org.apache.camel.builder.RouteBuilder; ++ ++/** ++ * Advice with tests ++ */ ++public class AdviceWithTasksTest extends ContextTestSupport { ++ ++ public void testUnknownId() throws Exception { ++ try { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ adviceById(""xxx"").replace().to(""mock:xxx""); ++ } ++ }); ++ fail(""Should hve thrown exception""); ++ } catch (IllegalArgumentException e) { ++ assertTrue(e.getMessage(), e.getMessage().startsWith(""There are no outputs which matches: xxx in the route"")); ++ } ++ } ++ ++ public void testReplace() throws Exception { ++ // START SNIPPET: e1 ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // advice the node in the route which has id = bar ++ // and replace it with the following route path ++ adviceById(""bar"").replace().multicast().to(""mock:a"").to(""mock:b""); ++ } ++ }); ++ // END SNIPPET: e1 ++ ++ getMockEndpoint(""mock:foo"").expectedMessageCount(1); ++ getMockEndpoint(""mock:bar"").expectedMessageCount(0); ++ getMockEndpoint(""mock:a"").expectedMessageCount(1); ++ getMockEndpoint(""mock:b"").expectedMessageCount(1); ++ getMockEndpoint(""mock:result"").expectedMessageCount(1); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ public void testRemove() throws Exception { ++ // START SNIPPET: e2 ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // advice the node in the route which has id = bar and remove it ++ adviceById(""bar"").remove(); ++ } ++ }); ++ // END SNIPPET: e2 ++ ++ getMockEndpoint(""mock:foo"").expectedMessageCount(1); ++ getMockEndpoint(""mock:result"").expectedMessageCount(1); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ ++ assertFalse(""Should not have removed id"", context.hasEndpoint(""mock:bar"") == null); ++ } ++ ++ public void testBefore() throws Exception { ++ // START SNIPPET: e3 ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // advice the node in the route which has id = bar ++ // and insert the following route path before the adviced node ++ adviceById(""bar"").before().to(""mock:a"").transform(constant(""Bye World"")); ++ } ++ }); ++ // END SNIPPET: e3 ++ ++ getMockEndpoint(""mock:foo"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:a"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:bar"").expectedBodiesReceived(""Bye World""); ++ getMockEndpoint(""mock:result"").expectedBodiesReceived(""Bye World""); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ public void testAfter() throws Exception { ++ // START SNIPPET: e4 ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // advice the node in the route which has id = bar ++ // and insert the following route path after the advice node ++ adviceById(""bar"").after().to(""mock:a"").transform(constant(""Bye World"")); ++ } ++ }); ++ // END SNIPPET: e4 ++ ++ getMockEndpoint(""mock:foo"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:a"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:bar"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:result"").expectedBodiesReceived(""Bye World""); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ @Override ++ protected RouteBuilder createRouteBuilder() throws Exception { ++ return new RouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ from(""direct:start"") ++ .to(""mock:foo"") ++ .to(""mock:bar"").id(""bar"") ++ .to(""mock:result""); ++ } ++ }; ++ } ++} +\ No newline at end of file +diff --git a/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksToStringPatternTest.java b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksToStringPatternTest.java +new file mode 100644 +index 0000000000000..f340167aa32e5 +--- /dev/null ++++ b/camel-core/src/test/java/org/apache/camel/processor/interceptor/AdviceWithTasksToStringPatternTest.java +@@ -0,0 +1,131 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.processor.interceptor; ++ ++import org.apache.camel.ContextTestSupport; ++import org.apache.camel.builder.AdviceWithRouteBuilder; ++import org.apache.camel.builder.RouteBuilder; ++ ++/** ++ * Advice with using to string matching ++ */ ++public class AdviceWithTasksToStringPatternTest extends ContextTestSupport { ++ ++ public void testUnknownId() throws Exception { ++ try { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ adviceByToString(""xxx"").replace().to(""mock:xxx""); ++ } ++ }); ++ fail(""Should hve thrown exception""); ++ } catch (IllegalArgumentException e) { ++ assertTrue(e.getMessage(), e.getMessage().startsWith(""There are no outputs which matches: xxx in the route"")); ++ } ++ } ++ ++ public void testReplace() throws Exception { ++ // START SNIPPET: e1 ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ // advice nodes in the route which has foo anywhere in their to string representation ++ // and replace them with the following route path ++ adviceByToString("".*foo.*"").replace().multicast().to(""mock:a"").to(""mock:b""); ++ } ++ }); ++ // END SNIPPET: e1 ++ ++ getMockEndpoint(""mock:foo"").expectedMessageCount(0); ++ getMockEndpoint(""mock:a"").expectedMessageCount(1); ++ getMockEndpoint(""mock:b"").expectedMessageCount(1); ++ getMockEndpoint(""mock:bar"").expectedMessageCount(1); ++ getMockEndpoint(""mock:result"").expectedMessageCount(1); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ public void testRemove() throws Exception { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ adviceByToString("".*bar.*"").remove(); ++ } ++ }); ++ ++ getMockEndpoint(""mock:foo"").expectedMessageCount(1); ++ getMockEndpoint(""mock:result"").expectedMessageCount(1); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ ++ assertFalse(""Should not have removed id"", context.hasEndpoint(""mock:bar"") == null); ++ } ++ ++ public void testBefore() throws Exception { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ adviceByToString("".*bar.*"").before().to(""mock:a"").transform(constant(""Bye World"")); ++ } ++ }); ++ ++ getMockEndpoint(""mock:foo"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:a"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:bar"").expectedBodiesReceived(""Bye World""); ++ getMockEndpoint(""mock:result"").expectedBodiesReceived(""Bye World""); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ public void testAfter() throws Exception { ++ context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ adviceByToString("".*bar.*"").after().to(""mock:a"").transform(constant(""Bye World"")); ++ } ++ }); ++ ++ getMockEndpoint(""mock:foo"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:a"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:bar"").expectedBodiesReceived(""Hello World""); ++ getMockEndpoint(""mock:result"").expectedBodiesReceived(""Bye World""); ++ ++ template.sendBody(""direct:start"", ""Hello World""); ++ ++ assertMockEndpointsSatisfied(); ++ } ++ ++ @Override ++ protected RouteBuilder createRouteBuilder() throws Exception { ++ return new RouteBuilder() { ++ @Override ++ public void configure() throws Exception { ++ from(""direct:start"") ++ .to(""mock:foo"") ++ .to(""mock:bar"") ++ .to(""mock:result""); ++ } ++ }; ++ } ++} +\ No newline at end of file" +ac93bc54a2c1a7b17d3a0b57fc9a24ec9d334c78,Delta Spike,"DELTASPIKE-289 WindowContext cleanup +",c,https://github.com/apache/deltaspike,"diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java +index fbd585cdb..14663c5af 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/spi/scope/window/WindowContext.java +@@ -30,7 +30,8 @@ + * session as @SessionScoped bean. + *

+ *

Every WindowContext is uniquely identified via a +- * 'windowId'. Each Thread is associated with at most ++ * 'windowId' inside the current Session. ++ * Each Thread is associated with at most + * one single windowId at a time. The {@link WindowContext} + * is the interface which allows resolving the current windowId + * associated with this very Thread.

+@@ -47,21 +48,12 @@ public interface WindowContext + * If no WindowContext exists with the very windowId we will create a new one. + * @param windowId + */ +- void activateWindowContext(String windowId); ++ void activateWindow(String windowId); + + /** +- * close the WindowContext with the currently activated windowId for the very Thread. ++ * close the WindowContext with the given windowId. + * @return true if any did exist, false otherwise + */ +- boolean closeCurrentWindowContext(); +- +- +- /** +- * Close all WindowContexts which are managed by the WindowContextManager. +- * This is necessary when the session gets closed down or the application closes. +- * @return +- */ +- void destroy(); +- ++ boolean closeWindow(String windowId); + + } +diff --git a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java +index 583faf80c..e30931ca2 100644 +--- a/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java ++++ b/deltaspike/core/api/src/main/java/org/apache/deltaspike/core/util/context/AbstractContext.java +@@ -154,9 +154,11 @@ public void destroyAllActive() + } + + /** +- * destroys all the Contextual Instances in the specified ContextualStorage. ++ * Destroys all the Contextual Instances in the specified ContextualStorage. ++ * This is a static method to allow various holder objects to cleanup ++ * properly in @PreDestroy. + */ +- public void destroyAllActive(ContextualStorage storage) ++ public static void destroyAllActive(ContextualStorage storage) + { + Map> contextMap = storage.getStorage(); + for (Map.Entry> entry : contextMap.entrySet()) +diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java +index d51342f41..8acd0e663 100644 +--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowBeanHolder.java +@@ -18,12 +18,14 @@ + */ + package org.apache.deltaspike.core.impl.scope.window; + ++import javax.annotation.PreDestroy; + import javax.enterprise.context.SessionScoped; + import javax.enterprise.inject.spi.BeanManager; + import java.io.Serializable; + import java.util.Map; + import java.util.concurrent.ConcurrentHashMap; + ++import org.apache.deltaspike.core.util.context.AbstractContext; + import org.apache.deltaspike.core.util.context.ContextualStorage; + + /** +@@ -41,6 +43,7 @@ public class WindowBeanHolder implements Serializable + */ + private volatile Map storageMap = new ConcurrentHashMap(); + ++ //X TODO review usage + public Map getStorageMap() + { + return storageMap; +@@ -86,4 +89,18 @@ public Map forceNewStorage() + storageMap = new ConcurrentHashMap(); + return oldStorageMap; + } ++ ++ @PreDestroy ++ public void destroyBeans() ++ { ++ // we replace the old windowBeanHolder beans with a new storage Map ++ // an afterwards destroy the old Beans without having to care about any syncs. ++ Map oldWindowContextStorages = forceNewStorage(); ++ ++ for (ContextualStorage contextualStorage : oldWindowContextStorages.values()) ++ { ++ AbstractContext.destroyAllActive(contextualStorage); ++ } ++ ++ } + } +diff --git a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java +index f20d02fe1..e9aa32661 100644 +--- a/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java ++++ b/deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/scope/window/WindowContextImpl.java +@@ -23,8 +23,6 @@ + import javax.enterprise.inject.spi.BeanManager; + + import java.lang.annotation.Annotation; +-import java.util.Map; +-import java.util.concurrent.ConcurrentHashMap; + + import org.apache.deltaspike.core.api.scope.WindowScoped; + import org.apache.deltaspike.core.spi.scope.window.WindowContext; +@@ -38,13 +36,18 @@ + public class WindowContextImpl extends AbstractContext implements WindowContext + { + /** +- * all the {@link WindowContext}s which are active in this very Session. ++ * Holds the currently active windowId of each Request + */ +- private Map windowContexts = new ConcurrentHashMap(); +- + private WindowIdHolder windowIdHolder; ++ ++ /** ++ * Contains the stored WindowScoped contextual instances. ++ */ + private WindowBeanHolder windowBeanHolder; + ++ /** ++ * needed for serialisation and passivationId ++ */ + private BeanManager beanManager; + + +@@ -55,8 +58,20 @@ public WindowContextImpl(BeanManager beanManager) + this.beanManager = beanManager; + } + ++ /** ++ * We need to pass the session scoped windowbean holder and the ++ * requestscoped windowIdHolder in a later phase because ++ * getBeans is only allowed from AfterDeploymentValidation onwards. ++ */ ++ void initWindowContext(WindowBeanHolder windowBeanHolder, WindowIdHolder windowIdHolder) ++ { ++ this.windowBeanHolder = windowBeanHolder; ++ this.windowIdHolder = windowIdHolder; ++ } ++ ++ + @Override +- public void activateWindowContext(String windowId) ++ public void activateWindow(String windowId) + { + windowIdHolder.setWindowId(windowId); + } +@@ -68,16 +83,15 @@ public String getCurrentWindowId() + } + + @Override +- public boolean closeCurrentWindowContext() ++ public boolean closeWindow(String windowId) + { +- String windowId = windowIdHolder.getWindowId(); + if (windowId == null) + { + return false; + } + +- WindowContext windowContext = windowContexts.get(windowId); +- if (windowContext == null) ++ ContextualStorage windowStorage = windowBeanHolder.getContextualStorage(beanManager, windowId); ++ if (windowStorage == null) + { + return false; + } +@@ -85,19 +99,6 @@ public boolean closeCurrentWindowContext() + return true; + } + +- @Override +- public synchronized void destroy() +- { +- // we replace the old windowBeanHolder beans with a new storage Map +- // an afterwards destroy the old Beans without having to care about any syncs. +- Map oldWindowContextStorages = windowBeanHolder.forceNewStorage(); +- +- for (ContextualStorage contextualStorage : oldWindowContextStorages.values()) +- { +- destroyAllActive(contextualStorage); +- } +- } +- + @Override + protected ContextualStorage getContextualStorage(boolean createIfNotExist) + { +@@ -127,9 +128,4 @@ public boolean isActive() + return windowId != null; + } + +- void initWindowContext(WindowBeanHolder windowBeanHolder, WindowIdHolder windowIdHolder) +- { +- this.windowBeanHolder = windowBeanHolder; +- this.windowIdHolder = windowIdHolder; +- } + } +diff --git a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java +index 68408fda5..39640b8d4 100644 +--- a/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java ++++ b/deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/scope/window/DefaultWindowContextTest.java +@@ -68,14 +68,14 @@ public void testWindowScoedBean() + Assert.assertNotNull(someWindowScopedBean); + + { +- windowContext.activateWindowContext(""window1""); ++ windowContext.activateWindow(""window1""); + someWindowScopedBean.setValue(""Hans""); + Assert.assertEquals(""Hans"", someWindowScopedBean.getValue()); + } + + // now we switch it away to another 'window' + { +- windowContext.activateWindowContext(""window2""); ++ windowContext.activateWindow(""window2""); + Assert.assertNull(someWindowScopedBean.getValue()); + someWindowScopedBean.setValue(""Karl""); + Assert.assertEquals(""Karl"", someWindowScopedBean.getValue()); +@@ -83,7 +83,7 @@ public void testWindowScoedBean() + + // and now back to the first window + { +- windowContext.activateWindowContext(""window1""); ++ windowContext.activateWindow(""window1""); + + // which must still contain the old value + Assert.assertEquals(""Hans"", someWindowScopedBean.getValue()); +@@ -91,7 +91,7 @@ public void testWindowScoedBean() + + // and again back to the second window + { +- windowContext.activateWindowContext(""window2""); ++ windowContext.activateWindow(""window2""); + + // which must still contain the old value of the 2nd window + Assert.assertEquals(""Karl"", someWindowScopedBean.getValue());" +541aae12ef82767479bcd53afb3681b46dd890a5,spring-framework,SPR-5802 - NullPointerException when using- @CookieValue annotation--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +index f6b7c4204360..e8fa23d6ac5f 100644 +--- a/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java ++++ b/org.springframework.web.portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +@@ -600,9 +600,12 @@ protected Object resolveCookieValue(String cookieName, Class paramType, NativeWe + if (Cookie.class.isAssignableFrom(paramType)) { + return cookieValue; + } +- else { ++ else if (cookieValue != null) { + return cookieValue.getValue(); + } ++ else { ++ return null; ++ } + } + + @Override" +f3554235b3abb5b5820b57f932398af5a8846b32,Delta Spike,"adding release notes draft for upcoming deltaspike-0.5 release +",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/readme/ReleaseNotes-0.5.txt b/deltaspike/readme/ReleaseNotes-0.5.txt +new file mode 100644 +index 000000000..ea682196b +--- /dev/null ++++ b/deltaspike/readme/ReleaseNotes-0.5.txt +@@ -0,0 +1,30 @@ ++Apache DeltaSpike-0.5 Release Notes ++ ++ ++The following modules and big features got added in the DeltaSpike-0.5 release: ++ ++* DeltaSpike-Data ++ ++The DeltaSpike Data module enhances JPA experience with declarative ++queries, reducing boilerplate to a minimum. DeltaSpike Data repositories ++can derive queries by simple method names, or by method annotations ++defining JPQL, named queries or even plain SQL - beside result pagination ++and sorting. The module also features auditing of entities and a simplified ++alternative to the Criteria API. ++ ++ ++* DeltaSpike-Servlet ++ ++The DeltaSpike Servlet module provides integration with the Java Servlet ++API. It adds support for injection of common servlet objects ++and propagates servlet events to the CDI event bus. ++ ++ ++* DeltaSpike-BeanValidation ++ ++The main feature of the Bean Validation module is to provide ++CDI integration in to ConstraintValidators. This allows you to ++inject CDI objects, EJBs etc in to your validators. ++ ++ ++" +1f363c2f0b1d5ee8cb7501a2a7a8994349724cc6,apache$hama,"Improve message buffering to save memory +git-svn-id: https://svn.apache.org/repos/asf/incubator/hama/trunk@1331732 13f79535-47bb-0310-9956-ffa450edef68 +",p,https://github.com/apache/hama,"diff --git a/CHANGES.txt b/CHANGES.txt +index ae4bd86f0..b430dddbb 100644 +--- a/CHANGES.txt ++++ b/CHANGES.txt +@@ -16,6 +16,7 @@ Release 0.5 - April 10, 2012 + + IMPROVEMENTS + ++ HAMA-521: Improve message buffering to save memory (Thomas Jungblut via edwardyoon) + HAMA-494: Remove hard-coded webapp path in HttpServer (edwardyoon) + HAMA-562: Record Reader/Writer objects should be initialized (edwardyoon) + HAMA-555: Separate bin and src distributions (edwardyoon) +diff --git a/conf/hama-default.xml b/conf/hama-default.xml +index 12fcdc306..f204ab861 100644 +--- a/conf/hama-default.xml ++++ b/conf/hama-default.xml +@@ -80,6 +80,11 @@ + /tmp/hama-${user.name} + Temporary directory on the local filesystem. + ++ ++ bsp.disk.queue.dir ++ ${hama.tmp.dir}/messages/ ++ Temporary directory on the local message buffer on disk. ++ + + bsp.child.java.opts + -Xmx512m +diff --git a/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java b/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java +index abd0801f9..8c8213557 100644 +--- a/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java ++++ b/core/src/main/java/org/apache/hama/bsp/BSPPeerImpl.java +@@ -20,7 +20,6 @@ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.util.Iterator; +-import java.util.LinkedList; + import java.util.Map.Entry; + + import org.apache.commons.logging.Log; +@@ -37,6 +36,7 @@ + import org.apache.hama.bsp.Counters.Counter; + import org.apache.hama.bsp.message.MessageManager; + import org.apache.hama.bsp.message.MessageManagerFactory; ++import org.apache.hama.bsp.message.MessageQueue; + import org.apache.hama.bsp.sync.SyncClient; + import org.apache.hama.bsp.sync.SyncException; + import org.apache.hama.bsp.sync.SyncServiceFactory; +@@ -165,7 +165,7 @@ public BSPPeerImpl(BSPJob job, Configuration conf, TaskAttemptID taskId, + TaskStatus.Phase.STARTING, counters)); + + messenger = MessageManagerFactory.getMessageManager(conf); +- messenger.init(this, conf, peerAddress); ++ messenger.init(taskId, this, conf, peerAddress); + + final String combinerName = conf.get(""bsp.combiner.class""); + if (combinerName != null) { +@@ -294,7 +294,9 @@ public final void sync() throws IOException, SyncException, + InterruptedException { + long startBarrier = System.currentTimeMillis(); + enterBarrier(); +- Iterator>> it = messenger ++ // normally all messages should been send now, finalizing the send phase ++ messenger.finishSendPhase(); ++ Iterator>> it = messenger + .getMessageIterator(); + + boolean shouldCheckPoint = false; +@@ -304,7 +306,7 @@ public final void sync() throws IOException, SyncException, + } + + while (it.hasNext()) { +- Entry> entry = it.next(); ++ Entry> entry = it.next(); + final InetSocketAddress addr = entry.getKey(); + final Iterable messages = entry.getValue(); + +@@ -357,16 +359,33 @@ protected final void leaveBarrier() throws SyncException { + + public final void close() throws SyncException, IOException, + InterruptedException { ++ // there are many catches, because we want to close always every component ++ // even if the one before failed. + if (in != null) { +- in.close(); ++ try { ++ in.close(); ++ } catch (Exception e) { ++ LOG.error(e); ++ } + } + if (outWriter != null) { +- outWriter.close(); ++ try { ++ outWriter.close(); ++ } catch (Exception e) { ++ LOG.error(e); ++ } + } + this.clear(); +- syncClient.close(); +- +- messenger.close(); ++ try { ++ syncClient.close(); ++ } catch (Exception e) { ++ LOG.error(e); ++ } ++ try { ++ messenger.close(); ++ } catch (Exception e) { ++ LOG.error(e); ++ } + } + + @Override +diff --git a/core/src/main/java/org/apache/hama/bsp/LocalBSPRunner.java b/core/src/main/java/org/apache/hama/bsp/LocalBSPRunner.java +index c773c9d88..f3b17ce5c 100644 +--- a/core/src/main/java/org/apache/hama/bsp/LocalBSPRunner.java ++++ b/core/src/main/java/org/apache/hama/bsp/LocalBSPRunner.java +@@ -45,8 +45,10 @@ + import org.apache.hama.HamaConfiguration; + import org.apache.hama.bsp.BSPJobClient.RawSplit; + import org.apache.hama.bsp.BSPMaster.State; ++import org.apache.hama.bsp.message.MemoryQueue; + import org.apache.hama.bsp.message.MessageManager; + import org.apache.hama.bsp.message.MessageManagerFactory; ++import org.apache.hama.bsp.message.MessageQueue; + import org.apache.hama.bsp.sync.SyncClient; + import org.apache.hama.bsp.sync.SyncException; + import org.apache.hama.bsp.sync.SyncServiceFactory; +@@ -332,14 +334,15 @@ public static class LocalMessageManager implements + @SuppressWarnings(""rawtypes"") + private static final ConcurrentHashMap managerMap = new ConcurrentHashMap(); + +- private final HashMap> localOutgoingMessages = new HashMap>(); ++ private final HashMap> localOutgoingMessages = new HashMap>(); + private static final ConcurrentHashMap socketCache = new ConcurrentHashMap(); + private final LinkedBlockingDeque localIncomingMessages = new LinkedBlockingDeque(); + + private BSPPeer peer; + + @Override +- public void init(BSPPeer peer, Configuration conf, InetSocketAddress peerAddress) { ++ public void init(TaskAttemptID attemptId, BSPPeer peer, ++ Configuration conf, InetSocketAddress peerAddress) { + this.peer = peer; + managerMap.put(peerAddress, this); + } +@@ -365,9 +368,9 @@ public void send(String peerName, M msg) throws IOException { + inetSocketAddress = BSPNetUtils.getAddress(peerName); + socketCache.put(peerName, inetSocketAddress); + } +- LinkedList msgs = localOutgoingMessages.get(inetSocketAddress); ++ MessageQueue msgs = localOutgoingMessages.get(inetSocketAddress); + if (msgs == null) { +- msgs = new LinkedList(); ++ msgs = new MemoryQueue(); + } + msgs.add(msg); + peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_SENT, 1L); +@@ -380,12 +383,13 @@ public void transfer(InetSocketAddress addr, BSPMessageBundle bundle) + throws IOException { + for (M value : bundle.getMessages()) { + managerMap.get(addr).localIncomingMessages.add(value); +- peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, 1L); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, ++ 1L); + } + } + + @Override +- public Iterator>> getMessageIterator() { ++ public Iterator>> getMessageIterator() { + return localOutgoingMessages.entrySet().iterator(); + } + +@@ -399,6 +403,12 @@ public int getNumCurrentMessages() { + return localIncomingMessages.size(); + } + ++ @Override ++ public void finishSendPhase() throws IOException { ++ // TODO Auto-generated method stub ++ ++ } ++ + } + + public static class LocalUmbilical implements BSPPeerProtocol { +diff --git a/core/src/main/java/org/apache/hama/bsp/message/AbstractMessageManager.java b/core/src/main/java/org/apache/hama/bsp/message/AbstractMessageManager.java +new file mode 100644 +index 000000000..509a66b03 +--- /dev/null ++++ b/core/src/main/java/org/apache/hama/bsp/message/AbstractMessageManager.java +@@ -0,0 +1,160 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.io.IOException; ++import java.net.InetSocketAddress; ++import java.util.Collection; ++import java.util.HashMap; ++import java.util.Iterator; ++import java.util.Map.Entry; ++ ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; ++import org.apache.hadoop.conf.Configurable; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.io.Writable; ++import org.apache.hadoop.util.ReflectionUtils; ++import org.apache.hama.bsp.BSPPeer; ++import org.apache.hama.bsp.BSPPeerImpl; ++import org.apache.hama.bsp.TaskAttemptID; ++import org.apache.hama.util.BSPNetUtils; ++ ++public abstract class AbstractMessageManager implements ++ MessageManager, Configurable { ++ ++ private static final Log LOG = LogFactory ++ .getLog(AbstractMessageManager.class); ++ ++ // conf is injected via reflection of the factory ++ protected Configuration conf; ++ protected final HashMap peerSocketCache = new HashMap(); ++ protected final HashMap> outgoingQueues = new HashMap>(); ++ protected MessageQueue localQueue; ++ // this must be a synchronized implementation: this is accessed per RPC ++ protected SynchronizedQueue localQueueForNextIteration; ++ protected BSPPeer peer; ++ // the peer address of this peer ++ protected InetSocketAddress peerAddress; ++ // the task attempt id ++ protected TaskAttemptID attemptId; ++ ++ @Override ++ public void init(TaskAttemptID attemptId, BSPPeer peer, ++ Configuration conf, InetSocketAddress peerAddress) { ++ this.attemptId = attemptId; ++ this.peer = peer; ++ this.conf = conf; ++ this.peerAddress = peerAddress; ++ localQueue = getQueue(); ++ localQueue.init(conf, attemptId); ++ localQueueForNextIteration = getSynchronizedQueue(); ++ localQueueForNextIteration.init(conf, attemptId); ++ } ++ ++ @Override ++ public void close() { ++ Collection> values = outgoingQueues.values(); ++ for (MessageQueue msgQueue : values) { ++ msgQueue.close(); ++ } ++ localQueue.close(); ++ } ++ ++ @Override ++ public void finishSendPhase() throws IOException { ++ Collection> values = outgoingQueues.values(); ++ for (MessageQueue msgQueue : values) { ++ msgQueue.prepareRead(); ++ } ++ } ++ ++ @Override ++ public final M getCurrentMessage() throws IOException { ++ return localQueue.poll(); ++ } ++ ++ @Override ++ public final int getNumCurrentMessages() { ++ return localQueue.size(); ++ } ++ ++ @Override ++ public final void clearOutgoingQueues() { ++ this.outgoingQueues.clear(); ++ localQueueForNextIteration.prepareRead(); ++ localQueue.prepareWrite(); ++ localQueue.addAll(localQueueForNextIteration.getMessageQueue()); ++ localQueue.prepareRead(); ++ localQueueForNextIteration.clear(); ++ } ++ ++ @Override ++ public void send(String peerName, M msg) throws IOException { ++ LOG.debug(""Send message ("" + msg.toString() + "") to "" + peerName); ++ InetSocketAddress targetPeerAddress = null; ++ // Get socket for target peer. ++ if (peerSocketCache.containsKey(peerName)) { ++ targetPeerAddress = peerSocketCache.get(peerName); ++ } else { ++ targetPeerAddress = BSPNetUtils.getAddress(peerName); ++ peerSocketCache.put(peerName, targetPeerAddress); ++ } ++ MessageQueue queue = outgoingQueues.get(targetPeerAddress); ++ if (queue == null) { ++ queue = getQueue(); ++ } ++ queue.add(msg); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_SENT, 1L); ++ outgoingQueues.put(targetPeerAddress, queue); ++ } ++ ++ @Override ++ public final Iterator>> getMessageIterator() { ++ return this.outgoingQueues.entrySet().iterator(); ++ } ++ ++ /** ++ * Returns a new queue implementation based on what was configured. If nothing ++ * has been configured for ""hama.messenger.queue.class"" then the ++ * {@link MemoryQueue} is used. ++ * ++ * @return a new queue implementation. ++ */ ++ protected MessageQueue getQueue() { ++ Class queueClass = conf.getClass(QUEUE_TYPE_CLASS, MemoryQueue.class); ++ @SuppressWarnings(""unchecked"") ++ MessageQueue newInstance = (MessageQueue) ReflectionUtils ++ .newInstance(queueClass, conf); ++ newInstance.init(conf, attemptId); ++ return newInstance; ++ } ++ ++ protected SynchronizedQueue getSynchronizedQueue() { ++ return SynchronizedQueue.synchronize(getQueue()); ++ } ++ ++ public final Configuration getConf() { ++ return conf; ++ } ++ ++ public final void setConf(Configuration conf) { ++ this.conf = conf; ++ } ++ ++} +diff --git a/core/src/main/java/org/apache/hama/bsp/message/AvroMessageManagerImpl.java b/core/src/main/java/org/apache/hama/bsp/message/AvroMessageManagerImpl.java +index 91558d14a..8f1f61592 100644 +--- a/core/src/main/java/org/apache/hama/bsp/message/AvroMessageManagerImpl.java ++++ b/core/src/main/java/org/apache/hama/bsp/message/AvroMessageManagerImpl.java +@@ -24,12 +24,8 @@ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.nio.ByteBuffer; +-import java.util.Deque; + import java.util.HashMap; + import java.util.Iterator; +-import java.util.LinkedList; +-import java.util.Map.Entry; +-import java.util.concurrent.ConcurrentLinkedQueue; + + import org.apache.avro.AvroRemoteException; + import org.apache.avro.ipc.NettyServer; +@@ -41,8 +37,8 @@ + import org.apache.hama.bsp.BSPMessageBundle; + import org.apache.hama.bsp.BSPPeer; + import org.apache.hama.bsp.BSPPeerImpl; ++import org.apache.hama.bsp.TaskAttemptID; + import org.apache.hama.bsp.message.compress.BSPCompressedBundle; +-import org.apache.hama.util.BSPNetUtils; + + public final class AvroMessageManagerImpl extends + CompressableMessageManager implements Sender { +@@ -50,39 +46,24 @@ public final class AvroMessageManagerImpl extends + private NettyServer server = null; + + private final HashMap> peers = new HashMap>(); +- private final HashMap peerSocketCache = new HashMap(); +- +- private final HashMap> outgoingQueues = new HashMap>(); +- private Deque localQueue = new LinkedList(); +- // this must be a synchronized implementation: this is accessed per RPC +- private final ConcurrentLinkedQueue localQueueForNextIteration = new ConcurrentLinkedQueue(); +- +- private BSPPeer peer; + + @Override +- public void init(BSPPeer peer, Configuration conf, +- InetSocketAddress addr) { +- this.peer = peer; ++ public void init(TaskAttemptID attemptId, BSPPeer peer, ++ Configuration conf, InetSocketAddress addr) { ++ super.init(attemptId, peer, conf, addr); + super.initCompression(conf); + server = new NettyServer(new SpecificResponder(Sender.class, this), addr); + } + + @Override + public void close() { ++ super.close(); + server.close(); + } + +- @Override +- public void clearOutgoingQueues() { +- this.outgoingQueues.clear(); +- localQueue.addAll(localQueueForNextIteration); +- localQueueForNextIteration.clear(); +- } +- + public void put(BSPMessageBundle messages) { +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, messages.getMessages() +- .size()); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, ++ messages.getMessages().size()); + Iterator iterator = messages.getMessages().iterator(); + while (iterator.hasNext()) { + this.localQueueForNextIteration.add(iterator.next()); +@@ -90,11 +71,6 @@ public void put(BSPMessageBundle messages) { + } + } + +- @Override +- public int getNumCurrentMessages() { +- return localQueue.size(); +- } +- + @SuppressWarnings(""unchecked"") + @Override + public void transfer(InetSocketAddress addr, BSPMessageBundle bundle) +@@ -125,42 +101,19 @@ public Void transfer(AvroBSPMessageBundle messagebundle) + return null; + } + +- @Override +- public M getCurrentMessage() throws IOException { +- return localQueue.poll(); +- } +- +- @Override +- public void send(String peerName, M msg) throws IOException { +- InetSocketAddress targetPeerAddress = null; +- // Get socket for target peer. +- if (peerSocketCache.containsKey(peerName)) { +- targetPeerAddress = peerSocketCache.get(peerName); +- } else { +- targetPeerAddress = BSPNetUtils.getAddress(peerName); +- peerSocketCache.put(peerName, targetPeerAddress); +- } +- LinkedList queue = outgoingQueues.get(targetPeerAddress); +- if (queue == null) { +- queue = new LinkedList(); +- } +- queue.add(msg); +- outgoingQueues.put(targetPeerAddress, queue); +- } +- + private final BSPMessageBundle deserializeMessage(ByteBuffer buffer) + throws IOException { + BSPMessageBundle msg = new BSPMessageBundle(); + byte[] byteArray = buffer.array(); + if (compressor == null) { +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.MESSAGE_BYTES_RECEIVED, byteArray.length); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.MESSAGE_BYTES_RECEIVED, ++ byteArray.length); + ByteArrayInputStream inArray = new ByteArrayInputStream(byteArray); + DataInputStream in = new DataInputStream(inArray); + msg.readFields(in); + } else { +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.COMPRESSED_BYTES_RECEIVED, byteArray.length); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.COMPRESSED_BYTES_RECEIVED, ++ byteArray.length); + msg = compressor.decompressBundle(new BSPCompressedBundle(byteArray)); + } + +@@ -175,20 +128,16 @@ private final ByteBuffer serializeMessage(BSPMessageBundle msg) + msg.write(out); + out.close(); + byte[] byteArray = outArray.toByteArray(); +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.MESSAGE_BYTES_TRANSFERED, byteArray.length); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.MESSAGE_BYTES_TRANSFERED, ++ byteArray.length); + return ByteBuffer.wrap(byteArray); + } else { + BSPCompressedBundle compMsgBundle = compressor.compressBundle(msg); + byte[] data = compMsgBundle.getData(); +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.COMPRESSED_BYTES_SENT, data.length); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.COMPRESSED_BYTES_SENT, ++ data.length); + return ByteBuffer.wrap(data); + } + } + +- @Override +- public Iterator>> getMessageIterator() { +- return this.outgoingQueues.entrySet().iterator(); +- } + } +diff --git a/core/src/main/java/org/apache/hama/bsp/message/CompressableMessageManager.java b/core/src/main/java/org/apache/hama/bsp/message/CompressableMessageManager.java +index 26d863498..269a4907c 100644 +--- a/core/src/main/java/org/apache/hama/bsp/message/CompressableMessageManager.java ++++ b/core/src/main/java/org/apache/hama/bsp/message/CompressableMessageManager.java +@@ -27,8 +27,7 @@ + * + * @param + */ +-public abstract class CompressableMessageManager implements +- MessageManager { ++public abstract class CompressableMessageManager extends AbstractMessageManager { + + protected BSPMessageCompressor compressor; + +diff --git a/core/src/main/java/org/apache/hama/bsp/message/DiskQueue.java b/core/src/main/java/org/apache/hama/bsp/message/DiskQueue.java +new file mode 100644 +index 000000000..22644ca45 +--- /dev/null ++++ b/core/src/main/java/org/apache/hama/bsp/message/DiskQueue.java +@@ -0,0 +1,289 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.io.IOException; ++import java.util.Collection; ++import java.util.Iterator; ++ ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.fs.FileSystem; ++import org.apache.hadoop.fs.Path; ++import org.apache.hadoop.io.NullWritable; ++import org.apache.hadoop.io.ObjectWritable; ++import org.apache.hadoop.io.SequenceFile; ++import org.apache.hadoop.io.Writable; ++import org.apache.hama.bsp.TaskAttemptID; ++ ++/** ++ * A disk based queue that is backed by a sequencefile.
++ * Structure is as follows:
++ * If ""bsp.disk.queue.dir"" is not defined, ""hama.tmp.dir"" will be used instead.
++ * ${hama.tmp.dir}/diskqueue/job_id/task_attempt_id/
++ * An ongoing sequencenumber will be appended to prevent inner collisions, ++ * however the job_id dir will never be deleted. So you need a cronjob to do the ++ * cleanup for you.
++ * This is currently not intended to be production ready ++ */ ++public final class DiskQueue implements MessageQueue { ++ ++ public static final String DISK_QUEUE_PATH_KEY = ""bsp.disk.queue.dir""; ++ ++ private final Log LOG = LogFactory.getLog(DiskQueue.class); ++ ++ private static volatile int ONGOING_SEQUENCE_NUMBER = 0; ++ private static final int MAX_RETRIES = 4; ++ private static final NullWritable NULL_WRITABLE = NullWritable.get(); ++ ++ private int size = 0; ++ // injected via reflection ++ private Configuration conf; ++ private FileSystem fs; ++ ++ private SequenceFile.Writer writer; ++ private SequenceFile.Reader reader; ++ private Path queuePath; ++ private TaskAttemptID id; ++ private final ObjectWritable writable = new ObjectWritable(); ++ ++ @Override ++ public void init(Configuration conf, TaskAttemptID id) { ++ this.id = id; ++ writable.setConf(conf); ++ try { ++ fs = FileSystem.get(conf); ++ String configuredQueueDir = conf.get(DISK_QUEUE_PATH_KEY); ++ Path queueDir = null; ++ if (configuredQueueDir == null) { ++ String hamaTmpDir = conf.get(""hama.tmp.dir""); ++ if (hamaTmpDir != null) { ++ queueDir = createDiskQueuePath(id, hamaTmpDir); ++ } else { ++ // use some local tmp dir ++ queueDir = createDiskQueuePath(id, ""/tmp/messageStorage/""); ++ } ++ } else { ++ queueDir = createDiskQueuePath(id, configuredQueueDir); ++ } ++ fs.mkdirs(queueDir); ++ queuePath = new Path(queueDir, (ONGOING_SEQUENCE_NUMBER++) ++ + ""_messages.seq""); ++ prepareWrite(); ++ } catch (IOException e) { ++ // we can't recover if something bad happens here.. ++ throw new RuntimeException(e); ++ } ++ } ++ ++ @Override ++ public void close() { ++ closeInternal(true); ++ try { ++ fs.delete(queuePath.getParent(), true); ++ } catch (IOException e) { ++ LOG.error(e); ++ } ++ } ++ ++ /** ++ * Close our writer internal, basically should be called after the computation ++ * phase ended. ++ */ ++ private void closeInternal(boolean delete) { ++ try { ++ if (writer != null) { ++ writer.close(); ++ writer = null; ++ } ++ } catch (IOException e) { ++ LOG.error(e); ++ } finally { ++ if (fs != null && delete) { ++ try { ++ fs.delete(queuePath, true); ++ } catch (IOException e) { ++ LOG.error(e); ++ } ++ } ++ if (writer != null) { ++ try { ++ writer.close(); ++ writer = null; ++ } catch (IOException e) { ++ LOG.error(e); ++ } ++ } ++ } ++ try { ++ if (reader != null) { ++ reader.close(); ++ reader = null; ++ } ++ } catch (IOException e) { ++ LOG.error(e); ++ } finally { ++ if (reader != null) { ++ try { ++ reader.close(); ++ reader = null; ++ } catch (IOException e) { ++ LOG.error(e); ++ } ++ } ++ } ++ } ++ ++ @Override ++ public void prepareRead() { ++ // make sure we've closed ++ closeInternal(false); ++ try { ++ reader = new SequenceFile.Reader(fs, queuePath, conf); ++ } catch (IOException e) { ++ // can't recover from that ++ LOG.error(e); ++ throw new RuntimeException(e); ++ } ++ } ++ ++ @Override ++ public void prepareWrite() { ++ try { ++ writer = new SequenceFile.Writer(fs, conf, queuePath, ++ ObjectWritable.class, NullWritable.class); ++ } catch (IOException e) { ++ // can't recover from that ++ LOG.error(e); ++ throw new RuntimeException(e); ++ } ++ } ++ ++ @Override ++ public final void addAll(Collection col) { ++ for (M item : col) { ++ add(item); ++ } ++ } ++ ++ @Override ++ public void addAll(MessageQueue otherqueue) { ++ M poll = null; ++ while ((poll = otherqueue.poll()) != null) { ++ add(poll); ++ } ++ } ++ ++ @Override ++ public final void add(M item) { ++ size++; ++ try { ++ writer.append(new ObjectWritable(item), NULL_WRITABLE); ++ } catch (IOException e) { ++ LOG.error(e); ++ } ++ } ++ ++ @Override ++ public final void clear() { ++ closeInternal(true); ++ size = 0; ++ init(conf, id); ++ } ++ ++ @SuppressWarnings(""unchecked"") ++ @Override ++ public final M poll() { ++ size--; ++ int tries = 1; ++ while (tries <= MAX_RETRIES) { ++ try { ++ boolean next = reader.next(writable, NULL_WRITABLE); ++ if (next) { ++ return (M) writable.get(); ++ } else { ++ closeInternal(false); ++ return null; ++ } ++ } catch (IOException e) { ++ LOG.error(""Retrying for the "" + tries + ""th time!"", e); ++ } ++ tries++; ++ } ++ throw new RuntimeException(""Message couldn't be read for "" + tries ++ + "" times! Giving up!""); ++ } ++ ++ @Override ++ public int size() { ++ return size; ++ } ++ ++ @Override ++ public Iterator iterator() { ++ return new DiskIterator(); ++ } ++ ++ @Override ++ public void setConf(Configuration conf) { ++ this.conf = conf; ++ } ++ ++ @Override ++ public Configuration getConf() { ++ return conf; ++ } ++ ++ private class DiskIterator implements Iterator { ++ ++ public DiskIterator() { ++ prepareRead(); ++ } ++ ++ @Override ++ public boolean hasNext() { ++ if (size == 0) { ++ closeInternal(false); ++ } ++ return size != 0; ++ } ++ ++ @Override ++ public M next() { ++ return poll(); ++ } ++ ++ @Override ++ public void remove() { ++ // no-op ++ } ++ ++ } ++ ++ /** ++ * Creates a generic Path based on the configured path and the task attempt id ++ * to store disk sequence files.
++ * Structure is as follows: ${hama.tmp.dir}/diskqueue/job_id/task_attempt_id/ ++ */ ++ public static Path createDiskQueuePath(TaskAttemptID id, String configuredPath) { ++ return new Path(new Path(new Path(configuredPath, ""diskqueue""), id ++ .getJobID().toString()), id.getTaskID().toString()); ++ } ++ ++} +diff --git a/core/src/main/java/org/apache/hama/bsp/message/HadoopMessageManagerImpl.java b/core/src/main/java/org/apache/hama/bsp/message/HadoopMessageManagerImpl.java +index da7339de5..cfa404d0f 100644 +--- a/core/src/main/java/org/apache/hama/bsp/message/HadoopMessageManagerImpl.java ++++ b/core/src/main/java/org/apache/hama/bsp/message/HadoopMessageManagerImpl.java +@@ -19,12 +19,7 @@ + + import java.io.IOException; + import java.net.InetSocketAddress; +-import java.util.Deque; + import java.util.HashMap; +-import java.util.Iterator; +-import java.util.LinkedList; +-import java.util.Map.Entry; +-import java.util.concurrent.ConcurrentLinkedQueue; + + import org.apache.commons.logging.Log; + import org.apache.commons.logging.LogFactory; +@@ -35,8 +30,8 @@ + import org.apache.hama.bsp.BSPMessageBundle; + import org.apache.hama.bsp.BSPPeer; + import org.apache.hama.bsp.BSPPeerImpl; ++import org.apache.hama.bsp.TaskAttemptID; + import org.apache.hama.bsp.message.compress.BSPCompressedBundle; +-import org.apache.hama.util.BSPNetUtils; + import org.apache.hama.util.CompressionUtil; + + /** +@@ -49,22 +44,14 @@ public final class HadoopMessageManagerImpl extends + private static final Log LOG = LogFactory + .getLog(HadoopMessageManagerImpl.class); + +- private Server server = null; +- private Configuration conf; +- + private final HashMap> peers = new HashMap>(); +- private final HashMap peerSocketCache = new HashMap(); + +- private final HashMap> outgoingQueues = new HashMap>(); +- private Deque localQueue = new LinkedList(); +- // this must be a synchronized implementation: this is accessed per RPC +- private final ConcurrentLinkedQueue localQueueForNextIteration = new ConcurrentLinkedQueue(); +- private BSPPeer peer; ++ private Server server = null; + + @Override +- public final void init(BSPPeer peer, Configuration conf, InetSocketAddress peerAddress) { +- this.peer = peer; +- this.conf = conf; ++ public final void init(TaskAttemptID attemptId, BSPPeer peer, ++ Configuration conf, InetSocketAddress peerAddress) { ++ super.init(attemptId, peer, conf, peerAddress); + super.initCompression(conf); + startRPCServer(conf, peerAddress); + } +@@ -85,53 +72,12 @@ private final void startRPCServer(Configuration conf, + + @Override + public final void close() { ++ super.close(); + if (server != null) { + server.stop(); + } + } + +- @Override +- public final M getCurrentMessage() throws IOException { +- return localQueue.poll(); +- } +- +- @Override +- public final void send(String peerName, M msg) throws IOException { +- LOG.debug(""Send message ("" + msg.toString() + "") to "" + peerName); +- InetSocketAddress targetPeerAddress = null; +- // Get socket for target peer. +- if (peerSocketCache.containsKey(peerName)) { +- targetPeerAddress = peerSocketCache.get(peerName); +- } else { +- targetPeerAddress = BSPNetUtils.getAddress(peerName); +- peerSocketCache.put(peerName, targetPeerAddress); +- } +- LinkedList queue = outgoingQueues.get(targetPeerAddress); +- if (queue == null) { +- queue = new LinkedList(); +- } +- queue.add(msg); +- peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_SENT, 1L); +- outgoingQueues.put(targetPeerAddress, queue); +- } +- +- @Override +- public final Iterator>> getMessageIterator() { +- return this.outgoingQueues.entrySet().iterator(); +- } +- +- @SuppressWarnings(""unchecked"") +- protected final HadoopMessageManager getBSPPeerConnection( +- InetSocketAddress addr) throws IOException { +- HadoopMessageManager peer = peers.get(addr); +- if (peer == null) { +- peer = (HadoopMessageManager) RPC.getProxy(HadoopMessageManager.class, +- HadoopMessageManager.versionID, addr, this.conf); +- this.peers.put(addr, peer); +- } +- return peer; +- } +- + @Override + public final void transfer(InetSocketAddress addr, BSPMessageBundle bundle) + throws IOException { +@@ -155,18 +101,22 @@ public final void transfer(InetSocketAddress addr, BSPMessageBundle bundle) + } + } + +- @Override +- public final void clearOutgoingQueues() { +- this.outgoingQueues.clear(); +- localQueue.addAll(localQueueForNextIteration); +- localQueueForNextIteration.clear(); ++ @SuppressWarnings(""unchecked"") ++ protected final HadoopMessageManager getBSPPeerConnection( ++ InetSocketAddress addr) throws IOException { ++ HadoopMessageManager peer = peers.get(addr); ++ if (peer == null) { ++ peer = (HadoopMessageManager) RPC.getProxy(HadoopMessageManager.class, ++ HadoopMessageManager.versionID, addr, this.conf); ++ this.peers.put(addr, peer); ++ } ++ return peer; + } + + @Override + public final void put(M msg) { + this.localQueueForNextIteration.add(msg); +- peer.incrementCounter( +- BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, 1L); ++ peer.incrementCounter(BSPPeerImpl.PeerCounter.TOTAL_MESSAGES_RECEIVED, 1L); + } + + @Override +@@ -184,11 +134,6 @@ public final void put(BSPCompressedBundle compMsgBundle) { + } + } + +- @Override +- public final int getNumCurrentMessages() { +- return localQueue.size(); +- } +- + @Override + public final long getProtocolVersion(String arg0, long arg1) + throws IOException { +diff --git a/core/src/main/java/org/apache/hama/bsp/message/MemoryQueue.java b/core/src/main/java/org/apache/hama/bsp/message/MemoryQueue.java +new file mode 100644 +index 000000000..e38f79588 +--- /dev/null ++++ b/core/src/main/java/org/apache/hama/bsp/message/MemoryQueue.java +@@ -0,0 +1,106 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.util.Collection; ++import java.util.Deque; ++import java.util.Iterator; ++import java.util.LinkedList; ++ ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.io.Writable; ++import org.apache.hama.bsp.TaskAttemptID; ++ ++/** ++ * LinkedList backed queue structure for bookkeeping messages. ++ */ ++public final class MemoryQueue implements MessageQueue { ++ ++ private final Deque deque = new LinkedList(); ++ private Configuration conf; ++ ++ @Override ++ public final void addAll(Collection col) { ++ deque.addAll(col); ++ } ++ ++ @Override ++ public void addAll(MessageQueue otherqueue) { ++ M poll = null; ++ while ((poll = otherqueue.poll()) != null) { ++ deque.add(poll); ++ } ++ } ++ ++ @Override ++ public final void add(M item) { ++ deque.add(item); ++ } ++ ++ @Override ++ public final void clear() { ++ deque.clear(); ++ } ++ ++ @Override ++ public final M poll() { ++ return deque.poll(); ++ } ++ ++ @Override ++ public final int size() { ++ return deque.size(); ++ } ++ ++ @Override ++ public final Iterator iterator() { ++ return deque.iterator(); ++ } ++ ++ @Override ++ public void setConf(Configuration conf) { ++ this.conf = conf; ++ } ++ ++ @Override ++ public Configuration getConf() { ++ return conf; ++ } ++ ++ // not doing much here ++ @Override ++ public void init(Configuration conf, TaskAttemptID id) { ++ ++ } ++ ++ @Override ++ public void close() { ++ ++ } ++ ++ @Override ++ public void prepareRead() { ++ ++ } ++ ++ @Override ++ public void prepareWrite() { ++ ++ } ++ ++} +diff --git a/core/src/main/java/org/apache/hama/bsp/message/MessageManager.java b/core/src/main/java/org/apache/hama/bsp/message/MessageManager.java +index 45c1ff6d1..6662a5290 100644 +--- a/core/src/main/java/org/apache/hama/bsp/message/MessageManager.java ++++ b/core/src/main/java/org/apache/hama/bsp/message/MessageManager.java +@@ -20,13 +20,13 @@ + import java.io.IOException; + import java.net.InetSocketAddress; + import java.util.Iterator; +-import java.util.LinkedList; + import java.util.Map.Entry; + + import org.apache.hadoop.conf.Configuration; + import org.apache.hadoop.io.Writable; + import org.apache.hama.bsp.BSPMessageBundle; + import org.apache.hama.bsp.BSPPeer; ++import org.apache.hama.bsp.TaskAttemptID; + + /** + * This manager takes care of the messaging. It is responsible to launch a +@@ -34,15 +34,16 @@ + * + */ + public interface MessageManager { ++ ++ public static final String QUEUE_TYPE_CLASS = ""hama.messenger.queue.class""; + + /** +- * Init can be used to start servers and initialize internal state. ++ * Init can be used to start servers and initialize internal state. If you are ++ * implementing a subclass, please call the super version of this method. + * +- * @param conf +- * @param peerAddress + */ +- public void init(BSPPeer peer, Configuration conf, +- InetSocketAddress peerAddress); ++ public void init(TaskAttemptID attemptId, BSPPeer peer, ++ Configuration conf, InetSocketAddress peerAddress); + + /** + * Close is called after a task ran. Should be used to cleanup things e.G. +@@ -53,7 +54,6 @@ public void init(BSPPeer peer, Configuration conf, + /** + * Get the current message. + * +- * @return + * @throws IOException + */ + public M getCurrentMessage() throws IOException; +@@ -61,25 +61,26 @@ public void init(BSPPeer peer, Configuration conf, + /** + * Send a message to the peer. + * +- * @param peerName +- * @param msg + * @throws IOException + */ + public void send(String peerName, M msg) throws IOException; + ++ /** ++ * Should be called when all messages were send with send(). ++ * ++ * @throws IOException ++ */ ++ public void finishSendPhase() throws IOException; ++ + /** + * Returns an iterator of messages grouped by peer. + * +- * @return + */ +- public Iterator>> getMessageIterator(); ++ public Iterator>> getMessageIterator(); + + /** + * This is the real transferring to a host with a bundle. + * +- * @param addr +- * @param bundle +- * @throws IOException + */ + public void transfer(InetSocketAddress addr, BSPMessageBundle bundle) + throws IOException; +@@ -92,7 +93,6 @@ public void transfer(InetSocketAddress addr, BSPMessageBundle bundle) + /** + * Gets the number of messages in the current queue. + * +- * @return + */ + public int getNumCurrentMessages(); + +diff --git a/core/src/main/java/org/apache/hama/bsp/message/MessageQueue.java b/core/src/main/java/org/apache/hama/bsp/message/MessageQueue.java +new file mode 100644 +index 000000000..94375d362 +--- /dev/null ++++ b/core/src/main/java/org/apache/hama/bsp/message/MessageQueue.java +@@ -0,0 +1,83 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.util.Collection; ++ ++import org.apache.hadoop.conf.Configurable; ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hama.bsp.TaskAttemptID; ++ ++/** ++ * Simple queue interface. ++ */ ++public interface MessageQueue extends Iterable, Configurable { ++ ++ /** ++ * Used to initialize the queue. ++ */ ++ public void init(Configuration conf, TaskAttemptID id); ++ ++ /** ++ * Finally close the queue. Commonly used to free resources. ++ */ ++ public void close(); ++ ++ /** ++ * Called to prepare a queue for reading. ++ */ ++ public void prepareRead(); ++ ++ /** ++ * Called to prepare a queue for writing. ++ */ ++ public void prepareWrite(); ++ ++ /** ++ * Adds a whole Java Collection to the implementing queue. ++ */ ++ public void addAll(Collection col); ++ ++ /** ++ * Adds the other queue to this queue. ++ */ ++ public void addAll(MessageQueue otherqueue); ++ ++ /** ++ * Adds a single item to the implementing queue. ++ */ ++ public void add(M item); ++ ++ /** ++ * Clears all entries in the given queue. ++ */ ++ public void clear(); ++ ++ /** ++ * Polls for the next item in the queue (FIFO). ++ * ++ * @return a new item or null if none are present. ++ */ ++ public M poll(); ++ ++ /** ++ * @return how many items are in the queue. ++ */ ++ public int size(); ++ ++} +diff --git a/core/src/main/java/org/apache/hama/bsp/message/SynchronizedQueue.java b/core/src/main/java/org/apache/hama/bsp/message/SynchronizedQueue.java +new file mode 100644 +index 000000000..978a954a7 +--- /dev/null ++++ b/core/src/main/java/org/apache/hama/bsp/message/SynchronizedQueue.java +@@ -0,0 +1,129 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.util.Collection; ++import java.util.Iterator; ++ ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hama.bsp.TaskAttemptID; ++ ++/** ++ * A global mutex based synchronized queue. ++ */ ++public final class SynchronizedQueue { ++ ++ private final MessageQueue queue; ++ private final Object mutex; ++ ++ private SynchronizedQueue(MessageQueue queue) { ++ this.queue = queue; ++ this.mutex = new Object(); ++ } ++ ++ private SynchronizedQueue(MessageQueue queue, Object mutex) { ++ this.queue = queue; ++ this.mutex = mutex; ++ } ++ ++ public Iterator iterator() { ++ synchronized (mutex) { ++ return queue.iterator(); ++ } ++ } ++ ++ public void setConf(Configuration conf) { ++ synchronized (mutex) { ++ queue.setConf(conf); ++ } ++ } ++ ++ public Configuration getConf() { ++ synchronized (mutex) { ++ return queue.getConf(); ++ } ++ } ++ ++ public void init(Configuration conf, TaskAttemptID id) { ++ synchronized (mutex) { ++ queue.init(conf, id); ++ } ++ } ++ ++ public void close() { ++ synchronized (mutex) { ++ } ++ queue.close(); ++ } ++ ++ public void prepareRead() { ++ synchronized (mutex) { ++ queue.prepareRead(); ++ } ++ } ++ ++ public void addAll(Collection col) { ++ synchronized (mutex) { ++ queue.addAll(col); ++ } ++ } ++ ++ public void add(T item) { ++ synchronized (mutex) { ++ queue.add(item); ++ } ++ } ++ ++ public void clear() { ++ synchronized (mutex) { ++ queue.clear(); ++ } ++ } ++ ++ public Object poll() { ++ synchronized (mutex) { ++ return queue.poll(); ++ } ++ } ++ ++ public int size() { ++ synchronized (mutex) { ++ return queue.size(); ++ } ++ } ++ ++ public MessageQueue getMessageQueue() { ++ synchronized (mutex) { ++ return queue; ++ } ++ } ++ ++ /* ++ * static constructor methods to be type safe ++ */ ++ ++ public static SynchronizedQueue synchronize(MessageQueue queue) { ++ return new SynchronizedQueue(queue); ++ } ++ ++ public static SynchronizedQueue synchronize(MessageQueue queue, ++ Object mutex) { ++ return new SynchronizedQueue(queue, mutex); ++ } ++ ++} +diff --git a/core/src/test/java/org/apache/hama/bsp/TestBSPMasterGroomServer.java b/core/src/test/java/org/apache/hama/bsp/TestBSPMasterGroomServer.java +index e0c3746d5..06bd9e08b 100644 +--- a/core/src/test/java/org/apache/hama/bsp/TestBSPMasterGroomServer.java ++++ b/core/src/test/java/org/apache/hama/bsp/TestBSPMasterGroomServer.java +@@ -34,6 +34,7 @@ + import org.apache.hama.Constants; + import org.apache.hama.HamaCluster; + import org.apache.hama.HamaConfiguration; ++import org.apache.hama.bsp.message.DiskQueue; + import org.apache.hama.examples.ClassSerializePrinting; + import org.apache.hama.zookeeper.QuorumPeer; + import org.apache.zookeeper.CreateMode; +@@ -48,6 +49,7 @@ public class TestBSPMasterGroomServer extends HamaCluster { + + private static Log LOG = LogFactory.getLog(TestBSPMasterGroomServer.class); + static String TMP_OUTPUT = ""/tmp/test-example/""; ++ public static final String TMP_OUTPUT_PATH = ""/tmp/messageQueue""; + static Path OUTPUT_PATH = new Path(TMP_OUTPUT + ""serialout""); + + private HamaConfiguration configuration; +@@ -58,6 +60,7 @@ public TestBSPMasterGroomServer() { + assertEquals(""Make sure master addr is set to localhost:"", ""localhost"", + configuration.get(""bsp.master.address"")); + configuration.set(""bsp.local.dir"", ""/tmp/hama-test""); ++ conf.set(DiskQueue.DISK_QUEUE_PATH_KEY, TMP_OUTPUT_PATH); + configuration.set(Constants.ZOOKEEPER_QUORUM, ""localhost""); + configuration.setInt(Constants.ZOOKEEPER_CLIENT_PORT, 21810); + configuration.set(""hama.sync.client.class"", +diff --git a/core/src/test/java/org/apache/hama/bsp/message/TestAvroMessageManager.java b/core/src/test/java/org/apache/hama/bsp/message/TestAvroMessageManager.java +index d2a4e3700..b5f28e979 100644 +--- a/core/src/test/java/org/apache/hama/bsp/message/TestAvroMessageManager.java ++++ b/core/src/test/java/org/apache/hama/bsp/message/TestAvroMessageManager.java +@@ -30,6 +30,7 @@ + import org.apache.hama.bsp.BSPPeer; + import org.apache.hama.bsp.BSPPeerImpl; + import org.apache.hama.bsp.Counters; ++import org.apache.hama.bsp.TaskAttemptID; + import org.apache.hama.bsp.message.compress.BSPMessageCompressorFactory; + import org.apache.hama.bsp.message.compress.SnappyCompressor; + import org.apache.hama.bsp.messages.BooleanMessage; +@@ -45,10 +46,13 @@ public class TestAvroMessageManager extends TestCase { + + private static final int SUM = DOUBLE_MSG_COUNT + BOOL_MSG_COUNT + + INT_MSG_COUNT; ++ ++ public static final String TMP_OUTPUT_PATH = ""/tmp/messageQueue""; + + public void testAvroMessenger() throws Exception { + BSPMessageBundle randomBundle = getRandomBundle(); + Configuration conf = new Configuration(); ++ conf.set(DiskQueue.DISK_QUEUE_PATH_KEY, TMP_OUTPUT_PATH); + MessageManager messageManager = MessageManagerFactory + .getMessageManager(conf); + conf.set(BSPMessageCompressorFactory.COMPRESSION_CODEC_CLASS, +@@ -61,8 +65,8 @@ public void testAvroMessenger() throws Exception { + + BSPPeer dummyPeer = new BSPPeerImpl( + conf, FileSystem.get(conf), new Counters()); +- +- messageManager.init(dummyPeer, conf, peer); ++ TaskAttemptID id = new TaskAttemptID(""1"", 1, 1, 1); ++ messageManager.init(id, dummyPeer, conf, peer); + + messageManager.transfer(peer, randomBundle); + +diff --git a/core/src/test/java/org/apache/hama/bsp/message/TestDiskQueue.java b/core/src/test/java/org/apache/hama/bsp/message/TestDiskQueue.java +new file mode 100644 +index 000000000..dcbbced20 +--- /dev/null ++++ b/core/src/test/java/org/apache/hama/bsp/message/TestDiskQueue.java +@@ -0,0 +1,83 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hama.bsp.message; ++ ++import java.util.Arrays; ++ ++import junit.framework.TestCase; ++ ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.io.IntWritable; ++import org.apache.hama.bsp.TaskAttemptID; ++import org.apache.hama.bsp.TaskID; ++import org.junit.Test; ++ ++public class TestDiskQueue extends TestCase { ++ ++ static Configuration conf = new Configuration(); ++ static { ++ conf.set(DiskQueue.DISK_QUEUE_PATH_KEY, ++ TestAvroMessageManager.TMP_OUTPUT_PATH); ++ } ++ ++ @Test ++ public void testDiskQueue() throws Exception { ++ DiskQueue queue = getQueue(); ++ checkQueue(queue); ++ queue.close(); ++ } ++ ++ @Test ++ public void testMultipleIterations() throws Exception { ++ DiskQueue queue = getQueue(); ++ for (int superstep = 0; superstep < 15; superstep++) { ++ checkQueue(queue); ++ } ++ queue.close(); ++ } ++ ++ public DiskQueue getQueue() { ++ TaskAttemptID id = new TaskAttemptID(new TaskID(""123"", 1, 2), 0); ++ DiskQueue queue = new DiskQueue(); ++ // normally this is injected via reflection ++ queue.setConf(conf); ++ queue.init(conf, id); ++ return queue; ++ } ++ ++ public void checkQueue(DiskQueue queue) { ++ queue.prepareWrite(); ++ for (int i = 0; i < 10; i++) { ++ queue.add(new IntWritable(i)); ++ } ++ ++ queue.addAll(Arrays.asList(new IntWritable(11), new IntWritable(12), ++ new IntWritable(13))); ++ assertEquals(13, queue.size()); ++ queue.prepareRead(); ++ ++ for (int i = 0; i < 9; i++) { ++ assertEquals(i, queue.poll().get()); ++ } ++ ++ queue.clear(); ++ ++ assertEquals(0, queue.size()); ++ } ++ ++} +diff --git a/core/src/test/java/org/apache/hama/bsp/message/TestHadoopMessageManager.java b/core/src/test/java/org/apache/hama/bsp/message/TestHadoopMessageManager.java +index f41ab043a..e5cf87cf2 100644 +--- a/core/src/test/java/org/apache/hama/bsp/message/TestHadoopMessageManager.java ++++ b/core/src/test/java/org/apache/hama/bsp/message/TestHadoopMessageManager.java +@@ -19,7 +19,6 @@ + + import java.net.InetSocketAddress; + import java.util.Iterator; +-import java.util.LinkedList; + import java.util.Map.Entry; + + import junit.framework.TestCase; +@@ -32,12 +31,31 @@ + import org.apache.hama.bsp.BSPPeer; + import org.apache.hama.bsp.BSPPeerImpl; + import org.apache.hama.bsp.Counters; ++import org.apache.hama.bsp.TaskAttemptID; + import org.apache.hama.util.BSPNetUtils; + + public class TestHadoopMessageManager extends TestCase { + +- public void testMessaging() throws Exception { ++ public static final String TMP_OUTPUT_PATH = ""/tmp/messageQueue""; ++ // increment is here to solve race conditions in parallel execution to choose ++ // other ports. ++ public static volatile int increment = 1; ++ ++ public void testMemoryMessaging() throws Exception { ++ Configuration conf = new Configuration(); ++ conf.set(MessageManager.QUEUE_TYPE_CLASS, ++ MemoryQueue.class.getCanonicalName()); ++ conf.set(DiskQueue.DISK_QUEUE_PATH_KEY, TMP_OUTPUT_PATH); ++ messagingInternal(conf); ++ } ++ ++ public void testDiskMessaging() throws Exception { + Configuration conf = new Configuration(); ++ conf.set(DiskQueue.DISK_QUEUE_PATH_KEY, TMP_OUTPUT_PATH); ++ messagingInternal(conf); ++ } ++ ++ private void messagingInternal(Configuration conf) throws Exception { + conf.set(MessageManagerFactory.MESSAGE_MANAGER_CLASS, + ""org.apache.hama.bsp.message.HadoopMessageManagerImpl""); + MessageManager messageManager = MessageManagerFactory +@@ -46,18 +64,20 @@ public void testMessaging() throws Exception { + assertTrue(messageManager instanceof HadoopMessageManagerImpl); + + InetSocketAddress peer = new InetSocketAddress( +- BSPNetUtils.getCanonicalHostname(), BSPNetUtils.getFreePort()); ++ BSPNetUtils.getCanonicalHostname(), BSPNetUtils.getFreePort() ++ + (increment++)); + BSPPeer dummyPeer = new BSPPeerImpl( + conf, FileSystem.get(conf), new Counters()); +- messageManager.init(dummyPeer, conf, peer); ++ TaskAttemptID id = new TaskAttemptID(""1"", 1, 1, 1); ++ messageManager.init(id, dummyPeer, conf, peer); + String peerName = peer.getHostName() + "":"" + peer.getPort(); + + messageManager.send(peerName, new IntWritable(1337)); + +- Iterator>> messageIterator = messageManager ++ Iterator>> messageIterator = messageManager + .getMessageIterator(); + +- Entry> entry = messageIterator ++ Entry> entry = messageIterator + .next(); + + assertEquals(entry.getKey(), peer); +@@ -77,5 +97,6 @@ public void testMessaging() throws Exception { + IntWritable currentMessage = messageManager.getCurrentMessage(); + + assertEquals(currentMessage.get(), 1337); ++ messageManager.close(); + } + }" +4634ca5cb8c8ad0a3c725363f3705a4078c04c9c,elasticsearch,Mapping: When _all is disabled,a,https://github.com/elastic/elasticsearch,"diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/AllFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/AllFieldMapper.java +index 3eafa63f880ef..79a3b4a43b6df 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/AllFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/AllFieldMapper.java +@@ -25,4 +25,9 @@ + public interface AllFieldMapper extends FieldMapper, InternalMapper { + + public static final String NAME = ""_all""; ++ ++ /** ++ * Is the all field enabled or not. ++ */ ++ public boolean enabled(); + } +\ No newline at end of file +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ByteFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ByteFieldMapper.java +index 1bde6b18de857..e890ff6c13104 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ByteFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ByteFieldMapper.java +@@ -160,7 +160,7 @@ protected ByteFieldMapper(Names names, int precisionStep, Field.Index index, Fie + } else { + value = ((Number) externalValue).byteValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Byte.toString(value), boost); + } + } else { +@@ -169,12 +169,12 @@ protected ByteFieldMapper(Names names, int precisionStep, Field.Index index, Fie + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = (byte) context.parser().shortValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DateFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DateFieldMapper.java +index 3ab03f09b0d0f..92b30ac51bf1b 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DateFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DateFieldMapper.java +@@ -194,7 +194,7 @@ protected DateFieldMapper(Names names, FormatDateTimeFormatter dateTimeFormatter + if (dateAsString == null) { + return null; + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), dateAsString, boost); + } + +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DoubleFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DoubleFieldMapper.java +index 406a49ebb3468..8fa0484fe45f3 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DoubleFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/DoubleFieldMapper.java +@@ -162,7 +162,7 @@ protected DoubleFieldMapper(Names names, int precisionStep, + } else { + value = ((Number) externalValue).doubleValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Double.toString(value), boost); + } + } else { +@@ -171,12 +171,12 @@ protected DoubleFieldMapper(Names names, int precisionStep, + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = context.parser().doubleValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/FloatFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/FloatFieldMapper.java +index 2553e11110f63..c4e859d146ade 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/FloatFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/FloatFieldMapper.java +@@ -161,7 +161,7 @@ protected FloatFieldMapper(Names names, int precisionStep, Field.Index index, Fi + } else { + value = ((Number) externalValue).floatValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Float.toString(value), boost); + } + } else { +@@ -170,12 +170,12 @@ protected FloatFieldMapper(Names names, int precisionStep, Field.Index index, Fi + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = context.parser().floatValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/IntegerFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/IntegerFieldMapper.java +index 292adcd425048..40d77a15430e6 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/IntegerFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/IntegerFieldMapper.java +@@ -161,7 +161,7 @@ protected IntegerFieldMapper(Names names, int precisionStep, Field.Index index, + } else { + value = ((Number) externalValue).intValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Integer.toString(value), boost); + } + } else { +@@ -170,12 +170,12 @@ protected IntegerFieldMapper(Names names, int precisionStep, Field.Index index, + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = context.parser().intValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/LongFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/LongFieldMapper.java +index 08f6512ff37f6..9498cd5ca2351 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/LongFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/LongFieldMapper.java +@@ -161,7 +161,7 @@ protected LongFieldMapper(Names names, int precisionStep, Field.Index index, Fie + } else { + value = ((Number) externalValue).longValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Long.toString(value), boost); + } + } else { +@@ -170,12 +170,12 @@ protected LongFieldMapper(Names names, int precisionStep, Field.Index index, Fie + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = context.parser().longValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ParseContext.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ParseContext.java +index 31c998915f0e6..668e56394bb91 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ParseContext.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ParseContext.java +@@ -199,6 +199,18 @@ public void uid(String uid) { + this.uid = uid; + } + ++ /** ++ * Is all included or not. Will always disable it if {@link org.elasticsearch.index.mapper.AllFieldMapper#enabled()} ++ * is false. If its enabled, then will return true only if the specific flag is null or ++ * its actual value (so, if not set, defaults to ""true""). ++ */ ++ public boolean includeInAll(Boolean specificIncludeInAll) { ++ if (!docMapper.allFieldMapper().enabled()) { ++ return false; ++ } ++ return specificIncludeInAll == null || specificIncludeInAll; ++ } ++ + public AllEntries allEntries() { + return this.allEntries; + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ShortFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ShortFieldMapper.java +index e82db319d9642..a685a18f6718c 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ShortFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ShortFieldMapper.java +@@ -161,7 +161,7 @@ protected ShortFieldMapper(Names names, int precisionStep, Field.Index index, Fi + } else { + value = ((Number) externalValue).shortValue(); + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), Short.toString(value), boost); + } + } else { +@@ -170,12 +170,12 @@ protected ShortFieldMapper(Names names, int precisionStep, Field.Index index, Fi + return null; + } + value = nullValue; +- if (nullValueAsString != null && (includeInAll == null || includeInAll)) { ++ if (nullValueAsString != null && (context.includeInAll(includeInAll))) { + context.allEntries().addText(names.fullName(), nullValueAsString, boost); + } + } else { + value = context.parser().shortValue(); +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), context.parser().text(), boost); + } + } +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/StringFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/StringFieldMapper.java +index fa9831ecf6d11..36b31b05102de 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/StringFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/StringFieldMapper.java +@@ -140,7 +140,7 @@ protected StringFieldMapper(Names names, Field.Index index, Field.Store store, F + if (value == null) { + return null; + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), value, boost); + } + if (!indexed() && !stored()) { +diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ip/IpFieldMapper.java b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ip/IpFieldMapper.java +index 112f0e405f20f..0b9cb391b314e 100644 +--- a/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ip/IpFieldMapper.java ++++ b/modules/elasticsearch/src/main/java/org/elasticsearch/index/mapper/xcontent/ip/IpFieldMapper.java +@@ -210,7 +210,7 @@ protected IpFieldMapper(Names names, int precisionStep, + if (ipAsString == null) { + return null; + } +- if (includeInAll == null || includeInAll) { ++ if (context.includeInAll(includeInAll)) { + context.allEntries().addText(names.fullName(), ipAsString, boost); + }" +a449a6993aa2850d828e87676210224b6f24d35b,tapiji,"updated licenses +",p,https://github.com/tapiji/tapiji,"diff --git a/at.ac.tuwien.inso.eclpise.i18n.feature/epl-v10.html b/at.ac.tuwien.inso.eclpise.i18n.feature/epl-v10.html +new file mode 100644 +index 00000000..ed4b1966 +--- /dev/null ++++ b/at.ac.tuwien.inso.eclpise.i18n.feature/epl-v10.html +@@ -0,0 +1,328 @@ ++ ++ ++ ++ ++ ++ ++ ++ ++Eclipse Public License - Version 1.0 ++ ++ ++ ++ ++ ++ ++
++ ++

Eclipse Public License - v 1.0 ++

++ ++

THE ACCOMPANYING PROGRAM IS PROVIDED UNDER ++THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, ++REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE ++OF THIS AGREEMENT.

++ ++

1. DEFINITIONS

++ ++

"Contribution" means:

++ ++

a) ++in the case of the initial Contributor, the initial code and documentation ++distributed under this Agreement, and
++b) in the case of each subsequent Contributor:

++ ++

i) ++changes to the Program, and

++ ++

ii) ++additions to the Program;

++ ++

where ++such changes and/or additions to the Program originate from and are distributed ++by that particular Contributor. A Contribution 'originates' from a Contributor ++if it was added to the Program by such Contributor itself or anyone acting on ++such Contributor's behalf. Contributions do not include additions to the ++Program which: (i) are separate modules of software distributed in conjunction ++with the Program under their own license agreement, and (ii) are not derivative ++works of the Program.

++ ++

"Contributor" means any person or ++entity that distributes the Program.

++ ++

"Licensed Patents " mean patent ++claims licensable by a Contributor which are necessarily infringed by the use ++or sale of its Contribution alone or when combined with the Program.

++ ++

"Program" means the Contributions ++distributed in accordance with this Agreement.

++ ++

"Recipient" means anyone who ++receives the Program under this Agreement, including all Contributors.

++ ++

2. GRANT OF RIGHTS

++ ++

a) ++Subject to the terms of this Agreement, each Contributor hereby grants Recipient ++a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly ++display, publicly perform, distribute and sublicense the Contribution of such ++Contributor, if any, and such derivative works, in source code and object code ++form.

++ ++

b) ++Subject to the terms of this Agreement, each Contributor hereby grants ++Recipient a non-exclusive, worldwide, royalty-free ++patent license under Licensed Patents to make, use, sell, offer to sell, import ++and otherwise transfer the Contribution of such Contributor, if any, in source ++code and object code form. This patent license shall apply to the combination ++of the Contribution and the Program if, at the time the Contribution is added ++by the Contributor, such addition of the Contribution causes such combination ++to be covered by the Licensed Patents. The patent license shall not apply to ++any other combinations which include the Contribution. No hardware per se is ++licensed hereunder.

++ ++

c) ++Recipient understands that although each Contributor grants the licenses to its ++Contributions set forth herein, no assurances are provided by any Contributor ++that the Program does not infringe the patent or other intellectual property ++rights of any other entity. Each Contributor disclaims any liability to Recipient ++for claims brought by any other entity based on infringement of intellectual ++property rights or otherwise. As a condition to exercising the rights and ++licenses granted hereunder, each Recipient hereby assumes sole responsibility ++to secure any other intellectual property rights needed, if any. For example, ++if a third party patent license is required to allow Recipient to distribute ++the Program, it is Recipient's responsibility to acquire that license before ++distributing the Program.

++ ++

d) ++Each Contributor represents that to its knowledge it has sufficient copyright ++rights in its Contribution, if any, to grant the copyright license set forth in ++this Agreement.

++ ++

3. REQUIREMENTS

++ ++

A Contributor may choose to distribute the ++Program in object code form under its own license agreement, provided that: ++

++ ++

a) ++it complies with the terms and conditions of this Agreement; and

++ ++

b) ++its license agreement:

++ ++

i) ++effectively disclaims on behalf of all Contributors all warranties and ++conditions, express and implied, including warranties or conditions of title ++and non-infringement, and implied warranties or conditions of merchantability ++and fitness for a particular purpose;

++ ++

ii) ++effectively excludes on behalf of all Contributors all liability for damages, ++including direct, indirect, special, incidental and consequential damages, such ++as lost profits;

++ ++

iii) ++states that any provisions which differ from this Agreement are offered by that ++Contributor alone and not by any other party; and

++ ++

iv) ++states that source code for the Program is available from such Contributor, and ++informs licensees how to obtain it in a reasonable manner on or through a ++medium customarily used for software exchange.

++ ++

When the Program is made available in source ++code form:

++ ++

a) ++it must be made available under this Agreement; and

++ ++

b) a ++copy of this Agreement must be included with each copy of the Program.

++ ++

Contributors may not remove or alter any ++copyright notices contained within the Program.

++ ++

Each Contributor must identify itself as the ++originator of its Contribution, if any, in a manner that reasonably allows ++subsequent Recipients to identify the originator of the Contribution.

++ ++

4. COMMERCIAL DISTRIBUTION

++ ++

Commercial distributors of software may ++accept certain responsibilities with respect to end users, business partners ++and the like. While this license is intended to facilitate the commercial use ++of the Program, the Contributor who includes the Program in a commercial ++product offering should do so in a manner which does not create potential ++liability for other Contributors. Therefore, if a Contributor includes the ++Program in a commercial product offering, such Contributor ("Commercial ++Contributor") hereby agrees to defend and indemnify every other ++Contributor ("Indemnified Contributor") against any losses, damages and ++costs (collectively "Losses") arising from claims, lawsuits and other ++legal actions brought by a third party against the Indemnified Contributor to ++the extent caused by the acts or omissions of such Commercial Contributor in ++connection with its distribution of the Program in a commercial product ++offering. The obligations in this section do not apply to any claims or Losses ++relating to any actual or alleged intellectual property infringement. In order ++to qualify, an Indemnified Contributor must: a) promptly notify the Commercial ++Contributor in writing of such claim, and b) allow the Commercial Contributor ++to control, and cooperate with the Commercial Contributor in, the defense and ++any related settlement negotiations. The Indemnified Contributor may participate ++in any such claim at its own expense.

++ ++

For example, a Contributor might include the ++Program in a commercial product offering, Product X. That Contributor is then a ++Commercial Contributor. If that Commercial Contributor then makes performance ++claims, or offers warranties related to Product X, those performance claims and ++warranties are such Commercial Contributor's responsibility alone. Under this ++section, the Commercial Contributor would have to defend claims against the ++other Contributors related to those performance claims and warranties, and if a ++court requires any other Contributor to pay any damages as a result, the ++Commercial Contributor must pay those damages.

++ ++

5. NO WARRANTY

++ ++

EXCEPT AS EXPRESSLY SET FORTH IN THIS ++AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT ++WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, ++WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, ++MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely ++responsible for determining the appropriateness of using and distributing the ++Program and assumes all risks associated with its exercise of rights under this ++Agreement , including but not limited to the risks and costs of program errors, ++compliance with applicable laws, damage to or loss of data, programs or ++equipment, and unavailability or interruption of operations.

++ ++

6. DISCLAIMER OF LIABILITY

++ ++

EXCEPT AS EXPRESSLY SET FORTH IN THIS ++AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ++ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ++(INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY ++OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ++NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF ++THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF ++THE POSSIBILITY OF SUCH DAMAGES.

++ ++

7. GENERAL

++ ++

If any provision of this Agreement is invalid ++or unenforceable under applicable law, it shall not affect the validity or ++enforceability of the remainder of the terms of this Agreement, and without ++further action by the parties hereto, such provision shall be reformed to the ++minimum extent necessary to make such provision valid and enforceable.

++ ++

If Recipient institutes patent litigation ++against any entity (including a cross-claim or counterclaim in a lawsuit) ++alleging that the Program itself (excluding combinations of the Program with ++other software or hardware) infringes such Recipient's patent(s), then such ++Recipient's rights granted under Section 2(b) shall terminate as of the date ++such litigation is filed.

++ ++

All Recipient's rights under this Agreement ++shall terminate if it fails to comply with any of the material terms or ++conditions of this Agreement and does not cure such failure in a reasonable ++period of time after becoming aware of such noncompliance. If all Recipient's ++rights under this Agreement terminate, Recipient agrees to cease use and ++distribution of the Program as soon as reasonably practicable. However, ++Recipient's obligations under this Agreement and any licenses granted by ++Recipient relating to the Program shall continue and survive.

++ ++

Everyone is permitted to copy and distribute ++copies of this Agreement, but in order to avoid inconsistency the Agreement is ++copyrighted and may only be modified in the following manner. The Agreement ++Steward reserves the right to publish new versions (including revisions) of ++this Agreement from time to time. No one other than the Agreement Steward has ++the right to modify this Agreement. The Eclipse Foundation is the initial ++Agreement Steward. The Eclipse Foundation may assign the responsibility to ++serve as the Agreement Steward to a suitable separate entity. Each new version ++of the Agreement will be given a distinguishing version number. The Program ++(including Contributions) may always be distributed subject to the version of ++the Agreement under which it was received. In addition, after a new version of ++the Agreement is published, Contributor may elect to distribute the Program ++(including its Contributions) under the new version. Except as expressly stated ++in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to ++the intellectual property of any Contributor under this Agreement, whether ++expressly, by implication, estoppel or otherwise. All rights in the Program not ++expressly granted under this Agreement are reserved.

++ ++

This Agreement is governed by the laws of the ++State of New York and the intellectual property laws of the United States of ++America. No party to this Agreement will bring a legal action under this ++Agreement more than one year after the cause of action arose. Each party waives ++its rights to a jury trial in any resulting litigation.

++ ++

 

++ ++
++ ++ ++ ++ +\ No newline at end of file +diff --git a/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml b/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml +index 02e71b03..df57a461 100644 +--- a/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml ++++ b/at.ac.tuwien.inso.eclpise.i18n.feature/feature.xml +@@ -1,6 +1,6 @@ + + + + +- *Eclipse Public License - v 1.0* +- +-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE +-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF +-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. +- +-*1. DEFINITIONS* +- +-"Contribution" means: +- +-a) in the case of the initial Contributor, the initial code and +-documentation distributed under this Agreement, and +- +-b) in the case of each subsequent Contributor: +- +-i) changes to the Program, and +- +-ii) additions to the Program; +- +-where such changes and/or additions to the Program originate from and +-are distributed by that particular Contributor. A Contribution +-'originates' from a Contributor if it was added to the Program by such +-Contributor itself or anyone acting on such Contributor's behalf. +-Contributions do not include additions to the Program which: (i) are +-separate modules of software distributed in conjunction with the Program +-under their own license agreement, and (ii) are not derivative works of +-the Program. +- +-"Contributor" means any person or entity that distributes the Program. +- +-"Licensed Patents" mean patent claims licensable by a Contributor which +-are necessarily infringed by the use or sale of its Contribution alone +-or when combined with the Program. +- +-"Program" means the Contributions distributed in accordance with this +-Agreement. +- +-"Recipient" means anyone who receives the Program under this Agreement, +-including all Contributors. +- +-*2. GRANT OF RIGHTS* +- +-a) Subject to the terms of this Agreement, each Contributor hereby +-grants Recipient a non-exclusive, worldwide, royalty-free copyright +-license to reproduce, prepare derivative works of, publicly display, +-publicly perform, distribute and sublicense the Contribution of such +-Contributor, if any, and such derivative works, in source code and +-object code form. +- +-b) Subject to the terms of this Agreement, each Contributor hereby +-grants Recipient a non-exclusive, worldwide, royalty-free patent license +-under Licensed Patents to make, use, sell, offer to sell, import and +-otherwise transfer the Contribution of such Contributor, if any, in +-source code and object code form. This patent license shall apply to the +-combination of the Contribution and the Program if, at the time the +-Contribution is added by the Contributor, such addition of the +-Contribution causes such combination to be covered by the Licensed +-Patents. The patent license shall not apply to any other combinations +-which include the Contribution. No hardware per se is licensed hereunder. +- +-c) Recipient understands that although each Contributor grants the +-licenses to its Contributions set forth herein, no assurances are +-provided by any Contributor that the Program does not infringe the +-patent or other intellectual property rights of any other entity. Each +-Contributor disclaims any liability to Recipient for claims brought by +-any other entity based on infringement of intellectual property rights +-or otherwise. As a condition to exercising the rights and licenses +-granted hereunder, each Recipient hereby assumes sole responsibility to +-secure any other intellectual property rights needed, if any. For +-example, if a third party patent license is required to allow Recipient +-to distribute the Program, it is Recipient's responsibility to acquire +-that license before distributing the Program. +- +-d) Each Contributor represents that to its knowledge it has sufficient +-copyright rights in its Contribution, if any, to grant the copyright +-license set forth in this Agreement. +- +-*3. REQUIREMENTS* +- +-A Contributor may choose to distribute the Program in object code form +-under its own license agreement, provided that: +- +-a) it complies with the terms and conditions of this Agreement; and +- +-b) its license agreement: +- +-i) effectively disclaims on behalf of all Contributors all warranties +-and conditions, express and implied, including warranties or conditions +-of title and non-infringement, and implied warranties or conditions of +-merchantability and fitness for a particular purpose; +- +-ii) effectively excludes on behalf of all Contributors all liability for +-damages, including direct, indirect, special, incidental and +-consequential damages, such as lost profits; +- +-iii) states that any provisions which differ from this Agreement are +-offered by that Contributor alone and not by any other party; and +- +-iv) states that source code for the Program is available from such +-Contributor, and informs licensees how to obtain it in a reasonable +-manner on or through a medium customarily used for software exchange. +- +-When the Program is made available in source code form: +- +-a) it must be made available under this Agreement; and +- +-b) a copy of this Agreement must be included with each copy of the Program. +- +-Contributors may not remove or alter any copyright notices contained +-within the Program. +- +-Each Contributor must identify itself as the originator of its +-Contribution, if any, in a manner that reasonably allows subsequent +-Recipients to identify the originator of the Contribution. +- +-*4. COMMERCIAL DISTRIBUTION* +- +-Commercial distributors of software may accept certain responsibilities +-with respect to end users, business partners and the like. While this +-license is intended to facilitate the commercial use of the Program, the +-Contributor who includes the Program in a commercial product offering +-should do so in a manner which does not create potential liability for +-other Contributors. Therefore, if a Contributor includes the Program in +-a commercial product offering, such Contributor ("Commercial +-Contributor") hereby agrees to defend and indemnify every other +-Contributor ("Indemnified Contributor") against any losses, damages and +-costs (collectively "Losses") arising from claims, lawsuits and other +-legal actions brought by a third party against the Indemnified +-Contributor to the extent caused by the acts or omissions of such +-Commercial Contributor in connection with its distribution of the +-Program in a commercial product offering. The obligations in this +-section do not apply to any claims or Losses relating to any actual or +-alleged intellectual property infringement. In order to qualify, an +-Indemnified Contributor must: a) promptly notify the Commercial +-Contributor in writing of such claim, and b) allow the Commercial +-Contributor to control, and cooperate with the Commercial Contributor +-in, the defense and any related settlement negotiations. The Indemnified +-Contributor may participate in any such claim at its own expense. +- +-For example, a Contributor might include the Program in a commercial +-product offering, Product X. That Contributor is then a Commercial +-Contributor. If that Commercial Contributor then makes performance +-claims, or offers warranties related to Product X, those performance +-claims and warranties are such Commercial Contributor's responsibility +-alone. Under this section, the Commercial Contributor would have to +-defend claims against the other Contributors related to those +-performance claims and warranties, and if a court requires any other +-Contributor to pay any damages as a result, the Commercial Contributor +-must pay those damages. +- +-*5. NO WARRANTY* +- +-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED +-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES +-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR +-A PARTICULAR PURPOSE. Each Recipient is solely responsible for +-determining the appropriateness of using and distributing the Program +-and assumes all risks associated with its exercise of rights under this +-Agreement , including but not limited to the risks and costs of program +-errors, compliance with applicable laws, damage to or loss of data, +-programs or equipment, and unavailability or interruption of operations. +- +-*6. DISCLAIMER OF LIABILITY* +- +-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR +-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF +-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR +-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +- +-*7. GENERAL* +- +-If any provision of this Agreement is invalid or unenforceable under +-applicable law, it shall not affect the validity or enforceability of +-the remainder of the terms of this Agreement, and without further action +-by the parties hereto, such provision shall be reformed to the minimum +-extent necessary to make such provision valid and enforceable. +- +-If Recipient institutes patent litigation against any entity (including +-a cross-claim or counterclaim in a lawsuit) alleging that the Program +-itself (excluding combinations of the Program with other software or +-hardware) infringes such Recipient's patent(s), then such Recipient's +-rights granted under Section 2(b) shall terminate as of the date such +-litigation is filed. +- +-All Recipient's rights under this Agreement shall terminate if it fails +-to comply with any of the material terms or conditions of this Agreement +-and does not cure such failure in a reasonable period of time after +-becoming aware of such noncompliance. If all Recipient's rights under +-this Agreement terminate, Recipient agrees to cease use and distribution +-of the Program as soon as reasonably practicable. However, Recipient's +-obligations under this Agreement and any licenses granted by Recipient +-relating to the Program shall continue and survive. +- +-Everyone is permitted to copy and distribute copies of this Agreement, +-but in order to avoid inconsistency the Agreement is copyrighted and may +-only be modified in the following manner. The Agreement Steward reserves +-the right to publish new versions (including revisions) of this +-Agreement from time to time. No one other than the Agreement Steward has +-the right to modify this Agreement. The Eclipse Foundation is the +-initial Agreement Steward. The Eclipse Foundation may assign the +-responsibility to serve as the Agreement Steward to a suitable separate +-entity. Each new version of the Agreement will be given a distinguishing +-version number. The Program (including Contributions) may always be +-distributed subject to the version of the Agreement under which it was +-received. In addition, after a new version of the Agreement is +-published, Contributor may elect to distribute the Program (including +-its Contributions) under the new version. Except as expressly stated in +-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses +-to the intellectual property of any Contributor under this Agreement, +-whether expressly, by implication, estoppel or otherwise. All rights in +-the Program not expressly granted under this Agreement are reserved. +- +-This Agreement is governed by the laws of the State of New York and the +-intellectual property laws of the United States of America. No party to +-this Agreement will bring a legal action under this Agreement more than +-one year after the cause of action arose. Each party waives its rights ++ *Eclipse Public License - v 1.0* ++ ++THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE ++PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF ++THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. ++ ++*1. DEFINITIONS* ++ ++"Contribution" means: ++ ++a) in the case of the initial Contributor, the initial code and ++documentation distributed under this Agreement, and ++ ++b) in the case of each subsequent Contributor: ++ ++i) changes to the Program, and ++ ++ii) additions to the Program; ++ ++where such changes and/or additions to the Program originate from and ++are distributed by that particular Contributor. A Contribution ++'originates' from a Contributor if it was added to the Program by such ++Contributor itself or anyone acting on such Contributor's behalf. ++Contributions do not include additions to the Program which: (i) are ++separate modules of software distributed in conjunction with the Program ++under their own license agreement, and (ii) are not derivative works of ++the Program. ++ ++"Contributor" means any person or entity that distributes the Program. ++ ++"Licensed Patents" mean patent claims licensable by a Contributor which ++are necessarily infringed by the use or sale of its Contribution alone ++or when combined with the Program. ++ ++"Program" means the Contributions distributed in accordance with this ++Agreement. ++ ++"Recipient" means anyone who receives the Program under this Agreement, ++including all Contributors. ++ ++*2. GRANT OF RIGHTS* ++ ++a) Subject to the terms of this Agreement, each Contributor hereby ++grants Recipient a non-exclusive, worldwide, royalty-free copyright ++license to reproduce, prepare derivative works of, publicly display, ++publicly perform, distribute and sublicense the Contribution of such ++Contributor, if any, and such derivative works, in source code and ++object code form. ++ ++b) Subject to the terms of this Agreement, each Contributor hereby ++grants Recipient a non-exclusive, worldwide, royalty-free patent license ++under Licensed Patents to make, use, sell, offer to sell, import and ++otherwise transfer the Contribution of such Contributor, if any, in ++source code and object code form. This patent license shall apply to the ++combination of the Contribution and the Program if, at the time the ++Contribution is added by the Contributor, such addition of the ++Contribution causes such combination to be covered by the Licensed ++Patents. The patent license shall not apply to any other combinations ++which include the Contribution. No hardware per se is licensed hereunder. ++ ++c) Recipient understands that although each Contributor grants the ++licenses to its Contributions set forth herein, no assurances are ++provided by any Contributor that the Program does not infringe the ++patent or other intellectual property rights of any other entity. Each ++Contributor disclaims any liability to Recipient for claims brought by ++any other entity based on infringement of intellectual property rights ++or otherwise. As a condition to exercising the rights and licenses ++granted hereunder, each Recipient hereby assumes sole responsibility to ++secure any other intellectual property rights needed, if any. For ++example, if a third party patent license is required to allow Recipient ++to distribute the Program, it is Recipient's responsibility to acquire ++that license before distributing the Program. ++ ++d) Each Contributor represents that to its knowledge it has sufficient ++copyright rights in its Contribution, if any, to grant the copyright ++license set forth in this Agreement. ++ ++*3. REQUIREMENTS* ++ ++A Contributor may choose to distribute the Program in object code form ++under its own license agreement, provided that: ++ ++a) it complies with the terms and conditions of this Agreement; and ++ ++b) its license agreement: ++ ++i) effectively disclaims on behalf of all Contributors all warranties ++and conditions, express and implied, including warranties or conditions ++of title and non-infringement, and implied warranties or conditions of ++merchantability and fitness for a particular purpose; ++ ++ii) effectively excludes on behalf of all Contributors all liability for ++damages, including direct, indirect, special, incidental and ++consequential damages, such as lost profits; ++ ++iii) states that any provisions which differ from this Agreement are ++offered by that Contributor alone and not by any other party; and ++ ++iv) states that source code for the Program is available from such ++Contributor, and informs licensees how to obtain it in a reasonable ++manner on or through a medium customarily used for software exchange. ++ ++When the Program is made available in source code form: ++ ++a) it must be made available under this Agreement; and ++ ++b) a copy of this Agreement must be included with each copy of the Program. ++ ++Contributors may not remove or alter any copyright notices contained ++within the Program. ++ ++Each Contributor must identify itself as the originator of its ++Contribution, if any, in a manner that reasonably allows subsequent ++Recipients to identify the originator of the Contribution. ++ ++*4. COMMERCIAL DISTRIBUTION* ++ ++Commercial distributors of software may accept certain responsibilities ++with respect to end users, business partners and the like. While this ++license is intended to facilitate the commercial use of the Program, the ++Contributor who includes the Program in a commercial product offering ++should do so in a manner which does not create potential liability for ++other Contributors. Therefore, if a Contributor includes the Program in ++a commercial product offering, such Contributor ("Commercial ++Contributor") hereby agrees to defend and indemnify every other ++Contributor ("Indemnified Contributor") against any losses, damages and ++costs (collectively "Losses") arising from claims, lawsuits and other ++legal actions brought by a third party against the Indemnified ++Contributor to the extent caused by the acts or omissions of such ++Commercial Contributor in connection with its distribution of the ++Program in a commercial product offering. The obligations in this ++section do not apply to any claims or Losses relating to any actual or ++alleged intellectual property infringement. In order to qualify, an ++Indemnified Contributor must: a) promptly notify the Commercial ++Contributor in writing of such claim, and b) allow the Commercial ++Contributor to control, and cooperate with the Commercial Contributor ++in, the defense and any related settlement negotiations. The Indemnified ++Contributor may participate in any such claim at its own expense. ++ ++For example, a Contributor might include the Program in a commercial ++product offering, Product X. That Contributor is then a Commercial ++Contributor. If that Commercial Contributor then makes performance ++claims, or offers warranties related to Product X, those performance ++claims and warranties are such Commercial Contributor's responsibility ++alone. Under this section, the Commercial Contributor would have to ++defend claims against the other Contributors related to those ++performance claims and warranties, and if a court requires any other ++Contributor to pay any damages as a result, the Commercial Contributor ++must pay those damages. ++ ++*5. NO WARRANTY* ++ ++EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ++ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, ++EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES ++OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR ++A PARTICULAR PURPOSE. Each Recipient is solely responsible for ++determining the appropriateness of using and distributing the Program ++and assumes all risks associated with its exercise of rights under this ++Agreement , including but not limited to the risks and costs of program ++errors, compliance with applicable laws, damage to or loss of data, ++programs or equipment, and unavailability or interruption of operations. ++ ++*6. DISCLAIMER OF LIABILITY* ++ ++EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ++ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, ++INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING ++WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF ++LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ++NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR ++DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED ++HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. ++ ++*7. GENERAL* ++ ++If any provision of this Agreement is invalid or unenforceable under ++applicable law, it shall not affect the validity or enforceability of ++the remainder of the terms of this Agreement, and without further action ++by the parties hereto, such provision shall be reformed to the minimum ++extent necessary to make such provision valid and enforceable. ++ ++If Recipient institutes patent litigation against any entity (including ++a cross-claim or counterclaim in a lawsuit) alleging that the Program ++itself (excluding combinations of the Program with other software or ++hardware) infringes such Recipient's patent(s), then such Recipient's ++rights granted under Section 2(b) shall terminate as of the date such ++litigation is filed. ++ ++All Recipient's rights under this Agreement shall terminate if it fails ++to comply with any of the material terms or conditions of this Agreement ++and does not cure such failure in a reasonable period of time after ++becoming aware of such noncompliance. If all Recipient's rights under ++this Agreement terminate, Recipient agrees to cease use and distribution ++of the Program as soon as reasonably practicable. However, Recipient's ++obligations under this Agreement and any licenses granted by Recipient ++relating to the Program shall continue and survive. ++ ++Everyone is permitted to copy and distribute copies of this Agreement, ++but in order to avoid inconsistency the Agreement is copyrighted and may ++only be modified in the following manner. The Agreement Steward reserves ++the right to publish new versions (including revisions) of this ++Agreement from time to time. No one other than the Agreement Steward has ++the right to modify this Agreement. The Eclipse Foundation is the ++initial Agreement Steward. The Eclipse Foundation may assign the ++responsibility to serve as the Agreement Steward to a suitable separate ++entity. Each new version of the Agreement will be given a distinguishing ++version number. The Program (including Contributions) may always be ++distributed subject to the version of the Agreement under which it was ++received. In addition, after a new version of the Agreement is ++published, Contributor may elect to distribute the Program (including ++its Contributions) under the new version. Except as expressly stated in ++Sections 2(a) and 2(b) above, Recipient receives no rights or licenses ++to the intellectual property of any Contributor under this Agreement, ++whether expressly, by implication, estoppel or otherwise. All rights in ++the Program not expressly granted under this Agreement are reserved. ++ ++This Agreement is governed by the laws of the State of New York and the ++intellectual property laws of the United States of America. No party to ++this Agreement will bring a legal action under this Agreement more than ++one year after the cause of action arose. Each party waives its rights + to a jury trial in any resulting litigation. + " +a8dbce159679cd031f60e6151399fa2cd5ac9374,hadoop,HADOOP-7223. FileContext createFlag combinations- are not clearly defined. Contributed by Suresh Srinivas.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1092565 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/hadoop,"diff --git a/CHANGES.txt b/CHANGES.txt +index a6186537bdbb6..7a2ece8c71744 100644 +--- a/CHANGES.txt ++++ b/CHANGES.txt +@@ -1,4 +1,4 @@ +-Hadoop Change Log ++Hn jaadoop Change Log + + Trunk (unreleased changes) + +@@ -139,6 +139,10 @@ Trunk (unreleased changes) + + HADOOP-7207. fs member of FSShell is not really needed (boryas) + ++ HADOOP-7223. FileContext createFlag combinations are not clearly defined. ++ (suresh) ++ ++ + Release 0.22.0 - Unreleased + + INCOMPATIBLE CHANGES +diff --git a/src/java/org/apache/hadoop/fs/ChecksumFs.java b/src/java/org/apache/hadoop/fs/ChecksumFs.java +index a55108598becd..87cd5a77dec39 100644 +--- a/src/java/org/apache/hadoop/fs/ChecksumFs.java ++++ b/src/java/org/apache/hadoop/fs/ChecksumFs.java +@@ -337,8 +337,9 @@ public ChecksumFSOutputSummer(final ChecksumFs fs, final Path file, + int bytesPerSum = fs.getBytesPerSum(); + int sumBufferSize = fs.getSumBufferSize(bytesPerSum, bufferSize); + this.sums = fs.getRawFs().createInternal(fs.getChecksumFile(file), +- EnumSet.of(CreateFlag.OVERWRITE), absolutePermission, sumBufferSize, +- replication, blockSize, progress, bytesPerChecksum, createParent); ++ EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), ++ absolutePermission, sumBufferSize, replication, blockSize, progress, ++ bytesPerChecksum, createParent); + sums.write(CHECKSUM_VERSION, 0, CHECKSUM_VERSION.length); + sums.writeInt(bytesPerSum); + } +diff --git a/src/java/org/apache/hadoop/fs/CreateFlag.java b/src/java/org/apache/hadoop/fs/CreateFlag.java +index 375876a8bdb40..4373124caabf4 100644 +--- a/src/java/org/apache/hadoop/fs/CreateFlag.java ++++ b/src/java/org/apache/hadoop/fs/CreateFlag.java +@@ -17,49 +17,63 @@ + */ + package org.apache.hadoop.fs; + ++import java.io.FileNotFoundException; ++import java.io.IOException; ++import java.util.EnumSet; ++ ++import org.apache.hadoop.HadoopIllegalArgumentException; + import org.apache.hadoop.classification.InterfaceAudience; + import org.apache.hadoop.classification.InterfaceStability; + + /**************************************************************** +- *CreateFlag specifies the file create semantic. Users can combine flags like:
+- * ++ * CreateFlag specifies the file create semantic. Users can combine flags like:
++ * + * EnumSet.of(CreateFlag.CREATE, CreateFlag.APPEND) + * +- * and pass it to {@link org.apache.hadoop.fs.FileSystem #create(Path f, FsPermission permission, +- * EnumSet flag, int bufferSize, short replication, long blockSize, +- * Progressable progress)}. +- * + *

+- * Combine {@link #OVERWRITE} with either {@link #CREATE} +- * or {@link #APPEND} does the same as only use +- * {@link #OVERWRITE}.
+- * Combine {@link #CREATE} with {@link #APPEND} has the semantic: ++ * ++ * Use the CreateFlag as follows: ++ *

    ++ *
  1. CREATE - to create a file if it does not exist, ++ * else throw FileAlreadyExists.
  2. ++ *
  3. APPEND - to append to a file if it exists, ++ * else throw FileNotFoundException.
  4. ++ *
  5. OVERWRITE - to truncate a file if it exists, ++ * else throw FileNotFoundException.
  6. ++ *
  7. CREATE|APPEND - to create a file if it does not exist, ++ * else append to an existing file.
  8. ++ *
  9. CREATE|OVERWRITE - to create a file if it does not exist, ++ * else overwrite an existing file.
  10. ++ *
++ * ++ * Following combination is not valid and will result in ++ * {@link HadoopIllegalArgumentException}: + *
    +- *
  1. create the file if it does not exist; +- *
  2. append the file if it already exists. ++ *
  3. APPEND|OVERWRITE
  4. ++ *
  5. CREATE|APPEND|OVERWRITE
  6. + *
+ *****************************************************************/ + @InterfaceAudience.Public +-@InterfaceStability.Stable ++@InterfaceStability.Evolving + public enum CreateFlag { + + /** +- * create the file if it does not exist, and throw an IOException if it ++ * Create a file. See javadoc for more description + * already exists + */ + CREATE((short) 0x01), + + /** +- * create the file if it does not exist, if it exists, overwrite it. ++ * Truncate/overwrite a file. Same as POSIX O_TRUNC. See javadoc for description. + */ + OVERWRITE((short) 0x02), + + /** +- * append to a file, and throw an IOException if it does not exist ++ * Append to a file. See javadoc for more description. + */ + APPEND((short) 0x04); + +- private short mode; ++ private final short mode; + + private CreateFlag(short mode) { + this.mode = mode; +@@ -68,4 +82,49 @@ private CreateFlag(short mode) { + short getMode() { + return mode; + } ++ ++ /** ++ * Validate the CreateFlag and throw exception if it is invalid ++ * @param flag set of CreateFlag ++ * @throws HadoopIllegalArgumentException if the CreateFlag is invalid ++ */ ++ public static void validate(EnumSet flag) { ++ if (flag == null || flag.isEmpty()) { ++ throw new HadoopIllegalArgumentException(flag ++ + "" does not specify any options""); ++ } ++ final boolean append = flag.contains(APPEND); ++ final boolean overwrite = flag.contains(OVERWRITE); ++ ++ // Both append and overwrite is an error ++ if (append && overwrite) { ++ throw new HadoopIllegalArgumentException( ++ flag + ""Both append and overwrite options cannot be enabled.""); ++ } ++ } ++ ++ /** ++ * Validate the CreateFlag for create operation ++ * @param path Object representing the path; usually String or {@link Path} ++ * @param pathExists pass true if the path exists in the file system ++ * @param flag set of CreateFlag ++ * @throws IOException on error ++ * @throws HadoopIllegalArgumentException if the CreateFlag is invalid ++ */ ++ public static void validate(Object path, boolean pathExists, ++ EnumSet flag) throws IOException { ++ validate(flag); ++ final boolean append = flag.contains(APPEND); ++ final boolean overwrite = flag.contains(OVERWRITE); ++ if (pathExists) { ++ if (!(append || overwrite)) { ++ throw new FileAlreadyExistsException(""File already exists: "" ++ + path.toString() ++ + "". Append or overwrite option must be specified in "" + flag); ++ } ++ } else if (!flag.contains(CREATE)) { ++ throw new FileNotFoundException(""Non existing file: "" + path.toString() ++ + "". Create option is not specified in "" + flag); ++ } ++ } + } +\ No newline at end of file +diff --git a/src/java/org/apache/hadoop/fs/FileContext.java b/src/java/org/apache/hadoop/fs/FileContext.java +index 2596daae5e7b4..e3163ea75e5b7 100644 +--- a/src/java/org/apache/hadoop/fs/FileContext.java ++++ b/src/java/org/apache/hadoop/fs/FileContext.java +@@ -511,7 +511,7 @@ public Path makeQualified(final Path path) { + * writing into the file. + * + * @param f the file name to open +- * @param createFlag gives the semantics of create: overwrite, append etc. ++ * @param createFlag gives the semantics of create; see {@link CreateFlag} + * @param opts file creation options; see {@link Options.CreateOpts}. + *
    + *
  • Progress - to report progress on the operation - default null +@@ -2057,7 +2057,10 @@ public boolean copy(final Path src, final Path dst, boolean deleteSource, + OutputStream out = null; + try { + in = open(qSrc); +- out = create(qDst, EnumSet.of(CreateFlag.OVERWRITE)); ++ EnumSet createFlag = overwrite ? EnumSet.of( ++ CreateFlag.CREATE, CreateFlag.OVERWRITE) : ++ EnumSet.of(CreateFlag.CREATE); ++ out = create(qDst, createFlag); + IOUtils.copyBytes(in, out, conf, true); + } catch (IOException e) { + IOUtils.closeStream(out); +diff --git a/src/java/org/apache/hadoop/fs/FileSystem.java b/src/java/org/apache/hadoop/fs/FileSystem.java +index be1c796a4caa3..8708b7d62de03 100644 +--- a/src/java/org/apache/hadoop/fs/FileSystem.java ++++ b/src/java/org/apache/hadoop/fs/FileSystem.java +@@ -717,24 +717,21 @@ protected FSDataOutputStream primitiveCreate(Path f, + FsPermission absolutePermission, EnumSet flag, int bufferSize, + short replication, long blockSize, Progressable progress, + int bytesPerChecksum) throws IOException { ++ ++ boolean pathExists = exists(f); ++ CreateFlag.validate(f, pathExists, flag); + + // Default impl assumes that permissions do not matter and + // nor does the bytesPerChecksum hence + // calling the regular create is good enough. + // FSs that implement permissions should override this. + +- if (exists(f)) { +- if (flag.contains(CreateFlag.APPEND)) { +- return append(f, bufferSize, progress); +- } else if (!flag.contains(CreateFlag.OVERWRITE)) { +- throw new IOException(""File already exists: "" + f); +- } +- } else { +- if (flag.contains(CreateFlag.APPEND) && !flag.contains(CreateFlag.CREATE)) +- throw new IOException(""File already exists: "" + f.toString()); ++ if (pathExists && flag.contains(CreateFlag.APPEND)) { ++ return append(f, bufferSize, progress); + } + +- return this.create(f, absolutePermission, flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, ++ return this.create(f, absolutePermission, ++ flag.contains(CreateFlag.OVERWRITE), bufferSize, replication, + blockSize, progress); + } + +diff --git a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java +index 18ef152baf35c..3a54fae955b7e 100644 +--- a/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java ++++ b/src/java/org/apache/hadoop/fs/RawLocalFileSystem.java +@@ -264,28 +264,6 @@ public FSDataOutputStream create(Path f, FsPermission permission, + return out; + } + +- +- @Override +- protected FSDataOutputStream primitiveCreate(Path f, +- FsPermission absolutePermission, EnumSet flag, +- int bufferSize, short replication, long blockSize, Progressable progress, +- int bytesPerChecksum) throws IOException { +- +- if(flag.contains(CreateFlag.APPEND)){ +- if (!exists(f)){ +- if(flag.contains(CreateFlag.CREATE)) { +- return create(f, false, bufferSize, replication, blockSize, null); +- } +- } +- return append(f, bufferSize, null); +- } +- +- FSDataOutputStream out = create(f, flag.contains(CreateFlag.OVERWRITE), +- bufferSize, replication, blockSize, progress); +- setPermission(f, absolutePermission); +- return out; +- } +- + public boolean rename(Path src, Path dst) throws IOException { + if (pathToFile(src).renameTo(pathToFile(dst))) { + return true; +diff --git a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java +index 1af5a6391bca2..b88f5b5c5d9ae 100644 +--- a/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java ++++ b/src/test/core/org/apache/hadoop/fs/FileContextMainOperationsBaseTest.java +@@ -21,8 +21,8 @@ + import java.io.FileNotFoundException; + import java.io.IOException; + import java.util.EnumSet; +-import java.util.Iterator; + ++import org.apache.hadoop.HadoopIllegalArgumentException; + import org.apache.hadoop.fs.Options.CreateOpts; + import org.apache.hadoop.fs.Options.Rename; + import org.apache.hadoop.fs.permission.FsPermission; +@@ -32,6 +32,7 @@ + import org.junit.Test; + + import static org.apache.hadoop.fs.FileContextTestHelper.*; ++import static org.apache.hadoop.fs.CreateFlag.*; + + /** + *

    +@@ -155,7 +156,7 @@ public void testWorkingDirectory() throws Exception { + + // Now open a file relative to the wd we just set above. + Path absolutePath = new Path(absoluteDir, ""foo""); +- fc.create(absolutePath, EnumSet.of(CreateFlag.CREATE)).close(); ++ fc.create(absolutePath, EnumSet.of(CREATE)).close(); + fc.open(new Path(""foo"")).close(); + + +@@ -645,7 +646,7 @@ private void writeReadAndDelete(int len) throws IOException { + + fc.mkdir(path.getParent(), FsPermission.getDefault(), true); + +- FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), ++ FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), + CreateOpts.repFac((short) 1), CreateOpts + .blockSize(getDefaultBlockSize())); + out.write(data, 0, len); +@@ -670,31 +671,93 @@ private void writeReadAndDelete(int len) throws IOException { + + } + ++ @Test(expected=HadoopIllegalArgumentException.class) ++ public void testNullCreateFlag() throws IOException { ++ Path p = getTestRootPath(fc, ""test/file""); ++ fc.create(p, null); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ @Test(expected=HadoopIllegalArgumentException.class) ++ public void testEmptyCreateFlag() throws IOException { ++ Path p = getTestRootPath(fc, ""test/file""); ++ fc.create(p, EnumSet.noneOf(CreateFlag.class)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ @Test(expected=FileAlreadyExistsException.class) ++ public void testCreateFlagCreateExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagCreateExistingFile""); ++ createFile(p); ++ fc.create(p, EnumSet.of(CREATE)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ @Test(expected=FileNotFoundException.class) ++ public void testCreateFlagOverwriteNonExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagOverwriteNonExistingFile""); ++ fc.create(p, EnumSet.of(OVERWRITE)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ + @Test +- public void testOverwrite() throws IOException { +- Path path = getTestRootPath(fc, ""test/hadoop/file""); +- +- fc.mkdir(path.getParent(), FsPermission.getDefault(), true); +- +- createFile(path); +- +- Assert.assertTrue(""Exists"", exists(fc, path)); +- Assert.assertEquals(""Length"", data.length, fc.getFileStatus(path).getLen()); +- +- try { +- fc.create(path, EnumSet.of(CreateFlag.CREATE)); +- Assert.fail(""Should throw IOException.""); +- } catch (IOException e) { +- // Expected +- } +- +- FSDataOutputStream out = fc.create(path,EnumSet.of(CreateFlag.OVERWRITE)); ++ public void testCreateFlagOverwriteExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagOverwriteExistingFile""); ++ createFile(p); ++ FSDataOutputStream out = fc.create(p, EnumSet.of(OVERWRITE)); ++ writeData(fc, p, out, data, data.length); ++ } ++ ++ @Test(expected=FileNotFoundException.class) ++ public void testCreateFlagAppendNonExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagAppendNonExistingFile""); ++ fc.create(p, EnumSet.of(APPEND)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ @Test ++ public void testCreateFlagAppendExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagAppendExistingFile""); ++ createFile(p); ++ FSDataOutputStream out = fc.create(p, EnumSet.of(APPEND)); ++ writeData(fc, p, out, data, 2 * data.length); ++ } ++ ++ @Test ++ public void testCreateFlagCreateAppendNonExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagCreateAppendNonExistingFile""); ++ FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); ++ writeData(fc, p, out, data, data.length); ++ } ++ ++ @Test ++ public void testCreateFlagCreateAppendExistingFile() throws IOException { ++ Path p = getTestRootPath(fc, ""test/testCreateFlagCreateAppendExistingFile""); ++ createFile(p); ++ FSDataOutputStream out = fc.create(p, EnumSet.of(CREATE, APPEND)); ++ writeData(fc, p, out, data, 2*data.length); ++ } ++ ++ @Test(expected=HadoopIllegalArgumentException.class) ++ public void testCreateFlagAppendOverwrite() throws IOException { ++ Path p = getTestRootPath(fc, ""test/nonExistent""); ++ fc.create(p, EnumSet.of(APPEND, OVERWRITE)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ @Test(expected=HadoopIllegalArgumentException.class) ++ public void testCreateFlagAppendCreateOverwrite() throws IOException { ++ Path p = getTestRootPath(fc, ""test/nonExistent""); ++ fc.create(p, EnumSet.of(CREATE, APPEND, OVERWRITE)); ++ Assert.fail(""Excepted exception not thrown""); ++ } ++ ++ private static void writeData(FileContext fc, Path p, FSDataOutputStream out, ++ byte[] data, long expectedLen) throws IOException { + out.write(data, 0, data.length); + out.close(); +- +- Assert.assertTrue(""Exists"", exists(fc, path)); +- Assert.assertEquals(""Length"", data.length, fc.getFileStatus(path).getLen()); +- ++ Assert.assertTrue(""Exists"", exists(fc, p)); ++ Assert.assertEquals(""Length"", expectedLen, fc.getFileStatus(p).getLen()); + } + + @Test +@@ -1057,7 +1120,7 @@ public void testOutputStreamClosedTwice() throws IOException { + //HADOOP-4760 according to Closeable#close() closing already-closed + //streams should have no effect. + Path src = getTestRootPath(fc, ""test/hadoop/file""); +- FSDataOutputStream out = fc.create(src, EnumSet.of(CreateFlag.CREATE), ++ FSDataOutputStream out = fc.create(src, EnumSet.of(CREATE), + Options.CreateOpts.createParent()); + + out.writeChar('H'); //write some data +@@ -1091,7 +1154,7 @@ public void testUnsupportedSymlink() throws IOException { + } + + protected void createFile(Path path) throws IOException { +- FSDataOutputStream out = fc.create(path, EnumSet.of(CreateFlag.CREATE), ++ FSDataOutputStream out = fc.create(path, EnumSet.of(CREATE), + Options.CreateOpts.createParent()); + out.write(data, 0, data.length); + out.close(); +diff --git a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java +index 97342951579ca..5124211d344db 100644 +--- a/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java ++++ b/src/test/core/org/apache/hadoop/fs/loadGenerator/DataGenerator.java +@@ -140,7 +140,8 @@ private void genFiles() throws IOException { + * a length of fileSize. The file is filled with character 'a'. + */ + private void genFile(Path file, long fileSize) throws IOException { +- FSDataOutputStream out = fc.create(file, EnumSet.of(CreateFlag.OVERWRITE), ++ FSDataOutputStream out = fc.create(file, ++ EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE), + CreateOpts.createParent(), CreateOpts.bufferSize(4096), + CreateOpts.repFac((short) 3)); + for(long i=0; i "")) != null) { +- exampleConsole.pushToConsole(""======>\"""" + line + ""\""\n""); ++ exampleConsole.pushToStdOut(""======>\"""" + line.getBuffer() + ""\""\n""); + +- if (line.equalsIgnoreCase(""quit"") || line.equalsIgnoreCase(""exit"") || +- line.equalsIgnoreCase(""reset"")) { ++ if (line.getBuffer().equalsIgnoreCase(""quit"") || line.getBuffer().equalsIgnoreCase(""exit"") || ++ line.getBuffer().equalsIgnoreCase(""reset"")) { + break; + } +- if(line.equalsIgnoreCase(""password"")) { ++ if(line.getBuffer().equalsIgnoreCase(""password"")) { + line = exampleConsole.read(""password: "", Character.valueOf((char) 0)); +- exampleConsole.pushToConsole(""password typed:"" + line + ""\n""); ++ exampleConsole.pushToStdOut(""password typed:"" + line + ""\n""); + + } +- if(line.equals(""clear"")) ++ //test stdErr ++ if(line.getBuffer().startsWith(""blah"")) { ++ exampleConsole.pushToStdErr(""blah. command not found.\n""); ++ } ++ if(line.getBuffer().equals(""clear"")) + exampleConsole.clear(); +- if(line.equals(""man"")) { ++ if(line.getBuffer().startsWith(""man"")) { + //exampleConsole.attachProcess(test); +- test.attach(); ++ test.attach(line); + } + } + if(line.equals(""reset"")) { +@@ -142,9 +149,9 @@ else if(co.getBuffer().equals(""deploy"")) { + exampleConsole = new Console(); + + while ((line = exampleConsole.read(""> "")) != null) { +- exampleConsole.pushToConsole(""======>\"""" + line + ""\""\n""); +- if (line.equalsIgnoreCase(""quit"") || line.equalsIgnoreCase(""exit"") || +- line.equalsIgnoreCase(""reset"")) { ++ exampleConsole.pushToStdOut(""======>\"""" + line + ""\""\n""); ++ if (line.getBuffer().equalsIgnoreCase(""quit"") || line.getBuffer().equalsIgnoreCase(""exit"") || ++ line.getBuffer().equalsIgnoreCase(""reset"")) { + break; + } + +diff --git a/src/main/java/org/jboss/jreadline/console/Buffer.java b/src/main/java/org/jboss/jreadline/console/Buffer.java +index b67eef2fd..9f352fac5 100644 +--- a/src/main/java/org/jboss/jreadline/console/Buffer.java ++++ b/src/main/java/org/jboss/jreadline/console/Buffer.java +@@ -373,27 +373,11 @@ protected void replaceChar(char rChar) { + line.setCharAt(getCursor(), rChar); + } + +- /** +- * Return the biggest common startsWith string +- * +- * @param completionList list to compare +- * @return biggest common startsWith string +- */ +- protected String findStartsWith(List completionList) { +- StringBuilder builder = new StringBuilder(); +- for(String completion : completionList) +- while(builder.length() < completion.length() && +- startsWith(completion.substring(0, builder.length()+1), completionList)) +- builder.append(completion.charAt(builder.length())); +- +- return builder.toString(); ++ protected boolean containRedirection() { ++ return (line.indexOf("">"") > -1 ); + } + +- private boolean startsWith(String criteria, List completionList) { +- for(String completion : completionList) +- if(!completion.startsWith(criteria)) +- return false; +- +- return true; ++ protected int getRedirectionPosition() { ++ return line.indexOf("">""); + } + } +diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java +index a127ae22d..e708d0df6 100644 +--- a/src/main/java/org/jboss/jreadline/console/Console.java ++++ b/src/main/java/org/jboss/jreadline/console/Console.java +@@ -29,7 +29,7 @@ + import org.jboss.jreadline.terminal.Terminal; + import org.jboss.jreadline.undo.UndoAction; + import org.jboss.jreadline.undo.UndoManager; +-import org.jboss.jreadline.util.ANSI; ++import org.jboss.jreadline.util.FileUtils; + import org.jboss.jreadline.util.LoggerUtil; + import org.jboss.jreadline.util.Parser; + +@@ -64,6 +64,8 @@ public class Console { + private boolean displayCompletion = false; + private boolean askDisplayCompletion = false; + private boolean running = false; ++ private boolean redirection = false; ++ private StringBuilder redirectionBuffer; + + private Logger logger = LoggerUtil.getLogger(getClass().getName()); + +@@ -105,7 +107,7 @@ public void reset(Settings settings) throws IOException { + Config.readRuntimeProperties(Settings.getInstance()); + + setTerminal(settings.getTerminal(), +- settings.getInputStream(), settings.getOutputStream()); ++ settings.getInputStream(), settings.getStdOut(), settings.getStdErr()); + + editMode = settings.getFullEditMode(); + +@@ -120,13 +122,16 @@ public void reset(Settings settings) throws IOException { + + + completionList = new ArrayList(); ++ completionList.add(new RedirectionCompletion()); ++ ++ redirectionBuffer = new StringBuilder(); + this.settings = settings; + running = true; + } + +- private void setTerminal(Terminal term, InputStream in, OutputStream out) { ++ private void setTerminal(Terminal term, InputStream in, OutputStream stdOut, OutputStream stdErr) { + terminal = term; +- terminal.init(in, out); ++ terminal.init(in, stdOut, stdErr); + } + + /** +@@ -163,20 +168,43 @@ public History getHistory() { + * @param input text + * @throws IOException stream + */ +- public void pushToConsole(String input) throws IOException { +- if(input != null && input.length() > 0) +- terminal.write(input); ++ public void pushToStdOut(String input) throws IOException { ++ if(input != null && input.length() > 0) { ++ //if redirection enabled, put it into a buffer ++ if(redirection) { ++ redirectionBuffer.append(input); ++ } ++ else ++ terminal.writeToStdOut(input); ++ } + } + + /** +- * @see #pushToConsole(String) ++ * @see #pushToStdOut + * + * @param input chars + * @throws IOException stream + */ +- public void pushToConsole(char[] input) throws IOException { +- if(input != null && input.length > 0) +- terminal.write(input); ++ public void pushToStdOut(char[] input) throws IOException { ++ if(input != null && input.length > 0) { ++ //if redirection enabled, put it into a buffer ++ if(redirection) ++ redirectionBuffer.append(input); ++ else ++ terminal.writeToStdOut(input); ++ } ++ } ++ ++ public void pushToStdErr(String input) throws IOException { ++ if(input != null && input.length() > 0) { ++ terminal.writeToStdErr(input); ++ } ++ } ++ ++ public void pushToStdErr(char[] input) throws IOException { ++ if(input != null && input.length > 0) { ++ terminal.writeToStdErr(input); ++ } + } + + /** +@@ -229,7 +257,7 @@ protected void attachProcess(ConsoleCommand cc) throws IOException { + */ + private void detachProcess() throws IOException { + command = null; +- printNewline(); ++ terminal.writeToStdOut(buffer.getPrompt()); + } + + +@@ -242,7 +270,7 @@ private void detachProcess() throws IOException { + * @return input stream + * @throws IOException stream + */ +- public String read(String prompt) throws IOException { ++ public ConsoleOutput read(String prompt) throws IOException { + return read(prompt, null); + } + +@@ -256,16 +284,24 @@ public String read(String prompt) throws IOException { + * @return input stream + * @throws IOException stream + */ +- public String read(String prompt, Character mask) throws IOException { ++ public ConsoleOutput read(String prompt, Character mask) throws IOException { + if(!running) + throw new RuntimeException(""Cant reuse a stopped Console before its reset again!""); ++ if(redirection) { ++ redirection = false; ++ persistRedirection(buffer.getLine()); ++ redirectionBuffer = new StringBuilder(); ++ } + + buffer.reset(prompt, mask); + if(command == null) +- terminal.write(buffer.getPrompt()); ++ terminal.writeToStdOut(buffer.getPrompt()); + search = null; + + while(true) { ++ if(command != null && !command.isAttached()) { ++ detachProcess(); ++ } + + int[] in = terminal.read(settings.isReadAhead()); + //for(int i : in) +@@ -276,17 +312,14 @@ public String read(String prompt, Character mask) throws IOException { + Operation operation = editMode.parseInput(in); + operation.setInput(in); + +- String result; +- if(command != null) { +- result = command.processOperation(operation); +- if(!command.isAttached()) +- detachProcess(); +- } ++ String result = null; ++ if(command != null) ++ command.processOperation(operation); + else + result = parseOperation(operation, mask); + + if(result != null) +- return result; ++ return parseConsoleOutput(result); + } + } + +@@ -311,8 +344,8 @@ private String parseOperation(Operation operation, Character mask) throws IOExce + //do not display complete, but make sure that the previous line + // is restored correctly + else { +- terminal.write(Config.getLineSeparator()); +- terminal.write(buffer.getLineWithPrompt()); ++ terminal.writeToStdOut(Config.getLineSeparator()); ++ terminal.writeToStdOut(buffer.getLineWithPrompt()); + syncCursor(); + } + } +@@ -507,7 +540,7 @@ private void doSearch(Search search) throws IOException { + // otherwise, restore the line + else { + redrawLine(); +- terminal.write(Buffer.printAnsi((buffer.getPrompt().length()+1)+""G"")); ++ terminal.writeToStdOut(Buffer.printAnsi((buffer.getPrompt().length() + 1) + ""G"")); + } + } + +@@ -569,8 +602,8 @@ private void setBufferLine(String newLine) throws IOException { + //int totalRows = (newLine.length()+buffer.getPrompt().length()) / getTerminalWidth() +1; + //logger.info(""ADDING ""+numNewRows+"", totalRows:""+totalRows+ + // "", currentRow:""+currentRow+"", cursorRow:""+cursorRow); +- terminal.write(Buffer.printAnsi(numNewRows + ""S"")); +- terminal.write(Buffer.printAnsi(numNewRows + ""A"")); ++ terminal.writeToStdOut(Buffer.printAnsi(numNewRows + ""S"")); ++ terminal.writeToStdOut(Buffer.printAnsi(numNewRows + ""A"")); + } + } + } +@@ -591,8 +624,8 @@ private void insertBufferLine(String insert, int position) throws IOException { + if((insert.length()+buffer.totalLength()) % getTerminalWidth() == 0) + numNewRows++; + if(numNewRows > 0) { +- terminal.write(Buffer.printAnsi(numNewRows+""S"")); +- terminal.write(Buffer.printAnsi(numNewRows+""A"")); ++ terminal.writeToStdOut(Buffer.printAnsi(numNewRows + ""S"")); ++ terminal.writeToStdOut(Buffer.printAnsi(numNewRows + ""A"")); + } + } + } +@@ -615,19 +648,19 @@ private void writeChar(int c, Character mask) throws IOException { + buffer.write((char) c); + if(mask != null) { + if(mask == 0) +- terminal.write(' '); //TODO: fix this hack ++ terminal.writeToStdOut(' '); //TODO: fix this hack + else +- terminal.write(mask); ++ terminal.writeToStdOut(mask); + } + else { +- terminal.write((char) c); ++ terminal.writeToStdOut((char) c); + } + + // add a 'fake' new line when inserting at the edge of terminal + if(buffer.getCursorWithPrompt() > getTerminalWidth() && + buffer.getCursorWithPrompt() % getTerminalWidth() == 1) { +- terminal.write((char) 32); +- terminal.write((char) 13); ++ terminal.writeToStdOut((char) 32); ++ terminal.writeToStdOut((char) 13); + } + + // if we insert somewhere other than the end of the line we need to redraw from cursor +@@ -645,8 +678,8 @@ private void writeChar(int c, Character mask) throws IOException { + totalRows--; + + if(ansiCurrentRow+(totalRows-currentRow) > getTerminalHeight()) { +- terminal.write(Buffer.printAnsi(""1S"")); //adding a line +- terminal.write(Buffer.printAnsi(""1A"")); // moving up a line ++ terminal.writeToStdOut(Buffer.printAnsi(""1S"")); //adding a line ++ terminal.writeToStdOut(Buffer.printAnsi(""1A"")); // moving up a line + } + } + redrawLine(); +@@ -753,10 +786,10 @@ public final void moveCursor(final int where) throws IOException { + (editMode.getCurrentAction() == Action.MOVE || + editMode.getCurrentAction() == Action.DELETE)) { + +- terminal.write(buffer.move(where, getTerminalWidth(), true)); ++ terminal.writeToStdOut(buffer.move(where, getTerminalWidth(), true)); + } + else { +- terminal.write(buffer.move(where, getTerminalWidth())); ++ terminal.writeToStdOut(buffer.move(where, getTerminalWidth())); + } + } + +@@ -780,38 +813,38 @@ private void drawLine(String line) throws IOException { + //+"", width:""+getTerminalWidth()+"", height:""+getTerminalHeight()+"", delta:""+buffer.getDelta() + //+"", buffer:""+buffer.getLine()); + +- terminal.write(Buffer.printAnsi(""s"")); //save cursor ++ terminal.writeToStdOut(Buffer.printAnsi(""s"")); //save cursor + + if(currentRow > 0) + for(int i=0; i buffer.getDelta(); i--) + sb.append(' '); +- terminal.write(sb.toString()); ++ terminal.writeToStdOut(sb.toString()); + } + + // move cursor to saved pos +- terminal.write(Buffer.printAnsi(""u"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""u"")); + } + // only clear the current line + else { +- terminal.write(Buffer.printAnsi(""s"")); //save cursor ++ terminal.writeToStdOut(Buffer.printAnsi(""s"")); //save cursor + //move cursor to 0. - need to do this to clear the entire line +- terminal.write(Buffer.printAnsi(""0G"")); +- terminal.write(Buffer.printAnsi(""2K"")); // clear line ++ terminal.writeToStdOut(Buffer.printAnsi(""0G"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""2K"")); // clear line + +- terminal.write(line); ++ terminal.writeToStdOut(line); + + // move cursor to saved pos +- terminal.write(Buffer.printAnsi(""u"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""u"")); + } + } + +@@ -829,7 +862,7 @@ private void printSearch(String searchTerm, String result) throws IOException { + out.append(result); + buffer.disablePrompt(true); + moveCursor(-buffer.getCursor()); +- terminal.write(Buffer.printAnsi(""1G""));//move the cursor all the way to the start of the line ++ terminal.writeToStdOut(Buffer.printAnsi(""1G""));//move the cursor all the way to the start of the line + setBufferLine(out.toString()); + moveCursor(cursor); + drawLine(buffer.getLine()); +@@ -843,7 +876,7 @@ private void printSearch(String searchTerm, String result) throws IOException { + */ + private void printNewline() throws IOException { + moveCursor(buffer.totalLength()); +- terminal.write(Config.getLineSeparator()); ++ terminal.writeToStdOut(Config.getLineSeparator()); + } + + /** +@@ -927,7 +960,7 @@ else if(possibleCompletions.size() == 1 && + } + else { + askDisplayCompletion = true; +- terminal.write(Config.getLineSeparator()+""Display all ""+completions.size()+ "" possibilities? (y or n)""); ++ terminal.writeToStdOut(Config.getLineSeparator() + ""Display all "" + completions.size() + "" possibilities? (y or n)""); + } + } + // display all +@@ -952,17 +985,17 @@ private void displayCompletion(String fullCompletion, String completion, boolean + if(completion.startsWith(buffer.getLine())) { + performAction(new PrevWordAction(buffer.getCursor(), Action.DELETE)); + buffer.write(completion); +- terminal.write(completion); ++ terminal.writeToStdOut(completion); + + //only append space if its an actual complete, not a partial + } + else { + buffer.write(completion); +- terminal.write(completion); ++ terminal.writeToStdOut(completion); + } + if(appendSpace && fullCompletion.startsWith(buffer.getLine())) { + buffer.write(' '); +- terminal.write(' '); ++ terminal.writeToStdOut(' '); + } + + redrawLine(); +@@ -976,8 +1009,8 @@ private void displayCompletion(String fullCompletion, String completion, boolean + */ + private void displayCompletions(List completions) throws IOException { + printNewline(); +- terminal.write(Parser.formatCompletions(completions, terminal.getHeight(), terminal.getWidth())); +- terminal.write(buffer.getLineWithPrompt()); ++ terminal.writeToStdOut(Parser.formatCompletions(completions, terminal.getHeight(), terminal.getWidth())); ++ terminal.writeToStdOut(buffer.getLineWithPrompt()); + //if we do a complete and the cursor is not at the end of the + //buffer we need to move it to the correct place + syncCursor(); +@@ -985,9 +1018,9 @@ private void displayCompletions(List completions) throws IOException { + + private void syncCursor() throws IOException { + if(buffer.getCursor() != buffer.getLine().length()) +- terminal.write(Buffer.printAnsi(( +- Math.abs( buffer.getCursor()- +- buffer.getLine().length())+""D""))); ++ terminal.writeToStdOut(Buffer.printAnsi(( ++ Math.abs(buffer.getCursor() - ++ buffer.getLine().length()) + ""D""))); + + } + +@@ -1008,7 +1041,7 @@ private void replace(int rChar) throws IOException { + private int getCurrentRow() { + if(settings.isAnsiConsole() && Config.isOSPOSIXCompatible()) { + try { +- terminal.write(Buffer.printAnsi(""6n"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""6n"")); + StringBuilder builder = new StringBuilder(8); + int row; + while((row = terminal.read(false)[0]) > -1 && row != 'R') { +@@ -1030,7 +1063,7 @@ private int getCurrentRow() { + private int getCurrentColumn() { + if(settings.isAnsiConsole() && Config.isOSPOSIXCompatible()) { + try { +- terminal.write(Buffer.printAnsi(""6n"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""6n"")); + StringBuilder builder = new StringBuilder(8); + int row; + while((row = settings.getInputStream().read()) > -1 && row != 'R' ) { +@@ -1068,12 +1101,33 @@ public void clear() throws IOException { + */ + public void clear(boolean includeBuffer) throws IOException { + //first clear console +- terminal.write(Buffer.printAnsi(""2J"")); ++ terminal.writeToStdOut(Buffer.printAnsi(""2J"")); + //move cursor to correct position +- terminal.write(Buffer.printAnsi(""1;1H"")); +- //then write prompt ++ terminal.writeToStdOut(Buffer.printAnsi(""1;1H"")); ++ //then writeToStdOut prompt + if(includeBuffer) +- terminal.write(buffer.getLineWithPrompt()); ++ terminal.writeToStdOut(buffer.getLineWithPrompt()); ++ } ++ ++ private ConsoleOutput parseConsoleOutput(String buffer) { ++ if(buffer.contains("">"")) { ++ redirection = true; ++ this.buffer.setLine(buffer.substring(buffer.indexOf("">"")+1, buffer.length()).trim()); ++ return new ConsoleOutput(buffer.substring(0, buffer.indexOf("">"")), true); ++ } ++ else { ++ return new ConsoleOutput(buffer, false); ++ } ++ } ++ ++ private void persistRedirection(String fileName) throws IOException { ++ try { ++ FileUtils.saveFile(new File(fileName), redirectionBuffer.toString(), false); ++ } ++ catch (IOException e) { ++ pushToStdErr(e.getMessage()); ++ } ++ + } + + } +diff --git a/src/main/java/org/jboss/jreadline/console/ConsoleCommand.java b/src/main/java/org/jboss/jreadline/console/ConsoleCommand.java +index bc7d89af8..5027da346 100644 +--- a/src/main/java/org/jboss/jreadline/console/ConsoleCommand.java ++++ b/src/main/java/org/jboss/jreadline/console/ConsoleCommand.java +@@ -32,6 +32,7 @@ public abstract class ConsoleCommand { + + boolean attached = false; + protected Console console = null; ++ boolean redirect = false; + + public ConsoleCommand(Console console) { + this.console = console; +@@ -43,9 +44,10 @@ public ConsoleCommand(Console console) { + * + * @throws IOException stream + */ +- public final void attach() throws IOException { ++ public final void attach(ConsoleOutput output) throws IOException { + attached = true; + this.console.attachProcess(this); ++ this.redirect = output.hasRedirectOrPipe(); + afterAttach(); + } + +@@ -68,6 +70,10 @@ public final void detach() throws IOException { + afterDetach(); + } + ++ public final boolean hasRedirect() { ++ return redirect; ++ } ++ + /** + * Called after attach(..) is called. + * +@@ -86,8 +92,7 @@ public final void detach() throws IOException { + * Called after every operation made by the user + * + * @param operation operation +- * @return string + * @throws IOException stream + */ +- public abstract String processOperation(Operation operation) throws IOException; ++ public abstract void processOperation(Operation operation) throws IOException; + } +diff --git a/src/main/java/org/jboss/jreadline/console/ConsoleOutput.java b/src/main/java/org/jboss/jreadline/console/ConsoleOutput.java +new file mode 100644 +index 000000000..582418bd2 +--- /dev/null ++++ b/src/main/java/org/jboss/jreadline/console/ConsoleOutput.java +@@ -0,0 +1,59 @@ ++/* ++ * JBoss, Home of Professional Open Source ++ * Copyright 2010, Red Hat Middleware LLC, and individual contributors ++ * by the @authors tag. See the copyright.txt in the distribution for a ++ * full listing of individual contributors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.jboss.jreadline.console; ++ ++/** ++ * Value object returned by Console when newline is pressed ++ * If the command is part of a pipeline sequence the stdOut and stdErr is populated accordingly ++ * ++ * @author Ståle W. Pedersen ++ */ ++public class ConsoleOutput { ++ ++ private String buffer; ++ private boolean redirectOrPipe; ++ private String stdOut; ++ private String stdErr; ++ ++ public ConsoleOutput(String buffer, boolean redirectOrPipe) { ++ this.buffer = buffer; ++ this.redirectOrPipe = redirectOrPipe; ++ } ++ ++ public ConsoleOutput(String buffer, String stdOut, String stdErr, boolean redirectOrPipe) { ++ this.buffer = buffer; ++ this.redirectOrPipe = redirectOrPipe; ++ this.stdOut = stdOut; ++ this.stdErr = stdErr; ++ } ++ ++ public String getBuffer() { ++ return buffer; ++ } ++ ++ public boolean hasRedirectOrPipe() { ++ return redirectOrPipe; ++ } ++ ++ public String getStdOut() { ++ return stdOut; ++ } ++ ++ public String getStdErr() { ++ return stdErr; ++ } ++} +diff --git a/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java b/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java +new file mode 100644 +index 000000000..a0bff94a4 +--- /dev/null ++++ b/src/main/java/org/jboss/jreadline/console/RedirectionCompletion.java +@@ -0,0 +1,47 @@ ++/* ++ * JBoss, Home of Professional Open Source ++ * Copyright 2010, Red Hat Middleware LLC, and individual contributors ++ * by the @authors tag. See the copyright.txt in the distribution for a ++ * full listing of individual contributors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.jboss.jreadline.console; ++ ++import org.jboss.jreadline.complete.CompleteOperation; ++import org.jboss.jreadline.complete.Completion; ++import org.jboss.jreadline.util.FileUtils; ++import org.jboss.jreadline.util.Parser; ++ ++import java.io.File; ++ ++/** ++ * Redirection completor ++ * ++ * @author Ståle W. Pedersen ++ */ ++public class RedirectionCompletion implements Completion { ++ ++ @Override ++ public void complete(CompleteOperation completeOperation) { ++ ++ if(completeOperation.getBuffer().contains("">"") && ++ completeOperation.getCursor() >= completeOperation.getBuffer().indexOf("">"")) { ++ ++ String word = ++ Parser.findWordClosestToCursorDividedByRedirectOrPipe( ++ completeOperation.getBuffer(), completeOperation.getCursor()); ++ completeOperation.addCompletionCandidates( ++ FileUtils.listMatchingDirectories(word, new File(System.getProperty(""user.dir"")))); ++ completeOperation.setOffset(completeOperation.getCursor()); ++ } ++ } ++} +diff --git a/src/main/java/org/jboss/jreadline/console/settings/Settings.java b/src/main/java/org/jboss/jreadline/console/settings/Settings.java +index b20107da5..509907a14 100644 +--- a/src/main/java/org/jboss/jreadline/console/settings/Settings.java ++++ b/src/main/java/org/jboss/jreadline/console/settings/Settings.java +@@ -40,7 +40,8 @@ public class Settings { + private String bellStyle; + private boolean ansiConsole = true; + private InputStream inputStream; +- private OutputStream outputStream; ++ private OutputStream stdOut; ++ private OutputStream stdErr; + private Terminal terminal; + private boolean readInputrc = true; + private File inputrc; +@@ -69,7 +70,8 @@ public void resetToDefaults() { + bellStyle = null; + ansiConsole = true; + inputStream = null; +- outputStream = null; ++ stdOut = null; ++ stdErr = null; + terminal = null; + readInputrc = true; + logFile = null; +@@ -235,21 +237,41 @@ public void setInputStream(InputStream inputStream) { + * If not set System.out is used + * @return out + */ +- public OutputStream getOutputStream() { +- if(outputStream == null) ++ public OutputStream getStdOut() { ++ if(stdOut == null) + return System.out; + else +- return outputStream; ++ return stdOut; + } + + /** + * Set where output should go to +- * @param outputStream output ++ * @param stdOut output + */ +- public void setOutputStream(OutputStream outputStream) { +- this.outputStream = outputStream; ++ public void setStdOut(OutputStream stdOut) { ++ this.stdOut = stdOut; + } + ++ /** ++ * If not set System.out is used ++ * @return out ++ */ ++ public OutputStream getStdErr() { ++ if(stdErr == null) ++ return System.err; ++ else ++ return stdErr; ++ } ++ ++ /** ++ * Set where output should go to ++ * @param stdErr output ++ */ ++ public void setStdErr(OutputStream stdErr) { ++ this.stdErr = stdErr; ++ } ++ ++ + /** + * Use the specified terminal implementation + * If not set, jreadline will try to use the best suited one +diff --git a/src/main/java/org/jboss/jreadline/history/FileHistory.java b/src/main/java/org/jboss/jreadline/history/FileHistory.java +index e78df7085..683ba6493 100644 +--- a/src/main/java/org/jboss/jreadline/history/FileHistory.java ++++ b/src/main/java/org/jboss/jreadline/history/FileHistory.java +@@ -7,7 +7,7 @@ + import java.net.URL; + + /** +- * Read the history file at init and write to it at shutdown ++ * Read the history file at init and writeToStdOut to it at shutdown + * + * @author Ståle W. Pedersen + */ +diff --git a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java +index 0840b6a60..708bf04b5 100644 +--- a/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java ++++ b/src/main/java/org/jboss/jreadline/terminal/POSIXTerminal.java +@@ -37,12 +37,13 @@ public class POSIXTerminal implements Terminal { + private boolean restored = false; + + private InputStream input; +- private Writer writer; +- ++ private Writer stdOut; ++ private Writer stdErr; ++ + private static final Logger logger = LoggerUtil.getLogger(POSIXTerminal.class.getName()); + + @Override +- public void init(InputStream inputStream, OutputStream outputStream) { ++ public void init(InputStream inputStream, OutputStream stdOut, OutputStream stdErr) { + // save the initial tty configuration + try { + ttyConfig = stty(""-g""); +@@ -71,7 +72,8 @@ public void init(InputStream inputStream, OutputStream outputStream) { + e.printStackTrace(); + } + +- writer = new PrintWriter( new OutputStreamWriter(outputStream)); ++ this.stdOut = new PrintWriter( new OutputStreamWriter(stdOut)); ++ this.stdErr = new PrintWriter( new OutputStreamWriter(stdErr)); + } + + /** +@@ -97,10 +99,10 @@ public int[] read(boolean readAhead) throws IOException { + * @see org.jboss.jreadline.terminal.Terminal + */ + @Override +- public void write(String out) throws IOException { ++ public void writeToStdOut(String out) throws IOException { + if(out != null && out.length() > 0) { +- writer.write(out); +- writer.flush(); ++ stdOut.write(out); ++ stdOut.flush(); + } + } + +@@ -108,10 +110,41 @@ public void write(String out) throws IOException { + * @see org.jboss.jreadline.terminal.Terminal + */ + @Override +- public void write(char[] out) throws IOException { ++ public void writeToStdOut(char[] out) throws IOException { + if(out != null && out.length > 0) { +- writer.write(out); +- writer.flush(); ++ stdOut.write(out); ++ stdOut.flush(); ++ } ++ } ++ ++ /** ++ * @see org.jboss.jreadline.terminal.Terminal ++ */ ++ @Override ++ public void writeToStdOut(char out) throws IOException { ++ stdOut.write(out); ++ stdOut.flush(); ++ } ++ ++ /** ++ * @see org.jboss.jreadline.terminal.Terminal ++ */ ++ @Override ++ public void writeToStdErr(String err) throws IOException { ++ if(err != null && err.length() > 0) { ++ stdErr.write(err); ++ stdErr.flush(); ++ } ++ } ++ ++ /** ++ * @see org.jboss.jreadline.terminal.Terminal ++ */ ++ @Override ++ public void writeToStdErr(char[] err) throws IOException { ++ if(err != null && err.length > 0) { ++ stdErr.write(err); ++ stdErr.flush(); + } + } + +@@ -119,9 +152,9 @@ public void write(char[] out) throws IOException { + * @see org.jboss.jreadline.terminal.Terminal + */ + @Override +- public void write(char out) throws IOException { +- writer.write(out); +- writer.flush(); ++ public void writeToStdErr(char err) throws IOException { ++ stdErr.write(err); ++ stdErr.flush(); + } + + /** +diff --git a/src/main/java/org/jboss/jreadline/terminal/Terminal.java b/src/main/java/org/jboss/jreadline/terminal/Terminal.java +index ad15ba02c..f3bdb0194 100644 +--- a/src/main/java/org/jboss/jreadline/terminal/Terminal.java ++++ b/src/main/java/org/jboss/jreadline/terminal/Terminal.java +@@ -31,9 +31,10 @@ public interface Terminal { + * Initialize the Terminal with which input/output stream it should use + * + * @param inputStream input +- * @param outputStream output ++ * @param stdOut standard output ++ * @param stdErr error output + */ +- void init(InputStream inputStream, OutputStream outputStream); ++ void init(InputStream inputStream, OutputStream stdOut, OutputStream stdErr); + + /** + * Read from the input stream (char by char) +@@ -44,28 +45,52 @@ public interface Terminal { + int[] read(boolean readAhead) throws IOException; + + /** +- * Write to the output stream ++ * Write to the standard output stream + * + * @param out what goes into the stream + * @throws IOException stream + */ +- void write(String out) throws IOException; ++ void writeToStdOut(String out) throws IOException; + + /** +- * Write to the output stream ++ * Write to the standard output stream + * + * @param out what goes into the stream + * @throws IOException stream + */ +- void write(char[] out) throws IOException; ++ void writeToStdOut(char[] out) throws IOException; + + /** +- * Write to the output stream ++ * Write to the standard output stream + * + * @param out what goes into the stream + * @throws IOException stream + */ +- void write(char out) throws IOException; ++ void writeToStdOut(char out) throws IOException; ++ ++ /** ++ * Write to the standard error stream ++ * ++ * @param err what goes into the stream ++ * @throws IOException stream ++ */ ++ void writeToStdErr(String err) throws IOException; ++ ++ /** ++ * Write to the standard error stream ++ * ++ * @param err what goes into the stream ++ * @throws IOException stream ++ */ ++ void writeToStdErr(char[] err) throws IOException; ++ ++ /** ++ * Write to the standard error stream ++ * ++ * @param err what goes into the stream ++ * @throws IOException stream ++ */ ++ void writeToStdErr(char err) throws IOException; + + /** + * @return terminal height +diff --git a/src/main/java/org/jboss/jreadline/terminal/TestTerminal.java b/src/main/java/org/jboss/jreadline/terminal/TestTerminal.java +index 603f391e1..540da22b8 100644 +--- a/src/main/java/org/jboss/jreadline/terminal/TestTerminal.java ++++ b/src/main/java/org/jboss/jreadline/terminal/TestTerminal.java +@@ -29,9 +29,9 @@ public class TestTerminal implements Terminal { + private Writer writer; + + @Override +- public void init(InputStream inputStream, OutputStream outputStream) { ++ public void init(InputStream inputStream, OutputStream stdOut, OutputStream stdErr) { + input = inputStream; +- writer = new PrintWriter(new OutputStreamWriter(outputStream)); ++ writer = new PrintWriter(new OutputStreamWriter(stdOut)); + } + + @Override +@@ -51,7 +51,7 @@ public int[] read(boolean readAhead) throws IOException { + } + + @Override +- public void write(String out) throws IOException { ++ public void writeToStdOut(String out) throws IOException { + if(out != null && out.length() > 0) { + writer.write(out); + writer.flush(); +@@ -59,7 +59,7 @@ public void write(String out) throws IOException { + } + + @Override +- public void write(char[] out) throws IOException { ++ public void writeToStdOut(char[] out) throws IOException { + if(out != null && out.length > 0) { + writer.write(out); + writer.flush(); +@@ -67,11 +67,33 @@ public void write(char[] out) throws IOException { + } + + @Override +- public void write(char out) throws IOException { ++ public void writeToStdOut(char out) throws IOException { + writer.write(out); + writer.flush(); + } + ++ @Override ++ public void writeToStdErr(String err) throws IOException { ++ if(err != null && err.length() > 0) { ++ writer.write(err); ++ writer.flush(); ++ } ++ } ++ ++ @Override ++ public void writeToStdErr(char[] err) throws IOException { ++ if(err != null && err.length > 0) { ++ writer.write(err); ++ writer.flush(); ++ } ++ } ++ ++ @Override ++ public void writeToStdErr(char err) throws IOException { ++ writer.write(err); ++ writer.flush(); ++ } ++ + @Override + public int getHeight() { + return 24; +diff --git a/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java b/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java +index 87d31fb36..4c41b3a62 100644 +--- a/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java ++++ b/src/main/java/org/jboss/jreadline/terminal/WindowsTerminal.java +@@ -29,12 +29,13 @@ + */ + public class WindowsTerminal implements Terminal { + +- private Writer writer; ++ private Writer stdOut; ++ private Writer stdErr; + private InputStream input; + + + @Override +- public void init(InputStream inputStream, OutputStream outputStream) { ++ public void init(InputStream inputStream, OutputStream stdOut, OutputStream stdErr) { + if(inputStream == System.in) { + System.out.println(""Using System.in""); + } +@@ -42,10 +43,12 @@ public void init(InputStream inputStream, OutputStream outputStream) { + //setting up reader + try { + //AnsiConsole.systemInstall(); +- writer = new PrintWriter( new OutputStreamWriter(new WindowsAnsiOutputStream(outputStream))); ++ this.stdOut = new PrintWriter( new OutputStreamWriter(new WindowsAnsiOutputStream(stdOut))); ++ this.stdErr = new PrintWriter( new OutputStreamWriter(new WindowsAnsiOutputStream(stdErr))); + } + catch (Exception ioe) { +- writer = new PrintWriter( new OutputStreamWriter(new AnsiOutputStream(outputStream))); ++ this.stdOut = new PrintWriter( new OutputStreamWriter(new AnsiOutputStream(stdOut))); ++ this.stdErr = new PrintWriter( new OutputStreamWriter(new AnsiOutputStream(stdErr))); + } + + this.input = inputStream; +@@ -72,25 +75,47 @@ public int[] read(boolean readAhead) throws IOException { + } + + @Override +- public void write(String out) throws IOException { ++ public void writeToStdOut(String out) throws IOException { + if(out != null && out.length() > 0) { +- writer.write(out); +- writer.flush(); ++ stdOut.write(out); ++ stdOut.flush(); + } + } + + @Override +- public void write(char[] out) throws IOException { ++ public void writeToStdOut(char[] out) throws IOException { + if(out != null && out.length > 0) { +- writer.write(out); +- writer.flush(); ++ stdOut.write(out); ++ stdOut.flush(); + } + } + + @Override +- public void write(char out) throws IOException { +- writer.write(out); +- writer.flush(); ++ public void writeToStdOut(char out) throws IOException { ++ stdOut.write(out); ++ stdOut.flush(); ++ } ++ ++ @Override ++ public void writeToStdErr(String err) throws IOException { ++ if(err != null && err.length() > 0) { ++ stdOut.write(err); ++ stdOut.flush(); ++ } ++ } ++ ++ @Override ++ public void writeToStdErr(char[] err) throws IOException { ++ if(err != null && err.length > 0) { ++ stdOut.write(err); ++ stdOut.flush(); ++ } ++ } ++ ++ @Override ++ public void writeToStdErr(char err) throws IOException { ++ stdOut.write(err); ++ stdOut.flush(); + } + + @Override +diff --git a/src/main/java/org/jboss/jreadline/util/FileUtils.java b/src/main/java/org/jboss/jreadline/util/FileUtils.java +new file mode 100644 +index 000000000..c8960ede5 +--- /dev/null ++++ b/src/main/java/org/jboss/jreadline/util/FileUtils.java +@@ -0,0 +1,218 @@ ++/* ++ * JBoss, Home of Professional Open Source ++ * Copyright 2010, Red Hat Middleware LLC, and individual contributors ++ * by the @authors tag. See the copyright.txt in the distribution for a ++ * full listing of individual contributors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.jboss.jreadline.util; ++ ++import org.jboss.jreadline.console.Config; ++ ++import java.io.File; ++import java.io.FileOutputStream; ++import java.io.FileWriter; ++import java.io.IOException; ++import java.util.ArrayList; ++import java.util.List; ++import java.util.regex.Pattern; ++ ++/** ++ * Helper to find proper files/directories given partial paths/filenames. ++ * Should be rewritten as its now just a hack to get it working. ++ * ++ * @author Ståle W. Pedersen ++ */ ++public class FileUtils { ++ ++ public static final Pattern startsWithParent = Pattern.compile(""^\\.\\..*""); ++ public static final Pattern containParent = ++ Pattern.compile(""[\\.\\.[""+ Config.getPathSeparator()+""]?]+""); ++ public static final Pattern space = Pattern.compile("".+\\s+.+""); ++ public static final Pattern startsWithSlash = ++ Pattern.compile(""^\\""+Config.getPathSeparator()+"".*""); ++ public static final Pattern endsWithSlash = ++ Pattern.compile("".*\\""+Config.getPathSeparator()+""$""); ++ ++ public static List listMatchingDirectories(String possibleDir, File cwd) { ++ // that starts with possibleDir ++ List returnFiles = new ArrayList(); ++ if (possibleDir.trim().isEmpty()) { ++ List allFiles = listDirectory(cwd); ++ for (String file : allFiles) ++ if (file.startsWith(possibleDir)) ++ returnFiles.add(file.substring(possibleDir.length())); ++ ++ return returnFiles; ++ } ++ else if (!startsWithSlash.matcher(possibleDir).matches() && ++ new File(cwd.getAbsolutePath() + ++ Config.getPathSeparator() +possibleDir).isDirectory()) { ++ if(!endsWithSlash.matcher(possibleDir).matches()){ ++ returnFiles.add(""/""); ++ return returnFiles; ++ } ++ else ++ return listDirectory(new File(cwd.getAbsolutePath() + ++ Config.getPathSeparator() ++ +possibleDir)); ++ } ++ else if(new File(cwd.getAbsolutePath() +Config.getPathSeparator()+ possibleDir).isFile()) { ++ returnFiles.add("" ""); ++ return returnFiles; ++ } ++ //else if(possibleDir.startsWith((""/"")) && new File(possibleDir).isFile()) { ++ else if(startsWithSlash.matcher(possibleDir).matches() && ++ new File(possibleDir).isFile()) { ++ returnFiles.add("" ""); ++ return returnFiles; ++ } ++ else { ++ returnFiles = new ArrayList(); ++ if(new File(possibleDir).isDirectory() && ++ !endsWithSlash.matcher(possibleDir).matches()) { ++ returnFiles.add(Config.getPathSeparator()); ++ return returnFiles; ++ } ++ else if(new File(possibleDir).isDirectory() && ++ !endsWithSlash.matcher(possibleDir).matches()) { ++ return listDirectory(new File(possibleDir)); ++ } ++ ++ //1.list possibleDir.substring(pos ++ String lastDir = null; ++ String rest = null; ++ if(possibleDir.contains(Config.getPathSeparator())) { ++ lastDir = possibleDir.substring(0,possibleDir.lastIndexOf(Config.getPathSeparator())); ++ rest = possibleDir.substring(possibleDir.lastIndexOf(Config.getPathSeparator())+1); ++ } ++ else { ++ if(new File(cwd+Config.getPathSeparator()+possibleDir).exists()) ++ lastDir = possibleDir; ++ else { ++ rest = possibleDir; ++ } ++ } ++ //System.out.println(""rest:""+rest); ++ //System.out.println(""lastDir:""+lastDir); ++ ++ List allFiles; ++ if(startsWithSlash.matcher(possibleDir).matches()) ++ allFiles = listDirectory(new File(Config.getPathSeparator()+lastDir)); ++ else if(lastDir != null) ++ allFiles = listDirectory(new File(cwd+ ++ Config.getPathSeparator()+lastDir)); ++ else ++ allFiles = listDirectory(cwd); ++ ++ //TODO: optimize ++ //1. remove those that do not start with rest, if its more than one ++ if(rest != null && !rest.isEmpty()) { ++ for (String file : allFiles) ++ if (file.startsWith(rest)) ++ //returnFiles.add(file); ++ returnFiles.add(file.substring(rest.length())); ++ } ++ else { ++ for(String file : allFiles) ++ returnFiles.add(file); ++ } ++ ++ if(returnFiles.size() > 1) { ++ String startsWith = Parser.findStartsWith(returnFiles); ++ if(startsWith != null && startsWith.length() > 0) { ++ returnFiles.clear(); ++ returnFiles.add(startsWith); ++ } ++ //need to list complete filenames ++ else { ++ returnFiles.clear(); ++ for (String file : allFiles) ++ if (file.startsWith(rest)) ++ returnFiles.add(file); ++ } ++ } ++ ++ return returnFiles; ++ ++ } ++ } ++ ++ private static List listDirectory(File path) { ++ List fileNames = new ArrayList(); ++ if(path != null && path.isDirectory()) ++ for(File file : path.listFiles()) ++ fileNames.add(file.getName()); ++ ++ return fileNames; ++ } ++ ++ public static String getDirectoryName(File path, File home) { ++ if(path.getAbsolutePath().startsWith(home.getAbsolutePath())) ++ return ""~""+path.getAbsolutePath().substring(home.getAbsolutePath().length()); ++ else ++ return path.getAbsolutePath(); ++ } ++ ++ /** ++ * Parse file name ++ * 1. .. = parent dir ++ * 2. ~ = home dir ++ * ++ * ++ * @param name file ++ * @param cwd current working directory ++ * @return file correct file ++ */ ++ public static File getFile(String name, String cwd) { ++ //contains .. ++ if(containParent.matcher(name).matches()) { ++ if(startsWithParent.matcher(name).matches()) { ++ ++ } ++ ++ } ++ else if(name.startsWith(""~"")) { ++ ++ } ++ else ++ return new File(name); ++ ++ return null; ++ } ++ ++ public static void saveFile(File file, String text, boolean append) throws IOException { ++ if(file.isDirectory()) { ++ throw new IOException(file+"": Is a directory""); ++ } ++ else if(file.isFile()) { ++ FileWriter fileWriter; ++ // append text at the end of the file ++ if(append) ++ fileWriter = new FileWriter(file, true); ++ //overwrite the file ++ else ++ fileWriter = new FileWriter(file, false); ++ ++ fileWriter.write(text); ++ fileWriter.flush(); ++ fileWriter.close(); ++ } ++ else { ++ //create a new file and write to it ++ FileWriter fileWriter = new FileWriter(file, false); ++ fileWriter.write(text); ++ fileWriter.flush(); ++ fileWriter.close(); ++ } ++ } ++} +diff --git a/src/main/java/org/jboss/jreadline/util/Parser.java b/src/main/java/org/jboss/jreadline/util/Parser.java +index 3e3617135..89e88ce53 100644 +--- a/src/main/java/org/jboss/jreadline/util/Parser.java ++++ b/src/main/java/org/jboss/jreadline/util/Parser.java +@@ -136,7 +136,7 @@ public static String findWordClosestToCursor(String text, int cursor) { + return text.trim().substring(text.lastIndexOf("" "")).trim(); + } + else +- return text; ++ return text.trim(); + } + else { + String rest = text.substring(0, cursor+1); +@@ -150,4 +150,19 @@ public static String findWordClosestToCursor(String text, int cursor) { + return rest.trim(); + } + } ++ ++ public static String findWordClosestToCursorDividedByRedirectOrPipe(String text, int cursor) { ++ //1. find all occurrences of pipe/redirect. ++ //2. find position thats closest to cursor. ++ //3. return word closest to it ++ String[] splitText = text.split("">|\\|""); ++ int length = 0; ++ for(String s : splitText) { ++ length += s.length()+1; ++ if(cursor <= length) { ++ return findWordClosestToCursor(s, cursor-(length-s.length())); ++ } ++ } ++ return """"; ++ } + } +diff --git a/src/test/java/org/jboss/jreadline/JReadlineTestCase.java b/src/test/java/org/jboss/jreadline/JReadlineTestCase.java +index 46de3b132..d09512438 100644 +--- a/src/test/java/org/jboss/jreadline/JReadlineTestCase.java ++++ b/src/test/java/org/jboss/jreadline/JReadlineTestCase.java +@@ -19,6 +19,7 @@ + import junit.framework.TestCase; + import org.jboss.jreadline.console.Config; + import org.jboss.jreadline.console.Console; ++import org.jboss.jreadline.console.ConsoleOutput; + import org.jboss.jreadline.console.settings.Settings; + import org.jboss.jreadline.edit.Mode; + import org.jboss.jreadline.terminal.TestTerminal; +@@ -40,7 +41,7 @@ public void assertEquals(String expected, TestBuffer buffer) throws IOException + settings.setReadInputrc(false); + settings.setTerminal(new TestTerminal()); + settings.setInputStream(new ByteArrayInputStream(buffer.getBytes())); +- settings.setOutputStream(new ByteArrayOutputStream()); ++ settings.setStdOut(new ByteArrayOutputStream()); + settings.setEditMode(Mode.EMACS); + settings.resetEditMode(); + settings.setReadAhead(false); +@@ -51,9 +52,9 @@ public void assertEquals(String expected, TestBuffer buffer) throws IOException + + String in = null; + while (true) { +- String tmp = console.read(null); ++ ConsoleOutput tmp = console.read(null); + if(tmp != null) +- in = tmp; ++ in = tmp.getBuffer(); + else + break; + } +@@ -72,7 +73,7 @@ public void assertEqualsViMode(String expected, TestBuffer buffer) throws IOExce + settings.setReadInputrc(false); + settings.setTerminal(new TestTerminal()); + settings.setInputStream(new ByteArrayInputStream(buffer.getBytes())); +- settings.setOutputStream(new ByteArrayOutputStream()); ++ settings.setStdOut(new ByteArrayOutputStream()); + settings.setReadAhead(false); + settings.setEditMode(Mode.VI); + settings.resetEditMode(); +@@ -83,9 +84,9 @@ public void assertEqualsViMode(String expected, TestBuffer buffer) throws IOExce + + String in = null; + while (true) { +- String tmp = console.read(null); ++ ConsoleOutput tmp = console.read(null); + if(tmp != null) +- in = tmp; ++ in = tmp.getBuffer(); + else + break; + } +diff --git a/src/test/java/org/jboss/jreadline/util/ParserTestCase.java b/src/test/java/org/jboss/jreadline/util/ParserTestCase.java +index ad4614d1d..f30edfa82 100644 +--- a/src/test/java/org/jboss/jreadline/util/ParserTestCase.java ++++ b/src/test/java/org/jboss/jreadline/util/ParserTestCase.java +@@ -44,4 +44,17 @@ public void testFindClosestWordToCursor() { + assertEquals("""", Parser.findWordClosestToCursor(""ls org/jboss/jreadlineshell/Shell.class"", 3) ); + } + ++ public void testFindWordClosestToCursorDividedByRedirectOrPipe() { ++ assertEquals(""foo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > foo"", 8)); ++ assertEquals(""foo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls | foo"", 8)); ++ assertEquals(""fo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > foo"", 7)); ++ assertEquals(""fo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls | foo"", 7)); ++ assertEquals(""foo"", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > foo "", 9)); ++ assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > foo "", 10)); ++ assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > "", 5)); ++ assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > "", 6)); ++ assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls > bla > "", 11)); ++ assertEquals("""", Parser.findWordClosestToCursorDividedByRedirectOrPipe(""ls | bla > "", 11)); ++ } ++ + }" +b4a6e4a98e5ca16889391a5db989b151f03ed208,Valadoc,"Add initial reading-support for +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +72ef7746017c1171199683ab682cb9e370720850,robotframework$swinglibrary,"Improved combobox testability +",p,https://github.com/MarketSquare/SwingLibrary,"diff --git a/test-application/src/main/java/org/robotframework/swing/testapp/TestApplication.java b/test-application/src/main/java/org/robotframework/swing/testapp/TestApplication.java +index 2a5b9a7c..91b84d45 100644 +--- a/test-application/src/main/java/org/robotframework/swing/testapp/TestApplication.java ++++ b/test-application/src/main/java/org/robotframework/swing/testapp/TestApplication.java +@@ -97,7 +97,16 @@ public String getText() { + } + }); + }}); +- panel.add(new ContentChangingCombobox()); ++ final ContentChangingCombobox contentChangingComboBox = new ContentChangingCombobox(); ++ panel.add(new JButton(""Reset Content Changing Combobox"") {{ ++ setName(""resetContentChangingComboBox""); ++ addActionListener(new ActionListener() { ++ public void actionPerformed(ActionEvent e) { ++ contentChangingComboBox.resetModel(); ++ } ++ }); ++ }}); ++ panel.add(contentChangingComboBox); + panel.add(new TestLabel()); + panel.add(new TestTable(""testTable"", getTestTableData())); + panel.add(new TestTable(""anotherTable"", getTestTableData())); +@@ -147,11 +156,14 @@ private Object[][] getFoobarTestTableData() { + + class ContentChangingCombobox extends JComboBox implements ActionListener { + ++ private static final String REMOVABLE_ITEM = ""Removable""; ++ private static final String[] ITEMS = new String[]{""Foo"", ""Bar"", ""Quux"", REMOVABLE_ITEM}; ++ + public ContentChangingCombobox() { + setEditable(true); + setName(""contentChangingCombobox""); + addActionListener(this); +- setModel(new DefaultComboBoxModel(new String[]{""Foo"", ""Bar"", ""Quux""})); ++ setModel(new DefaultComboBoxModel(ITEMS)); + } + + @Override +@@ -159,7 +171,8 @@ public void actionPerformed(ActionEvent event) { + if (event.getActionCommand().equals(""comboBoxChanged"")) { + String selected = (String) getSelectedItem(); + List items = new ArrayList(); +- items.add(selected); ++ if (! selected.equals(REMOVABLE_ITEM)) ++ items.add(selected); + ComboBoxModel model = getModel(); + for (int i=0, size = model.getSize(); i < size; i++) { + String item = (String) model.getElementAt(i); +@@ -169,7 +182,11 @@ public void actionPerformed(ActionEvent event) { + setModel(new DefaultComboBoxModel(items.toArray())); + setSelectedIndex(0); + } +- } ++ } ++ ++ public void resetModel() { ++ setModel(new DefaultComboBoxModel(ITEMS)); ++ } + } + + class PopupPanel extends JPanel {" +cd2f14637bcecec0081104d749cd1bf10f28b07d,ReactiveX-RxJava,Fixed issue -799 - Added break to possibly-infinite- loop in CompositeException.attachCallingThreadStack--,c,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/util/CompositeException.java b/rxjava-core/src/main/java/rx/util/CompositeException.java +index bca5dcfbf7..439b9400b2 100644 +--- a/rxjava-core/src/main/java/rx/util/CompositeException.java ++++ b/rxjava-core/src/main/java/rx/util/CompositeException.java +@@ -18,7 +18,9 @@ + import java.util.ArrayList; + import java.util.Collection; + import java.util.Collections; ++import java.util.HashSet; + import java.util.List; ++import java.util.Set; + + /** + * Exception that is a composite of 1 or more other exceptions. +@@ -84,9 +86,16 @@ private static String getStackTraceAsString(StackTraceElement[] stack) { + return s.toString(); + } + +- private static void attachCallingThreadStack(Throwable e, Throwable cause) { ++ /* package-private */ static void attachCallingThreadStack(Throwable e, Throwable cause) { ++ Set seenCauses = new HashSet(); ++ + while (e.getCause() != null) { + e = e.getCause(); ++ if (seenCauses.contains(e.getCause())) { ++ break; ++ } else { ++ seenCauses.add(e.getCause()); ++ } + } + // we now have 'e' as the last in the chain + try { +@@ -98,12 +107,13 @@ private static void attachCallingThreadStack(Throwable e, Throwable cause) { + } + } + +- private final static class CompositeExceptionCausalChain extends RuntimeException { ++ /* package-private */ final static class CompositeExceptionCausalChain extends RuntimeException { + private static final long serialVersionUID = 3875212506787802066L; ++ /* package-private */ static String MESSAGE = ""Chain of Causes for CompositeException In Order Received =>""; + + @Override + public String getMessage() { +- return ""Chain of Causes for CompositeException In Order Received =>""; ++ return MESSAGE; + } + } + +diff --git a/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java b/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java +new file mode 100644 +index 0000000000..0e80cf0309 +--- /dev/null ++++ b/rxjava-core/src/test/java/rx/util/CompositeExceptionTest.java +@@ -0,0 +1,70 @@ ++/** ++ * Copyright 2013 Netflix, Inc. ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package rx.util; ++ ++import static org.junit.Assert.*; ++ ++import org.junit.Test; ++ ++import java.util.ArrayList; ++import java.util.List; ++ ++public class CompositeExceptionTest { ++ ++ private final Throwable ex1 = new Throwable(""Ex1""); ++ private final Throwable ex2 = new Throwable(""Ex2"", ex1); ++ private final Throwable ex3 = new Throwable(""Ex3"", ex2); ++ ++ private final CompositeException compositeEx; ++ ++ public CompositeExceptionTest() { ++ List throwables = new ArrayList(); ++ throwables.add(ex1); ++ throwables.add(ex2); ++ throwables.add(ex3); ++ compositeEx = new CompositeException(throwables); ++ } ++ ++ @Test ++ public void testAttachCallingThreadStackParentThenChild() { ++ CompositeException.attachCallingThreadStack(ex1, ex2); ++ assertEquals(""Ex2"", ex1.getCause().getMessage()); ++ } ++ ++ @Test ++ public void testAttachCallingThreadStackChildThenParent() { ++ CompositeException.attachCallingThreadStack(ex2, ex1); ++ assertEquals(""Ex1"", ex2.getCause().getMessage()); ++ } ++ ++ @Test ++ public void testAttachCallingThreadStackAddComposite() { ++ CompositeException.attachCallingThreadStack(ex1, compositeEx); ++ assertEquals(""Ex2"", ex1.getCause().getMessage()); ++ } ++ ++ @Test ++ public void testAttachCallingThreadStackAddToComposite() { ++ CompositeException.attachCallingThreadStack(compositeEx, ex1); ++ assertEquals(CompositeException.CompositeExceptionCausalChain.MESSAGE, compositeEx.getCause().getMessage()); ++ } ++ ++ @Test ++ public void testAttachCallingThreadStackAddCompositeToItself() { ++ CompositeException.attachCallingThreadStack(compositeEx, compositeEx); ++ assertEquals(CompositeException.CompositeExceptionCausalChain.MESSAGE, compositeEx.getCause().getMessage()); ++ } ++} +\ No newline at end of file" +01ff1c8a77ed63405af637be35318ee693dcd1c5,restlet-framework-java, - Deprecated ServletConverter and added an- equivalent ServletAdapter class to prevent confusion with the - ConverterService reintroduced in Restlet 1.2. - Added root Helper class.--,p,https://github.com/restlet/restlet-framework-java,"diff --git a/build/tmpl/text/changes.txt b/build/tmpl/text/changes.txt +index 1a4dc4b5ff..3bdf989f0d 100644 +--- a/build/tmpl/text/changes.txt ++++ b/build/tmpl/text/changes.txt +@@ -5,7 +5,9 @@ Changes log + + - @version-full@ (@release-date@) + - Breaking changes +- - ++ - Deprecated ServletConverter and added an equivalent ++ ServletAdapter class to prevent confusion with the ++ ConverterService reintroduced in Restlet 1.2. + - Bugs fixed + - Fixed bug with a ServerResource when an annotated method does + not return a value. +diff --git a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java +index 4a32217c8d..6accbacefd 100644 +--- a/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java ++++ b/modules/org.restlet.ext.jaxrs/src/org/restlet/ext/jaxrs/internal/util/Util.java +@@ -78,8 +78,8 @@ + import org.restlet.data.Response; + import org.restlet.engine.http.ContentType; + import org.restlet.engine.http.HttpClientCall; +-import org.restlet.engine.http.HttpClientConverter; +-import org.restlet.engine.http.HttpServerConverter; ++import org.restlet.engine.http.HttpClientAdapter; ++import org.restlet.engine.http.HttpServerAdapter; + import org.restlet.engine.http.HttpUtils; + import org.restlet.engine.util.DateUtils; + import org.restlet.ext.jaxrs.internal.core.UnmodifiableMultivaluedMap; +@@ -306,7 +306,7 @@ public static void copyResponseHeaders( + restletResponse.setEntity(new EmptyRepresentation()); + } + +- HttpClientConverter.copyResponseTransportHeaders(headers, ++ HttpClientAdapter.copyResponseTransportHeaders(headers, + restletResponse); + HttpClientCall.copyResponseEntityHeaders(headers, restletResponse + .getEntity()); +@@ -324,8 +324,8 @@ public static void copyResponseHeaders( + */ + public static Series copyResponseHeaders(Response restletResponse) { + final Series headers = new Form(); +- HttpServerConverter.addResponseHeaders(restletResponse, headers); +- HttpServerConverter.addEntityHeaders(restletResponse.getEntity(), ++ HttpServerAdapter.addResponseHeaders(restletResponse, headers); ++ HttpServerAdapter.addEntityHeaders(restletResponse.getEntity(), + headers); + return headers; + } +diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java +new file mode 100644 +index 0000000000..48ac006096 +--- /dev/null ++++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletAdapter.java +@@ -0,0 +1,243 @@ ++/** ++ * Copyright 2005-2009 Noelios Technologies. ++ * ++ * The contents of this file are subject to the terms of one of the following ++ * open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the ++ * ""Licenses""). You can select the license that you prefer but you may not use ++ * this file except in compliance with one of these Licenses. ++ * ++ * You can obtain a copy of the LGPL 3.0 license at ++ * http://www.opensource.org/licenses/lgpl-3.0.html ++ * ++ * You can obtain a copy of the LGPL 2.1 license at ++ * http://www.opensource.org/licenses/lgpl-2.1.php ++ * ++ * You can obtain a copy of the CDDL 1.0 license at ++ * http://www.opensource.org/licenses/cddl1.php ++ * ++ * You can obtain a copy of the EPL 1.0 license at ++ * http://www.opensource.org/licenses/eclipse-1.0.php ++ * ++ * See the Licenses for the specific language governing permissions and ++ * limitations under the Licenses. ++ * ++ * Alternatively, you can obtain a royalty free commercial license with less ++ * limitations, transferable or non-transferable, directly at ++ * http://www.noelios.com/products/restlet-engine ++ * ++ * Restlet is a registered trademark of Noelios Technologies. ++ */ ++ ++package org.restlet.ext.servlet; ++ ++import java.io.IOException; ++import java.util.Enumeration; ++ ++import javax.servlet.ServletContext; ++import javax.servlet.ServletException; ++import javax.servlet.http.HttpServletRequest; ++import javax.servlet.http.HttpServletResponse; ++ ++import org.restlet.Context; ++import org.restlet.Restlet; ++import org.restlet.data.Reference; ++import org.restlet.engine.http.HttpRequest; ++import org.restlet.engine.http.HttpResponse; ++import org.restlet.engine.http.HttpServerAdapter; ++import org.restlet.ext.servlet.internal.ServletCall; ++import org.restlet.ext.servlet.internal.ServletLogger; ++ ++/** ++ * HTTP adapter from Servlet calls to Restlet calls. This class can be used in ++ * any Servlet, just create a new instance and override the service() method in ++ * your Servlet to delegate all those calls to this class's service() method. ++ * Remember to set the target Restlet, for example using a Restlet Router ++ * instance. You can get the Restlet context directly on instances of this ++ * class, it will be based on the parent Servlet's context for logging purpose.
    ++ *
    ++ * This class is especially useful when directly integrating Restlets with ++ * Spring managed Web applications. Here is a simple usage example: ++ * ++ *

    ++ * public class TestServlet extends HttpServlet {
    ++ *     private ServletAdapter adapter;
    ++ * 
    ++ *     public void init() throws ServletException {
    ++ *         super.init();
    ++ *         this.adapter = new ServletAdapter(getServletContext());
    ++ * 
    ++ *         Restlet trace = new Restlet(this.adapter.getContext()) {
    ++ *             public void handle(Request req, Response res) {
    ++ *                 getLogger().info("Hello World");
    ++ *                 res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
    ++ *             }
    ++ *         };
    ++ * 
    ++ *         this.adapter.setTarget(trace);
    ++ *     }
    ++ * 
    ++ *     protected void service(HttpServletRequest req, HttpServletResponse res)
    ++ *             throws ServletException, IOException {
    ++ *         this.adapter.service(req, res);
    ++ *     }
    ++ * }
    ++ * 
    ++ * ++ * @author Jerome Louvel ++ */ ++public class ServletAdapter extends HttpServerAdapter { ++ /** The target Restlet. */ ++ private volatile Restlet target; ++ ++ /** ++ * Constructor. Remember to manually set the ""target"" property before ++ * invoking the service() method. ++ * ++ * @param context ++ * The Servlet context. ++ */ ++ public ServletAdapter(ServletContext context) { ++ this(context, null); ++ } ++ ++ /** ++ * Constructor. ++ * ++ * @param context ++ * The Servlet context. ++ * @param target ++ * The target Restlet. ++ */ ++ public ServletAdapter(ServletContext context, Restlet target) { ++ super(new Context(new ServletLogger(context))); ++ this.target = target; ++ } ++ ++ /** ++ * Returns the base reference of new Restlet requests. ++ * ++ * @param request ++ * The Servlet request. ++ * @return The base reference of new Restlet requests. ++ */ ++ public Reference getBaseRef(HttpServletRequest request) { ++ Reference result = null; ++ final String basePath = request.getContextPath() ++ + request.getServletPath(); ++ final String baseUri = request.getRequestURL().toString(); ++ // Path starts at first slash after scheme:// ++ final int pathStart = baseUri.indexOf(""/"", ++ request.getScheme().length() + 3); ++ if (basePath.length() == 0) { ++ // basePath is empty in case the webapp is mounted on root context ++ if (pathStart != -1) { ++ result = new Reference(baseUri.substring(0, pathStart)); ++ } else { ++ result = new Reference(baseUri); ++ } ++ } else { ++ if (pathStart != -1) { ++ final int baseIndex = baseUri.indexOf(basePath, pathStart); ++ if (baseIndex != -1) { ++ result = new Reference(baseUri.substring(0, baseIndex ++ + basePath.length())); ++ } ++ } ++ } ++ ++ return result; ++ } ++ ++ /** ++ * Returns the root reference of new Restlet requests. By default it returns ++ * the result of getBaseRef(). ++ * ++ * @param request ++ * The Servlet request. ++ * @return The root reference of new Restlet requests. ++ */ ++ public Reference getRootRef(HttpServletRequest request) { ++ return getBaseRef(request); ++ } ++ ++ /** ++ * Returns the target Restlet. ++ * ++ * @return The target Restlet. ++ */ ++ public Restlet getTarget() { ++ return this.target; ++ } ++ ++ /** ++ * Services a HTTP Servlet request as a Restlet request handled by the ++ * ""target"" Restlet. ++ * ++ * @param request ++ * The HTTP Servlet request. ++ * @param response ++ * The HTTP Servlet response. ++ */ ++ public void service(HttpServletRequest request, HttpServletResponse response) ++ throws ServletException, IOException { ++ if (getTarget() != null) { ++ // Set the current context ++ Context.setCurrent(getContext()); ++ ++ // Convert the Servlet call to a Restlet call ++ final ServletCall servletCall = new ServletCall(request ++ .getLocalAddr(), request.getLocalPort(), request, response); ++ final HttpRequest httpRequest = toRequest(servletCall); ++ final HttpResponse httpResponse = new HttpResponse(servletCall, ++ httpRequest); ++ ++ // Adjust the relative reference ++ httpRequest.getResourceRef().setBaseRef(getBaseRef(request)); ++ ++ // Adjust the root reference ++ httpRequest.setRootRef(getRootRef(request)); ++ ++ // Handle the request and commit the response ++ getTarget().handle(httpRequest, httpResponse); ++ commit(httpResponse); ++ } else { ++ getLogger().warning(""Unable to find the Restlet target""); ++ } ++ } ++ ++ /** ++ * Sets the target Restlet. ++ * ++ * @param target ++ * The target Restlet. ++ */ ++ public void setTarget(Restlet target) { ++ this.target = target; ++ } ++ ++ /** ++ * Converts a low-level Servlet call into a high-level Restlet request. In ++ * addition to the parent {@link HttpServerAdapter}, it also copies the ++ * Servlet's request attributes into the Restlet's request attributes map. ++ * ++ * @param servletCall ++ * The low-level Servlet call. ++ * @return A new high-level uniform request. ++ */ ++ @SuppressWarnings(""unchecked"") ++ public HttpRequest toRequest(ServletCall servletCall) { ++ final HttpRequest result = super.toRequest(servletCall); ++ ++ // Copy all Servlet's request attributes ++ String attributeName; ++ for (final Enumeration namesEnum = servletCall.getRequest() ++ .getAttributeNames(); namesEnum.hasMoreElements();) { ++ attributeName = namesEnum.nextElement(); ++ result.getAttributes().put(attributeName, ++ servletCall.getRequest().getAttribute(attributeName)); ++ } ++ ++ return result; ++ } ++ ++} +diff --git a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java +index 407e52a214..cf5c0a7918 100644 +--- a/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java ++++ b/modules/org.restlet.ext.servlet/src/org/restlet/ext/servlet/ServletConverter.java +@@ -43,7 +43,7 @@ + import org.restlet.data.Reference; + import org.restlet.engine.http.HttpRequest; + import org.restlet.engine.http.HttpResponse; +-import org.restlet.engine.http.HttpServerConverter; ++import org.restlet.engine.http.HttpServerAdapter; + import org.restlet.ext.servlet.internal.ServletCall; + import org.restlet.ext.servlet.internal.ServletLogger; + +@@ -60,184 +60,186 @@ + * + *
    +  * public class TestServlet extends HttpServlet {
    +- * 	private ServletConverter converter;
    ++ *     private ServletConverter converter;
    +  * 
    +- * 	public void init() throws ServletException {
    +- * 		super.init();
    +- * 		this.converter = new ServletConverter(getServletContext());
    ++ *     public void init() throws ServletException {
    ++ *         super.init();
    ++ *         this.converter = new ServletConverter(getServletContext());
    +  * 
    +- * 		Restlet trace = new Restlet(this.converter.getContext()) {
    +- * 			public void handle(Request req, Response res) {
    +- * 				getLogger().info("Hello World");
    +- * 				res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
    +- * 			}
    +- * 		};
    ++ *         Restlet trace = new Restlet(this.converter.getContext()) {
    ++ *             public void handle(Request req, Response res) {
    ++ *                 getLogger().info("Hello World");
    ++ *                 res.setEntity("Hello World!", MediaType.TEXT_PLAIN);
    ++ *             }
    ++ *         };
    +  * 
    +- * 		this.converter.setTarget(trace);
    +- * 	}
    ++ *         this.converter.setTarget(trace);
    ++ *     }
    +  * 
    +- * 	protected void service(HttpServletRequest req, HttpServletResponse res)
    +- * 			throws ServletException, IOException {
    +- * 		this.converter.service(req, res);
    +- * 	}
    ++ *     protected void service(HttpServletRequest req, HttpServletResponse res)
    ++ *             throws ServletException, IOException {
    ++ *         this.converter.service(req, res);
    ++ *     }
    +  * }
    +  * 
    + * + * @author Jerome Louvel ++ * @deprecated Use {@link ServletAdapter} instead. + */ +-public class ServletConverter extends HttpServerConverter { +- /** The target Restlet. */ +- private volatile Restlet target; +- +- /** +- * Constructor. Remember to manually set the ""target"" property before +- * invoking the service() method. +- * +- * @param context +- * The Servlet context. +- */ +- public ServletConverter(ServletContext context) { +- this(context, null); +- } +- +- /** +- * Constructor. +- * +- * @param context +- * The Servlet context. +- * @param target +- * The target Restlet. +- */ +- public ServletConverter(ServletContext context, Restlet target) { +- super(new Context(new ServletLogger(context))); +- this.target = target; +- } +- +- /** +- * Returns the base reference of new Restlet requests. +- * +- * @param request +- * The Servlet request. +- * @return The base reference of new Restlet requests. +- */ +- public Reference getBaseRef(HttpServletRequest request) { +- Reference result = null; +- final String basePath = request.getContextPath() +- + request.getServletPath(); +- final String baseUri = request.getRequestURL().toString(); +- // Path starts at first slash after scheme:// +- final int pathStart = baseUri.indexOf(""/"", +- request.getScheme().length() + 3); +- if (basePath.length() == 0) { +- // basePath is empty in case the webapp is mounted on root context +- if (pathStart != -1) { +- result = new Reference(baseUri.substring(0, pathStart)); +- } else { +- result = new Reference(baseUri); +- } +- } else { +- if (pathStart != -1) { +- final int baseIndex = baseUri.indexOf(basePath, pathStart); +- if (baseIndex != -1) { +- result = new Reference(baseUri.substring(0, baseIndex +- + basePath.length())); +- } +- } +- } +- +- return result; +- } +- +- /** +- * Returns the root reference of new Restlet requests. By default it returns +- * the result of getBaseRef(). +- * +- * @param request +- * The Servlet request. +- * @return The root reference of new Restlet requests. +- */ +- public Reference getRootRef(HttpServletRequest request) { +- return getBaseRef(request); +- } +- +- /** +- * Returns the target Restlet. +- * +- * @return The target Restlet. +- */ +- public Restlet getTarget() { +- return this.target; +- } +- +- /** +- * Services a HTTP Servlet request as a Restlet request handled by the +- * ""target"" Restlet. +- * +- * @param request +- * The HTTP Servlet request. +- * @param response +- * The HTTP Servlet response. +- */ +- public void service(HttpServletRequest request, HttpServletResponse response) +- throws ServletException, IOException { +- if (getTarget() != null) { +- // Set the current context +- Context.setCurrent(getContext()); +- +- // Convert the Servlet call to a Restlet call +- final ServletCall servletCall = new ServletCall(request +- .getLocalAddr(), request.getLocalPort(), request, response); +- final HttpRequest httpRequest = toRequest(servletCall); +- final HttpResponse httpResponse = new HttpResponse(servletCall, +- httpRequest); +- +- // Adjust the relative reference +- httpRequest.getResourceRef().setBaseRef(getBaseRef(request)); +- +- // Adjust the root reference +- httpRequest.setRootRef(getRootRef(request)); +- +- // Handle the request and commit the response +- getTarget().handle(httpRequest, httpResponse); +- commit(httpResponse); +- } else { +- getLogger().warning(""Unable to find the Restlet target""); +- } +- } +- +- /** +- * Sets the target Restlet. +- * +- * @param target +- * The target Restlet. +- */ +- public void setTarget(Restlet target) { +- this.target = target; +- } +- +- /** +- * Converts a low-level Servlet call into a high-level Restlet request. In +- * addition to the parent HttpServerConverter class, it also copies the +- * Servlet's request attributes into the Restlet's request attributes map. +- * +- * @param servletCall +- * The low-level Servlet call. +- * @return A new high-level uniform request. +- */ +- @SuppressWarnings(""unchecked"") +- public HttpRequest toRequest(ServletCall servletCall) { +- final HttpRequest result = super.toRequest(servletCall); +- +- // Copy all Servlet's request attributes +- String attributeName; +- for (final Enumeration namesEnum = servletCall.getRequest() +- .getAttributeNames(); namesEnum.hasMoreElements();) { +- attributeName = namesEnum.nextElement(); +- result.getAttributes().put(attributeName, +- servletCall.getRequest().getAttribute(attributeName)); +- } +- +- return result; +- } ++@Deprecated ++public class ServletConverter extends HttpServerAdapter { ++ /** The target Restlet. */ ++ private volatile Restlet target; ++ ++ /** ++ * Constructor. Remember to manually set the ""target"" property before ++ * invoking the service() method. ++ * ++ * @param context ++ * The Servlet context. ++ */ ++ public ServletConverter(ServletContext context) { ++ this(context, null); ++ } ++ ++ /** ++ * Constructor. ++ * ++ * @param context ++ * The Servlet context. ++ * @param target ++ * The target Restlet. ++ */ ++ public ServletConverter(ServletContext context, Restlet target) { ++ super(new Context(new ServletLogger(context))); ++ this.target = target; ++ } ++ ++ /** ++ * Returns the base reference of new Restlet requests. ++ * ++ * @param request ++ * The Servlet request. ++ * @return The base reference of new Restlet requests. ++ */ ++ public Reference getBaseRef(HttpServletRequest request) { ++ Reference result = null; ++ final String basePath = request.getContextPath() ++ + request.getServletPath(); ++ final String baseUri = request.getRequestURL().toString(); ++ // Path starts at first slash after scheme:// ++ final int pathStart = baseUri.indexOf(""/"", ++ request.getScheme().length() + 3); ++ if (basePath.length() == 0) { ++ // basePath is empty in case the webapp is mounted on root context ++ if (pathStart != -1) { ++ result = new Reference(baseUri.substring(0, pathStart)); ++ } else { ++ result = new Reference(baseUri); ++ } ++ } else { ++ if (pathStart != -1) { ++ final int baseIndex = baseUri.indexOf(basePath, pathStart); ++ if (baseIndex != -1) { ++ result = new Reference(baseUri.substring(0, baseIndex ++ + basePath.length())); ++ } ++ } ++ } ++ ++ return result; ++ } ++ ++ /** ++ * Returns the root reference of new Restlet requests. By default it returns ++ * the result of getBaseRef(). ++ * ++ * @param request ++ * The Servlet request. ++ * @return The root reference of new Restlet requests. ++ */ ++ public Reference getRootRef(HttpServletRequest request) { ++ return getBaseRef(request); ++ } ++ ++ /** ++ * Returns the target Restlet. ++ * ++ * @return The target Restlet. ++ */ ++ public Restlet getTarget() { ++ return this.target; ++ } ++ ++ /** ++ * Services a HTTP Servlet request as a Restlet request handled by the ++ * ""target"" Restlet. ++ * ++ * @param request ++ * The HTTP Servlet request. ++ * @param response ++ * The HTTP Servlet response. ++ */ ++ public void service(HttpServletRequest request, HttpServletResponse response) ++ throws ServletException, IOException { ++ if (getTarget() != null) { ++ // Set the current context ++ Context.setCurrent(getContext()); ++ ++ // Convert the Servlet call to a Restlet call ++ final ServletCall servletCall = new ServletCall(request ++ .getLocalAddr(), request.getLocalPort(), request, response); ++ final HttpRequest httpRequest = toRequest(servletCall); ++ final HttpResponse httpResponse = new HttpResponse(servletCall, ++ httpRequest); ++ ++ // Adjust the relative reference ++ httpRequest.getResourceRef().setBaseRef(getBaseRef(request)); ++ ++ // Adjust the root reference ++ httpRequest.setRootRef(getRootRef(request)); ++ ++ // Handle the request and commit the response ++ getTarget().handle(httpRequest, httpResponse); ++ commit(httpResponse); ++ } else { ++ getLogger().warning(""Unable to find the Restlet target""); ++ } ++ } ++ ++ /** ++ * Sets the target Restlet. ++ * ++ * @param target ++ * The target Restlet. ++ */ ++ public void setTarget(Restlet target) { ++ this.target = target; ++ } ++ ++ /** ++ * Converts a low-level Servlet call into a high-level Restlet request. In ++ * addition to the parent HttpServerConverter class, it also copies the ++ * Servlet's request attributes into the Restlet's request attributes map. ++ * ++ * @param servletCall ++ * The low-level Servlet call. ++ * @return A new high-level uniform request. ++ */ ++ @SuppressWarnings(""unchecked"") ++ public HttpRequest toRequest(ServletCall servletCall) { ++ final HttpRequest result = super.toRequest(servletCall); ++ ++ // Copy all Servlet's request attributes ++ String attributeName; ++ for (final Enumeration namesEnum = servletCall.getRequest() ++ .getAttributeNames(); namesEnum.hasMoreElements();) { ++ attributeName = namesEnum.nextElement(); ++ result.getAttributes().put(attributeName, ++ servletCall.getRequest().getAttribute(attributeName)); ++ } ++ ++ return result; ++ } + + } +diff --git a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java +index c5647a2625..12824a3b0d 100644 +--- a/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java ++++ b/modules/org.restlet.ext.spring/src/org/restlet/ext/spring/RestletFrameworkServlet.java +@@ -39,11 +39,10 @@ + import org.restlet.Application; + import org.restlet.Context; + import org.restlet.Restlet; +-import org.restlet.ext.servlet.ServletConverter; ++import org.restlet.ext.servlet.ServletAdapter; + import org.springframework.beans.BeansException; + import org.springframework.web.servlet.FrameworkServlet; + +- + /** + * A Servlet which provides an automatic Restlet integration with an existing + * {@link org.springframework.web.context.WebApplicationContext}. The usage is +@@ -97,16 +96,53 @@ public class RestletFrameworkServlet extends FrameworkServlet { + + private static final long serialVersionUID = 1L; + +- /** The converter of Servlet calls into Restlet equivalents. */ +- private volatile ServletConverter converter; ++ /** The adapter of Servlet calls into Restlet equivalents. */ ++ private volatile ServletAdapter adapter; + + /** The bean name of the target Restlet. */ + private volatile String targetRestletBeanName; + ++ /** ++ * Creates the Restlet {@link Context} to use if the target application does ++ * not already have a context associated, or if the target restlet is not an ++ * {@link Application} at all. ++ *

    ++ * Uses a simple {@link Context} by default. ++ * ++ * @return A new instance of {@link Context} ++ */ ++ protected Context createContext() { ++ return new Context(); ++ } ++ + @Override + protected void doService(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { +- getConverter().service(request, response); ++ getAdapter().service(request, response); ++ } ++ ++ /** ++ * Provides access to the {@link ServletAdapter} used to handle requests. ++ * Exposed so that subclasses may do additional configuration, if necessary, ++ * by overriding {@link #initFrameworkServlet()}. ++ * ++ * @return The adapter of Servlet calls into Restlet equivalents. ++ */ ++ protected ServletAdapter getAdapter() { ++ return this.adapter; ++ } ++ ++ /** ++ * Provides access to the {@link ServletConverter} used to handle requests. ++ * Exposed so that subclasses may do additional configuration, if necessary, ++ * by overriding {@link #initFrameworkServlet()}. ++ * ++ * @return The converter of Servlet calls into Restlet equivalents. ++ * @deprecated Use {@link #getAdapter()} instead. ++ */ ++ @Deprecated ++ protected ServletAdapter getConverter() { ++ return this.adapter; + } + + /** +@@ -129,22 +165,11 @@ public String getTargetRestletBeanName() { + : this.targetRestletBeanName; + } + +- /** +- * Provides access to the {@link ServletConverter} used to handle requests. +- * Exposed so that subclasses may do additional configuration, if necessary, +- * by overriding {@link #initFrameworkServlet()}. +- * +- * @return The converter of Servlet calls into Restlet equivalents. +- */ +- protected ServletConverter getConverter() { +- return this.converter; +- } +- + @Override + protected void initFrameworkServlet() throws ServletException, + BeansException { + super.initFrameworkServlet(); +- this.converter = new ServletConverter(getServletContext()); ++ this.adapter = new ServletAdapter(getServletContext()); + + org.restlet.Application application; + if (getTargetRestlet() instanceof Application) { +@@ -156,20 +181,7 @@ protected void initFrameworkServlet() throws ServletException, + if (application.getContext() == null) { + application.setContext(createContext()); + } +- this.converter.setTarget(application); +- } +- +- /** +- * Creates the Restlet {@link Context} to use if the target application does +- * not already have a context associated, or if the target restlet is not an +- * {@link Application} at all. +- *

    +- * Uses a simple {@link Context} by default. +- * +- * @return A new instance of {@link Context} +- */ +- protected Context createContext() { +- return new Context(); ++ this.adapter.setTarget(application); + } + + /** +diff --git a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java +index 66dd3da4c5..3c1f5cb406 100644 +--- a/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java ++++ b/modules/org.restlet.ext.xdb/src/org/restlet/ext/xdb/XdbServletConverter.java +@@ -47,7 +47,7 @@ + import org.restlet.data.Reference; + import org.restlet.engine.http.HttpRequest; + import org.restlet.engine.http.HttpResponse; +-import org.restlet.engine.http.HttpServerConverter; ++import org.restlet.engine.http.HttpServerAdapter; + import org.restlet.ext.servlet.internal.ServletLogger; + + +@@ -89,7 +89,7 @@ + * + * @author Marcelo F. Ochoa (mochoa@ieee.org) + */ +-public class XdbServletConverter extends HttpServerConverter { ++public class XdbServletConverter extends HttpServerAdapter { + /** The target Restlet. */ + private volatile Restlet target; + +diff --git a/modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java b/modules/org.restlet/src/org/restlet/engine/Helper.java +similarity index 56% +rename from modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java +rename to modules/org.restlet/src/org/restlet/engine/Helper.java +index ae2463059e..493f28593c 100644 +--- a/modules/org.restlet/src/org/restlet/engine/converter/RepresentationConverter.java ++++ b/modules/org.restlet/src/org/restlet/engine/Helper.java +@@ -28,41 +28,13 @@ + * Restlet is a registered trademark of Noelios Technologies. + */ + +-package org.restlet.engine.converter; +- +-import java.util.List; +- +-import org.restlet.representation.Representation; +-import org.restlet.representation.Variant; +-import org.restlet.resource.UniformResource; ++package org.restlet.engine; + + /** +- * Converter between the DOM API and Representation classes. ++ * Abstract marker class parent of all engine helpers. + * + * @author Jerome Louvel + */ +-public class RepresentationConverter extends ConverterHelper { +- +- @Override +- public List> getObjectClasses(Variant variant) { +- return null; +- } +- +- @Override +- public List getVariants(Class objectClass) { +- return null; +- } +- +- @Override +- public T toObject(Representation representation, Class targetClass, +- UniformResource resource) { +- return null; +- } +- +- @Override +- public Representation toRepresentation(Object object, +- Variant targetVariant, UniformResource resource) { +- return null; +- } ++public abstract class Helper { + + } +diff --git a/modules/org.restlet/src/org/restlet/engine/RestletHelper.java b/modules/org.restlet/src/org/restlet/engine/RestletHelper.java +index 687905d4c6..b7946d1497 100644 +--- a/modules/org.restlet/src/org/restlet/engine/RestletHelper.java ++++ b/modules/org.restlet/src/org/restlet/engine/RestletHelper.java +@@ -48,7 +48,7 @@ + * + * @author Jerome Louvel + */ +-public abstract class RestletHelper { ++public abstract class RestletHelper extends Helper { + + /** + * The map of attributes exchanged between the API and the Engine via this +diff --git a/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java b/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java +index 9713868eb3..425a80ebcb 100644 +--- a/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java ++++ b/modules/org.restlet/src/org/restlet/engine/converter/ConverterHelper.java +@@ -34,6 +34,7 @@ + import java.util.ArrayList; + import java.util.List; + ++import org.restlet.engine.Helper; + import org.restlet.representation.Representation; + import org.restlet.representation.Variant; + import org.restlet.resource.UniformResource; +@@ -43,7 +44,7 @@ + * + * @author Jerome Louvel + */ +-public abstract class ConverterHelper { ++public abstract class ConverterHelper extends Helper { + + /** + * Adds an object class to the given list. Creates a new list if necessary. +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java +similarity index 99% +rename from modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java +rename to modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java +index c9829e1a4e..77358036f4 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpConverter.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpAdapter.java +@@ -41,7 +41,7 @@ + * + * @author Jerome Louvel + */ +-public class HttpConverter { ++public class HttpAdapter { + /** The context. */ + private volatile Context context; + +@@ -51,7 +51,7 @@ public class HttpConverter { + * @param context + * The context to use. + */ +- public HttpConverter(Context context) { ++ public HttpAdapter(Context context) { + this.context = context; + } + +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java +similarity index 99% +rename from modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java +rename to modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java +index 734bbe09a8..9931682e53 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientConverter.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientAdapter.java +@@ -60,7 +60,7 @@ + * + * @author Jerome Louvel + */ +-public class HttpClientConverter extends HttpConverter { ++public class HttpClientAdapter extends HttpAdapter { + /** + * Copies headers into a response. + * +@@ -150,7 +150,7 @@ public static void copyResponseTransportHeaders( + * @param context + * The context to use. + */ +- public HttpClientConverter(Context context) { ++ public HttpClientAdapter(Context context) { + super(context); + } + +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java +index 06cf1278b3..7bf3df5ebd 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientCall.java +@@ -76,7 +76,7 @@ public abstract class HttpClientCall extends HttpCall { + * if no representation has been provided and the response has not + * sent any entity header. + * @throws NumberFormatException +- * @see HttpClientConverter#copyResponseTransportHeaders(Iterable, Response) ++ * @see HttpClientAdapter#copyResponseTransportHeaders(Iterable, Response) + */ + public static Representation copyResponseEntityHeaders( + Iterable responseHeaders, Representation representation) +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java +index 1e8d886ce5..24a6864a32 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpClientHelper.java +@@ -52,7 +52,7 @@ + * + * converter + * String +- * org.restlet.engine.http.HttpClientConverter ++ * org.restlet.engine.http.HttpClientAdapter + * Class name of the converter of low-level HTTP calls into high level + * requests and responses. + * +@@ -62,7 +62,7 @@ + */ + public abstract class HttpClientHelper extends ClientHelper { + /** The converter from uniform calls to HTTP calls. */ +- private volatile HttpClientConverter converter; ++ private volatile HttpClientAdapter converter; + + /** + * Constructor. +@@ -89,13 +89,12 @@ public HttpClientHelper(Client client) { + * + * @return the converter from uniform calls to HTTP calls. + */ +- public HttpClientConverter getConverter() throws Exception { ++ public HttpClientAdapter getConverter() throws Exception { + if (this.converter == null) { + final String converterClass = getHelpedParameters().getFirstValue( +- ""converter"", ""org.restlet.engine.http.HttpClientConverter""); +- this.converter = (HttpClientConverter) Class +- .forName(converterClass).getConstructor(Context.class) +- .newInstance(getContext()); ++ ""converter"", ""org.restlet.engine.http.HttpClientAdapter""); ++ this.converter = (HttpClientAdapter) Class.forName(converterClass) ++ .getConstructor(Context.class).newInstance(getContext()); + } + + return this.converter; +@@ -120,7 +119,7 @@ public void handle(Request request, Response response) { + * @param converter + * The converter to set. + */ +- public void setConverter(HttpClientConverter converter) { ++ public void setConverter(HttpClientAdapter converter) { + this.converter = converter; + } + } +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java +similarity index 99% +rename from modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java +rename to modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java +index 279f45bb48..7807170363 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerConverter.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerAdapter.java +@@ -59,7 +59,7 @@ + * + * @author Jerome Louvel + */ +-public class HttpServerConverter extends HttpConverter { ++public class HttpServerAdapter extends HttpAdapter { + /** + * Copies the entity headers from the {@link Representation} to the + * {@link Series}. +@@ -267,7 +267,7 @@ public static void addResponseHeaders(Response response, + * @param context + * The client context. + */ +- public HttpServerConverter(Context context) { ++ public HttpServerAdapter(Context context) { + super(context); + } + +diff --git a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java +index dbc15c966a..ad23a92851 100644 +--- a/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java ++++ b/modules/org.restlet/src/org/restlet/engine/http/HttpServerHelper.java +@@ -61,7 +61,7 @@ + * + * converter + * String +- * org.restlet.engine.http.HttpServerConverter ++ * org.restlet.engine.http.HttpServerAdapter + * Class name of the converter of low-level HTTP calls into high level + * requests and responses. + * +@@ -71,7 +71,7 @@ + */ + public class HttpServerHelper extends ServerHelper { + /** The converter from HTTP calls to uniform calls. */ +- private volatile HttpServerConverter converter; ++ private volatile HttpServerAdapter converter; + + /** + * Default constructor. Note that many methods assume that a non-null server +@@ -98,13 +98,13 @@ public HttpServerHelper(Server server) { + * + * @return the converter from HTTP calls to uniform calls. + */ +- public HttpServerConverter getConverter() { ++ public HttpServerAdapter getConverter() { + if (this.converter == null) { + try { + final String converterClass = getHelpedParameters() + .getFirstValue(""converter"", +- ""org.restlet.engine.http.HttpServerConverter""); +- this.converter = (HttpServerConverter) Engine.loadClass( ++ ""org.restlet.engine.http.HttpServerAdapter""); ++ this.converter = (HttpServerAdapter) Engine.loadClass( + converterClass).getConstructor(Context.class) + .newInstance(getContext()); + } catch (IllegalArgumentException e) { +@@ -163,7 +163,7 @@ public void handle(HttpServerCall httpCall) { + * @param converter + * The converter to set. + */ +- public void setConverter(HttpServerConverter converter) { ++ public void setConverter(HttpServerAdapter converter) { + this.converter = converter; + } + } +diff --git a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java +index 49cb48fddc..d0eb2c05df 100644 +--- a/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java ++++ b/modules/org.restlet/src/org/restlet/engine/security/AuthenticatorHelper.java +@@ -40,6 +40,7 @@ + import org.restlet.data.Request; + import org.restlet.data.Response; + import org.restlet.data.Status; ++import org.restlet.engine.Helper; + import org.restlet.security.Guard; + import org.restlet.util.Series; + +@@ -48,243 +49,243 @@ + * + * @author Jerome Louvel + */ +-public abstract class AuthenticatorHelper { ++public abstract class AuthenticatorHelper extends Helper { + +- /** The supported challenge scheme. */ +- private volatile ChallengeScheme challengeScheme; ++ /** The supported challenge scheme. */ ++ private volatile ChallengeScheme challengeScheme; + +- /** Indicates if client side authentication is supported. */ +- private volatile boolean clientSide; ++ /** Indicates if client side authentication is supported. */ ++ private volatile boolean clientSide; + +- /** Indicates if server side authentication is supported. */ +- private volatile boolean serverSide; ++ /** Indicates if server side authentication is supported. */ ++ private volatile boolean serverSide; + +- /** +- * Constructor. +- * +- * @param challengeScheme +- * The supported challenge scheme. +- * @param clientSide +- * Indicates if client side authentication is supported. +- * @param serverSide +- * Indicates if server side authentication is supported. +- */ +- public AuthenticatorHelper(ChallengeScheme challengeScheme, +- boolean clientSide, boolean serverSide) { +- this.challengeScheme = challengeScheme; +- this.clientSide = clientSide; +- this.serverSide = serverSide; +- } ++ /** ++ * Constructor. ++ * ++ * @param challengeScheme ++ * The supported challenge scheme. ++ * @param clientSide ++ * Indicates if client side authentication is supported. ++ * @param serverSide ++ * Indicates if server side authentication is supported. ++ */ ++ public AuthenticatorHelper(ChallengeScheme challengeScheme, ++ boolean clientSide, boolean serverSide) { ++ this.challengeScheme = challengeScheme; ++ this.clientSide = clientSide; ++ this.serverSide = serverSide; ++ } + +- /** +- * Indicates if the call is properly authenticated. You are guaranteed that +- * the request has a challenge response with a scheme matching the one +- * supported by the plugin. +- * +- * @param cr +- * The challenge response in the request. +- * @param request +- * The request to authenticate. +- * @param guard +- * The associated guard to callback. +- * @return -1 if the given credentials were invalid, 0 if no credentials +- * were found and 1 otherwise. +- * @see Guard#checkSecret(Request, String, char[]) +- * @deprecated See new org.restlet.security package. +- */ +- @Deprecated +- public int authenticate(ChallengeResponse cr, Request request, Guard guard) { +- int result = Guard.AUTHENTICATION_MISSING; ++ /** ++ * Indicates if the call is properly authenticated. You are guaranteed that ++ * the request has a challenge response with a scheme matching the one ++ * supported by the plugin. ++ * ++ * @param cr ++ * The challenge response in the request. ++ * @param request ++ * The request to authenticate. ++ * @param guard ++ * The associated guard to callback. ++ * @return -1 if the given credentials were invalid, 0 if no credentials ++ * were found and 1 otherwise. ++ * @see Guard#checkSecret(Request, String, char[]) ++ * @deprecated See new org.restlet.security package. ++ */ ++ @Deprecated ++ public int authenticate(ChallengeResponse cr, Request request, Guard guard) { ++ int result = Guard.AUTHENTICATION_MISSING; + +- // The challenge schemes are compatible +- final String identifier = cr.getIdentifier(); +- final char[] secret = cr.getSecret(); ++ // The challenge schemes are compatible ++ final String identifier = cr.getIdentifier(); ++ final char[] secret = cr.getSecret(); + +- // Check the credentials +- if ((identifier != null) && (secret != null)) { +- result = guard.checkSecret(request, identifier, secret) ? Guard.AUTHENTICATION_VALID +- : Guard.AUTHENTICATION_INVALID; +- } ++ // Check the credentials ++ if ((identifier != null) && (secret != null)) { ++ result = guard.checkSecret(request, identifier, secret) ? Guard.AUTHENTICATION_VALID ++ : Guard.AUTHENTICATION_INVALID; ++ } + +- return result; +- } ++ return result; ++ } + +- /** +- * Challenges the client by adding a challenge request to the response and +- * by setting the status to CLIENT_ERROR_UNAUTHORIZED. +- * +- * @param response +- * The response to update. +- * @param stale +- * Indicates if the new challenge is due to a stale response. +- * @param guard +- * The associated guard to callback. +- * @deprecated See new org.restlet.security package. +- */ +- @Deprecated +- public void challenge(Response response, boolean stale, Guard guard) { +- response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); +- response.setChallengeRequest(new ChallengeRequest(guard.getScheme(), +- guard.getRealm())); +- } ++ /** ++ * Challenges the client by adding a challenge request to the response and ++ * by setting the status to CLIENT_ERROR_UNAUTHORIZED. ++ * ++ * @param response ++ * The response to update. ++ * @param stale ++ * Indicates if the new challenge is due to a stale response. ++ * @param guard ++ * The associated guard to callback. ++ * @deprecated See new org.restlet.security package. ++ */ ++ @Deprecated ++ public void challenge(Response response, boolean stale, Guard guard) { ++ response.setStatus(Status.CLIENT_ERROR_UNAUTHORIZED); ++ response.setChallengeRequest(new ChallengeRequest(guard.getScheme(), ++ guard.getRealm())); ++ } + +- /** +- * Formats a challenge request as a HTTP header value. +- * +- * @param request +- * The challenge request to format. +- * @return The authenticate header value. +- */ +- public String format(ChallengeRequest request) { +- final StringBuilder sb = new StringBuilder(); +- sb.append(request.getScheme().getTechnicalName()); ++ /** ++ * Formats a challenge request as a HTTP header value. ++ * ++ * @param request ++ * The challenge request to format. ++ * @return The authenticate header value. ++ */ ++ public String format(ChallengeRequest request) { ++ final StringBuilder sb = new StringBuilder(); ++ sb.append(request.getScheme().getTechnicalName()); + +- if (request.getRealm() != null) { +- sb.append("" realm=\"""").append(request.getRealm()).append('""'); +- } ++ if (request.getRealm() != null) { ++ sb.append("" realm=\"""").append(request.getRealm()).append('""'); ++ } + +- formatParameters(sb, request.getParameters(), request); +- return sb.toString(); +- } ++ formatParameters(sb, request.getParameters(), request); ++ return sb.toString(); ++ } + +- /** +- * Formats a challenge response as raw credentials. +- * +- * @param challenge +- * The challenge response to format. +- * @param request +- * The parent request. +- * @param httpHeaders +- * The current request HTTP headers. +- * @return The authorization header value. +- */ +- public String format(ChallengeResponse challenge, Request request, +- Series httpHeaders) { +- final StringBuilder sb = new StringBuilder(); +- sb.append(challenge.getScheme().getTechnicalName()).append(' '); ++ /** ++ * Formats a challenge response as raw credentials. ++ * ++ * @param challenge ++ * The challenge response to format. ++ * @param request ++ * The parent request. ++ * @param httpHeaders ++ * The current request HTTP headers. ++ * @return The authorization header value. ++ */ ++ public String format(ChallengeResponse challenge, Request request, ++ Series httpHeaders) { ++ final StringBuilder sb = new StringBuilder(); ++ sb.append(challenge.getScheme().getTechnicalName()).append(' '); + +- if (challenge.getCredentials() != null) { +- sb.append(challenge.getCredentials()); +- } else { +- formatCredentials(sb, challenge, request, httpHeaders); +- } ++ if (challenge.getCredentials() != null) { ++ sb.append(challenge.getCredentials()); ++ } else { ++ formatCredentials(sb, challenge, request, httpHeaders); ++ } + +- return sb.toString(); +- } ++ return sb.toString(); ++ } + +- /** +- * Formats a challenge response as raw credentials. +- * +- * @param sb +- * The String builder to update. +- * @param challenge +- * The challenge response to format. +- * @param request +- * The parent request. +- * @param httpHeaders +- * The current request HTTP headers. +- */ +- public abstract void formatCredentials(StringBuilder sb, +- ChallengeResponse challenge, Request request, +- Series httpHeaders); ++ /** ++ * Formats a challenge response as raw credentials. ++ * ++ * @param sb ++ * The String builder to update. ++ * @param challenge ++ * The challenge response to format. ++ * @param request ++ * The parent request. ++ * @param httpHeaders ++ * The current request HTTP headers. ++ */ ++ public abstract void formatCredentials(StringBuilder sb, ++ ChallengeResponse challenge, Request request, ++ Series httpHeaders); + +- /** +- * Formats the parameters of a challenge request, to be appended to the +- * scheme technical name and realm. +- * +- * @param sb +- * The string builder to update. +- * @param parameters +- * The parameters to format. +- * @param request +- * The challenger request. +- */ +- public void formatParameters(StringBuilder sb, +- Series parameters, ChallengeRequest request) { +- } ++ /** ++ * Formats the parameters of a challenge request, to be appended to the ++ * scheme technical name and realm. ++ * ++ * @param sb ++ * The string builder to update. ++ * @param parameters ++ * The parameters to format. ++ * @param request ++ * The challenger request. ++ */ ++ public void formatParameters(StringBuilder sb, ++ Series parameters, ChallengeRequest request) { ++ } + +- /** +- * Returns the supported challenge scheme. +- * +- * @return The supported challenge scheme. +- */ +- public ChallengeScheme getChallengeScheme() { +- return this.challengeScheme; +- } ++ /** ++ * Returns the supported challenge scheme. ++ * ++ * @return The supported challenge scheme. ++ */ ++ public ChallengeScheme getChallengeScheme() { ++ return this.challengeScheme; ++ } + +- /** +- * Returns the context's logger. +- * +- * @return The context's logger. +- */ +- public Logger getLogger() { +- return Context.getCurrentLogger(); +- } ++ /** ++ * Returns the context's logger. ++ * ++ * @return The context's logger. ++ */ ++ public Logger getLogger() { ++ return Context.getCurrentLogger(); ++ } + +- /** +- * Indicates if client side authentication is supported. +- * +- * @return True if client side authentication is supported. +- */ +- public boolean isClientSide() { +- return this.clientSide; +- } ++ /** ++ * Indicates if client side authentication is supported. ++ * ++ * @return True if client side authentication is supported. ++ */ ++ public boolean isClientSide() { ++ return this.clientSide; ++ } + +- /** +- * Indicates if server side authentication is supported. +- * +- * @return True if server side authentication is supported. +- */ +- public boolean isServerSide() { +- return this.serverSide; +- } ++ /** ++ * Indicates if server side authentication is supported. ++ * ++ * @return True if server side authentication is supported. ++ */ ++ public boolean isServerSide() { ++ return this.serverSide; ++ } + +- /** +- * Parses an authenticate header into a challenge request. +- * +- * @param header +- * The HTTP header value to parse. +- */ +- public void parseRequest(ChallengeRequest cr, String header) { +- } ++ /** ++ * Parses an authenticate header into a challenge request. ++ * ++ * @param header ++ * The HTTP header value to parse. ++ */ ++ public void parseRequest(ChallengeRequest cr, String header) { ++ } + +- /** +- * Parses an authorization header into a challenge response. +- * +- * @param request +- * The request. +- */ +- public void parseResponse(ChallengeResponse cr, Request request) { +- } ++ /** ++ * Parses an authorization header into a challenge response. ++ * ++ * @param request ++ * The request. ++ */ ++ public void parseResponse(ChallengeResponse cr, Request request) { ++ } + +- /** +- * Sets the supported challenge scheme. +- * +- * @param challengeScheme +- * The supported challenge scheme. +- */ +- public void setChallengeScheme(ChallengeScheme challengeScheme) { +- this.challengeScheme = challengeScheme; +- } ++ /** ++ * Sets the supported challenge scheme. ++ * ++ * @param challengeScheme ++ * The supported challenge scheme. ++ */ ++ public void setChallengeScheme(ChallengeScheme challengeScheme) { ++ this.challengeScheme = challengeScheme; ++ } + +- /** +- * Indicates if client side authentication is supported. +- * +- * @param clientSide +- * True if client side authentication is supported. +- */ +- public void setClientSide(boolean clientSide) { +- this.clientSide = clientSide; +- } ++ /** ++ * Indicates if client side authentication is supported. ++ * ++ * @param clientSide ++ * True if client side authentication is supported. ++ */ ++ public void setClientSide(boolean clientSide) { ++ this.clientSide = clientSide; ++ } + +- /** +- * Indicates if server side authentication is supported. +- * +- * @param serverSide +- * True if server side authentication is supported. +- */ +- public void setServerSide(boolean serverSide) { +- this.serverSide = serverSide; +- } ++ /** ++ * Indicates if server side authentication is supported. ++ * ++ * @param serverSide ++ * True if server side authentication is supported. ++ */ ++ public void setServerSide(boolean serverSide) { ++ this.serverSide = serverSide; ++ } + + }" +59b8a139d72463fbf324e851a9e6daf918fe1b22,spring-framework,JndiObjectFactoryBean explicitly only chooses- public interfaces as default proxy interfaces (SPR-5869)--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java +index 9914e0dbdae3..504a96ad8c64 100644 +--- a/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java ++++ b/org.springframework.context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2002-2009 the original author or authors. ++ * Copyright 2002-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. +@@ -17,7 +17,7 @@ + package org.springframework.jndi; + + import java.lang.reflect.Method; +- ++import java.lang.reflect.Modifier; + import javax.naming.Context; + import javax.naming.NamingException; + +@@ -295,7 +295,12 @@ private static Object createJndiObjectProxy(JndiObjectFactoryBean jof) throws Na + throw new IllegalStateException( + ""Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'""); + } +- proxyFactory.setInterfaces(ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader)); ++ Class[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader); ++ for (Class ifc : ifcs) { ++ if (Modifier.isPublic(ifc.getModifiers())) { ++ proxyFactory.addInterface(ifc); ++ } ++ } + } + if (jof.exposeAccessContext) { + proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate()));" +7d5216168878a13826d5475cbf933b7799224eb5,intellij-community,CPP-560 New Welcome Screen for CLion--,a,https://github.com/JetBrains/intellij-community,"diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java +index 786a5825e7837..b1b0db1fd0d74 100644 +--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java ++++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java +@@ -107,11 +107,11 @@ public Dimension getPreferredSize() { + JPanel progressPanel = new JPanel(new VerticalFlowLayout(true, false)); + progressPanel.add(progressBar); + final LinkLabel cancelLink = new LinkLabel(""Cancel"", AllIcons.Actions.Cancel); +- JPanel linkWrapper = new JPanel(new FlowLayout(FlowLayout.CENTER)); ++ JPanel linkWrapper = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0)); + linkWrapper.add(cancelLink); + progressPanel.add(linkWrapper); + +- JPanel buttonPanel = new JPanel(new VerticalFlowLayout()); ++ JPanel buttonPanel = new JPanel(new VerticalFlowLayout(0, 0)); + buttonPanel.add(installButton); + + buttonWrapper.add(buttonPanel, ""button""); +@@ -238,7 +238,7 @@ public void linkSelected(LinkLabel aSource, Object aLinkData) { + protected Color getColor() { + return ColorUtil.withAlpha(JBColor.foreground(), .2); + } +- }, BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP))); ++ }, BorderFactory.createEmptyBorder(0, GAP / 2, 0, GAP / 2))); + cursor++; + }" +ebfb482c3ee955f24be4d2802c1e06d6f0aa0d1c,restlet-framework-java,Removed debug traces.--,p,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java +index 142b1c1b3a..4fee45c339 100755 +--- a/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java ++++ b/modules/org.restlet.ext.odata/src/org/restlet/ext/odata/Query.java +@@ -328,10 +328,8 @@ public void execute() throws Exception { + ClientResource resource = new ClientResource(targetUri); + resource.setChallengeResponse(service.getCredentials()); + +- Representation result = new StringRepresentation(resource.get( +- MediaType.APPLICATION_ATOM).getText()); +- System.out.println(targetUri); +- System.out.println(result.getText()); ++ Representation result = resource.get(MediaType.APPLICATION_ATOM); ++ + service.setLatestRequest(resource.getRequest()); + service.setLatestResponse(resource.getResponse());" +589edc7aec4e95e8249f99dc703bb799203ac89f,Vala,"Copy default_expression in FormalParameter.copy +",c,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +d47f33629bcc15db2d0f9d75289b0d0da4850799,drools,add support for maven version ranges--,a,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java +index 5d61f05c047..418d8c0f14a 100644 +--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java ++++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieRepositoryImpl.java +@@ -14,9 +14,19 @@ + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + ++import java.math.BigInteger; + import java.net.URL; ++import java.util.ArrayList; ++import java.util.Arrays; + import java.util.HashMap; ++import java.util.Iterator; ++import java.util.List; ++import java.util.ListIterator; ++import java.util.Locale; + import java.util.Map; ++import java.util.Properties; ++import java.util.Stack; ++import java.util.TreeMap; + import java.util.concurrent.atomic.AtomicReference; + + public class KieRepositoryImpl +@@ -30,7 +40,7 @@ public class KieRepositoryImpl + + static final KieRepositoryImpl INSTANCE = new KieRepositoryImpl(); + +- private final Map kieModules = new HashMap(); ++ private final KieModuleRepo kieModuleRepo = new KieModuleRepo(); + + private final AtomicReference defaultGAV = new AtomicReference( new GAVImpl( DEFAULT_GROUP, + DEFAULT_ARTIFACT, +@@ -47,8 +57,7 @@ public GAV getDefaultGAV() { + } + + public void addKieModule(KieModule kieModule) { +- kieModules.put(kieModule.getGAV(), +- kieModule); ++ kieModuleRepo.store(kieModule); + log.info( ""KieModule was added:"" + kieModule); + } + +@@ -57,7 +66,9 @@ public Results verfyKieModule(GAV gav) { + } + + public KieModule getKieModule(GAV gav) { +- KieModule kieModule = kieModules.get( gav ); ++ VersionRange versionRange = new VersionRange(gav.getVersion()); ++ ++ KieModule kieModule = kieModuleRepo.load(gav, versionRange); + if ( kieModule == null ) { + log.debug( ""KieModule Lookup. GAV {} was not in cache, checking classpath"", + gav.toExternalForm() ); +@@ -164,5 +175,441 @@ public KieModule getKieModule(Resource resource) { + throw new RuntimeException(""Unable to fetch module from resource :"" + res, e); + } + } +- ++ ++ private static class KieModuleRepo { ++ private final Map> kieModules = new HashMap>(); ++ ++ void store(KieModule kieModule) { ++ GAV gav = kieModule.getGAV(); ++ String ga = gav.getGroupId() + "":"" + gav.getArtifactId(); ++ ++ TreeMap artifactMap = kieModules.get(ga); ++ if (artifactMap == null) { ++ artifactMap = new TreeMap(); ++ kieModules.put(ga, artifactMap); ++ } ++ artifactMap.put(new ComparableVersion(gav.getVersion()), kieModule); ++ } ++ ++ KieModule load(GAV gav, VersionRange versionRange) { ++ String ga = gav.getGroupId() + "":"" + gav.getArtifactId(); ++ TreeMap artifactMap = kieModules.get(ga); ++ if (artifactMap == null) { ++ return null; ++ } ++ ++ if (versionRange.fixed) { ++ return artifactMap.get(new ComparableVersion(gav.getVersion())); ++ } ++ ++ if (versionRange.upperBound == null) { ++ return artifactMap.lastEntry().getValue(); ++ } ++ ++ Map.Entry entry = versionRange.upperInclusive ? ++ artifactMap.ceilingEntry(new ComparableVersion(versionRange.upperBound)) : ++ artifactMap.lowerEntry(new ComparableVersion(versionRange.upperBound)); ++ ++ if (entry == null) { ++ return null; ++ } ++ ++ if (versionRange.lowerBound == null) { ++ return entry.getValue(); ++ } ++ ++ int versionComparison = entry.getKey().compareTo(new ComparableVersion(versionRange.lowerBound)); ++ return versionComparison > 0 || (versionComparison == 0 && versionRange.lowerInclusive) ? entry.getValue() : null; ++ } ++ } ++ ++ private static class VersionRange { ++ private String lowerBound; ++ private String upperBound; ++ private boolean lowerInclusive; ++ private boolean upperInclusive; ++ private boolean fixed; ++ ++ private VersionRange(String version) { ++ parse(version); ++ } ++ ++ private void parse(String version) { ++ if (""LATEST"".equals(version) || ""RELEASE"".equals(version)) { ++ fixed = false; ++ lowerBound = ""1.0""; ++ upperBound = null; ++ lowerInclusive = true; ++ upperInclusive = false; ++ return; ++ } ++ ++ if (version.charAt(0) != '(' && version.charAt(0) != '[') { ++ fixed = true; ++ lowerBound = version; ++ upperBound = version; ++ lowerInclusive = true; ++ upperInclusive = true; ++ return; ++ } ++ ++ lowerInclusive = version.charAt(0) == '['; ++ upperInclusive = version.charAt(version.length()-1) == ']'; ++ ++ int commaPos = version.indexOf(','); ++ if (commaPos < 0) { ++ fixed = true; ++ lowerBound = version.substring(1, version.length() - 1); ++ upperBound = lowerBound; ++ } else { ++ if (commaPos > 1) { ++ lowerBound = version.substring(1, commaPos); ++ } ++ if (commaPos < version.length()-2) { ++ upperBound = version.substring(commaPos + 1, version.length() - 1); ++ } ++ } ++ } ++ } ++ ++ public static class ComparableVersion implements Comparable { ++ private String value; ++ ++ private String canonical; ++ ++ private ListItem items; ++ ++ private interface Item { ++ final int INTEGER_ITEM = 0; ++ final int STRING_ITEM = 1; ++ final int LIST_ITEM = 2; ++ ++ int compareTo( Item item ); ++ ++ int getType(); ++ ++ boolean isNull(); ++ } ++ ++ private static class IntegerItem implements Item { ++ private static final BigInteger BigInteger_ZERO = new BigInteger( ""0"" ); ++ ++ private final BigInteger value; ++ ++ public static final IntegerItem ZERO = new IntegerItem(); ++ ++ private IntegerItem() { ++ this.value = BigInteger_ZERO; ++ } ++ ++ public IntegerItem( String str ) { ++ this.value = new BigInteger( str ); ++ } ++ ++ public int getType() { ++ return INTEGER_ITEM; ++ } ++ ++ public boolean isNull() { ++ return BigInteger_ZERO.equals( value ); ++ } ++ ++ public int compareTo( Item item ) { ++ if ( item == null ) ++ { ++ return BigInteger_ZERO.equals( value ) ? 0 : 1; // 1.0 == 1, 1.1 > 1 ++ } ++ ++ switch ( item.getType() ) ++ { ++ case INTEGER_ITEM: ++ return value.compareTo( ( (IntegerItem) item ).value ); ++ ++ case STRING_ITEM: ++ return 1; // 1.1 > 1-sp ++ ++ case LIST_ITEM: ++ return 1; // 1.1 > 1-1 ++ ++ default: ++ throw new RuntimeException( ""invalid item: "" + item.getClass() ); ++ } ++ } ++ ++ public String toString() { ++ return value.toString(); ++ } ++ } ++ ++ /** ++ * Represents a string in the version item list, usually a qualifier. ++ */ ++ private static class StringItem implements Item { ++ private static final String[] QUALIFIERS = { ""alpha"", ""beta"", ""milestone"", ""rc"", ""snapshot"", """", ""sp"" }; ++ ++ private static final List _QUALIFIERS = Arrays.asList(QUALIFIERS); ++ ++ private static final Properties ALIASES = new Properties(); ++ ++ static { ++ ALIASES.put( ""ga"", """" ); ++ ALIASES.put( ""final"", """" ); ++ ALIASES.put( ""cr"", ""rc"" ); ++ } ++ ++ /** ++ * A comparable value for the empty-string qualifier. This one is used to determine if a given qualifier makes ++ * the version older than one without a qualifier, or more recent. ++ */ ++ private static final String RELEASE_VERSION_INDEX = String.valueOf( _QUALIFIERS.indexOf( """" ) ); ++ ++ private String value; ++ ++ public StringItem( String value, boolean followedByDigit ) { ++ if ( followedByDigit && value.length() == 1 ) { ++ // a1 = alpha-1, b1 = beta-1, m1 = milestone-1 ++ switch ( value.charAt( 0 ) ) { ++ case 'a': ++ value = ""alpha""; ++ break; ++ case 'b': ++ value = ""beta""; ++ break; ++ case 'm': ++ value = ""milestone""; ++ break; ++ } ++ } ++ this.value = ALIASES.getProperty( value , value ); ++ } ++ ++ public int getType() { ++ return STRING_ITEM; ++ } ++ ++ public boolean isNull() { ++ return ( comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ) == 0 ); ++ } ++ ++ /** ++ * Returns a comparable value for a qualifier. ++ * ++ * This method both takes into account the ordering of known qualifiers as well as lexical ordering for unknown ++ * qualifiers. ++ * ++ * just returning an Integer with the index here is faster, but requires a lot of if/then/else to check for -1 ++ * or QUALIFIERS.size and then resort to lexical ordering. Most comparisons are decided by the first character, ++ * so this is still fast. If more characters are needed then it requires a lexical sort anyway. ++ * ++ * @param qualifier ++ * @return an equivalent value that can be used with lexical comparison ++ */ ++ public static String comparableQualifier( String qualifier ) { ++ int i = _QUALIFIERS.indexOf( qualifier ); ++ ++ return i == -1 ? _QUALIFIERS.size() + ""-"" + qualifier : String.valueOf( i ); ++ } ++ ++ public int compareTo( Item item ) { ++ if ( item == null ) { ++ // 1-rc < 1, 1-ga > 1 ++ return comparableQualifier( value ).compareTo( RELEASE_VERSION_INDEX ); ++ } ++ switch ( item.getType() ) { ++ case INTEGER_ITEM: ++ return -1; // 1.any < 1.1 ? ++ ++ case STRING_ITEM: ++ return comparableQualifier( value ).compareTo( comparableQualifier( ( (StringItem) item ).value ) ); ++ ++ case LIST_ITEM: ++ return -1; // 1.any < 1-1 ++ ++ default: ++ throw new RuntimeException( ""invalid item: "" + item.getClass() ); ++ } ++ } ++ ++ public String toString() { ++ return value; ++ } ++ } ++ ++ /** ++ * Represents a version list item. This class is used both for the global item list and for sub-lists (which start ++ * with '-(number)' in the version specification). ++ */ ++ private static class ListItem extends ArrayList implements Item { ++ public int getType() { ++ return LIST_ITEM; ++ } ++ ++ public boolean isNull() { ++ return ( size() == 0 ); ++ } ++ ++ void normalize() { ++ for( ListIterator iterator = listIterator( size() ); iterator.hasPrevious(); ) { ++ Item item = iterator.previous(); ++ if ( item.isNull() ) { ++ iterator.remove(); // remove null trailing items: 0, """", empty list ++ } else { ++ break; ++ } ++ } ++ } ++ ++ public int compareTo( Item item ) { ++ if ( item == null ) { ++ if ( size() == 0 ) { ++ return 0; // 1-0 = 1- (normalize) = 1 ++ } ++ Item first = get( 0 ); ++ return first.compareTo( null ); ++ } ++ switch ( item.getType() ) { ++ case INTEGER_ITEM: ++ return -1; // 1-1 < 1.0.x ++ ++ case STRING_ITEM: ++ return 1; // 1-1 > 1-sp ++ ++ case LIST_ITEM: ++ Iterator left = iterator(); ++ Iterator right = ( (ListItem) item ).iterator(); ++ ++ while ( left.hasNext() || right.hasNext() ) { ++ Item l = left.hasNext() ? left.next() : null; ++ Item r = right.hasNext() ? right.next() : null; ++ ++ // if this is shorter, then invert the compare and mul with -1 ++ int result = l == null ? -1 * r.compareTo( l ) : l.compareTo( r ); ++ ++ if ( result != 0 ) { ++ return result; ++ } ++ } ++ ++ return 0; ++ ++ default: ++ throw new RuntimeException( ""invalid item: "" + item.getClass() ); ++ } ++ } ++ ++ public String toString() { ++ StringBuilder buffer = new StringBuilder( ""("" ); ++ for( Iterator iter = iterator(); iter.hasNext(); ) ++ { ++ buffer.append( iter.next() ); ++ if ( iter.hasNext() ) ++ { ++ buffer.append( ',' ); ++ } ++ } ++ buffer.append( ')' ); ++ return buffer.toString(); ++ } ++ } ++ ++ public ComparableVersion( String version ) { ++ parseVersion( version ); ++ } ++ ++ public final void parseVersion( String version ) { ++ this.value = version; ++ ++ items = new ListItem(); ++ ++ version = version.toLowerCase( Locale.ENGLISH ); ++ ++ ListItem list = items; ++ ++ Stack stack = new Stack(); ++ stack.push( list ); ++ ++ boolean isDigit = false; ++ ++ int startIndex = 0; ++ ++ for ( int i = 0; i < version.length(); i++ ) { ++ char c = version.charAt( i ); ++ ++ if ( c == '.' ) { ++ if ( i == startIndex ) { ++ list.add( IntegerItem.ZERO ); ++ } else { ++ list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); ++ } ++ startIndex = i + 1; ++ } else if ( c == '-' ) { ++ if ( i == startIndex ) { ++ list.add( IntegerItem.ZERO ); ++ } else { ++ list.add( parseItem( isDigit, version.substring( startIndex, i ) ) ); ++ } ++ startIndex = i + 1; ++ ++ if ( isDigit ) { ++ list.normalize(); // 1.0-* = 1-* ++ ++ if ( ( i + 1 < version.length() ) && Character.isDigit( version.charAt( i + 1 ) ) ) { ++ // new ListItem only if previous were digits and new char is a digit, ++ // ie need to differentiate only 1.1 from 1-1 ++ list.add( list = new ListItem() ); ++ ++ stack.push( list ); ++ } ++ } ++ } ++ else if ( Character.isDigit( c ) ) { ++ if ( !isDigit && i > startIndex ) { ++ list.add( new StringItem( version.substring( startIndex, i ), true ) ); ++ startIndex = i; ++ } ++ ++ isDigit = true; ++ } else { ++ if ( isDigit && i > startIndex ) { ++ list.add( parseItem( true, version.substring( startIndex, i ) ) ); ++ startIndex = i; ++ } ++ ++ isDigit = false; ++ } ++ } ++ ++ if ( version.length() > startIndex ) { ++ list.add( parseItem( isDigit, version.substring( startIndex ) ) ); ++ } ++ ++ while ( !stack.isEmpty() ) { ++ list = (ListItem) stack.pop(); ++ list.normalize(); ++ } ++ ++ canonical = items.toString(); ++ } ++ ++ private static Item parseItem( boolean isDigit, String buf ) { ++ return isDigit ? new IntegerItem( buf ) : new StringItem( buf, false ); ++ } ++ ++ public int compareTo( ComparableVersion o ) { ++ return items.compareTo( o.items ); ++ } ++ ++ public String toString() { ++ return value; ++ } ++ ++ public boolean equals( Object o ) { ++ return ( o instanceof ComparableVersion ) && canonical.equals( ( (ComparableVersion) o ).canonical ); ++ } ++ ++ public int hashCode() { ++ return canonical.hashCode(); ++ } ++ } + } ++ +diff --git a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java +index 8024bf64c42..66a7de75d5f 100644 +--- a/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java ++++ b/drools-compiler/src/main/java/org/kie/builder/impl/KieServicesImpl.java +@@ -1,9 +1,5 @@ + package org.kie.builder.impl; + +-import static org.drools.compiler.io.memory.MemoryFileSystem.readFromJar; +- +-import java.io.File; +- + import org.drools.audit.KnowledgeRuntimeLoggerProviderImpl; + import org.drools.command.impl.CommandFactoryServiceImpl; + import org.drools.concurrent.ExecutorProviderImpl; +@@ -25,6 +21,10 @@ + import org.kie.persistence.jpa.KieStoreServices; + import org.kie.util.ServiceRegistryImpl; + ++import java.io.File; ++ ++import static org.drools.compiler.io.memory.MemoryFileSystem.readFromJar; ++ + public class KieServicesImpl implements KieServices { + private ResourceFactoryService resourceFactory; + +@@ -60,7 +60,11 @@ public KieContainer getKieClasspathContainer() { + } + + public KieContainer getKieContainer(GAV gav) { +- KieProject kProject = new KieModuleKieProject( ( InternalKieModule ) getKieRepository().getKieModule(gav), getKieRepository() ); ++ InternalKieModule kieModule = (InternalKieModule)getKieRepository().getKieModule(gav); ++ if (kieModule == null) { ++ throw new RuntimeException(""Cannot find KieModule: "" + gav); ++ } ++ KieProject kProject = new KieModuleKieProject( kieModule, getKieRepository() ); + return new KieContainerImpl( kProject, getKieRepository() ); + } + +diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java +index 09a22735675..5e8ae855efc 100644 +--- a/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java ++++ b/drools-compiler/src/test/java/org/drools/integrationtests/KieHelloWorldTest.java +@@ -84,7 +84,7 @@ public void testHelloWorldWithPackages() throws Exception { + .generateAndWritePomXML( gav ) + .write(""src/main/resources/KBase1/org/pkg1/r1.drl"", drl1) + .write(""src/main/resources/KBase1/org/pkg2/r2.drl"", drl2) +- .writeKModuleXML( createKieProjectWithPackages(kf, ""org.pkg1"").toXML()); ++ .writeKModuleXML(createKieProjectWithPackages(kf, ""org.pkg1"").toXML()); + ks.newKieBuilder( kfs ).build(); + + KieSession ksession = ks.getKieContainer(gav).getKieSession(""KSession1""); +@@ -139,8 +139,64 @@ private KieModuleModel createKieProjectWithPackages(KieFactory kf, String pkg) { + + KieSessionModel ksession1 = kieBaseModel1.newKieSessionModel(""KSession1"") + .setType( KieSessionType.STATEFUL ) +- .setClockType( ClockTypeOption.get(""realtime"") ); ++ .setClockType(ClockTypeOption.get(""realtime"")); + + return kproj; + } +-} ++ ++ @Test ++ public void testHelloWorldOnVersionRange() throws Exception { ++ KieServices ks = KieServices.Factory.get(); ++ KieFactory kf = KieFactory.Factory.get(); ++ ++ buildVersion(ks, kf, ""Hello World"", ""1.0""); ++ buildVersion(ks, kf, ""Aloha Earth"", ""1.1""); ++ buildVersion(ks, kf, ""Hi Universe"", ""1.2""); ++ ++ GAV latestGav = kf.newGav(""org.kie"", ""hello-world"", ""LATEST""); ++ ++ KieSession ksession = ks.getKieContainer(latestGav).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Hello World"")); ++ assertEquals( 0, ksession.fireAllRules() ); ++ ++ ksession = ks.getKieContainer(latestGav).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Hi Universe"")); ++ assertEquals( 1, ksession.fireAllRules() ); ++ ++ GAV gav1 = kf.newGav(""org.kie"", ""hello-world"", ""1.0""); ++ ++ ksession = ks.getKieContainer(gav1).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Hello World"")); ++ assertEquals( 1, ksession.fireAllRules() ); ++ ++ ksession = ks.getKieContainer(gav1).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Hi Universe"")); ++ assertEquals( 0, ksession.fireAllRules() ); ++ ++ GAV gav2 = kf.newGav(""org.kie"", ""hello-world"", ""[1.0,1.2)""); ++ ++ ksession = ks.getKieContainer(gav2).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Aloha Earth"")); ++ assertEquals( 1, ksession.fireAllRules() ); ++ ++ ksession = ks.getKieContainer(gav2).getKieSession(""KSession1""); ++ ksession.insert(new Message(""Hi Universe"")); ++ assertEquals( 0, ksession.fireAllRules() ); ++ } ++ ++ private void buildVersion(KieServices ks, KieFactory kf, String message, String version) { ++ String drl = ""package org.drools\n"" + ++ ""rule R1 when\n"" + ++ "" $m : Message( message == \"""" + message+ ""\"" )\n"" + ++ ""then\n"" + ++ ""end\n""; ++ ++ GAV gav = kf.newGav(""org.kie"", ""hello-world"", version); ++ ++ KieFileSystem kfs = kf.newKieFileSystem() ++ .generateAndWritePomXML( gav ) ++ .write(""src/main/resources/KBase1/org/pkg1/r1.drl"", drl) ++ .writeKModuleXML(createKieProjectWithPackages(kf, ""*"").toXML()); ++ ks.newKieBuilder( kfs ).build(); ++ } ++} +\ No newline at end of file +diff --git a/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java b/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java +index bef63bce73d..bb664538a27 100644 +--- a/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java ++++ b/kie-ci/src/main/java/org/drools/scanner/DependencyDescriptor.java +@@ -67,7 +67,7 @@ public String getType() { + } + + public boolean isFixedVersion() { +- return !isSnapshot() && !version.equals(""LATEST"") && !version.equals("")""); ++ return !isSnapshot() && !version.equals(""LATEST"") && !version.equals(""RELEASE""); + } + + public boolean isSnapshot() { +diff --git a/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java b/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java +index 9cad4a12bbe..c57c373347e 100644 +--- a/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java ++++ b/kie-ci/src/main/java/org/drools/scanner/KieRepositoryScannerImpl.java +@@ -166,6 +166,9 @@ private Collection scanForUpdates(Collection dep + List newArtifacts = new ArrayList(); + for (DependencyDescriptor dependency : dependencies) { + Artifact newArtifact = getArtifactResolver().resolveArtifact(dependency.toResolvableString()); ++ if (newArtifact == null) { ++ continue; ++ } + DependencyDescriptor resolvedDep = new DependencyDescriptor(newArtifact); + if (resolvedDep.isNewerThan(dependency)) { + newArtifacts.add(newArtifact); +diff --git a/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java b/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java +index 95b75930554..77b33dee482 100644 +--- a/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java ++++ b/kie-ci/src/test/java/org/drools/scanner/KieRepositoryScannerTest.java +@@ -141,7 +141,7 @@ public void testScannerOnPomProject() throws Exception { + InternalKieModule kJar1 = createKieJarWithClass(ks, kf, gav1, 2, 7); + repository.deployArtifact(gav1, kJar1, createKPom(gav1)); + +- KieContainer kieContainer = ks.getKieContainer(kf.newGav(""org.kie"", ""scanner-master-test"", ""1.0"")); ++ KieContainer kieContainer = ks.getKieContainer(kf.newGav(""org.kie"", ""scanner-master-test"", ""LATEST"")); + KieSession ksession = kieContainer.getKieSession(""KSession1""); + checkKSession(ksession, 14);" +73ea4cb8ebbefe934d9f088e99903b15772fa445,orientdb,Implemented self-repair in case the security is- broken. This new method in the ODatabaseListener interface will allow to- handle corruptions in better way.--Console now displays a message and after a user input fix it. Cool!-,a,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +e106a9c058ec31a3048be99359aa35f1dfb16d69,aeshell$aesh,"further completion support +",a,https://github.com/aeshell/aesh,"diff --git a/src/main/java/Example.java b/src/main/java/Example.java +index 175af4841..88866babd 100644 +--- a/src/main/java/Example.java ++++ b/src/main/java/Example.java +@@ -1,7 +1,10 @@ ++import org.jboss.jreadline.complete.Completion; + import org.jboss.jreadline.console.Console; + + import java.io.IOException; + import java.io.PrintWriter; ++import java.util.ArrayList; ++import java.util.List; + + /** + * @author Ståle W. Pedersen +@@ -15,6 +18,20 @@ public static void main(String[] args) throws IOException { + + PrintWriter out = new PrintWriter(System.out); + ++ Completion completer = new Completion() { ++ @Override ++ public List complete(String line, int cursor) { ++ // very simple completor ++ List commands = new ArrayList(); ++ if(line.length() < 1 || line.startsWith(""f"") || line.startsWith(""fo"")) ++ commands.add(""foo""); ++ ++ return commands; ++ } ++ }; ++ ++ console.addCompletion(completer); ++ + String line; + while ((line = console.read(""> "")) != null) { + console.pushToConsole(""======>\"""" + line + ""\n""); +diff --git a/src/main/java/org/jboss/jreadline/console/Console.java b/src/main/java/org/jboss/jreadline/console/Console.java +index 0aa5815d0..f8e01f292 100644 +--- a/src/main/java/org/jboss/jreadline/console/Console.java ++++ b/src/main/java/org/jboss/jreadline/console/Console.java +@@ -266,7 +266,7 @@ else if(action == Action.CASE) { + changeCase(); + } + else if(action == Action.COMPLETE) { +- //complete(); ++ complete(); + } + else if(action == Action.EXIT) { + //deleteCurrentCharacter(); +@@ -544,7 +544,7 @@ private boolean undo() throws IOException { + return false; + } + +- private void complete() { ++ private void complete() throws IOException { + if(completionList.size() < 1) + return; + +@@ -560,21 +560,45 @@ private void complete() { + return; + // only one hit, do a completion + else if(possibleCompletions.size() == 1) +- doCompletion(possibleCompletions.get(0)); ++ displayCompletion(possibleCompletions.get(0)); + // more than one hit... + else { +- //TODO: implement this ++ String startsWith = buffer.findStartsWith(possibleCompletions); ++ if(startsWith.length() > 0) ++ displayCompletion(startsWith); ++ else { ++ displayCompletions(possibleCompletions); ++ } + } + + } + + /** + * TODO: insert the completion into the buffer ++ * 1. go back a word ++ * 2. insert the word + * + * @param completion ++ * @throws java.io.IOException stream + */ +- private void doCompletion(String completion) { ++ private void displayCompletion(String completion) throws IOException { ++ performAction(new PrevWordAction(buffer.getCursor(), Action.DELETE)); ++ buffer.write(completion); ++ outStream.write(completion); + ++ redrawLineFromCursor(); + } + ++ private void displayCompletions(List possibleCompletions) { ++ if(possibleCompletions.size() > 50) { ++ // display ask... ++ } ++ // display all ++ else { ++ ++ } ++ ++ } ++ ++ + }" +e2ffe19d36e25a9d208e53a534f878e8605ed5ab,intellij-community,cleanup--,p,https://github.com/JetBrains/intellij-community,"diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +index a34084fa28eaf..6fb2c80e3d801 100644 +--- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java ++++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +@@ -137,7 +137,7 @@ public Boolean fun(String s) { + private final CompileServerClasspathManager myClasspathManager = new CompileServerClasspathManager(); + private final Executor myPooledThreadExecutor = new Executor() { + @Override +- public void execute(Runnable command) { ++ public void execute(@NotNull Runnable command) { + ApplicationManager.getApplication().executeOnPooledThread(command); + } + }; +@@ -478,7 +478,7 @@ public void run() { + globals = buildGlobalSettings(); + myGlobals = globals; + } +- CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges = null; ++ CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; + final SequentialTaskExecutor projectTaskQueue; + synchronized (myProjectDataMap) { + ProjectData data = myProjectDataMap.get(projectPath); +@@ -761,21 +761,12 @@ private Process launchBuildProcess(Project project, final int port, final UUID s + cmdLine.addParameter(""-D""+ GlobalOptions.HOSTNAME_OPTION + ""="" + host); + + // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language +- final String lang = System.getProperty(""user.language""); +- if (lang != null) { +- //noinspection HardCodedStringLiteral +- cmdLine.addParameter(""-Duser.language="" + lang); +- } +- final String country = System.getProperty(""user.country""); +- if (country != null) { +- //noinspection HardCodedStringLiteral +- cmdLine.addParameter(""-Duser.country="" + country); +- } +- //noinspection HardCodedStringLiteral +- final String region = System.getProperty(""user.region""); +- if (region != null) { +- //noinspection HardCodedStringLiteral +- cmdLine.addParameter(""-Duser.region="" + region); ++ String[] propertyNames = {""user.language"", ""user.country"", ""user.region""}; ++ for (String name : propertyNames) { ++ final String value = System.getProperty(name); ++ if (value != null) { ++ cmdLine.addParameter(""-D"" + name + ""="" + value); ++ } + } + + cmdLine.addParameter(""-classpath""); +diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java +index 38d0aa113a458..ac843603c68b7 100644 +--- a/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java ++++ b/jps/jps-builders/src/org/jetbrains/jps/api/CmdlineProtoUtil.java +@@ -22,7 +22,7 @@ public static CmdlineRemoteProto.Message.ControllerMessage createMakeRequest(Str + List scopes, + final Map userData, + final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, +- final CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { ++ final @Nullable CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { + return createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type.MAKE, project, scopes, + userData, Collections.emptyList(), + globals, event); +@@ -33,7 +33,7 @@ public static CmdlineRemoteProto.Message.ControllerMessage createForceCompileReq + Collection paths, + final Map userData, + final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, +- final CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { ++ final @Nullable CmdlineRemoteProto.Message.ControllerMessage.FSEvent event) { + return createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type.FORCED_COMPILATION, project, + scopes, userData, paths, globals, event); + } +@@ -63,7 +63,7 @@ public static TargetTypeBuildScope createAllTargetsScope(BuildTargetType type + + private static CmdlineRemoteProto.Message.ControllerMessage createBuildParametersMessage(CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.Type buildType, + String project, +- List scopes, ++ List scopes, + Map userData, + Collection paths, + final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals, +@@ -99,7 +99,7 @@ public static CmdlineRemoteProto.Message.KeyValuePair createPair(String key, Str + } + + +- public static CmdlineRemoteProto.Message.Failure createFailure(String description, Throwable cause) { ++ public static CmdlineRemoteProto.Message.Failure createFailure(String description, @Nullable Throwable cause) { + final CmdlineRemoteProto.Message.Failure.Builder builder = CmdlineRemoteProto.Message.Failure.newBuilder(); + builder.setDescription(description); + if (cause != null) {" +ce2995c49d111b5749a88b4de2065a3a68551386,hbase,HBASE-1136 HashFunction inadvertently destroys- some randomness; REVERTING--git-svn-id: https://svn.apache.org/repos/asf/hadoop/hbase/trunk@735880 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/CHANGES.txt b/CHANGES.txt +index 7e9c80101764..970250b4eaeb 100644 +--- a/CHANGES.txt ++++ b/CHANGES.txt +@@ -3,8 +3,6 @@ Release 0.20.0 - Unreleased + INCOMPATIBLE CHANGES + + BUG FIXES +- HBASE-1136 HashFunction inadvertently destroys some randomness +- (Jonathan Ellis via Stack) + HBASE-1140 ""ant clean test"" fails (Nitay Joffe via Stack) + + IMPROVEMENTS +diff --git a/src/java/org/onelab/filter/HashFunction.java b/src/java/org/onelab/filter/HashFunction.java +index cf97c7bcaa26..a0c26964e2f6 100644 +--- a/src/java/org/onelab/filter/HashFunction.java ++++ b/src/java/org/onelab/filter/HashFunction.java +@@ -118,8 +118,7 @@ public int[] hash(Key k){ + } + int[] result = new int[nbHash]; + for (int i = 0, initval = 0; i < nbHash; i++) { +- initval = hashFunction.hash(b, initval); +- result[i] = Math.abs(initval) % maxValue; ++ initval = result[i] = Math.abs(hashFunction.hash(b, initval) % maxValue); + } + return result; + }//end hash() +diff --git a/src/test/org/onelab/test/TestFilter.java b/src/test/org/onelab/test/TestFilter.java +index 363fc9451481..6c88c1ab33f4 100644 +--- a/src/test/org/onelab/test/TestFilter.java ++++ b/src/test/org/onelab/test/TestFilter.java +@@ -274,7 +274,7 @@ public void testCountingBloomFilter() throws UnsupportedEncodingException { + bf.add(k2); + bf.add(k3); + assertTrue(bf.membershipTest(key)); +- assertFalse(bf.membershipTest(k2)); ++ assertTrue(bf.membershipTest(new StringKey(""graknyl""))); + assertFalse(bf.membershipTest(new StringKey(""xyzzy""))); + assertFalse(bf.membershipTest(new StringKey(""abcd""))); + +@@ -287,7 +287,7 @@ public void testCountingBloomFilter() throws UnsupportedEncodingException { + bf2.add(key); + bf.or(bf2); + assertTrue(bf.membershipTest(key)); +- assertTrue(bf.membershipTest(k2)); ++ assertTrue(bf.membershipTest(new StringKey(""graknyl""))); + assertFalse(bf.membershipTest(new StringKey(""xyzzy""))); + assertFalse(bf.membershipTest(new StringKey(""abcd"")));" +4405698ee99fe26d0ac9317a2df96096f2731a7b,hbase,HBASE-7703 Eventually all online snapshots fail- due to Timeout at same regionserver.--Online snapshot attempts would fail due to timeout because a rowlock could not be obtained. Prior to this a-cancellation occurred which likely grabbed the lock without cleaning it properly. The fix here is to use nice cancel-instead of interrupting cancel on failures.----git-svn-id: https://svn.apache.org/repos/asf/hbase/branches/hbase-7290@1445866 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hbase,"diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/snapshot/RegionServerSnapshotManager.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/snapshot/RegionServerSnapshotManager.java +index 3e5238e7b281..1282585d52eb 100644 +--- a/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/snapshot/RegionServerSnapshotManager.java ++++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/snapshot/RegionServerSnapshotManager.java +@@ -347,7 +347,11 @@ void cancelTasks() throws InterruptedException { + Collection> tasks = futures; + LOG.debug(""cancelling "" + tasks.size() + "" tasks for snapshot "" + name); + for (Future f: tasks) { +- f.cancel(true); ++ // TODO Ideally we'd interrupt hbase threads when we cancel. However it seems that there ++ // are places in the HBase code where row/region locks are taken and not released in a ++ // finally block. Thus we cancel without interrupting. Cancellations will be slower to ++ // complete but we won't suffer from unreleased locks due to poor code discipline. ++ f.cancel(false); + } + + // evict remaining tasks and futures from taskPool." +e517f55833c7ec02676bd850e9cd8f302a8a713f,ReactiveX-RxJava,Add finally0 to Observable.java .--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java +index 5d11c7b9ed..72c400dbf7 100644 +--- a/rxjava-core/src/main/java/rx/Observable.java ++++ b/rxjava-core/src/main/java/rx/Observable.java +@@ -1182,6 +1182,18 @@ public static Observable concat(Observable... source) { + return _create(OperationConcat.concat(source)); + } + ++ /** ++ * Emits the same objects as the given Observable, calling the given action ++ * when it calls onComplete or onError. ++ * @param source an observable ++ * @param action an action to be called when the source completes or errors. ++ * @return an Observable that emits the same objects, then calls the action. ++ * @see MSDN: Observable.Finally Method ++ */ ++ public static Observable finally0(Observable source, Action0 action) { ++ return _create(OperationFinally.finally0(source, action)); ++ } ++ + /** + * Groups the elements of an observable and selects the resulting elements by using a specified function. + * +diff --git a/rxjava-core/src/main/java/rx/operators/OperationFinally.java b/rxjava-core/src/main/java/rx/operators/OperationFinally.java +index 0eddc57d2f..4474e11936 100644 +--- a/rxjava-core/src/main/java/rx/operators/OperationFinally.java ++++ b/rxjava-core/src/main/java/rx/operators/OperationFinally.java +@@ -1,12 +1,12 @@ + /** + * Copyright 2013 Netflix, Inc. +- * ++ * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at +- * ++ * + * http://www.apache.org/licenses/LICENSE-2.0 +- * ++ * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@@ -23,15 +23,12 @@ + import java.util.List; + import java.util.concurrent.CountDownLatch; + +-import org.junit.Assert; +-import org.junit.Before; + import org.junit.Test; + + import rx.Observable; + import rx.Observer; + import rx.Subscription; + import rx.util.AtomicObservableSubscription; +-import rx.util.AtomicObserver; + import rx.util.functions.Action0; + import rx.util.functions.Func1; + +@@ -42,16 +39,16 @@ public final class OperationFinally { + * exception). The returned observable is exactly as threadsafe as the + * source observable; in particular, any situation allowing the source to + * call onComplete or onError multiple times allows the returned observable +- * to call the action multiple times. ++ * to call the final action multiple times. + *

    + * Note that ""finally"" is a Java reserved word and cannot be an identifier, + * so we use ""finally0"". +- * ++ * + * @param sequence An observable sequence of elements + * @param action An action to be taken when the sequence is complete or throws an exception + * @return An observable sequence with the same elements as the input. + * After the last element is consumed (just before {@link Observer#onComplete} is called), +- * or when an exception is thrown (just before {@link Observer#onError}), the action will be taken. ++ * or when an exception is thrown (just before {@link Observer#onError}), the action will be called. + * @see http://msdn.microsoft.com/en-us/library/hh212133(v=vs.103).aspx + */ + public static Func1, Subscription> finally0(final Observable sequence, final Action0 action) { +@@ -121,25 +118,24 @@ private static class TestAction implements Action0 { + called++; + } + } +- ++ + @Test + public void testFinally() { + final String[] n = {""1"", ""2"", ""3""}; + final Observable nums = Observable.toObservable(n); + TestAction action = new TestAction(); + action.called = 0; +- @SuppressWarnings(""unchecked"") + Observable fin = Observable.create(finally0(nums, action)); + @SuppressWarnings(""unchecked"") + Observer aObserver = mock(Observer.class); + fin.subscribe(aObserver); +- Assert.assertEquals(1, action.called); ++ assertEquals(1, action.called); + + action.called = 0; + Observable error = Observable.error(new RuntimeException(""expected"")); + fin = Observable.create(finally0(error, action)); + fin.subscribe(aObserver); +- Assert.assertEquals(1, action.called); ++ assertEquals(1, action.called); + } + } +-} +\ No newline at end of file ++}" +3e0e71690424ab386f97e3b3f18751748cf52e49,intellij-community,FrameWrapper: do not restore frame state as- iconified (IDEA-87792)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java +index bde382d88062c..2eac7039600d0 100644 +--- a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java ++++ b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java +@@ -309,7 +309,7 @@ protected void loadFrameState() { + } + } + +- if (extendedState == Frame.ICONIFIED || extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) { ++ if (extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) { + ((JFrame)frame).setExtendedState(extendedState); + } + }" +5fe6054a3835b11a4432e3da770f779183de4291,Mylyn Reviews,"Minor cleanup + +-ignore warning about internal api +-minor reformatting +",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java +index d9265032..81c8bf28 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/CreateReviewActionFromAttachment.java +@@ -39,6 +39,12 @@ + import org.eclipse.mylyn.tasks.ui.TasksUi; + import org.eclipse.ui.IActionDelegate; + ++/** ++ * ++ * @author mattk ++ * ++ */ ++@SuppressWarnings(""restriction"") + public class CreateReviewActionFromAttachment extends Action implements + IActionDelegate { + +@@ -53,7 +59,8 @@ public void run(IAction action) { + ITaskDataManager manager = TasksUi.getTaskDataManager(); + TaskData parentTaskData = manager.getTaskData(taskAttachment + .getTask()); +- ITaskProperties parentTask= TaskProperties.fromTaskData(manager, parentTaskData); ++ ITaskProperties parentTask = TaskProperties.fromTaskData(manager, ++ parentTaskData); + + TaskMapper initializationData = new TaskMapper(parentTaskData); + IReviewMapper taskMapper = ReviewsUiPlugin.getMapper(); +@@ -69,12 +76,13 @@ public void run(IAction action) { + + ITaskProperties taskProperties = TaskProperties.fromTaskData( + manager, taskData); +- taskProperties.setSummary(""[review] "" + parentTask.getDescription()); ++ taskProperties ++ .setSummary(""[review] "" + parentTask.getDescription()); + + String reviewer = taskRepository.getUserName(); + taskProperties.setAssignedTo(reviewer); + +- initTaskProperties(taskMapper, taskProperties,parentTask); ++ initTaskProperties(taskMapper, taskProperties, parentTask); + + TasksUiInternal.createAndOpenNewTask(taskData); + } catch (CoreException e) { +@@ -84,15 +92,13 @@ public void run(IAction action) { + } + + private void initTaskProperties(IReviewMapper taskMapper, +- ITaskProperties taskProperties,ITaskProperties parentTask) { ++ ITaskProperties taskProperties, ITaskProperties parentTask) { + ReviewScope scope = new ReviewScope(); + for (ITaskAttachment taskAttachment : selection2) { + // FIXME date from task attachment +- Attachment attachment = ReviewsUtil +- .findAttachment(taskAttachment.getFileName(), +- taskAttachment.getAuthor().getPersonId(), +- taskAttachment.getCreationDate().toString(), +- parentTask); ++ Attachment attachment = ReviewsUtil.findAttachment(taskAttachment ++ .getFileName(), taskAttachment.getAuthor().getPersonId(), ++ taskAttachment.getCreationDate().toString(), parentTask); + if (attachment.isPatch()) { + scope.addScope(new PatchScopeItem(attachment)); + } else { +@@ -127,5 +133,4 @@ public void selectionChanged(IAction action, ISelection selection) { + } + } + } +- + } +diff --git a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java +index a7b674ca..71f035d5 100644 +--- a/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java ++++ b/tbr/org.eclipse.mylyn.reviews.tasks.ui/src/org/eclipse/mylyn/reviews/tasks/ui/internal/editors/ReviewTaskEditorPage.java +@@ -40,6 +40,7 @@ + /* + * @author Kilian Matt + */ ++@SuppressWarnings(""restriction"") + public class ReviewTaskEditorPage extends AbstractTaskEditorPage { + private ReviewScope scope;" +100f571c9a2835d5a30a55374b9be74c147e031f,ReactiveX-RxJava,forEach with Action1 but not Observer--I re-read the MSDN docs and found the previous implementation wasn't complying with the contract.--http://msdn.microsoft.com/en-us/library/hh211815(v=vs.103).aspx--I believe this now does.-,c,https://github.com/ReactiveX/RxJava,"diff --git a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy +index 7f62af5724..967c096691 100644 +--- a/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy ++++ b/language-adaptors/rxjava-groovy/src/test/groovy/rx/lang/groovy/ObservableTests.groovy +@@ -22,6 +22,7 @@ import java.util.Arrays; + + import org.junit.Before; + import org.junit.Test; ++import static org.junit.Assert.*; + import org.mockito.Mock; + import org.mockito.MockitoAnnotations; + +@@ -222,33 +223,17 @@ def class ObservableTests { + verify(a, times(1)).received(3); + } + +- @Test +- public void testForEachWithComplete() { +- Observable.create(new AsyncObservable()).forEach({ result -> a.received(result)}, {}, {a.received('done')}); +- verify(a, times(1)).received(1); +- verify(a, times(1)).received(2); +- verify(a, times(1)).received(3); +- verify(a, times(1)).received(""done""); +- } +- + @Test + public void testForEachWithError() { +- Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')}, {err -> a.received(err.message)}); +- verify(a, times(0)).received(1); +- verify(a, times(0)).received(2); +- verify(a, times(0)).received(3); +- verify(a, times(1)).received(""err""); +- verify(a, times(0)).received(""done""); +- } +- +- @Test +- public void testForEachWithCompleteAndError() { +- Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')}, {err -> a.received(err.message)}, {a.received('done')},); ++ try { ++ Observable.create(new AsyncObservable()).forEach({ result -> throw new RuntimeException('err')}); ++ fail(""we expect an exception to be thrown""); ++ }catch(Exception e) { ++ ++ } + verify(a, times(0)).received(1); + verify(a, times(0)).received(2); + verify(a, times(0)).received(3); +- verify(a, times(1)).received(""err""); +- verify(a, times(0)).received(""done""); + } + + def class AsyncObservable implements Func1, Subscription> { +diff --git a/rxjava-core/src/main/java/rx/Observable.java b/rxjava-core/src/main/java/rx/Observable.java +index 86e85be0f5..ba9cc6827b 100644 +--- a/rxjava-core/src/main/java/rx/Observable.java ++++ b/rxjava-core/src/main/java/rx/Observable.java +@@ -26,6 +26,7 @@ + import java.util.concurrent.Future; + import java.util.concurrent.TimeUnit; + import java.util.concurrent.TimeoutException; ++import java.util.concurrent.atomic.AtomicReference; + + import org.junit.Before; + import org.junit.Test; +@@ -334,33 +335,39 @@ public void onNext(T args) { + } + + /** +- * Blocking version of {@link #subscribe(Observer)}. ++ * Invokes an action for each element in the observable sequence, and blocks until the sequence is terminated. + *

    + * NOTE: This will block even if the Observable is asynchronous. ++ *

    ++ * This is similar to {@link #subscribe(Observer)} but blocks. Because it blocks it does not need the {@link Observer#onCompleted()} or {@link Observer#onError(Exception)} methods. + * +- * @param observer ++ * @param onNext ++ * {@link Action1} ++ * @throws RuntimeException ++ * if error occurs + */ +- public void forEach(final Observer observer) { ++ public void forEach(final Action1 onNext) { + final CountDownLatch latch = new CountDownLatch(1); ++ final AtomicReference exceptionFromOnError = new AtomicReference(); ++ + subscribe(new Observer() { + public void onCompleted() { +- try { +- observer.onCompleted(); +- } finally { +- latch.countDown(); +- } ++ latch.countDown(); + } + + public void onError(Exception e) { +- try { +- observer.onError(e); +- } finally { +- latch.countDown(); +- } ++ /* ++ * If we receive an onError event we set the reference on the outer thread ++ * so we can git it and throw after the latch.await(). ++ * ++ * We do this instead of throwing directly since this may be on a different thread and the latch is still waiting. ++ */ ++ exceptionFromOnError.set(e); ++ latch.countDown(); + } + + public void onNext(T args) { +- observer.onNext(args); ++ onNext.call(args); + } + }); + // block until the subscription completes and then return +@@ -369,46 +376,21 @@ public void onNext(T args) { + } catch (InterruptedException e) { + throw new RuntimeException(""Interrupted while waiting for subscription to complete."", e); + } +- } +- +- @SuppressWarnings({ ""rawtypes"", ""unchecked"" }) +- public void forEach(final Map callbacks) { +- // lookup and memoize onNext +- Object _onNext = callbacks.get(""onNext""); +- if (_onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } +- final FuncN onNext = Functions.from(_onNext); +- +- forEach(new Observer() { +- +- public void onCompleted() { +- Object onComplete = callbacks.get(""onCompleted""); +- if (onComplete != null) { +- Functions.from(onComplete).call(); +- } +- } +- +- public void onError(Exception e) { +- handleError(e); +- Object onError = callbacks.get(""onError""); +- if (onError != null) { +- Functions.from(onError).call(e); +- } +- } + +- public void onNext(Object args) { +- onNext.call(args); ++ if (exceptionFromOnError.get() != null) { ++ if (exceptionFromOnError.get() instanceof RuntimeException) { ++ throw (RuntimeException) exceptionFromOnError.get(); ++ } else { ++ throw new RuntimeException(exceptionFromOnError.get()); + } +- +- }); ++ } + } + + @SuppressWarnings({ ""rawtypes"", ""unchecked"" }) + public void forEach(final Object o) { +- if (o instanceof Observer) { +- // in case a dynamic language is not correctly handling the overloaded methods and we receive an Observer just forward to the correct method. +- forEach((Observer) o); ++ if (o instanceof Action1) { ++ // in case a dynamic language is not correctly handling the overloaded methods and we receive an Action1 just forward to the correct method. ++ forEach((Action1) o); + } + + // lookup and memoize onNext +@@ -417,156 +399,15 @@ public void forEach(final Object o) { + } + final FuncN onNext = Functions.from(o); + +- forEach(new Observer() { +- +- public void onCompleted() { +- // do nothing +- } +- +- public void onError(Exception e) { +- handleError(e); +- // no callback defined +- } +- +- public void onNext(Object args) { +- onNext.call(args); +- } +- +- }); +- } +- +- public void forEach(final Action1 onNext) { +- +- forEach(new Observer() { +- +- public void onCompleted() { +- // do nothing +- } +- +- public void onError(Exception e) { +- handleError(e); +- // no callback defined +- } +- +- public void onNext(T args) { +- if (onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } +- onNext.call(args); +- } +- +- }); +- } +- +- @SuppressWarnings({ ""rawtypes"", ""unchecked"" }) +- public void forEach(final Object onNext, final Object onError) { +- // lookup and memoize onNext +- if (onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } +- final FuncN onNextFunction = Functions.from(onNext); +- +- forEach(new Observer() { ++ forEach(new Action1() { + +- public void onCompleted() { +- // do nothing +- } +- +- public void onError(Exception e) { +- handleError(e); +- if (onError != null) { +- Functions.from(onError).call(e); +- } +- } +- +- public void onNext(Object args) { +- onNextFunction.call(args); +- } +- +- }); +- } +- +- public void forEach(final Action1 onNext, final Action1 onError) { +- +- forEach(new Observer() { +- +- public void onCompleted() { +- // do nothing +- } +- +- public void onError(Exception e) { +- handleError(e); +- if (onError != null) { +- onError.call(e); +- } +- } +- +- public void onNext(T args) { +- if (onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } ++ public void call(Object args) { + onNext.call(args); + } + + }); + } + +- @SuppressWarnings({ ""rawtypes"", ""unchecked"" }) +- public void forEach(final Object onNext, final Object onError, final Object onComplete) { +- // lookup and memoize onNext +- if (onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } +- final FuncN onNextFunction = Functions.from(onNext); +- +- forEach(new Observer() { +- +- public void onCompleted() { +- if (onComplete != null) { +- Functions.from(onComplete).call(); +- } +- } +- +- public void onError(Exception e) { +- handleError(e); +- if (onError != null) { +- Functions.from(onError).call(e); +- } +- } +- +- public void onNext(Object args) { +- onNextFunction.call(args); +- } +- +- }); +- } +- +- public void forEach(final Action1 onNext, final Action1 onError, final Action0 onComplete) { +- +- forEach(new Observer() { +- +- public void onCompleted() { +- onComplete.call(); +- } +- +- public void onError(Exception e) { +- handleError(e); +- if (onError != null) { +- onError.call(e); +- } +- } +- +- public void onNext(T args) { +- if (onNext == null) { +- throw new RuntimeException(""onNext must be implemented""); +- } +- onNext.call(args); +- } +- +- }); +- } +- +- + /** + * Allow the {@link RxJavaErrorHandler} to receive the exception from onError. + *" +84ff885f72d1ec8228407b6cdc9c09d342b5a0dc,kotlin,Constructor body generation extracted as a method- (+ migrated to Printer for convenience)--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +0578ba96dfe44b8264b74329764137084f8b62c8,apache$maven-plugins,"[MWAR-81] Request enhancement to pattern matching for packagingIncludes/packagingExcludes functionality (regular expressions?) +Submitted by: Nicolas Marcotte +Reviewed by: Dennis Lundberg +o Minor adjustments to code style +o Added a page to the site with examples +git-svn-id: https://svn.apache.org/repos/asf/maven/plugins/trunk@1203638 13f79535-47bb-0310-9956-ffa450edef68 +",p,https://github.com/apache/maven-plugins,"diff --git a/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java b/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java +index 1d629accad..56d48e039d 100644 +--- a/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java ++++ b/maven-war-plugin/src/main/java/org/apache/maven/plugin/war/WarMojo.java +@@ -75,7 +75,9 @@ public class WarMojo + /** + * The comma separated list of tokens to exclude from the WAR before + * packaging. This option may be used to implement the skinny WAR use +- * case. ++ * case. Note the you can use the Java Regular Expressions engine to ++ * include and exclude specific pattern using the expression %regex[]. ++ * Hint: read the about (?!Pattern). + * + * @parameter + * @since 2.1-alpha-2 +@@ -85,7 +87,9 @@ public class WarMojo + /** + * The comma separated list of tokens to include in the WAR before + * packaging. By default everything is included. This option may be used +- * to implement the skinny WAR use case. ++ * to implement the skinny WAR use case. Note the you can use the ++ * Java Regular Expressions engine to include and exclude specific pattern ++ * using the expression %regex[]. + * + * @parameter + * @since 2.1-beta-1 +diff --git a/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm b/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm +new file mode 100644 +index 0000000000..c1d832d9f6 +--- /dev/null ++++ b/maven-war-plugin/src/site/apt/examples/including-excluding-files-from-war.apt.vm +@@ -0,0 +1,82 @@ ++ ------ ++ Including and Excluding Files From the WAR ++ ------ ++ Dennis Lundberg ++ ------ ++ 2011-11-21 ++ ------ ++ ++~~ Licensed to the Apache Software Foundation (ASF) under one ++~~ or more contributor license agreements. See the NOTICE file ++~~ distributed with this work for additional information ++~~ regarding copyright ownership. The ASF licenses this file ++~~ to you under the Apache License, Version 2.0 (the ++~~ ""License""); you may not use this file except in compliance ++~~ with the License. You may obtain a copy of the License at ++~~ ++~~ http://www.apache.org/licenses/LICENSE-2.0 ++~~ ++~~ Unless required by applicable law or agreed to in writing, ++~~ software distributed under the License is distributed on an ++~~ ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++~~ KIND, either express or implied. See the License for the ++~~ specific language governing permissions and limitations ++~~ under the License. ++ ++~~ NOTE: For help with the syntax of this file, see: ++~~ http://maven.apache.org/doxia/references/apt-format.html ++ ++Including and Excluding Files From the WAR ++ ++ ++ It is possible to include or exclude certain files from the WAR file, by using the <<<\>>> and <<<\>>> configuration parameters. They each take a comma-separated list of Ant file set patterns. You can use wildcards such as <<<**>>> to indicate multiple directories and <<<*>>> to indicate an optional part of a file or directory name. ++ ++ Here is an example where we exclude all JAR files from <<>>: ++ +++-----------------+ ++ ++ ... ++ ++ ++ ++ maven-war-plugin ++ ${project.version} ++ ++ WEB-INF/lib/*.jar ++ ++ ++ ++ ++ ... ++ +++-----------------+ ++ ++ Sometimes even such wildcards are not enough. In these cases you can use regular expressions with the <<<%regex[]>>> syntax. Here is a real life use case in which this is used. In this example we want to exclude any commons-logging and log4j JARs, but we do not want to exclude the log4j-over-slf4j JAR. So we want to exclude <<.jar>>> but keep the <<.jar>>>. ++ +++-----------------+ ++ ++ ... ++ ++ ++ ++ maven-war-plugin ++ ${project.version} ++ ++ ++ ++ WEB-INF/lib/commons-logging-*.jar, ++ %regex[WEB-INF/lib/log4j-(?!over-slf4j).*.jar] ++ ++ ++ ++ ++ ++ ... ++ +++-----------------+ ++ ++ If you have more real life examples of using regular expressions, we'd like to know about them. Please file an issue in {{{../issue-tracking.html}our issue tracker}} with your configuration, so we can expand this page. +diff --git a/maven-war-plugin/src/site/apt/index.apt b/maven-war-plugin/src/site/apt/index.apt +index 61078ae81a..b51358e336 100644 +--- a/maven-war-plugin/src/site/apt/index.apt ++++ b/maven-war-plugin/src/site/apt/index.apt +@@ -81,6 +81,8 @@ Maven WAR Plugin + + * {{{./examples/skinny-wars.html}Creating Skinny WARs}} + ++ * {{{./examples/including-excluding-files-from-war.html}Including and Excluding Files From the WAR}} ++ + * {{{./examples/file-name-mapping.html}Using File Name Mapping}} + + [] +diff --git a/maven-war-plugin/src/site/site.xml b/maven-war-plugin/src/site/site.xml +index f6f9aa7bfa..2244644cc9 100644 +--- a/maven-war-plugin/src/site/site.xml ++++ b/maven-war-plugin/src/site/site.xml +@@ -38,6 +38,7 @@ under the License. + + + ++ + + + +diff --git a/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java b/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java +index c53c7c3cab..f590a19236 100644 +--- a/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java ++++ b/maven-war-plugin/src/test/java/org/apache/maven/plugin/war/WarMojoTest.java +@@ -93,6 +93,38 @@ public void testSimpleWar() + new String[]{null, mojo.getWebXml().toString(), null, null, null, null} ); + } + ++ public void testSimpleWarPackagingExcludeWithIncludesRegEx() ++ throws Exception ++ { ++ String testId = ""SimpleWarPackagingExcludeWithIncludesRegEx""; ++ MavenProject4CopyConstructor project = new MavenProject4CopyConstructor(); ++ String outputDir = getTestDirectory().getAbsolutePath() + ""/"" + testId + ""-output""; ++ File webAppDirectory = new File( getTestDirectory(), testId ); ++ WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() ); ++ String warName = ""simple""; ++ File webAppSource = createWebAppSource( testId ); ++ File classesDir = createClassesDir( testId, true ); ++ File xmlSource = createXMLConfigDir( testId, new String[]{""web.xml""} ); ++ ++ project.setArtifact( warArtifact ); ++ this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project ); ++ setVariableValueToObject( mojo, ""outputDirectory"", outputDir ); ++ setVariableValueToObject( mojo, ""warName"", warName ); ++ mojo.setWebXml( new File( xmlSource, ""web.xml"" ) ); ++ setVariableValueToObject( mojo,""packagingIncludes"",""%regex[(.(?!exile))+]"" ); ++ ++ ++ mojo.execute(); ++ ++ //validate jar file ++ File expectedJarFile = new File( outputDir, ""simple.war"" ); ++ assertJarContent( expectedJarFile, new String[]{""META-INF/MANIFEST.MF"", ""WEB-INF/web.xml"", ""pansit.jsp"", ++ ""META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml"", ++ ""META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties""}, ++ new String[]{null, mojo.getWebXml().toString(), null, null, null, }, ++ new String[]{""org/web/app/last-exile.jsp""} ); ++ } ++ + public void testClassifier() + throws Exception + { +@@ -383,6 +415,12 @@ public void testAttachClassesWithCustomClassifier() + + protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent ) + throws IOException ++ { ++ return assertJarContent( expectedJarFile, files, filesContent, null ); ++ } ++ ++ protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent, final String[] mustNotBeInJar ) ++ throws IOException + { + // Sanity check + assertEquals( ""Could not test, files and filesContent lenght does not match"", files.length, +@@ -404,6 +442,7 @@ protected Map assertJarContent( final File expectedJarFile, final String[] files + for ( int i = 0; i < files.length; i++ ) + { + String file = files[i]; ++ + assertTrue( ""File["" + file + ""] not found in archive"", jarContent.containsKey( file ) ); + if ( filesContent[i] != null ) + { +@@ -411,6 +450,16 @@ protected Map assertJarContent( final File expectedJarFile, final String[] files + IOUtil.toString( jarFile.getInputStream( (ZipEntry) jarContent.get( file ) ) ) ); + } + } ++ if( mustNotBeInJar!=null ) ++ { ++ for ( int i = 0; i < mustNotBeInJar.length; i++ ) ++ { ++ String file = mustNotBeInJar[i]; ++ ++ assertFalse( ""File["" + file + ""] found in archive"", jarContent.containsKey( file ) ); ++ ++ } ++ } + return jarContent; + }" +e4e85d3facf1633ea6a058d186dfbcf75f3e3a07,Delta Spike,"DELTASPIKE-315 provide common EntityManagerFactoryProducer +",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java +new file mode 100644 +index 000000000..ca59d9bc0 +--- /dev/null ++++ b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceConfigurationProvider.java +@@ -0,0 +1,39 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import java.util.Properties; ++ ++/** ++ * Provide the configuration for the EntityManagerFactory ++ * which gets produced with a given {@link PersistenceUnitName}. ++ * ++ * By default we provide a configuration which con be configured ++ * differently depending on the -DdatabaseVendor and the ++ * {@link org.apache.deltaspike.core.api.projectstage.ProjectStage} ++ */ ++public interface PersistenceConfigurationProvider ++{ ++ ++ /** ++ * @param persistenceUnitName the name of the persistence unit in persistence.xml ++ * @return the additional Properties from the configuration. ++ */ ++ Properties getEntityManagerFactoryConfiguration(String persistenceUnitName); ++} +diff --git a/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java +new file mode 100644 +index 000000000..45e94581f +--- /dev/null ++++ b/deltaspike/modules/jpa/api/src/main/java/org/apache/deltaspike/test/jpa/api/entitymanager/PersistenceUnitName.java +@@ -0,0 +1,48 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import javax.enterprise.util.Nonbinding; ++import javax.inject.Qualifier; ++import java.lang.annotation.Documented; ++import java.lang.annotation.Retention; ++import java.lang.annotation.RetentionPolicy; ++import java.lang.annotation.Target; ++ ++import static java.lang.annotation.ElementType.FIELD; ++import static java.lang.annotation.ElementType.METHOD; ++import static java.lang.annotation.ElementType.PARAMETER; ++import static java.lang.annotation.ElementType.TYPE; ++ ++/** ++ * The name of the PersistenceUnit to get picked up by the ++ * EntityManagerFactoryProducer. ++ */ ++@Target( { TYPE, METHOD, PARAMETER, FIELD }) ++@Retention(value= RetentionPolicy.RUNTIME) ++@Documented ++@Qualifier ++public @interface PersistenceUnitName ++{ ++ /** ++ * @return the name of the persistence unit. ++ */ ++ @Nonbinding ++ String value(); ++} +diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java +new file mode 100644 +index 000000000..05129f3a5 +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/EntityManagerFactoryProducer.java +@@ -0,0 +1,67 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.jpa.impl.entitymanager; ++ ++import javax.enterprise.context.Dependent; ++import javax.enterprise.inject.Produces; ++import javax.enterprise.inject.spi.InjectionPoint; ++import javax.inject.Inject; ++import javax.persistence.EntityManagerFactory; ++import javax.persistence.Persistence; ++import java.util.Properties; ++import java.util.logging.Logger; ++ ++import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceConfigurationProvider; ++import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceUnitName; ++ ++ ++/** ++ * TODO ++ */ ++public class EntityManagerFactoryProducer ++{ ++ private static final Logger LOG = Logger.getLogger(EntityManagerFactoryProducer.class.getName()); ++ ++ ++ private @Inject PersistenceConfigurationProvider persistenceConfigurationProvider; ++ ++ ++ @Produces ++ @Dependent ++ @PersistenceUnitName(""any"") // the value is nonbinding, thus this is just a dummy parameter here ++ public EntityManagerFactory createEntityManagerFactoryForUnit(InjectionPoint injectionPoint) ++ { ++ PersistenceUnitName unitNameAnnotation = injectionPoint.getAnnotated().getAnnotation(PersistenceUnitName.class); ++ ++ if (unitNameAnnotation == null) ++ { ++ LOG.warning(""@PersisteneUnitName annotation could not be found at EntityManagerFactory injection point!""); ++ ++ return null; ++ } ++ ++ String unitName = unitNameAnnotation.value(); ++ ++ Properties properties = persistenceConfigurationProvider.getEntityManagerFactoryConfiguration(unitName); ++ ++ EntityManagerFactory emf = Persistence.createEntityManagerFactory(unitName, properties); ++ ++ return emf; ++ } ++} +diff --git a/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java +new file mode 100644 +index 000000000..1271a12b8 +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/main/java/org/apache/deltaspike/jpa/impl/entitymanager/PersistenceConfigurationProviderImpl.java +@@ -0,0 +1,43 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.jpa.impl.entitymanager; ++ ++import javax.enterprise.context.ApplicationScoped; ++ ++ ++import java.util.Properties; ++ ++import org.apache.deltaspike.test.jpa.api.entitymanager.PersistenceConfigurationProvider; ++ ++/** ++ * Default implementation of the PersistenceConfigurationProvider ++ */ ++@ApplicationScoped ++public class PersistenceConfigurationProviderImpl implements PersistenceConfigurationProvider ++{ ++ @Override ++ public Properties getEntityManagerFactoryConfiguration(String persistenceUnitName) ++ { ++ Properties unitProperties = new Properties(); ++ ++ //X TODO fill properties ++ ++ return unitProperties; ++ } ++} +diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java +new file mode 100644 +index 000000000..62b8d032c +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/EntityManagerFactoryProducerTest.java +@@ -0,0 +1,80 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import javax.inject.Inject; ++import javax.persistence.EntityManager; ++import javax.persistence.spi.PersistenceProviderResolverHolder; ++ ++import org.apache.deltaspike.test.category.SeCategory; ++import org.apache.deltaspike.test.jpa.api.shared.TestEntityManager; ++import org.apache.deltaspike.test.util.ArchiveUtils; ++import org.jboss.arquillian.container.test.api.Deployment; ++import org.jboss.arquillian.junit.Arquillian; ++import org.jboss.shrinkwrap.api.ShrinkWrap; ++import org.jboss.shrinkwrap.api.asset.EmptyAsset; ++import org.jboss.shrinkwrap.api.asset.StringAsset; ++import org.jboss.shrinkwrap.api.spec.JavaArchive; ++import org.jboss.shrinkwrap.api.spec.WebArchive; ++ ++import org.junit.Assert; ++import org.junit.Test; ++import org.junit.experimental.categories.Category; ++import org.junit.runner.RunWith; ++ ++@RunWith(Arquillian.class) ++@Category(SeCategory.class) ++public class EntityManagerFactoryProducerTest ++{ ++ ++ @Deployment ++ public static WebArchive deploy() ++ { ++ // set the dummy PersistenceProviderResolver which creates our DummyEntityManagerFactory ++ PersistenceProviderResolverHolder.setPersistenceProviderResolver(new TestPersistenceProviderResolver()); ++ ++ JavaArchive testJar = ShrinkWrap.create(JavaArchive.class, ""unitDefinitionTest.jar"") ++ .addPackage(ArchiveUtils.SHARED_PACKAGE) ++ .addPackage(EntityManagerFactoryProducerTest.class.getPackage().getName()) ++ .addAsManifestResource(EmptyAsset.INSTANCE, ""beans.xml"") ++ .addAsResource(new StringAsset(TestPersistenceProviderResolver.class.getName()), ++ ""META-INF/services/javax.persistence.spi.PersistenceProviderResolver""); ++ ++ return ShrinkWrap.create(WebArchive.class) ++ .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreAndJpaArchive()) ++ .addAsLibraries(testJar) ++ .addAsWebInfResource(ArchiveUtils.getBeansXml(), ""beans.xml""); ++ } ++ ++ ++ @Inject ++ @SampleDb ++ private EntityManager entityManager; ++ ++ @Test ++ public void testUnitDefinitionQualifier() throws Exception ++ { ++ Assert.assertNotNull(entityManager); ++ Assert.assertNotNull(entityManager.getDelegate()); ++ ++ Assert.assertTrue(entityManager.getDelegate() instanceof TestEntityManager); ++ TestEntityManager tem = (TestEntityManager) entityManager.getDelegate(); ++ Assert.assertEquals(""testPersistenceUnit"", tem.getUnitName()); ++ } ++} +diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java +new file mode 100644 +index 000000000..6c57195e3 +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleDb.java +@@ -0,0 +1,40 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import javax.inject.Qualifier; ++import java.lang.annotation.Retention; ++import java.lang.annotation.Target; ++ ++import static java.lang.annotation.ElementType.FIELD; ++import static java.lang.annotation.ElementType.METHOD; ++import static java.lang.annotation.ElementType.PARAMETER; ++import static java.lang.annotation.ElementType.TYPE; ++import static java.lang.annotation.RetentionPolicy.RUNTIME; ++ ++ ++/** ++ * Sample Database Qualifier ++ */ ++@Target( { TYPE, METHOD, PARAMETER, FIELD }) ++@Retention(value= RUNTIME) ++@Qualifier ++public @interface SampleDb ++{ ++} +diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java +new file mode 100644 +index 000000000..238c049a4 +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/SampleEntityManagerProducer.java +@@ -0,0 +1,52 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import javax.enterprise.context.ApplicationScoped; ++import javax.enterprise.context.RequestScoped; ++import javax.enterprise.inject.Disposes; ++import javax.enterprise.inject.Produces; ++import javax.inject.Inject; ++import javax.persistence.EntityManager; ++import javax.persistence.EntityManagerFactory; ++ ++/** ++ * Sample producer for a @SampleDb EntityManager. ++ */ ++@ApplicationScoped ++@SuppressWarnings(""unused"") ++public class SampleEntityManagerProducer ++{ ++ @Inject ++ @PersistenceUnitName(""testPersistenceUnit"") ++ private EntityManagerFactory emf; ++ ++ @Produces ++ @RequestScoped ++ @SampleDb ++ public EntityManager createEntityManager() ++ { ++ return emf.createEntityManager(); ++ } ++ ++ public void closeEm(@Disposes @SampleDb EntityManager em) ++ { ++ em.close(); ++ } ++} +diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java +new file mode 100644 +index 000000000..acd6a651f +--- /dev/null ++++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/entitymanager/TestPersistenceProviderResolver.java +@@ -0,0 +1,159 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.test.jpa.api.entitymanager; ++ ++import javax.enterprise.inject.Typed; ++import javax.persistence.Cache; ++import javax.persistence.EntityManager; ++import javax.persistence.EntityManagerFactory; ++import javax.persistence.PersistenceUnitUtil; ++import javax.persistence.criteria.CriteriaBuilder; ++import javax.persistence.metamodel.Metamodel; ++import javax.persistence.spi.PersistenceProvider; ++import javax.persistence.spi.PersistenceProviderResolver; ++import javax.persistence.spi.PersistenceUnitInfo; ++import javax.persistence.spi.ProviderUtil; ++import java.util.ArrayList; ++import java.util.List; ++import java.util.Map; ++ ++import org.apache.deltaspike.test.jpa.api.shared.TestEntityManager; ++ ++/** ++ * PersistenceProviderResolver for dummy PersistenceProviders. ++ */ ++@Typed() ++public class TestPersistenceProviderResolver implements PersistenceProviderResolver ++{ ++ private List persistenceProviders; ++ ++ public TestPersistenceProviderResolver() ++ { ++ this.persistenceProviders = new ArrayList(); ++ this.persistenceProviders.add(new DummyPersistenceProvider()); ++ } ++ ++ @Override ++ public void clearCachedProviders() ++ { ++ } ++ ++ @Override ++ public List getPersistenceProviders() ++ { ++ return persistenceProviders; ++ } ++ ++ ++ @Typed() ++ public static class DummyPersistenceProvider implements PersistenceProvider ++ { ++ @Override ++ public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) ++ { ++ return new DummyEntityManagerFactory(); ++ } ++ ++ @Override ++ public EntityManagerFactory createEntityManagerFactory(String emName, Map map) ++ { ++ return new DummyEntityManagerFactory(emName, map); ++ } ++ ++ @Override ++ public ProviderUtil getProviderUtil() ++ { ++ return null; ++ } ++ } ++ ++ @Typed() ++ public static class DummyEntityManagerFactory implements EntityManagerFactory ++ { ++ private final String emName; ++ private final Map map; ++ ++ public DummyEntityManagerFactory() ++ { ++ this.emName = null; ++ this.map = null; ++ ++ } ++ ++ public DummyEntityManagerFactory(String emName, Map map) ++ { ++ this.emName = emName; ++ this.map = map; ++ } ++ ++ ++ @Override ++ public void close() ++ { ++ } ++ ++ @Override ++ public EntityManager createEntityManager() ++ { ++ return new TestEntityManager(emName); ++ } ++ ++ @Override ++ public EntityManager createEntityManager(Map map) ++ { ++ return new TestEntityManager(emName); ++ } ++ ++ @Override ++ public CriteriaBuilder getCriteriaBuilder() ++ { ++ return null; ++ } ++ ++ @Override ++ public Metamodel getMetamodel() ++ { ++ return null; ++ } ++ ++ @Override ++ public boolean isOpen() ++ { ++ return false; ++ } ++ ++ @Override ++ public Map getProperties() ++ { ++ return map; ++ } ++ ++ @Override ++ public Cache getCache() ++ { ++ return null; ++ } ++ ++ @Override ++ public PersistenceUnitUtil getPersistenceUnitUtil() ++ { ++ return null; ++ } ++ } ++} +diff --git a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java +index face0a853..44654f592 100644 +--- a/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java ++++ b/deltaspike/modules/jpa/impl/src/test/java/org/apache/deltaspike/test/jpa/api/shared/TestEntityManager.java +@@ -38,6 +38,21 @@ public class TestEntityManager implements EntityManager + + private boolean open = true; + private boolean flushed = false; ++ private String unitName = null; ++ ++ public TestEntityManager() ++ { ++ } ++ ++ public TestEntityManager(String name) ++ { ++ this.unitName = name; ++ } ++ ++ public String getUnitName() ++ { ++ return unitName; ++ } + + @Override + public void persist(Object entity) +@@ -240,7 +255,7 @@ public T unwrap(Class cls) + @Override + public Object getDelegate() + { +- throw new IllegalStateException(""not implemented""); ++ return this; + } + + @Override" +296212eab186b860fd9494db9ed238b341fc2975,kotlin,Merge two JetTypeMapper-mapToCallableMethod- methods--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +ce7f1b2f0c49c2c536f16595888caaf893108ee0,Delta Spike,"add small helper script to quickly verify most important scenarios +",p,https://github.com/apache/deltaspike,"diff --git a/deltaspike/buildall.sh b/deltaspike/buildall.sh +new file mode 100755 +index 000000000..840fefbfa +--- /dev/null ++++ b/deltaspike/buildall.sh +@@ -0,0 +1,33 @@ ++#!/bin/sh ++##################################################################################### ++# Licensed to the Apache Software Foundation (ASF) under one ++# or more contributor license agreements. See the NOTICE file ++# distributed with this work for additional information ++# regarding copyright ownership. The ASF licenses this file ++# to you under the Apache License, Version 2.0 (the ++# ""License""); you may not use this file except in compliance ++# with the License. You may obtain a copy of the License at ++# ++# http://www.apache.org/licenses/LICENSE-2.0 ++# ++# Unless required by applicable law or agreed to in writing, ++# software distributed under the License is distributed on an ++# ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++# KIND, either express or implied. See the License for the ++# specific language governing permissions and limitations ++# under the License. ++##################################################################################### ++# ++# this is a small helper script for building a few container constellations locally ++# you can easily check the output via $> tail mvn-*.log | less ++# ++##################################################################################### ++ ++rm mvn-*log ++mvn clean install -POWB -Dowb.version=1.1.8 | tee mvn-owb1_1_8.log ++mvn clean install -POWB -Dowb.version=1.2.1-SNAPSHOT -Dopenejb.owb.version=1.1.8 | tee mvn-owb1_2_1.log ++mvn clean install -PWeld -Dweld.version=1.1.10.Final | tee mvn-weld1_1_10.log ++mvn clean install -Ptomee-build-managed -Dtomee.version=1.6.0-SNAPSHOT -Dopenejb.version=4.6.0-SNAPSHOT -Dopenejb.owb.version=1.2.1-SNAPSHOT | tee mvn-tomee_1_6_0.log ++mvn clean install -Ptomee-build-managed -Dtomee.version=1.5.2 -Dopenejb.version=4.5.2 -Dopenejb.owb.version=1.1.8 | tee mvn-tomee_1_5_2.log ++mvn clean install -Pjbossas-build-managed-7 | tee mvn-jbossas_7.log ++" +362e94ffa7bc065e0a88f6f999c9c491b06e8946,Vala,"girparser: use identifier prefix from GIR when appropriate + +Fixes bug 731066 +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +233a1b898725fc39f3f14346c716b5f52b3f0e0a,camel,improved the camel-bam module to handle- concurrent processing better & dealing with JDBC/JPA exceptions if concurrent- updates to the same process occur at the same time; also added more better- tests--git-svn-id: https://svn.apache.org/repos/asf/activemq/camel/trunk@563909 13f79535-47bb-0310-9956-ffa450edef68-,p,https://github.com/apache/camel,"diff --git a/components/camel-bam/pom.xml b/components/camel-bam/pom.xml +index ca95a39352679..d590b452ff48c 100644 +--- a/components/camel-bam/pom.xml ++++ b/components/camel-bam/pom.xml +@@ -42,35 +42,38 @@ + org.apache.camel + camel-spring + +- +- +- org.springframework +- spring +- +- +- +- commons-logging +- commons-logging-api +- +- + + javax.persistence + persistence-api + 1.0 + + ++ + + org.apache.camel + camel-core + test-jar +- true + test + + + org.apache.camel + camel-spring + test-jar +- true ++ test ++ ++ ++ org.apache.camel ++ camel-juel ++ test ++ ++ ++ commons-logging ++ commons-logging ++ test ++ ++ ++ log4j ++ log4j + test + + + +- +- mysql +- mysql-connector-java +- 5.0.5 +- test +- + + + junit +@@ -110,6 +107,7 @@ + + false + true ++ pertest + + **/*Test.* + +@@ -163,6 +161,41 @@ + + + ++ ++ derby ++ ++ ++ ++ ${basedir}/src/test/profiles/derby ++ ++ ++ ${basedir}/src/test/resources ++ ++ ++ ++ ++ ++ org.hibernate ++ hibernate-entitymanager ++ test ++ ++ ++ org.hibernate ++ hibernate ++ test ++ ++ ++ org.apache.derby ++ derby ++ test ++ ++ ++ org.apache.geronimo.specs ++ geronimo-jta_1.0.1B_spec ++ test ++ ++ ++ + + + mysql +@@ -188,8 +221,9 @@ + test + + +- hsqldb +- hsqldb ++ mysql ++ mysql-connector-java ++ 5.0.5 + test + + +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/model/ActivityState.java b/components/camel-bam/src/main/java/org/apache/camel/bam/model/ActivityState.java +index 2237b7412453d..b00d817dece2f 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/model/ActivityState.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/model/ActivityState.java +@@ -16,7 +16,9 @@ + */ + package org.apache.camel.bam.model; + +-import java.util.Date; ++import org.apache.camel.bam.processor.ProcessContext; ++import org.apache.camel.bam.rules.ActivityRules; ++import org.apache.camel.util.ObjectHelper; + + import javax.persistence.CascadeType; + import javax.persistence.Entity; +@@ -26,10 +28,8 @@ + import javax.persistence.ManyToOne; + import javax.persistence.Temporal; + import javax.persistence.TemporalType; +- +-import org.apache.camel.bam.processor.ProcessContext; +-import org.apache.camel.bam.rules.ActivityRules; +-import org.apache.camel.util.ObjectHelper; ++import javax.persistence.Transient; ++import java.util.Date; + + /** + * The default state for a specific activity within a process +@@ -56,7 +56,7 @@ public Long getId() { + + @Override + public String toString() { +- return ""ActivityState["" + getId() + "" "" + getActivityDefinition() + ""]""; ++ return ""ActivityState["" + getId() + "" on "" + getProcessInstance() + "" "" + getActivityDefinition() + ""]""; + } + + public synchronized void processExchange(ActivityRules activityRules, ProcessContext context) throws Exception { +@@ -147,6 +147,15 @@ public void setTimeCompleted(Date timeCompleted) { + } + } + ++ @Transient ++ public String getCorrelationKey() { ++ ProcessInstance pi = getProcessInstance(); ++ if (pi == null) { ++ return null; ++ } ++ return pi.getCorrelationKey(); ++ } ++ + // Implementation methods + // ----------------------------------------------------------------------- + +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/model/ProcessInstance.java b/components/camel-bam/src/main/java/org/apache/camel/bam/model/ProcessInstance.java +index 3acc9b04ade76..a74913be344e5 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/model/ProcessInstance.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/model/ProcessInstance.java +@@ -19,15 +19,7 @@ + import java.util.Collection; + import java.util.Date; + import java.util.HashSet; +- +-import javax.persistence.CascadeType; +-import javax.persistence.Entity; +-import javax.persistence.FetchType; +-import javax.persistence.GeneratedValue; +-import javax.persistence.Id; +-import javax.persistence.ManyToOne; +-import javax.persistence.OneToMany; +-import javax.persistence.UniqueConstraint; ++import javax.persistence.*; + + import org.apache.camel.bam.rules.ActivityRules; + import org.apache.commons.logging.Log; +@@ -39,27 +31,29 @@ + * @version $Revision: $ + */ + @Entity +-@UniqueConstraint(columnNames = {""correlationKey"" }) +-public class ProcessInstance extends TemporalEntity { ++public class ProcessInstance { + private static final transient Log LOG = LogFactory.getLog(ProcessInstance.class); + private ProcessDefinition processDefinition; + private Collection activityStates = new HashSet(); + private String correlationKey; ++ private Date timeStarted; ++ private Date timeCompleted; + + public ProcessInstance() { + setTimeStarted(new Date()); + } + + public String toString() { +- return getClass().getName() + ""[id: "" + getId() + "", key: "" + getCorrelationKey() + ""]""; ++ return ""ProcessInstance["" + getCorrelationKey() + ""]""; + } + +- // This crap is required to work around a bug in hibernate +- @Override + @Id +- @GeneratedValue +- public Long getId() { +- return super.getId(); ++ public String getCorrelationKey() { ++ return correlationKey; ++ } ++ ++ public void setCorrelationKey(String correlationKey) { ++ this.correlationKey = correlationKey; + } + + @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST }) +@@ -80,15 +74,34 @@ public void setActivityStates(Collection activityStates) { + this.activityStates = activityStates; + } + +- public String getCorrelationKey() { +- return correlationKey; ++ ++ @Transient ++ public boolean isStarted() { ++ return timeStarted != null; + } + +- public void setCorrelationKey(String correlationKey) { +- this.correlationKey = correlationKey; ++ @Transient ++ public boolean isCompleted() { ++ return timeCompleted != null; ++ } ++ ++ @Temporal(TemporalType.TIME) ++ public Date getTimeStarted() { ++ return timeStarted; ++ } ++ ++ public void setTimeStarted(Date timeStarted) { ++ this.timeStarted = timeStarted; ++ } ++ ++ @Temporal(TemporalType.TIME) ++ public Date getTimeCompleted() { ++ return timeCompleted; + } + +- // Helper methods ++ public void setTimeCompleted(Date timeCompleted) { ++ this.timeCompleted = timeCompleted; ++ } // Helper methods + //------------------------------------------------------------------------- + + /** +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/BamProcessorSupport.java b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/BamProcessorSupport.java +index 4a5acf317efff..ce221ab4d58a8 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/BamProcessorSupport.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/BamProcessorSupport.java +@@ -16,25 +16,27 @@ + */ + package org.apache.camel.bam.processor; + +-import java.lang.reflect.ParameterizedType; +-import java.lang.reflect.Type; +- + import org.apache.camel.Exchange; + import org.apache.camel.Expression; + import org.apache.camel.Processor; + import org.apache.camel.RuntimeCamelException; + import org.apache.commons.logging.Log; + import org.apache.commons.logging.LogFactory; +- ++import org.springframework.dao.DataIntegrityViolationException; ++import org.springframework.orm.jpa.JpaSystemException; + import org.springframework.transaction.TransactionStatus; + import org.springframework.transaction.support.TransactionCallback; + import org.springframework.transaction.support.TransactionTemplate; + ++import javax.persistence.EntityExistsException; ++import java.lang.reflect.ParameterizedType; ++import java.lang.reflect.Type; ++ + /** + * A base {@link Processor} for working on BAM which a derived + * class would do the actual persistence such as the {@link JpaBamProcessor} +- * ++ * + * @version $Revision: $ + */ + public abstract class BamProcessorSupport implements Processor { +@@ -42,6 +44,15 @@ public abstract class BamProcessorSupport implements Processor { + private Class entityType; + private Expression correlationKeyExpression; + private TransactionTemplate transactionTemplate; ++ private int maximumRetries = 30; ++ ++ public int getMaximumRetries() { ++ return maximumRetries; ++ } ++ ++ public void setMaximumRetries(int maximumRetries) { ++ this.maximumRetries = maximumRetries; ++ } + + protected BamProcessorSupport(TransactionTemplate transactionTemplate, Expression correlationKeyExpression) { + this.transactionTemplate = transactionTemplate; +@@ -49,12 +60,12 @@ protected BamProcessorSupport(TransactionTemplate transactionTemplate, Expressio + + Type type = getClass().getGenericSuperclass(); + if (type instanceof ParameterizedType) { +- ParameterizedType parameterizedType = (ParameterizedType)type; ++ ParameterizedType parameterizedType = (ParameterizedType) type; + Type[] arguments = parameterizedType.getActualTypeArguments(); + if (arguments.length > 0) { + Type argumentType = arguments[0]; + if (argumentType instanceof Class) { +- this.entityType = (Class)argumentType; ++ this.entityType = (Class) argumentType; + } + } + } +@@ -70,27 +81,46 @@ protected BamProcessorSupport(TransactionTemplate transactionTemplate, Expressio + } + + public void process(final Exchange exchange) { +- transactionTemplate.execute(new TransactionCallback() { +- public Object doInTransaction(TransactionStatus status) { +- try { +- Object key = getCorrelationKey(exchange); ++ Object entity = null; ++ for (int i = 0; entity == null && i < maximumRetries; i++) { ++ if (i > 0) { ++ LOG.info(""Retry attempt due to duplicate row: "" + i); ++ } ++ entity = transactionTemplate.execute(new TransactionCallback() { ++ public Object doInTransaction(TransactionStatus status) { ++ try { ++ Object key = getCorrelationKey(exchange); + +- T entity = loadEntity(exchange, key); ++ T entity = loadEntity(exchange, key); + +- if (LOG.isDebugEnabled()) { +- LOG.debug(""Correlation key: "" + key + "" with entity: "" + entity); +- } +- processEntity(exchange, entity); ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Correlation key: "" + key + "" with entity: "" + entity); ++ } ++ processEntity(exchange, entity); + +- return entity; +- } catch (Exception e) { +- if (LOG.isDebugEnabled()) { +- LOG.debug(""Caught: "" + e, e); ++ return entity; ++ } ++ catch (JpaSystemException e) { ++ if (LOG.isDebugEnabled()) { ++ LOG.debug(""Likely exception is due to duplicate row in concurrent setting: "" + e, e); ++ } ++ LOG.info(""Attempt to insert duplicate row due to concurrency issue, so retrying: "" + e); ++ return retryDueToDuplicate(status); ++ } ++ catch (DataIntegrityViolationException e) { ++ Throwable throwable = e.getCause(); ++ if (throwable instanceof EntityExistsException) { ++ LOG.info(""Attempt to insert duplicate row due to concurrency issue, so retrying: "" + throwable); ++ return retryDueToDuplicate(status); ++ } ++ return onError(status, throwable); ++ } ++ catch (Throwable e) { ++ return onError(status, e); + } +- throw new RuntimeCamelException(e); + } +- } +- }); ++ }); ++ } + } + + // Properties +@@ -116,4 +146,15 @@ protected Object getCorrelationKey(Exchange exchange) throws NoCorrelationKeyExc + } + return value; + } ++ ++ protected Object retryDueToDuplicate(TransactionStatus status) { ++ status.setRollbackOnly(); ++ return null; ++ } ++ ++ protected Object onError(TransactionStatus status, Throwable e) { ++ status.setRollbackOnly(); ++ LOG.error(""Caught: "" + e, e); ++ throw new RuntimeCamelException(e); ++ } + } +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessor.java b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessor.java +index 84b249e01ebf2..09026f19d585c 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessor.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessor.java +@@ -18,12 +18,12 @@ + + import org.apache.camel.Exchange; + import org.apache.camel.Expression; ++import org.apache.camel.Processor; + import org.apache.camel.bam.model.ActivityState; + import org.apache.camel.bam.model.ProcessInstance; + import org.apache.camel.bam.rules.ActivityRules; + import org.apache.commons.logging.Log; + import org.apache.commons.logging.LogFactory; +- + import org.springframework.orm.jpa.JpaTemplate; + import org.springframework.transaction.support.TransactionTemplate; + +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessorSupport.java b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessorSupport.java +index 15d9c5f987348..281f5815351ae 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessorSupport.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/processor/JpaBamProcessorSupport.java +@@ -16,30 +16,34 @@ + */ + package org.apache.camel.bam.processor; + +-import java.util.List; +- + import org.apache.camel.Exchange; + import org.apache.camel.Expression; + import org.apache.camel.Processor; + import org.apache.camel.bam.model.ProcessDefinition; + import org.apache.camel.bam.rules.ActivityRules; + import org.apache.camel.util.IntrospectionSupport; +- ++import org.apache.commons.logging.Log; ++import org.apache.commons.logging.LogFactory; + import org.springframework.orm.jpa.JpaTemplate; + import org.springframework.transaction.support.TransactionTemplate; + ++import java.util.List; ++ + /** + * A base class for JPA based BAM which can use any entity to store the process + * instance information which allows derived classes to specialise the process + * instance entity. +- * ++ * + * @version $Revision: $ + */ + public class JpaBamProcessorSupport extends BamProcessorSupport { ++ private static final transient Log LOG = LogFactory.getLog(JpaBamProcessorSupport.class); ++ + private ActivityRules activityRules; + private JpaTemplate template; + private String findByKeyQuery; + private String keyPropertyName = ""correlationKey""; ++ private boolean correlationKeyIsPrimary = true; + + public JpaBamProcessorSupport(TransactionTemplate transactionTemplate, JpaTemplate template, Expression correlationKeyExpression, ActivityRules activityRules, Class entitytype) { + super(transactionTemplate, correlationKeyExpression, entitytype); +@@ -88,24 +92,48 @@ public void setTemplate(JpaTemplate template) { + this.template = template; + } + ++ public boolean isCorrelationKeyIsPrimary() { ++ return correlationKeyIsPrimary; ++ } ++ ++ public void setCorrelationKeyIsPrimary(boolean correlationKeyIsPrimary) { ++ this.correlationKeyIsPrimary = correlationKeyIsPrimary; ++ } ++ + // Implementatiom methods + // ----------------------------------------------------------------------- + protected T loadEntity(Exchange exchange, Object key) { +- List list = template.find(getFindByKeyQuery(), key); +- T entity = null; +- if (!list.isEmpty()) { +- entity = list.get(0); +- } ++ T entity = findEntityByCorrelationKey(key); + if (entity == null) { + entity = createEntity(exchange, key); + setKeyProperty(entity, key); + ProcessDefinition definition = ProcessDefinition.getRefreshedProcessDefinition(template, getActivityRules().getProcessRules().getProcessDefinition()); + setProcessDefinitionProperty(entity, definition); + template.persist(entity); ++ ++ // Now we must flush to avoid concurrent updates clashing trying to insert the ++ // same row ++ LOG.debug(""About to flush on entity: "" + entity + "" with key: "" + key); ++ template.flush(); + } + return entity; + } + ++ protected T findEntityByCorrelationKey(Object key) { ++ if (isCorrelationKeyIsPrimary()) { ++ return template.find(getEntityType(), key); ++ } ++ else { ++ List list = template.find(getFindByKeyQuery(), key); ++ if (list.isEmpty()) { ++ return null; ++ } ++ else { ++ return list.get(0); ++ } ++ } ++ } ++ + /** + * Sets the key property on the new entity + */ +@@ -121,14 +149,15 @@ protected void setProcessDefinitionProperty(T entity, ProcessDefinition processD + * Create a new instance of the entity for the given key + */ + protected T createEntity(Exchange exchange, Object key) { +- return (T)exchange.getContext().getInjector().newInstance(getEntityType()); ++ return (T) exchange.getContext().getInjector().newInstance(getEntityType()); + } + + protected void processEntity(Exchange exchange, T entity) throws Exception { + if (entity instanceof Processor) { +- Processor processor = (Processor)entity; ++ Processor processor = (Processor) entity; + processor.process(exchange); +- } else { ++ } ++ else { + // TODO add other extension points - eg. passing in Activity + throw new IllegalArgumentException(""No processor defined for this route""); + } +diff --git a/components/camel-bam/src/main/java/org/apache/camel/bam/rules/ActivityRules.java b/components/camel-bam/src/main/java/org/apache/camel/bam/rules/ActivityRules.java +index 2373fa0dbde6a..b0118e593268e 100644 +--- a/components/camel-bam/src/main/java/org/apache/camel/bam/rules/ActivityRules.java ++++ b/components/camel-bam/src/main/java/org/apache/camel/bam/rules/ActivityRules.java +@@ -74,16 +74,6 @@ public void processExchange(Exchange exchange, ProcessInstance process) { + public ActivityDefinition getActivityDefinition() { + // lets always query for it, to avoid issues with refreshing before a commit etc + return builder.findOrCreateActivityDefinition(activityName); +-/* +- if (activityDefinition == null) { +- activityDefinition = builder.findOrCreateActivityDefinition(activityName); +- } +- else { +- // lets refresh it +- builder.getJpaTemplate().refresh(activityDefinition); +- } +- return activityDefinition; +-*/ + } + + public void setActivityDefinition(ActivityDefinition activityDefinition) { +diff --git a/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java b/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java +index 0f6c2514a7cf3..34fc2d36aa12e 100644 +--- a/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java ++++ b/components/camel-bam/src/test/java/org/apache/camel/bam/BamRouteTest.java +@@ -17,28 +17,26 @@ + package org.apache.camel.bam; + + import org.apache.camel.builder.RouteBuilder; ++import static org.apache.camel.builder.xml.XPathBuilder.xpath; + import org.apache.camel.component.mock.MockEndpoint; + import org.apache.camel.spring.SpringTestSupport; +- ++import static org.apache.camel.util.Time.seconds; + import org.springframework.context.support.ClassPathXmlApplicationContext; + import org.springframework.orm.jpa.JpaTemplate; + import org.springframework.transaction.support.TransactionTemplate; + +-import static org.apache.camel.builder.xml.XPathBuilder.xpath; +-import static org.apache.camel.util.Time.seconds; +- + /** + * @version $Revision: $ + */ + public class BamRouteTest extends SpringTestSupport { ++ protected MockEndpoint overdueEndpoint; + +- public void testSendingToFirstActivityOnlyResultsInOverdueMessage() throws Exception { +- MockEndpoint overdueEndpoint = resolveMandatoryEndpoint(""mock:overdue"", MockEndpoint.class); ++ public void testBam() throws Exception { + overdueEndpoint.expectedMessageCount(1); + + template.sendBody(""direct:a"", ""world!""); + +- overdueEndpoint.assertIsSatisfied(5000); ++ overdueEndpoint.assertIsSatisfied(); + } + + protected ClassPathXmlApplicationContext createApplicationContext() { +@@ -48,7 +46,11 @@ protected ClassPathXmlApplicationContext createApplicationContext() { + @Override + protected void setUp() throws Exception { + super.setUp(); ++ + camelContext.addRoutes(createRouteBuilder()); ++ ++ overdueEndpoint = resolveMandatoryEndpoint(""mock:overdue"", MockEndpoint.class); ++ overdueEndpoint.setDefaulResultWaitMillis(8000); + } + + protected RouteBuilder createRouteBuilder() throws Exception { +diff --git a/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleActivitiesConcurrentlyTest.java b/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleActivitiesConcurrentlyTest.java +new file mode 100644 +index 0000000000000..8714dc1f29dd4 +--- /dev/null ++++ b/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleActivitiesConcurrentlyTest.java +@@ -0,0 +1,43 @@ ++/** ++ * ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.bam; ++ ++import static org.apache.camel.language.juel.JuelExpression.el; ++ ++/** ++ * @version $Revision: 1.1 $ ++ */ ++public class MultipleActivitiesConcurrentlyTest extends MultipleProcessesTest { ++ ++ @Override ++ public void testBam() throws Exception { ++ overdueEndpoint.expectedMessageCount(1); ++ overdueEndpoint.message(0).predicate(el(""${in.body.correlationKey == '124'}"")); ++ ++ Thread thread = new Thread(""B sender"") { ++ public void run() { ++ sendBMessages(); ++ } ++ }; ++ thread.start(); ++ ++ sendAMessages(); ++ ++ overdueEndpoint.assertIsSatisfied(); ++ } ++} +diff --git a/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleProcessesTest.java b/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleProcessesTest.java +new file mode 100644 +index 0000000000000..c9cbf4456933f +--- /dev/null ++++ b/components/camel-bam/src/test/java/org/apache/camel/bam/MultipleProcessesTest.java +@@ -0,0 +1,48 @@ ++/** ++ * ++ * Licensed to the Apache Software Foundation (ASF) under one or more ++ * contributor license agreements. See the NOTICE file distributed with ++ * this work for additional information regarding copyright ownership. ++ * The ASF licenses this file to You under the Apache License, Version 2.0 ++ * (the ""License""); you may not use this file except in compliance with ++ * the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.camel.bam; ++ ++import static org.apache.camel.language.juel.JuelExpression.el; ++ ++/** ++ * @version $Revision: 1.1 $ ++ */ ++public class MultipleProcessesTest extends BamRouteTest { ++ ++ @Override ++ public void testBam() throws Exception { ++ overdueEndpoint.expectedMessageCount(1); ++ overdueEndpoint.message(0).predicate(el(""${in.body.correlationKey == '124'}"")); ++ ++ sendAMessages(); ++ sendBMessages(); ++ ++ overdueEndpoint.assertIsSatisfied(); ++ } ++ ++ protected void sendAMessages() { ++ template.sendBody(""direct:a"", ""A""); ++ template.sendBody(""direct:a"", ""B""); ++ template.sendBody(""direct:a"", ""C""); ++ } ++ ++ protected void sendBMessages() { ++ template.sendBody(""direct:b"", ""A""); ++ template.sendBody(""direct:b"", ""C""); ++ } ++} +diff --git a/components/camel-bam/src/test/profiles/derby/META-INF/persistence.xml b/components/camel-bam/src/test/profiles/derby/META-INF/persistence.xml +new file mode 100644 +index 0000000000000..1ee96e339587a +--- /dev/null ++++ b/components/camel-bam/src/test/profiles/derby/META-INF/persistence.xml +@@ -0,0 +1,35 @@ ++ ++ ++ ++ ++ ++ org.apache.camel.bam.model.ActivityDefinition ++ org.apache.camel.bam.model.ActivityState ++ org.apache.camel.bam.model.ProcessDefinition ++ org.apache.camel.bam.model.ProcessInstance ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/components/camel-bam/src/test/profiles/mysql/META-INF/persistence.xml b/components/camel-bam/src/test/profiles/mysql/META-INF/persistence.xml +index ad93d7cbd1b1d..5b76d5d3cab1c 100644 +--- a/components/camel-bam/src/test/profiles/mysql/META-INF/persistence.xml ++++ b/components/camel-bam/src/test/profiles/mysql/META-INF/persistence.xml +@@ -28,6 +28,11 @@ + + + ++ ++ ++ ++ ++ + + + +diff --git a/components/camel-bam/src/test/resources/log4j.properties b/components/camel-bam/src/test/resources/log4j.properties +index 0fe69a1406688..7aab19225406e 100644 +--- a/components/camel-bam/src/test/resources/log4j.properties ++++ b/components/camel-bam/src/test/resources/log4j.properties +@@ -18,12 +18,13 @@ + # + # The logging properties used for eclipse testing, We want to see debug output on the console. + # +-log4j.rootLogger=INFO, out ++log4j.rootLogger=DEBUG, out + +-#log4j.logger.org.apache.activemq=DEBUG ++# uncomment the next line to debug Camel + log4j.logger.org.apache.camel=DEBUG +-log4j.logger.org.springframework=WARN +-log4j.logger.org.hibernate=WARN ++ ++#log4j.logger.org.springframework=WARN ++#log4j.logger.org.hibernate=WARN + + # CONSOLE appender not used by default + log4j.appender.out=org.apache.log4j.ConsoleAppender +diff --git a/examples/camel-example-bam/src/main/resources/META-INF/persistence.xml b/examples/camel-example-bam/src/main/resources/META-INF/persistence.xml +index ace49a9c84cc6..e60477e5471e7 100644 +--- a/examples/camel-example-bam/src/main/resources/META-INF/persistence.xml ++++ b/examples/camel-example-bam/src/main/resources/META-INF/persistence.xml +@@ -31,6 +31,12 @@ + + + ++ ++ ++ + + + " +e5ad59a45147e27b7c2a7a7aed9272f87a5d4746,intellij-community,WI-31168 Unable to save settings after upgrade- to 2016.1 (cherry picked from commit 5b98073)--,c,https://github.com/JetBrains/intellij-community,"diff --git a/platform/platform-impl/src/com/intellij/remote/RemoteCredentialsHolder.java b/platform/platform-impl/src/com/intellij/remote/RemoteCredentialsHolder.java +index c437aeda7a4b8..1d9b61d4a782f 100644 +--- a/platform/platform-impl/src/com/intellij/remote/RemoteCredentialsHolder.java ++++ b/platform/platform-impl/src/com/intellij/remote/RemoteCredentialsHolder.java +@@ -176,6 +176,7 @@ public void setUseKeyPair(boolean useKeyPair) { + myUseKeyPair = useKeyPair; + } + ++ @NotNull + public String getSerializedUserName() { + if (myAnonymous || myUserName == null) return """"; + return myUserName; +@@ -268,7 +269,7 @@ public void load(Element element) { + + public void save(Element rootElement) { + rootElement.setAttribute(HOST, StringUtil.notNullize(getHost())); +- rootElement.setAttribute(PORT, getLiteralPort()); ++ rootElement.setAttribute(PORT, StringUtil.notNullize(getLiteralPort())); + rootElement.setAttribute(ANONYMOUS, Boolean.toString(isAnonymous())); + rootElement.setAttribute(USERNAME, getSerializedUserName()); + rootElement.setAttribute(PASSWORD, getSerializedPassword());" +17fdbe6c71b97305d5c1d8dd78a6c7b249c9e481,tomakehurst$wiremock,"More flexibility with request body matching +",p,https://github.com/wiremock/wiremock,"diff --git a/docs-v2/_docs/record-playback.md b/docs-v2/_docs/record-playback.md +index 4f701d4f25..42ae79074c 100644 +--- a/docs-v2/_docs/record-playback.md ++++ b/docs-v2/_docs/record-playback.md +@@ -191,6 +191,11 @@ POST /__admin/recordings/start + ""caseInsensitive"" : true + } + }, ++ ""requestBodyPattern"" : { ++ ""matcher"" : ""equalToJson"", ++ ""ignoreArrayOrder"" : false, ++ ""ignoreExtraElements"" : true ++ }, + ""extractBodyCriteria"" : { + ""textSizeThreshold"" : ""2048"", + ""binarySizeThreshold"" : ""10240"" +@@ -200,10 +205,6 @@ POST /__admin/recordings/start + ""transformers"" : [ ""modify-response-header"" ], + ""transformerParameters"" : { + ""headerValue"" : ""123"" +- }, +- ""jsonMatchingFlags"" : { +- ""ignoreArrayOrder"" : false, +- ""ignoreExtraElements"" : true + } + } + ``` +@@ -245,6 +246,11 @@ POST /__admin/recordings/snapshot + ""caseInsensitive"" : true + } + }, ++ ""requestBodyPattern"" : { ++ ""matcher"" : ""equalToJson"", ++ ""ignoreArrayOrder"" : false, ++ ""ignoreExtraElements"" : true ++ }, + ""extractBodyCriteria"" : { + ""textSizeThreshold"" : ""2 kb"", + ""binarySizeThreshold"" : ""1 Mb"" +@@ -255,10 +261,6 @@ POST /__admin/recordings/snapshot + ""transformers"" : [ ""modify-response-header"" ], + ""transformerParameters"" : { + ""headerValue"" : ""123"" +- }, +- ""jsonMatchingFlags"" : { +- ""ignoreArrayOrder"" : false, +- ""ignoreExtraElements"" : true + } + } + ``` +@@ -355,20 +357,26 @@ As with other types of WireMock extension, parameters can be supplied. The exact + ``` + + +-### JSON matching flags ++### Request body matching + +-When a stub is recorded from a request with a JSON body, its body match operator will be set to `equalToJson` (rather than `equalTo`, the default). +-This operator has two optional parameters, indicating whether array order should be ignored, and whether extra elements should be ignored. ++By default, the body match operator for a recorded stub is based on the `Content-Type` header of the request. For `*/json` MIME types, the operator will be `equalToJson` with both the `ignoreArrayOrder` and `ignoreExtraElements` options set to `true`. For `*/xml` MIME types, it will use `equalToXml`. Otherwise, it will use `equalTo` with the `caseInsensitive` option set to `false`. ++ ++ This behavior can be customized via the `requestBodyPattern` parameter, which accepts a `matcher` (either `equalTo`, `equalToJson`, `equalToXml`, or `auto`) and any relevant matcher options (`ignoreArrayOrder`, `ignoreExtraElements`, or `caseInsensitive`). For example, here's how to preserve the default behavior, but set `ignoreArrayOrder` to `false` when `equalToJson` is used: + + ```json +-""jsonMatchingFlags"" : { +- ""ignoreArrayOrder"" : false, +- ""ignoreExtraElements"" : true ++""requestBodyPattern"" : { ++ ""matcher"": ""auto"", ++ ""ignoreArrayOrder"" : false + } + ``` + +-If not specified, both of these will default to `false`. +- ++If you want to always match request bodies with `equalTo` case-insensitively, regardless of the MIME type, use: ++```json ++""requestBodyPattern"" : { ++ ""matcher"": ""equalTo"", ++ ""caseInsenstivie"" : true ++ } ++``` + + > **note** + > +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java +index dc834bac28..655f96cf6e 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpec.java +@@ -34,6 +34,8 @@ public class RecordSpec { + private final ProxiedServeEventFilters filters; + // Headers from the request to include in the stub mapping, if they match the corresponding matcher + private final Map captureHeaders; ++ // Factory for the StringValuePattern that will be used to match request bodies ++ private final RequestBodyPatternFactory requestBodyPatternFactory; + // Criteria for extracting body from responses + private final ResponseDefinitionBodyMatcher extractBodyCriteria; + // How to format StubMappings in the response body +@@ -46,30 +48,29 @@ public class RecordSpec { + private final List transformers; + // Parameters for stub mapping transformers + private final Parameters transformerParameters; +- private final JsonMatchingFlags jsonMatchingFlags; + + @JsonCreator + public RecordSpec( + @JsonProperty(""targetBaseUrl"") String targetBaseUrl, + @JsonProperty(""filters"") ProxiedServeEventFilters filters, + @JsonProperty(""captureHeaders"") Map captureHeaders, ++ @JsonProperty(""requestBodyPattern"") RequestBodyPatternFactory requestBodyPatternFactory, + @JsonProperty(""extractBodyCriteria"") ResponseDefinitionBodyMatcher extractBodyCriteria, + @JsonProperty(""outputFormat"") SnapshotOutputFormatter outputFormat, + @JsonProperty(""persist"") Boolean persist, + @JsonProperty(""repeatsAsScenarios"") Boolean repeatsAsScenarios, + @JsonProperty(""transformers"") List transformers, +- @JsonProperty(""transformerParameters"") Parameters transformerParameters, +- @JsonProperty(""jsonMatchingFlags"") JsonMatchingFlags jsonMatchingFlags) { ++ @JsonProperty(""transformerParameters"") Parameters transformerParameters) { + this.targetBaseUrl = targetBaseUrl; + this.filters = filters == null ? new ProxiedServeEventFilters() : filters; + this.captureHeaders = captureHeaders; ++ this.requestBodyPatternFactory = requestBodyPatternFactory == null ? RequestBodyAutomaticPatternFactory.DEFAULTS : requestBodyPatternFactory; + this.extractBodyCriteria = extractBodyCriteria; + this.outputFormat = outputFormat == null ? SnapshotOutputFormatter.FULL : outputFormat; + this.persist = persist == null ? true : persist; + this.repeatsAsScenarios = repeatsAsScenarios; + this.transformers = transformers; + this.transformerParameters = transformerParameters; +- this.jsonMatchingFlags = jsonMatchingFlags; + } + + private RecordSpec() { +@@ -79,7 +80,7 @@ private RecordSpec() { + public static final RecordSpec DEFAULTS = new RecordSpec(); + + public static RecordSpec forBaseUrl(String targetBaseUrl) { +- return new RecordSpec(targetBaseUrl, null, null, null, null, null, true, null, null, null); ++ return new RecordSpec(targetBaseUrl, null, null, null, null, null, null, true, null, null); + } + + public String getTargetBaseUrl() { +@@ -110,7 +111,5 @@ public Boolean getRepeatsAsScenarios() { + + public ResponseDefinitionBodyMatcher getExtractBodyCriteria() { return extractBodyCriteria; } + +- public JsonMatchingFlags getJsonMatchingFlags() { +- return jsonMatchingFlags; +- } ++ public RequestBodyPatternFactory getRequestBodyPatternFactory() { return requestBodyPatternFactory; } + } +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java +index 4fea93623a..862056c43f 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RecordSpecBuilder.java +@@ -16,8 +16,7 @@ + package com.github.tomakehurst.wiremock.recording; + + import com.github.tomakehurst.wiremock.extension.Parameters; +-import com.github.tomakehurst.wiremock.matching.RequestPattern; +-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; ++import com.github.tomakehurst.wiremock.matching.*; + + import java.util.List; + import java.util.Map; +@@ -32,13 +31,13 @@ public class RecordSpecBuilder { + private RequestPatternBuilder filterRequestPatternBuilder; + private List filterIds; + private Map headers = newLinkedHashMap(); ++ private RequestBodyPatternFactory requestBodyPatternFactory; + private long maxTextBodySize = ResponseDefinitionBodyMatcher.DEFAULT_MAX_TEXT_SIZE; + private long maxBinaryBodySize = ResponseDefinitionBodyMatcher.DEFAULT_MAX_BINARY_SIZE; + private boolean persistentStubs = true; + private boolean repeatsAsScenarios = true; + private List transformerNames; + private Parameters transformerParameters; +- private JsonMatchingFlags jsonMatchingFlags; + + public RecordSpecBuilder forTarget(String targetBaseUrl) { + this.targetBaseUrl = targetBaseUrl; +@@ -98,6 +97,26 @@ public RecordSpecBuilder captureHeader(String key, Boolean caseInsensitive) { + return this; + } + ++ public RecordSpecBuilder requestBodyAutoPattern(boolean ignoreArrayOrder, boolean ignoreExtraElements, boolean caseInsensitive) { ++ this.requestBodyPatternFactory = new RequestBodyAutomaticPatternFactory(ignoreArrayOrder, ignoreExtraElements, caseInsensitive); ++ return this; ++ } ++ ++ public RecordSpecBuilder requestBodyEqualToJsonPattern(boolean ignoreArrayOrder, boolean ignoreExtraElements) { ++ this.requestBodyPatternFactory = new RequestBodyEqualToJsonPatternFactory(ignoreArrayOrder, ignoreExtraElements); ++ return this; ++ } ++ ++ public RecordSpecBuilder requestBodyEqualToXmlPattern() { ++ this.requestBodyPatternFactory = new RequestBodyEqualToXmlPatternFactory(); ++ return this; ++ } ++ ++ public RecordSpecBuilder requestBodyEqualToPattern(boolean caseInsensitive) { ++ this.requestBodyPatternFactory = new RequestBodyEqualToPatternFactory(caseInsensitive); ++ return this; ++ } ++ + public RecordSpec build() { + RequestPattern filterRequestPattern = filterRequestPatternBuilder != null ? + filterRequestPatternBuilder.build() : +@@ -112,17 +131,12 @@ public RecordSpec build() { + targetBaseUrl, + filters, + headers.isEmpty() ? null : headers, ++ requestBodyPatternFactory, + responseDefinitionBodyMatcher, + SnapshotOutputFormatter.FULL, + persistentStubs, + repeatsAsScenarios, + transformerNames, +- transformerParameters, +- jsonMatchingFlags); +- } +- +- public RecordSpecBuilder jsonBodyMatchFlags(boolean ignoreArrayOrder, boolean ignoreExtraElements) { +- this.jsonMatchingFlags = new JsonMatchingFlags(ignoreArrayOrder, ignoreExtraElements); +- return this; ++ transformerParameters); + } + } +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java b/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java +index a80b967ced..9bbe627f16 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/Recorder.java +@@ -106,7 +106,7 @@ public SnapshotRecordResult takeSnapshot(List serveEvents, RecordSpe + final List stubMappings = serveEventsToStubMappings( + Lists.reverse(serveEvents), + recordSpec.getFilters(), +- new SnapshotStubMappingGenerator(recordSpec.getCaptureHeaders(), recordSpec.getJsonMatchingFlags()), ++ new SnapshotStubMappingGenerator(recordSpec.getCaptureHeaders(), recordSpec.getRequestBodyPatternFactory()), + getStubMappingPostProcessor(admin.getOptions(), recordSpec) + ); + +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java +new file mode 100644 +index 0000000000..f0f3c3bc50 +--- /dev/null ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactory.java +@@ -0,0 +1,78 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.fasterxml.jackson.annotation.JsonCreator; ++import com.fasterxml.jackson.annotation.JsonProperty; ++import com.github.tomakehurst.wiremock.http.ContentTypeHeader; ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern; ++import com.github.tomakehurst.wiremock.matching.EqualToPattern; ++import com.github.tomakehurst.wiremock.matching.EqualToXmlPattern; ++import com.github.tomakehurst.wiremock.matching.StringValuePattern; ++ ++public class RequestBodyAutomaticPatternFactory implements RequestBodyPatternFactory { ++ ++ private final Boolean caseInsensitive; ++ private final Boolean ignoreArrayOrder; ++ private final Boolean ignoreExtraElements; ++ ++ @JsonCreator ++ public RequestBodyAutomaticPatternFactory( ++ @JsonProperty(""ignoreArrayOrder"") Boolean ignoreArrayOrder, ++ @JsonProperty(""ignoreExtraElements"") Boolean ignoreExtraElements, ++ @JsonProperty(""caseInsensitive"") Boolean caseInsensitive) { ++ this.ignoreArrayOrder = ignoreArrayOrder == null ? true : ignoreArrayOrder; ++ this.ignoreExtraElements = ignoreExtraElements == null ? true : ignoreExtraElements; ++ this.caseInsensitive = caseInsensitive == null ? false : caseInsensitive; ++ } ++ ++ private RequestBodyAutomaticPatternFactory() { ++ this(null, null, null); ++ } ++ ++ public static final RequestBodyAutomaticPatternFactory DEFAULTS = new RequestBodyAutomaticPatternFactory(); ++ ++ public Boolean isIgnoreArrayOrder() { ++ return ignoreArrayOrder; ++ } ++ ++ public Boolean isIgnoreExtraElements() { ++ return ignoreExtraElements; ++ } ++ ++ public Boolean isCaseInsensitive() { ++ return caseInsensitive; ++ } ++ ++ /** ++ * If request body was JSON or XML, use ""equalToJson"" or ""equalToXml"" (respectively) in the RequestPattern so it's ++ * easier to read. Otherwise, just use ""equalTo"" ++ */ ++ @Override ++ public StringValuePattern forRequest(Request request) { ++ final ContentTypeHeader contentType = request.getHeaders().getContentTypeHeader(); ++ if (contentType.mimeTypePart() != null) { ++ if (contentType.mimeTypePart().contains(""json"")) { ++ return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements); ++ } else if (contentType.mimeTypePart().contains(""xml"")) { ++ return new EqualToXmlPattern(request.getBodyAsString()); ++ } ++ } ++ ++ return new EqualToPattern(request.getBodyAsString(), caseInsensitive); ++ } ++} +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java +similarity index 62% +rename from src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java +rename to src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java +index 2a7f3c69fe..87b54fc90c 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/JsonMatchingFlags.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactory.java +@@ -15,15 +15,20 @@ + */ + package com.github.tomakehurst.wiremock.recording; + ++import com.fasterxml.jackson.annotation.JsonCreator; + import com.fasterxml.jackson.annotation.JsonProperty; ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern; + +-public class JsonMatchingFlags { ++public class RequestBodyEqualToJsonPatternFactory implements RequestBodyPatternFactory { + + private final Boolean ignoreArrayOrder; + private final Boolean ignoreExtraElements; + +- public JsonMatchingFlags(@JsonProperty(""ignoreArrayOrder"") Boolean ignoreArrayOrder, +- @JsonProperty(""ignoreExtraElements"") Boolean ignoreExtraElements) { ++ @JsonCreator ++ public RequestBodyEqualToJsonPatternFactory( ++ @JsonProperty(""ignoreArrayOrder"") Boolean ignoreArrayOrder, ++ @JsonProperty(""ignoreExtraElements"") Boolean ignoreExtraElements) { + this.ignoreArrayOrder = ignoreArrayOrder; + this.ignoreExtraElements = ignoreExtraElements; + } +@@ -35,4 +40,9 @@ public Boolean isIgnoreArrayOrder() { + public Boolean isIgnoreExtraElements() { + return ignoreExtraElements; + } ++ ++ @Override ++ public EqualToJsonPattern forRequest(Request request) { ++ return new EqualToJsonPattern(request.getBodyAsString(), ignoreArrayOrder, ignoreExtraElements); ++ } + } +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java +new file mode 100644 +index 0000000000..f6c7b9dad0 +--- /dev/null ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToPatternFactory.java +@@ -0,0 +1,40 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.fasterxml.jackson.annotation.JsonCreator; ++import com.fasterxml.jackson.annotation.JsonProperty; ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.EqualToPattern; ++ ++public class RequestBodyEqualToPatternFactory implements RequestBodyPatternFactory { ++ ++ private final Boolean caseInsensitive; ++ ++ @JsonCreator ++ public RequestBodyEqualToPatternFactory(@JsonProperty(""caseInsensitive"") Boolean caseInsensitive) { ++ this.caseInsensitive = caseInsensitive; ++ } ++ ++ public Boolean isCaseInsensitive() { ++ return caseInsensitive; ++ } ++ ++ @Override ++ public EqualToPattern forRequest(Request request) { ++ return new EqualToPattern(request.getBodyAsString(), caseInsensitive); ++ } ++} +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java +new file mode 100644 +index 0000000000..0c31cc75c7 +--- /dev/null ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToXmlPatternFactory.java +@@ -0,0 +1,27 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.EqualToXmlPattern; ++ ++public class RequestBodyEqualToXmlPatternFactory implements RequestBodyPatternFactory { ++ ++ @Override ++ public EqualToXmlPattern forRequest(Request request) { ++ return new EqualToXmlPattern(request.getBodyAsString()); ++ } ++} +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java +new file mode 100644 +index 0000000000..c2f350d292 +--- /dev/null ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactory.java +@@ -0,0 +1,40 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.fasterxml.jackson.annotation.JsonSubTypes; ++import com.fasterxml.jackson.annotation.JsonTypeInfo; ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.StringValuePattern; ++ ++/** ++ * Factory for the StringValuePattern to use in a recorded stub mapping to match request bodies ++ */ ++@JsonTypeInfo( ++ use = JsonTypeInfo.Id.NAME, ++ include = JsonTypeInfo.As.PROPERTY, ++ property = ""matcher"", ++ defaultImpl = RequestBodyAutomaticPatternFactory.class ++) ++@JsonSubTypes({ ++ @JsonSubTypes.Type(value = RequestBodyAutomaticPatternFactory.class, name = ""auto""), ++ @JsonSubTypes.Type(value = RequestBodyEqualToPatternFactory.class, name = ""equalTo""), ++ @JsonSubTypes.Type(value = RequestBodyEqualToJsonPatternFactory.class, name = ""equalToJson""), ++ @JsonSubTypes.Type(value = RequestBodyEqualToXmlPatternFactory.class, name = ""equalToXml"") ++}) ++public interface RequestBodyPatternFactory { ++ StringValuePattern forRequest(Request request); ++} +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java +index 65c7c36afd..dd194e99b7 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformer.java +@@ -15,9 +15,6 @@ + */ + package com.github.tomakehurst.wiremock.recording; + +-import com.fasterxml.jackson.annotation.JsonCreator; +-import com.fasterxml.jackson.annotation.JsonProperty; +-import com.github.tomakehurst.wiremock.http.ContentTypeHeader; + import com.github.tomakehurst.wiremock.http.Request; + import com.github.tomakehurst.wiremock.matching.*; + import com.google.common.base.Function; +@@ -33,13 +30,13 @@ + */ + public class RequestPatternTransformer implements Function { + private final Map headers; +- private final JsonMatchingFlags jsonMatchingFlags; ++ private final RequestBodyPatternFactory bodyPatternFactory; + +- @JsonCreator +- public RequestPatternTransformer(@JsonProperty(""headers"") Map headers, +- @JsonProperty(""jsonMatchingFlags"") JsonMatchingFlags jsonMatchingFlags) { ++ public RequestPatternTransformer( ++ Map headers, ++ RequestBodyPatternFactory bodyPatternFactory) { + this.headers = headers; +- this.jsonMatchingFlags = jsonMatchingFlags; ++ this.bodyPatternFactory = bodyPatternFactory; + } + + /** +@@ -62,29 +59,10 @@ public RequestPatternBuilder apply(Request request) { + } + + String body = request.getBodyAsString(); +- if (body != null && !body.isEmpty()) { +- builder.withRequestBody(valuePatternForContentType(request)); ++ if (bodyPatternFactory != null && body != null && !body.isEmpty()) { ++ builder.withRequestBody(bodyPatternFactory.forRequest(request)); + } + + return builder; + } +- +- /** +- * If request body was JSON or XML, use ""equalToJson"" or ""equalToXml"" (respectively) in the RequestPattern so it's +- * easier to read. Otherwise, just use ""equalTo"" +- */ +- private StringValuePattern valuePatternForContentType(Request request) { +- final ContentTypeHeader contentType = request.getHeaders().getContentTypeHeader(); +- if (contentType.mimeTypePart() != null) { +- if (contentType.mimeTypePart().contains(""json"")) { +- return jsonMatchingFlags == null ? +- equalToJson(request.getBodyAsString()) : +- equalToJson(request.getBodyAsString(), jsonMatchingFlags.isIgnoreArrayOrder(), jsonMatchingFlags.isIgnoreExtraElements()); +- } else if (contentType.mimeTypePart().contains(""xml"")) { +- return equalToXml(request.getBodyAsString()); +- } +- } +- +- return equalTo(request.getBodyAsString()); +- } + } +diff --git a/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java b/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java +index 32e9ecebad..5fb93f6715 100644 +--- a/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java ++++ b/src/main/java/com/github/tomakehurst/wiremock/recording/SnapshotStubMappingGenerator.java +@@ -40,9 +40,9 @@ public SnapshotStubMappingGenerator( + this.responseTransformer = responseTransformer; + } + +- public SnapshotStubMappingGenerator(Map captureHeaders, JsonMatchingFlags jsonMatchingFlags) { ++ public SnapshotStubMappingGenerator(Map captureHeaders, RequestBodyPatternFactory requestBodyPatternFactory) { + this( +- new RequestPatternTransformer(captureHeaders, jsonMatchingFlags), ++ new RequestPatternTransformer(captureHeaders, requestBodyPatternFactory), + new LoggedResponseDefinitionTransformer() + ); + } +diff --git a/src/main/resources/raml/examples/record-spec.example.json b/src/main/resources/raml/examples/record-spec.example.json +index 8fff7ed1bc..fef1992388 100644 +--- a/src/main/resources/raml/examples/record-spec.example.json ++++ b/src/main/resources/raml/examples/record-spec.example.json +@@ -10,6 +10,11 @@ + ""caseInsensitive"" : true + } + }, ++ ""requestBodyPattern"" : { ++ ""matcher"" : ""equalToJson"", ++ ""ignoreArrayOrder"" : false, ++ ""ignoreExtraElements"" : true ++ }, + ""extractBodyCriteria"" : { + ""textSizeThreshold"" : ""2048"", + ""binarySizeThreshold"" : ""10240"" +@@ -19,9 +24,5 @@ + ""transformers"" : [ ""modify-response-header"" ], + ""transformerParameters"" : { + ""headerValue"" : ""123"" +- }, +- ""jsonMatchingFlags"" : { +- ""ignoreArrayOrder"" : false, +- ""ignoreExtraElements"" : true + } + } +\ No newline at end of file +diff --git a/src/main/resources/raml/examples/snapshot-spec.example.json b/src/main/resources/raml/examples/snapshot-spec.example.json +index 45317b706f..b9a3e18fba 100644 +--- a/src/main/resources/raml/examples/snapshot-spec.example.json ++++ b/src/main/resources/raml/examples/snapshot-spec.example.json +@@ -10,6 +10,11 @@ + ""caseInsensitive"" : true + } + }, ++ ""requestBodyPattern"" : { ++ ""matcher"" : ""equalToJson"", ++ ""ignoreArrayOrder"" : false, ++ ""ignoreExtraElements"" : true ++ }, + ""extractBodyCriteria"" : { + ""textSizeThreshold"" : ""2 kb"", + ""binarySizeThreshold"" : ""1 Mb"" +@@ -20,9 +25,5 @@ + ""transformers"" : [ ""modify-response-header"" ], + ""transformerParameters"" : { + ""headerValue"" : ""123"" +- }, +- ""jsonMatchingFlags"" : { +- ""ignoreArrayOrder"" : false, +- ""ignoreExtraElements"" : true + } + } +\ No newline at end of file +diff --git a/src/main/resources/raml/schemas/record-spec.schema.json b/src/main/resources/raml/schemas/record-spec.schema.json +index 4c49d63585..e3db883663 100644 +--- a/src/main/resources/raml/schemas/record-spec.schema.json ++++ b/src/main/resources/raml/schemas/record-spec.schema.json +@@ -18,6 +18,29 @@ + } + } + }, ++ ""requestBodyPattern"": { ++ ""type"": ""object"", ++ ""properties"": { ++ ""matcher"": { ++ ""type"": ""string"", ++ ""enum"": [ ++ ""equalTo"", ++ ""equalToJson"", ++ ""equalToXml"", ++ ""auto"" ++ ] ++ }, ++ ""ignoreArrayOrder"": { ++ ""type"": ""boolean"" ++ }, ++ ""ignoreExtraElements"": { ++ ""type"": ""boolean"" ++ }, ++ ""caseInsensitive"": { ++ ""type"": ""boolean"" ++ } ++ } ++ }, + ""filters"": { + ""type"": ""object"", + ""properties"": { +@@ -35,17 +58,6 @@ + } + } + }, +- ""jsonMatchingFlags"": { +- ""type"": ""object"", +- ""properties"": { +- ""ignoreArrayOrder"": { +- ""type"": ""boolean"" +- }, +- ""ignoreExtraElements"": { +- ""type"": ""boolean"" +- } +- } +- }, + ""persist"": { + ""type"": ""boolean"" + }, +diff --git a/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java +index dc3233ed89..e7c592e9c0 100644 +--- a/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java ++++ b/src/test/java/com/github/tomakehurst/wiremock/RecordingDslAcceptanceTest.java +@@ -199,7 +199,7 @@ public void supportsInstanceClientWithSpec() { + adminClient.startStubRecording( + recordSpec() + .forTarget(targetBaseUrl) +- .jsonBodyMatchFlags(true, true) ++ .requestBodyEqualToJsonPattern(true, true) + ); + + client.postJson(""/record-this-with-body"", ""{}""); +@@ -218,7 +218,7 @@ public void supportsDirectDslCallsWithSpec() { + proxyingService.startRecording( + recordSpec() + .forTarget(targetBaseUrl) +- .jsonBodyMatchFlags(true, true) ++ .requestBodyEqualToJsonPattern(true, true) + ); + + client.postJson(""/record-this-with-body"", ""{}""); +diff --git a/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java b/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java +index 89129b6cfb..35a96d31bd 100644 +--- a/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java ++++ b/src/test/java/com/github/tomakehurst/wiremock/SnapshotDslAcceptanceTest.java +@@ -22,9 +22,7 @@ + import com.github.tomakehurst.wiremock.extension.StubMappingTransformer; + import com.github.tomakehurst.wiremock.http.RequestMethod; + import com.github.tomakehurst.wiremock.http.ResponseDefinition; +-import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern; +-import com.github.tomakehurst.wiremock.matching.EqualToPattern; +-import com.github.tomakehurst.wiremock.matching.StringValuePattern; ++import com.github.tomakehurst.wiremock.matching.*; + import com.github.tomakehurst.wiremock.stubbing.Scenario; + import com.github.tomakehurst.wiremock.stubbing.StubMapping; + import com.github.tomakehurst.wiremock.testsupport.WireMatchers; +@@ -106,8 +104,8 @@ public void snapshotRecordsAllLoggedRequestsWhenNoParametersPassed() throws Exce + JSONAssert.assertEquals(""{ \""counter\"": 55 }"", bodyPattern.getExpected(), true); + + EqualToJsonPattern equalToJsonPattern = (EqualToJsonPattern) bodyPattern; +- assertThat(equalToJsonPattern.isIgnoreArrayOrder(), nullValue()); +- assertThat(equalToJsonPattern.isIgnoreExtraElements(), nullValue()); ++ assertThat(equalToJsonPattern.isIgnoreArrayOrder(), is(true)); ++ assertThat(equalToJsonPattern.isIgnoreExtraElements(), is(true)); + } + + @Test +@@ -253,27 +251,64 @@ public void appliesTransformerWithParameters() { + } + + @Test +- public void supportsConfigurationOfJsonBodyMatching() { ++ public void supportsConfigurationOfAutoRequestBodyPatternFactory() { + client.postJson(""/some-json"", ""{}""); ++ client.postWithBody(""/some-json"", """", ""application/xml"", ""utf-8""); ++ client.postWithBody(""/some-json"", ""foo"", ""application/text"", ""utf-8""); + +- List mappings = snapshotRecord( +- recordSpec().jsonBodyMatchFlags(true, true) +- ); ++ List mappings = snapshotRecord(recordSpec().requestBodyAutoPattern(false, false, true)); ++ ++ EqualToJsonPattern jsonBodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0); ++ assertThat(jsonBodyPattern.getEqualToJson(), is(""{}"")); ++ assertThat(jsonBodyPattern.isIgnoreArrayOrder(), is(false)); ++ assertThat(jsonBodyPattern.isIgnoreExtraElements(), is(false)); ++ ++ EqualToXmlPattern xmlBodyPattern = (EqualToXmlPattern) mappings.get(1).getRequest().getBodyPatterns().get(0); ++ assertThat(xmlBodyPattern.getEqualToXml(), is("""")); ++ ++ EqualToPattern textBodyPattern = (EqualToPattern) mappings.get(2).getRequest().getBodyPatterns().get(0); ++ assertThat(textBodyPattern.getEqualTo(), is(""foo"")); ++ assertThat(textBodyPattern.getCaseInsensitive(), is(true)); ++ } ++ ++ @Test ++ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToJsonPattern() { ++ client.postJson(""/some-json"", ""{}""); ++ ++ List mappings = snapshotRecord(recordSpec().requestBodyEqualToJsonPattern(false, true)); + + EqualToJsonPattern bodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0); +- assertThat(bodyPattern.isIgnoreArrayOrder(), is(true)); ++ assertThat(bodyPattern.isIgnoreArrayOrder(), is(false)); + assertThat(bodyPattern.isIgnoreExtraElements(), is(true)); + } + + @Test +- public void defaultsToNoJsonBodyMatchingFlags() { ++ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToXmlPattern() { ++ client.postWithBody(""/some-json"", """", ""application/xml"", ""utf-8""); ++ ++ List mappings = snapshotRecord(recordSpec().requestBodyEqualToXmlPattern()); ++ ++ assertThat(mappings.get(0).getRequest().getBodyPatterns().get(0), instanceOf(EqualToXmlPattern.class)); ++ } ++ ++ @Test ++ public void supportsConfigurationOfRequestBodyPatternFactoryWithEqualToPattern() { ++ client.postWithBody(""/some-json"", ""foo"", ""application/text"", ""utf-8""); ++ ++ List mappings = snapshotRecord(recordSpec().requestBodyEqualToPattern(true)); ++ ++ EqualToPattern bodyPattern = (EqualToPattern) mappings.get(0).getRequest().getBodyPatterns().get(0); ++ assertThat(bodyPattern.getCaseInsensitive(), is(true)); ++ } ++ ++ @Test ++ public void defaultsToAutomaticRequestBodyPattern() { + client.postJson(""/some-json"", ""{}""); + + List mappings = snapshotRecord(recordSpec()); + + EqualToJsonPattern bodyPattern = (EqualToJsonPattern) mappings.get(0).getRequest().getBodyPatterns().get(0); +- assertThat(bodyPattern.isIgnoreArrayOrder(), nullValue()); +- assertThat(bodyPattern.isIgnoreExtraElements(), nullValue()); ++ assertThat(bodyPattern, is(new EqualToJsonPattern(""{}"", true, true))); + } + + @Test +diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java +new file mode 100644 +index 0000000000..a64088f4c6 +--- /dev/null ++++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyAutomaticPatternFactoryTest.java +@@ -0,0 +1,87 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.github.tomakehurst.wiremock.http.Request; ++import com.github.tomakehurst.wiremock.matching.*; ++import org.junit.Test; ++ ++import static org.hamcrest.Matchers.is; ++import static org.junit.Assert.assertThat; ++import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest; ++ ++public class RequestBodyAutomaticPatternFactoryTest { ++ private final static String JSON_TEST_STRING = ""{ \""foo\"": 1 }""; ++ private final static String XML_TEST_STRING = """"; ++ ++ @Test ++ public void forRequestWithTextBodyIsCaseSensitiveByDefault() { ++ Request request = mockRequest().body(JSON_TEST_STRING); ++ EqualToPattern pattern = (EqualToPattern) patternForRequest(request); ++ ++ assertThat(pattern.getEqualTo(), is(JSON_TEST_STRING)); ++ assertThat(pattern.getCaseInsensitive(), is(false)); ++ } ++ ++ @Test ++ public void forRequestWithTextBodyRespectsCaseInsensitiveOption() { ++ Request request = mockRequest().body(JSON_TEST_STRING); ++ RequestBodyAutomaticPatternFactory patternFactory = new RequestBodyAutomaticPatternFactory(false, false, true); ++ EqualToPattern pattern = (EqualToPattern) patternFactory.forRequest(request); ++ ++ assertThat(pattern.getEqualTo(), is(JSON_TEST_STRING)); ++ assertThat(pattern.getCaseInsensitive(), is(true)); ++ } ++ ++ @Test ++ public void forRequestWithJsonBodyIgnoresExtraElementsAndArrayOrderByDefault() { ++ Request request = mockRequest() ++ .header(""Content-Type"", ""application/json"") ++ .body(JSON_TEST_STRING); ++ EqualToJsonPattern pattern = (EqualToJsonPattern) patternForRequest(request); ++ ++ assertThat(pattern.getEqualToJson(), is(JSON_TEST_STRING)); ++ assertThat(pattern.isIgnoreExtraElements(), is(true)); ++ assertThat(pattern.isIgnoreArrayOrder(), is(true)); ++ } ++ ++ @Test ++ public void forRequestWithJsonBodyRespectsOptions() { ++ RequestBodyAutomaticPatternFactory patternFactory = new RequestBodyAutomaticPatternFactory(false, false, false); ++ Request request = mockRequest() ++ .header(""Content-Type"", ""application/json"") ++ .body(JSON_TEST_STRING); ++ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(request); ++ ++ assertThat(pattern.getEqualToJson(), is(JSON_TEST_STRING)); ++ assertThat(pattern.isIgnoreExtraElements(), is(false)); ++ assertThat(pattern.isIgnoreArrayOrder(), is(false)); ++ } ++ ++ @Test ++ public void forRequestWithXmlBody() { ++ Request request = mockRequest() ++ .header(""Content-Type"", ""application/xml"") ++ .body(XML_TEST_STRING); ++ EqualToXmlPattern pattern = (EqualToXmlPattern) patternForRequest(request); ++ ++ assertThat(pattern.getEqualToXml(), is(XML_TEST_STRING)); ++ } ++ ++ private static StringValuePattern patternForRequest(Request request) { ++ return RequestBodyAutomaticPatternFactory.DEFAULTS.forRequest(request); ++ } ++} +diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java +new file mode 100644 +index 0000000000..4b30beebef +--- /dev/null ++++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyEqualToJsonPatternFactoryTest.java +@@ -0,0 +1,46 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.github.tomakehurst.wiremock.matching.EqualToJsonPattern; ++import org.junit.Test; ++ ++import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest; ++import static org.hamcrest.Matchers.is; ++import static org.junit.Assert.assertThat; ++ ++public class RequestBodyEqualToJsonPatternFactoryTest { ++ ++ @Test ++ public void withIgnoreArrayOrder() { ++ RequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(true, false); ++ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body(""{}"")); ++ ++ assertThat(pattern.getEqualToJson(), is(""{}"")); ++ assertThat(pattern.isIgnoreExtraElements(), is(false)); ++ assertThat(pattern.isIgnoreArrayOrder(), is(true)); ++ } ++ ++ @Test ++ public void withIgnoreExtraElements() { ++ RequestBodyEqualToJsonPatternFactory patternFactory = new RequestBodyEqualToJsonPatternFactory(false, true); ++ EqualToJsonPattern pattern = (EqualToJsonPattern) patternFactory.forRequest(mockRequest().body(""{}"")); ++ ++ assertThat(pattern.getEqualToJson(), is(""{}"")); ++ assertThat(pattern.isIgnoreExtraElements(), is(true)); ++ assertThat(pattern.isIgnoreArrayOrder(), is(false)); ++ } ++} +diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java +new file mode 100644 +index 0000000000..ee2b6c3021 +--- /dev/null ++++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestBodyPatternFactoryJsonDeserializerTest.java +@@ -0,0 +1,76 @@ ++/* ++ * Copyright (C) 2011 Thomas Akehurst ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package com.github.tomakehurst.wiremock.recording; ++ ++import com.github.tomakehurst.wiremock.common.Json; ++import com.github.tomakehurst.wiremock.matching.*; ++import org.junit.Test; ++ ++import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest; ++import static org.hamcrest.Matchers.instanceOf; ++import static org.hamcrest.Matchers.is; ++import static org.junit.Assert.assertThat; ++ ++public class RequestBodyPatternFactoryJsonDeserializerTest { ++ @Test ++ public void correctlyDeserializesWithEmptyObject() { ++ RequestBodyPatternFactory bodyPatternFactory = deserializeJson(""{}""); ++ assertThat(bodyPatternFactory, instanceOf(RequestBodyAutomaticPatternFactory.class)); ++ } ++ ++ @Test ++ public void correctlyDeserializesWithAutoMatcher() { ++ RequestBodyPatternFactory bodyPatternFactory = deserializeJson(""{ \""matcher\"": \""auto\"" }""); ++ assertThat(bodyPatternFactory, instanceOf(RequestBodyAutomaticPatternFactory.class)); ++ } ++ ++ @Test ++ public void correctlyDeserializesWithEqualToMatcher() { ++ RequestBodyPatternFactory bodyPatternFactory = deserializeJson( ++ ""{ \n"" + ++ "" \""matcher\"": \""equalTo\"", \n"" + ++ "" \""caseInsensitive\"": true \n"" + ++ ""} "" ++ ); ++ EqualToPattern bodyPattern = (EqualToPattern) bodyPatternFactory.forRequest(mockRequest()); ++ assertThat(bodyPattern.getCaseInsensitive(), is(true)); ++ } ++ ++ @Test ++ public void correctlyDeserializesWithEqualToJsonMatcher() { ++ RequestBodyPatternFactory bodyPatternFactory = deserializeJson( ++ ""{ \n"" + ++ "" \""matcher\"": \""equalToJson\"", \n"" + ++ "" \""ignoreArrayOrder\"": false, \n"" + ++ "" \""ignoreExtraElements\"": true \n"" + ++ ""} "" ++ ); ++ EqualToJsonPattern bodyPattern = (EqualToJsonPattern) bodyPatternFactory.forRequest(mockRequest().body(""1"")); ++ assertThat(bodyPattern.isIgnoreArrayOrder(), is(false)); ++ assertThat(bodyPattern.isIgnoreExtraElements(), is(true)); ++ ++ } ++ ++ @Test ++ public void correctlyDeserializesWithEqualToXmlMatcher() { ++ RequestBodyPatternFactory bodyPatternFactory = deserializeJson(""{ \""matcher\"": \""equalToXml\"" }""); ++ assertThat(bodyPatternFactory, instanceOf(RequestBodyEqualToXmlPatternFactory.class)); ++ } ++ ++ private static RequestBodyPatternFactory deserializeJson(String json) { ++ return Json.read(json, RequestBodyPatternFactory.class); ++ } ++} +diff --git a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java +index 007a2d24c2..3bbe1ac1b8 100644 +--- a/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java ++++ b/src/test/java/com/github/tomakehurst/wiremock/recording/RequestPatternTransformerTest.java +@@ -15,75 +15,50 @@ + */ + package com.github.tomakehurst.wiremock.recording; + +-import com.github.tomakehurst.wiremock.recording.CaptureHeadersSpec; +-import com.github.tomakehurst.wiremock.recording.RequestPatternTransformer; + import com.github.tomakehurst.wiremock.http.Request; + import com.github.tomakehurst.wiremock.http.RequestMethod; +-import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder; ++import com.github.tomakehurst.wiremock.matching.*; ++import com.google.common.collect.ImmutableMap; + import org.junit.Test; + + import java.util.Map; + + import static com.github.tomakehurst.wiremock.client.WireMock.*; + import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest; +-import static com.google.common.collect.Maps.newLinkedHashMap; + import static org.junit.Assert.assertEquals; + + public class RequestPatternTransformerTest { + @Test +- public void applyWithDefaultsAndNoBody() { ++ public void applyIncludesMethodAndUrlMatchers() { + Request request = mockRequest() + .url(""/foo"") + .method(RequestMethod.GET) + .header(""User-Agent"", ""foo"") + .header(""X-Foo"", ""bar""); ++ + RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.GET, urlEqualTo(""/foo"")); + +- // Default is to include method and URL exactly + assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build()); + } + + @Test +- public void applyWithUrlAndPlainTextBody() { ++ public void applyWithHeaders() { + Request request = mockRequest() +- .url(""/foo"") +- .method(RequestMethod.GET) +- .body(""HELLO"") +- .header(""Accept"", ""foo"") +- .header(""User-Agent"", ""bar""); ++ .url(""/"") ++ .method(RequestMethod.POST) ++ .header(""X-CaseSensitive"", ""foo"") ++ .header(""X-Ignored"", ""ignored"") ++ .header(""X-CaseInsensitive"", ""Baz""); + +- RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.GET, urlEqualTo(""/foo"")) +- .withRequestBody(equalTo(""HELLO"")); ++ RequestPatternBuilder expected = new RequestPatternBuilder(RequestMethod.POST, urlEqualTo(""/"")) ++ .withHeader(""X-CaseSensitive"", equalTo(""foo"")) ++ .withHeader(""X-CaseInsensitive"", equalToIgnoreCase(""Baz"")); + +- Map headers = newLinkedHashMap(); ++ Map headers = ImmutableMap.of( ++ ""X-CaseSensitive"", new CaptureHeadersSpec(false), ++ ""X-CaseInsensitive"", new CaptureHeadersSpec(true) ++ ); + + assertEquals(expected.build(), new RequestPatternTransformer(headers, null).apply(request).build()); + } +- +- @Test +- public void applyWithOnlyJsonBody() { +- Request request = mockRequest() +- .url(""/somewhere"") +- .header(""Content-Type"", ""application/json"") +- .body(""['hello']""); +- RequestPatternBuilder expected = new RequestPatternBuilder() +- .withUrl(""/somewhere"") +- .withRequestBody(equalToJson(""['hello']"")); +- +- assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build()); +- } +- +- @Test +- public void applyWithOnlyXmlBody() { +- Request request = mockRequest() +- .url(""/somewhere"") +- .header(""Content-Type"", ""application/xml"") +- .body(""""); +- +- RequestPatternBuilder expected = new RequestPatternBuilder() +- .withUrl(""/somewhere"") +- .withRequestBody(equalToXml("""")); +- +- assertEquals(expected.build(), new RequestPatternTransformer(null, null).apply(request).build()); +- } + } +diff --git a/src/test/java/ignored/Examples.java b/src/test/java/ignored/Examples.java +index 4dd2fd738b..fc50a248de 100644 +--- a/src/test/java/ignored/Examples.java ++++ b/src/test/java/ignored/Examples.java +@@ -417,7 +417,7 @@ public void recordingDsl() { + .ignoreRepeatRequests() + .transformers(""modify-response-header"") + .transformerParameters(Parameters.one(""headerValue"", ""123"")) +- .jsonBodyMatchFlags(false, true) ++ .requestBodyEqualToJsonPattern(false, true) + ); + + System.out.println(Json.write(recordSpec() +@@ -431,7 +431,7 @@ public void recordingDsl() { + .ignoreRepeatRequests() + .transformers(""modify-response-header"") + .transformerParameters(Parameters.one(""headerValue"", ""123"")) +- .jsonBodyMatchFlags(false, true) ++ .requestBodyEqualToJsonPattern(false, true) + .build())); + } + +@@ -449,7 +449,7 @@ public void snapshotDsl() { + .ignoreRepeatRequests() + .transformers(""modify-response-header"") + .transformerParameters(Parameters.one(""headerValue"", ""123"")) +- .jsonBodyMatchFlags(false, true) ++ .requestBodyEqualToJsonPattern(false, true) + ); + + System.out.println(Json.write(recordSpec() +@@ -463,7 +463,7 @@ public void snapshotDsl() { + .ignoreRepeatRequests() + .transformers(""modify-response-header"") + .transformerParameters(Parameters.one(""headerValue"", ""123"")) +- .jsonBodyMatchFlags(false, true) ++ .requestBodyEqualToJsonPattern(false, true) + .build())); + } + }" +737771ba18bca7bdd3e8684f06f127b6f16f6e18,Delta Spike,"DELTASPIKE-277 add JsfMessage API +",a,https://github.com/apache/deltaspike,"diff --git a/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/message/JsfMessage.java b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/message/JsfMessage.java +new file mode 100644 +index 000000000..01bbdd70d +--- /dev/null ++++ b/deltaspike/modules/jsf/api/src/main/java/org/apache/deltaspike/jsf/message/JsfMessage.java +@@ -0,0 +1,48 @@ ++/* ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, ++ * software distributed under the License is distributed on an ++ * ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++ * KIND, either express or implied. See the License for the ++ * specific language governing permissions and limitations ++ * under the License. ++ */ ++package org.apache.deltaspike.jsf.message; ++ ++/** ++ *

    An injectable component for typesafe FacesMessages. ++ * T must be a class which is annotated with ++ * {@link org.apache.deltaspike.core.api.message.annotation.MessageBundle}

    ++ * ++ *

    Usage: ++ *

    ++ * @Inject
    ++ * JsfMessage<MyMessages> msg;
    ++ * ...
    ++ * msg.addError().userNotLoggedIn();
    ++ * 
    ++ *

    MessageBundle methods which are used as JsfMessage can return a ++ * {@link org.apache.deltaspike.core.api.message.Message} or a String. ++ * In case of a String we use it for both the summary and detail ++ * information on the FacesMessage.

    ++ *

    If a Message is returned, we lookup the 'detail' and 'summary' ++ * categories (see {@link org.apache.deltaspike.core.api.message.Message#toString(String)} ++ * for creating the FacesMessage.

    ++ * ++ */ ++public interface JsfMessage ++{ ++ T addError(); ++ T addFatal(); ++ T addInfo(); ++ T addWarn(); ++}" +8ee465103850a3dca018273fe5952e40d5c45a66,spring-framework,Improve StringUtils.cleanPath--Issue: SPR-11793-,c,https://github.com/spring-projects/spring-framework,"diff --git a/spring-core/src/main/java/org/springframework/util/StringUtils.java b/spring-core/src/main/java/org/springframework/util/StringUtils.java +index 126cab69fcd3..b659486a19d0 100644 +--- a/spring-core/src/main/java/org/springframework/util/StringUtils.java ++++ b/spring-core/src/main/java/org/springframework/util/StringUtils.java +@@ -622,7 +622,12 @@ public static String cleanPath(String path) { + String prefix = """"; + if (prefixIndex != -1) { + prefix = pathToUse.substring(0, prefixIndex + 1); +- pathToUse = pathToUse.substring(prefixIndex + 1); ++ if (prefix.contains(""/"")) { ++ prefix = """"; ++ } ++ else { ++ pathToUse = pathToUse.substring(prefixIndex + 1); ++ } + } + if (pathToUse.startsWith(FOLDER_SEPARATOR)) { + prefix = prefix + FOLDER_SEPARATOR; +diff --git a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +index b366ed7f96d0..c362a92ed529 100644 +--- a/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java ++++ b/spring-core/src/test/java/org/springframework/util/StringUtilsTests.java +@@ -299,6 +299,8 @@ public void testCleanPath() { + assertEquals(""../mypath/myfile"", StringUtils.cleanPath(""../mypath/../mypath/myfile"")); + assertEquals(""../mypath/myfile"", StringUtils.cleanPath(""mypath/../../mypath/myfile"")); + assertEquals(""/../mypath/myfile"", StringUtils.cleanPath(""/../mypath/myfile"")); ++ assertEquals(""/mypath/myfile"", StringUtils.cleanPath(""/a/:b/../../mypath/myfile"")); ++ assertEquals(""file:///c:/path/to/the%20file.txt"", StringUtils.cleanPath(""file:///c:/some/../path/to/the%20file.txt"")); + } + + public void testPathEquals() {" +e931ef7e6e360b1a89e3f0d97fbc8332852b8dcd,intellij-community,move suppress/settings intention down- (IDEA-72320 )--,c,https://github.com/JetBrains/intellij-community,"diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java +new file mode 100644 +index 0000000000000..51882b4824e92 +--- /dev/null ++++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/emptyIntention/LowPriority.java +@@ -0,0 +1,6 @@ ++class Test { ++ void method() { ++ final String i = """"; ++ i = """"; ++ } ++} +\ No newline at end of file +diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java +index 3381bec67ed7f..f1d7457625e91 100644 +--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java ++++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/EmptyIntentionInspectionQuickFixTest.java +@@ -4,6 +4,7 @@ + import com.intellij.codeInsight.intention.IntentionAction; + import com.intellij.codeInspection.LocalInspectionTool; + import com.intellij.codeInspection.ProblemsHolder; ++import com.intellij.codeInspection.defUse.DefUseInspection; + import com.intellij.psi.JavaElementVisitor; + import com.intellij.psi.PsiElementVisitor; + import com.intellij.psi.PsiLiteralExpression; +@@ -26,7 +27,7 @@ protected String getBasePath() { + + @Override + protected LocalInspectionTool[] configureLocalInspectionTools() { +- return new LocalInspectionTool[]{new LocalInspectionTool() { ++ return new LocalInspectionTool[]{new DefUseInspection(), new LocalInspectionTool() { + @Override + @Nls + @NotNull +@@ -74,4 +75,26 @@ public void testX() throws Exception { + } + assertEquals(1, emptyActions.size()); + } ++ ++ public void testLowPriority() throws Exception { ++ configureByFile(getBasePath() + ""/LowPriority.java""); ++ List emptyActions = getAvailableActions(); ++ int i = 0; ++ for(;i < emptyActions.size(); i++) { ++ final IntentionAction intentionAction = emptyActions.get(i); ++ if (""Make 'i' not final"".equals(intentionAction.getText())) { ++ break; ++ } ++ if (intentionAction instanceof EmptyIntentionAction) { ++ fail(""Low priority action prior to quick fix""); ++ } ++ } ++ assertTrue(i < emptyActions.size()); ++ for (; i < emptyActions.size(); i++) { ++ if (emptyActions.get(i) instanceof EmptyIntentionAction) { ++ return; ++ } ++ } ++ fail(""Missed inspection setting action""); ++ } + } +diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java +index 8808e65288f17..f74376b27b1d0 100644 +--- a/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java ++++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/EmptyIntentionAction.java +@@ -29,7 +29,7 @@ + * User: anna + * Date: May 11, 2005 + */ +-public final class EmptyIntentionAction implements IntentionAction{ ++public final class EmptyIntentionAction implements IntentionAction, LowPriorityAction{ + private final String myName; + + public EmptyIntentionAction(@NotNull String name) {" +df09fcb6a53b70a828698fbad71e681edbcdc7f4,ReactiveX-RxJava,ObserveOn/SubscribeOn unit tests--,p,https://github.com/ReactiveX/RxJava,"diff --git a/rxjava-core/src/main/java/rx/concurrency/ForwardingScheduler.java b/rxjava-core/src/main/java/rx/concurrency/ForwardingScheduler.java +new file mode 100644 +index 0000000000..2714808766 +--- /dev/null ++++ b/rxjava-core/src/main/java/rx/concurrency/ForwardingScheduler.java +@@ -0,0 +1,56 @@ ++/** ++ * Copyright 2013 Netflix, Inc. ++ * ++ * Licensed under the Apache License, Version 2.0 (the ""License""); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package rx.concurrency; ++ ++import rx.Scheduler; ++import rx.Subscription; ++import rx.util.functions.Action0; ++import rx.util.functions.Func0; ++ ++import java.util.concurrent.TimeUnit; ++ ++public class ForwardingScheduler implements Scheduler { ++ private final Scheduler underlying; ++ ++ public ForwardingScheduler(Scheduler underlying) { ++ this.underlying = underlying; ++ } ++ ++ @Override ++ public Subscription schedule(Action0 action) { ++ return underlying.schedule(action); ++ } ++ ++ @Override ++ public Subscription schedule(Func0 action) { ++ return underlying.schedule(action); ++ } ++ ++ @Override ++ public Subscription schedule(Action0 action, long timespan, TimeUnit unit) { ++ return underlying.schedule(action, timespan, unit); ++ } ++ ++ @Override ++ public Subscription schedule(Func0 action, long timespan, TimeUnit unit) { ++ return underlying.schedule(action, timespan, unit); ++ } ++ ++ @Override ++ public long now() { ++ return underlying.now(); ++ } ++} +\ No newline at end of file +diff --git a/rxjava-core/src/main/java/rx/concurrency/ImmediateScheduler.java b/rxjava-core/src/main/java/rx/concurrency/ImmediateScheduler.java +index 59908e4e0c..e54d178ae0 100644 +--- a/rxjava-core/src/main/java/rx/concurrency/ImmediateScheduler.java ++++ b/rxjava-core/src/main/java/rx/concurrency/ImmediateScheduler.java +@@ -38,8 +38,9 @@ private ImmediateScheduler() { + + @Override + public Subscription schedule(Func0 action) { +- action.call(); +- return Subscriptions.empty(); ++ DiscardableAction discardableAction = new DiscardableAction(action); ++ discardableAction.call(); ++ return discardableAction; + } + + public static class UnitTest { +diff --git a/rxjava-core/src/main/java/rx/concurrency/Schedulers.java b/rxjava-core/src/main/java/rx/concurrency/Schedulers.java +index 61b51d070d..9f5ff2065d 100644 +--- a/rxjava-core/src/main/java/rx/concurrency/Schedulers.java ++++ b/rxjava-core/src/main/java/rx/concurrency/Schedulers.java +@@ -44,4 +44,8 @@ public static Scheduler executor(Executor executor) { + public static Scheduler scheduledExecutor(ScheduledExecutorService executor) { + return new ScheduledExecutorServiceScheduler(executor); + } ++ ++ public static Scheduler forwardingScheduler(Scheduler underlying) { ++ return new ForwardingScheduler(underlying); ++ } + } +diff --git a/rxjava-core/src/main/java/rx/operators/OperationObserveOn.java b/rxjava-core/src/main/java/rx/operators/OperationObserveOn.java +index 85228f2cff..4e6e14bb85 100644 +--- a/rxjava-core/src/main/java/rx/operators/OperationObserveOn.java ++++ b/rxjava-core/src/main/java/rx/operators/OperationObserveOn.java +@@ -15,14 +15,20 @@ + */ + package rx.operators; + ++import org.junit.Test; + import rx.Observable; + import rx.Observer; + import rx.Scheduler; + import rx.Subscription; ++import rx.concurrency.Schedulers; + import rx.util.functions.Action0; +-import rx.util.functions.Func0; + import rx.util.functions.Func1; + ++import static org.mockito.Matchers.any; ++import static org.mockito.Mockito.*; ++import static org.mockito.Mockito.times; ++import static org.mockito.Mockito.verify; ++ + public class OperationObserveOn { + + public static Func1, Subscription> observeOn(Observable source, Scheduler scheduler) { +@@ -64,23 +70,46 @@ public void call() { + } + + @Override +- public void onError(Exception e) { ++ public void onError(final Exception e) { + scheduler.schedule(new Action0() { + @Override + public void call() { +- underlying.onCompleted(); ++ underlying.onError(e); + } + }); + } + + @Override +- public void onNext(T args) { ++ public void onNext(final T args) { + scheduler.schedule(new Action0() { + @Override + public void call() { +- underlying.onCompleted(); ++ underlying.onNext(args); + } + }); + } + } ++ ++ public static class UnitTest { ++ ++ @Test ++ @SuppressWarnings(""unchecked"") ++ public void testObserveOn() { ++ ++ Scheduler scheduler = spy(Schedulers.forwardingScheduler(Schedulers.immediate())); ++ ++ Observer observer = mock(Observer.class); ++ Observable.create(observeOn(Observable.toObservable(1, 2, 3), scheduler)).subscribe(observer); ++ ++ verify(scheduler, times(4)).schedule(any(Action0.class)); ++ verifyNoMoreInteractions(scheduler); ++ ++ verify(observer, times(1)).onNext(1); ++ verify(observer, times(1)).onNext(2); ++ verify(observer, times(1)).onNext(3); ++ verify(observer, times(1)).onCompleted(); ++ } ++ ++ } ++ + } +diff --git a/rxjava-core/src/main/java/rx/operators/OperationSubscribeOn.java b/rxjava-core/src/main/java/rx/operators/OperationSubscribeOn.java +index b59dd5f37d..104a134657 100644 +--- a/rxjava-core/src/main/java/rx/operators/OperationSubscribeOn.java ++++ b/rxjava-core/src/main/java/rx/operators/OperationSubscribeOn.java +@@ -15,14 +15,19 @@ + */ + package rx.operators; + ++import org.junit.Test; + import rx.Observable; + import rx.Observer; + import rx.Scheduler; + import rx.Subscription; ++import rx.concurrency.Schedulers; + import rx.util.functions.Action0; + import rx.util.functions.Func0; + import rx.util.functions.Func1; + ++import static org.mockito.Matchers.any; ++import static org.mockito.Mockito.*; ++ + public class OperationSubscribeOn { + + public static Func1, Subscription> subscribeOn(Observable source, Scheduler scheduler) { +@@ -68,4 +73,30 @@ public void call() { + }); + } + } +-} ++ ++ public static class UnitTest { ++ ++ @Test ++ @SuppressWarnings(""unchecked"") ++ public void testSubscribeOn() { ++ Observable w = Observable.toObservable(1, 2, 3); ++ ++ Scheduler scheduler = spy(Schedulers.forwardingScheduler(Schedulers.immediate())); ++ ++ Observer observer = mock(Observer.class); ++ Subscription subscription = Observable.create(subscribeOn(w, scheduler)).subscribe(observer); ++ ++ verify(scheduler, times(1)).schedule(any(Func0.class)); ++ subscription.unsubscribe(); ++ verify(scheduler, times(1)).schedule(any(Action0.class)); ++ verifyNoMoreInteractions(scheduler); ++ ++ verify(observer, times(1)).onNext(1); ++ verify(observer, times(1)).onNext(2); ++ verify(observer, times(1)).onNext(3); ++ verify(observer, times(1)).onCompleted(); ++ } ++ ++ } ++ ++} +\ No newline at end of file" +a035e9fd8a5bde10c26338d7b23f75dbf59f1352,drools,JBRULES-2121: JavaDialect isn't creating unique ids- - fixed name that is checked--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@26929 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java +index 8d9bf344fe1..e6a9f723ae8 100644 +--- a/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java ++++ b/drools-compiler/src/main/java/org/drools/rule/builder/dialect/java/JavaDialect.java +@@ -721,7 +721,7 @@ public static String getUniqueLegalName(final String packageName, + + counter++; + final String fileName = packageName.replaceAll( ""\\."", +- ""/"" ) + newName + ""_"" + counter + ext; ++ ""/"" ) + ""/"" + newName + ""_"" + counter + ""."" + ext; + + //MVEL:test null to Fix failing test on org.drools.rule.builder.dialect.mvel.MVELConsequenceBuilderTest.testImperativeCodeError() + exists = src != null && src.isAvailable( fileName );" +509945a1f658f711c334c978037f07c7c3d250a7,eclipse-color-theme$eclipse-color-theme,"More flexibility to parsing functions to be used from external +",p,https://github.com/eclipse-color-theme/eclipse-color-theme,"diff --git a/com.github.eclipsecolortheme/src/com/github/eclipsecolortheme/mapper/GenericMapper.java b/com.github.eclipsecolortheme/src/com/github/eclipsecolortheme/mapper/GenericMapper.java +index 81733652..7d91fff9 100644 +--- a/com.github.eclipsecolortheme/src/com/github/eclipsecolortheme/mapper/GenericMapper.java ++++ b/com.github.eclipsecolortheme/src/com/github/eclipsecolortheme/mapper/GenericMapper.java +@@ -37,12 +37,35 @@ public void parseMapping(InputStream input) + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.parse(input); +- Element root = document.getDocumentElement(); +- parseMappings(root); +- parseSemanticHighlightingMappings(root); ++ parseMapping(document.getDocumentElement()); + } + +- private void parseMappings(Element root) { ++ /** ++ * Parse mapping from input file. ++ * @param root Root element for parsing ++ * @throws SAXException ++ * @throws IOException ++ * @throws ParserConfigurationException ++ */ ++ public void parseMapping(Element root) ++ throws SAXException, IOException, ParserConfigurationException { ++ parseMapping(root, mappings); ++ } ++ ++ /** ++ * Parse mapping from input file. ++ * @param root Root element for parsing ++ * @throws SAXException ++ * @throws IOException ++ * @throws ParserConfigurationException ++ */ ++ public void parseMapping(Element root, Map map) ++ throws SAXException, IOException, ParserConfigurationException { ++ parseMappings(root, map); ++ parseSemanticHighlightingMappings(root, map); ++ } ++ ++ private void parseMappings(Element root, Map map) { + Node mappingsNode = root.getElementsByTagName(""mappings"").item(0); + NodeList mappingNodes = mappingsNode.getChildNodes(); + for (int i = 0; i < mappingNodes.getLength(); i++) { +@@ -50,12 +73,12 @@ private void parseMappings(Element root) { + if (mappingNode.hasAttributes()) { + String pluginKey = extractAttribute(mappingNode, ""pluginKey""); + String themeKey = extractAttribute(mappingNode, ""themeKey""); +- mappings.put(pluginKey, createMapping(pluginKey, themeKey)); ++ map.put(pluginKey, createMapping(pluginKey, themeKey)); + } + } + } + +- private void parseSemanticHighlightingMappings(Element root) { ++ private void parseSemanticHighlightingMappings(Element root, Map map) { + Node mappingsNode = root.getElementsByTagName(""semanticHighlightingMappings"").item(0); + if (mappingsNode != null) { + NodeList mappingNodes = mappingsNode.getChildNodes(); +@@ -64,7 +87,7 @@ private void parseSemanticHighlightingMappings(Element root) { + if (mappingNode.hasAttributes()) { + String pluginKey = extractAttribute(mappingNode, ""pluginKey""); + String themeKey = extractAttribute(mappingNode, ""themeKey""); +- mappings.put(pluginKey, createSemanticHighlightingMapping(pluginKey, themeKey)); ++ map.put(pluginKey, createSemanticHighlightingMapping(pluginKey, themeKey)); + } + } + }" +5f2db5a15b6dce33253c7d6ba766db4ac2292957,Valadoc,"libvaladoc: gir-reader: accept #[id]->[id|func] +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +7d5abf3972158a3b24d2e075c20bde604de3e813,Valadoc,"libvaladoc: reorder @param +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +0453b2486ed9ef95942e6f304171a05a89b25590,isa-tools$isacreator,"Term tagger now partially working. Currently works on the whole investigation although does no String substitution yet to replace the freetext with ontology terms. +Next week will add functionality to: +1) visualise the freetext which was annotated; +2) add term tagging on a per spreadsheet basis; +3) add term tagging on a per study basis; +4) when you right click on a term or a selection of terms which are in a column requiring ontologies, you can click 'tag with ontology' and it will start tagging the terms and display the results +",p,https://github.com/isa-tools/isacreator,"diff --git a/trunk/src/main/java/org/isatools/isacreator/apiutils/InvestigationUtils.java b/trunk/src/main/java/org/isatools/isacreator/apiutils/InvestigationUtils.java +new file mode 100644 +index 00000000..ecf4d9f6 +--- /dev/null ++++ b/trunk/src/main/java/org/isatools/isacreator/apiutils/InvestigationUtils.java +@@ -0,0 +1,47 @@ ++package org.isatools.isacreator.apiutils; ++ ++import org.isatools.isacreator.model.Assay; ++import org.isatools.isacreator.model.Investigation; ++import org.isatools.isacreator.model.Study; ++ ++import java.util.HashMap; ++import java.util.Map; ++import java.util.Set; ++ ++/** ++ * Created by the ISA team ++ * ++ * @author Eamonn Maguire (eamonnmag@gmail.com) ++ *

    ++ * Date: 03/02/2011 ++ * Time: 16:21 ++ */ ++public class InvestigationUtils { ++ ++ ++ /** ++ * Method return all the unannotated freetext found in the Investigation ++ * ++ * @param investigation @see Investigation ++ * @return Map from Assay object (general container for spreadsheet) to a Map from the Column Name to it's unannotated values ++ */ ++ public static Map>> getFreeTextInInvestigationSpreadsheets(Investigation investigation) { ++ ++ Map>> result = new HashMap>>(); ++ ++ Map studies = investigation.getStudies(); ++ ++ for (String studyId : studies.keySet()) { ++ Study study = studies.get(studyId); ++ ++ result.put(study.getStudySample(), ++ SpreadsheetUtils.getFreetextInSpreadsheet(study.getStudySample().getSpreadsheetUI().getTable())); ++ ++ for (Assay assay : study.getAssays().values()) { ++ result.put(assay, SpreadsheetUtils.getFreetextInSpreadsheet(assay.getSpreadsheetUI().getTable())); ++ } ++ } ++ ++ return result; ++ } ++} +diff --git a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/utils/SpreadsheetUtils.java b/trunk/src/main/java/org/isatools/isacreator/apiutils/SpreadsheetUtils.java +similarity index 64% +rename from trunk/src/main/java/org/isatools/isacreator/spreadsheet/utils/SpreadsheetUtils.java +rename to trunk/src/main/java/org/isatools/isacreator/apiutils/SpreadsheetUtils.java +index 403ea978..826b509d 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/utils/SpreadsheetUtils.java ++++ b/trunk/src/main/java/org/isatools/isacreator/apiutils/SpreadsheetUtils.java +@@ -35,14 +35,16 @@ ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) + The ISA Team and the ISA software suite have been funded by the EU Carcinogenomics project (http://www.carcinogenomics.eu), the UK BBSRC (http://www.bbsrc.ac.uk), the UK NERC-NEBC (http://nebc.nerc.ac.uk) and in part by the EU NuGO consortium (http://www.nugo.org/everyone). + */ + +-package org.isatools.isacreator.spreadsheet.utils; ++package org.isatools.isacreator.apiutils; + + import org.apache.commons.collections15.map.ListOrderedMap; + import org.apache.commons.collections15.set.ListOrderedSet; ++import org.isatools.isacreator.configuration.DataTypes; + import org.isatools.isacreator.spreadsheet.Spreadsheet; ++import org.isatools.isacreator.spreadsheet.Utils; + +-import java.util.Map; +-import java.util.Set; ++import javax.swing.table.TableColumn; ++import java.util.*; + + /** + * SpreadsheetUtils +@@ -140,4 +142,73 @@ public static String[][] getSpreadsheetDataSubset(Spreadsheet targetSheet, int n + + return data; + } ++ ++ /** ++ * Gets the freetext terms (which ideally should be ontology terms) in a Spreadsheet object ++ * ++ * @param spreadsheet @see Spreadsheet ++ * @return Map> ++ */ ++ public static Map> getFreetextInSpreadsheet(Spreadsheet spreadsheet) { ++ Enumeration columns = spreadsheet.getTable().getColumnModel().getColumns(); ++ ++ Map> columnToFreeText = new HashMap>(); ++ ++ while (columns.hasMoreElements()) { ++ TableColumn tc = columns.nextElement(); ++ ++ if (spreadsheet.getTableReferenceObject().getClassType(tc.getHeaderValue().toString().trim()) ++ == DataTypes.ONTOLOGY_TERM) { ++ ++ int colIndex = Utils.convertModelIndexToView(spreadsheet.getTable(), tc.getModelIndex()); ++ ++ for (int row = 0; row < spreadsheet.getTable().getRowCount(); row++) { ++ ++ String columnValue = (spreadsheet.getTable().getValueAt(row, colIndex) == null) ? """" ++ : spreadsheet.getTable().getValueAt(row, ++ colIndex).toString(); ++ ++ if (columnValue != null && !columnValue.trim().equals("""")) { ++ if (!columnToFreeText.containsKey(tc.getHeaderValue().toString())) { ++ columnToFreeText.put(tc.getHeaderValue().toString(), new HashSet()); ++ } ++ columnToFreeText.get(tc.getHeaderValue().toString()).add(columnValue); ++ } ++ } ++ } ++ } ++ ++ return columnToFreeText; ++ } ++ ++ /** ++ * Method returns a Set of all the files defined in a spreadsheet. These locations are used to zip up the data files ++ * in the ISArchive for submission to the index. ++ * ++ * @return Set of files defined in the spreadsheet ++ */ ++ public static Set getFilesDefinedInTable(Spreadsheet spreadsheet) { ++ Enumeration columns = spreadsheet.getTable().getColumnModel().getColumns(); ++ Set files = new HashSet(); ++ ++ while (columns.hasMoreElements()) { ++ TableColumn tc = columns.nextElement(); ++ ++ if (spreadsheet.getTableReferenceObject().acceptsFileLocations(tc.getHeaderValue().toString())) { ++ int colIndex = Utils.convertModelIndexToView(spreadsheet.getTable(), tc.getModelIndex()); ++ ++ for (int row = 0; row < spreadsheet.getTable().getRowCount(); row++) { ++ String s = (spreadsheet.getTable().getValueAt(row, colIndex) == null) ? """" ++ : spreadsheet.getTable().getValueAt(row, ++ colIndex).toString(); ++ ++ if (s != null && !s.trim().equals("""")) { ++ files.add(s); ++ } ++ } ++ } ++ } ++ ++ return files; ++ } + } +diff --git a/trunk/src/main/java/org/isatools/isacreator/apiutils/StudyUtils.java b/trunk/src/main/java/org/isatools/isacreator/apiutils/StudyUtils.java +new file mode 100644 +index 00000000..6ab5e7ad +--- /dev/null ++++ b/trunk/src/main/java/org/isatools/isacreator/apiutils/StudyUtils.java +@@ -0,0 +1,12 @@ ++package org.isatools.isacreator.apiutils; ++ ++/** ++ * Created by the ISA team ++ * ++ * @author Eamonn Maguire (eamonnmag@gmail.com) ++ *

    ++ * Date: 03/02/2011 ++ * Time: 16:21 ++ */ ++public class StudyUtils { ++} +diff --git a/trunk/src/main/java/org/isatools/isacreator/gui/ISAcreator.java b/trunk/src/main/java/org/isatools/isacreator/gui/ISAcreator.java +index 9b4674a8..835ba713 100755 +--- a/trunk/src/main/java/org/isatools/isacreator/gui/ISAcreator.java ++++ b/trunk/src/main/java/org/isatools/isacreator/gui/ISAcreator.java +@@ -52,6 +52,8 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + import org.isatools.isacreator.io.UserProfile; + import org.isatools.isacreator.io.UserProfileIO; + import org.isatools.isacreator.model.Investigation; ++import org.isatools.isacreator.ontologiser.adaptors.InvestigationAdaptor; ++import org.isatools.isacreator.ontologiser.ui.OntologiserUI; + import org.isatools.isacreator.ontologymanager.OntologyConsumer; + import org.isatools.isacreator.ontologymanager.OntologySourceRefObject; + import org.isatools.isacreator.ontologyselectiontool.OntologyObject; +@@ -488,27 +490,35 @@ public void actionPerformed(ActionEvent e) { + + menuBar.add(view); + +- JMenu plugins = new JMenu(""plugins""); ++ JMenu plugins = new JMenu(""utilities""); + +- JMenu exporters = new JMenu(""Sample Tracking""); +- exporters.addMouseListener(new MouseAdapter() { ++ ++ JMenu sampleTracking = new JMenu(""Sample Tracking""); ++ sampleTracking.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent mouseEvent) { + updateExportList(); + } + }); + +-// JMenu mgRastExport = new JMenu(""export study to mg-rast""); +-// mgRastExport.setIcon(mgRastIcon); +-// menusRequiringStudyIds.put(""mgrast"", mgRastExport); +-// exporters.add(mgRastExport); ++ JMenuItem tagInvestigation = new JMenuItem(""Autotagging""); ++ tagInvestigation.addMouseListener(new MouseAdapter() { ++ @Override ++ public void mousePressed(MouseEvent mouseEvent) { ++ OntologiserUI ontologiserUI = new OntologiserUI(ISAcreator.this, new InvestigationAdaptor(getDataEntryEnvironment().getInvestigation())); ++ ontologiserUI.createGUI(); ++ ++ showJDialogAsSheet(ontologiserUI); ++ } ++ }); + + JMenu qrCodeExport = new JMenu(""generate QR codes for Study samples""); + qrCodeExport.setIcon(qrCodeIcon); + menusRequiringStudyIds.put(""qr"", qrCodeExport); +- exporters.add(qrCodeExport); ++ sampleTracking.add(qrCodeExport); + +- plugins.add(exporters); ++ plugins.add(sampleTracking); ++ plugins.add(tagInvestigation); + + menuBar.add(plugins); + +diff --git a/trunk/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java b/trunk/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java +index 755a4142..1c105743 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java ++++ b/trunk/src/main/java/org/isatools/isacreator/mgrast/utils/APIHook.java +@@ -38,12 +38,12 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + package org.isatools.isacreator.mgrast.utils; + + import org.apache.commons.collections15.set.ListOrderedSet; ++import org.isatools.isacreator.apiutils.SpreadsheetUtils; + import org.isatools.isacreator.gui.ISAcreator; + import org.isatools.isacreator.model.Assay; + import org.isatools.isacreator.model.Investigation; + import org.isatools.isacreator.model.Study; + import org.isatools.isacreator.spreadsheet.Spreadsheet; +-import org.isatools.isacreator.spreadsheet.utils.SpreadsheetUtils; + + import java.util.*; + +diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/ContentAdaptor.java b/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/ContentAdaptor.java +new file mode 100644 +index 00000000..e9cc8f9e +--- /dev/null ++++ b/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/ContentAdaptor.java +@@ -0,0 +1,30 @@ ++package org.isatools.isacreator.ontologiser.adaptors; ++ ++import org.isatools.isacreator.ontologiser.model.OntologisedResult; ++ ++import java.util.Set; ++ ++/** ++ * Created by the ISA team ++ * ++ * @author Eamonn Maguire (eamonnmag@gmail.com) ++ *

    ++ * Date: 03/02/2011 ++ * Time: 22:40 ++ */ ++public interface ContentAdaptor { ++ ++ /** ++ * Mechanism to get the terms to be annotated ++ * ++ * @return @see Set ++ */ ++ public Set getTerms(); ++ ++ /** ++ * Will be the mechanism to replace the content ++ * ++ * @param result @see Set ++ */ ++ public void replaceTerms(Set result); ++} +diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/InvestigationAdaptor.java b/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/InvestigationAdaptor.java +new file mode 100644 +index 00000000..44cb00e0 +--- /dev/null ++++ b/trunk/src/main/java/org/isatools/isacreator/ontologiser/adaptors/InvestigationAdaptor.java +@@ -0,0 +1,62 @@ ++package org.isatools.isacreator.ontologiser.adaptors; ++ ++import org.isatools.isacreator.apiutils.InvestigationUtils; ++import org.isatools.isacreator.model.Assay; ++import org.isatools.isacreator.model.Investigation; ++import org.isatools.isacreator.ontologiser.model.OntologisedResult; ++ ++import java.util.HashSet; ++import java.util.Map; ++import java.util.Set; ++ ++/** ++ * Created by the ISA team ++ * ++ * @author Eamonn Maguire (eamonnmag@gmail.com) ++ *

    ++ * Date: 03/02/2011 ++ * Time: 22:43 ++ */ ++public class InvestigationAdaptor implements ContentAdaptor { ++ ++ private Investigation investigation; ++ ++ // by creating and maintaining this Map, we are able to locate which Spreadsheets ++ // contain which terms, making string substitution much quicker. ++ ++ private Map> assayToTerms; ++ ++ public InvestigationAdaptor(Investigation investigation) { ++ this.investigation = investigation; ++ } ++ ++ public void replaceTerms(Set annotations) { ++ // todo ++ for (OntologisedResult annotation : annotations) { ++ ++ } ++ } ++ ++ public Set getTerms() { ++ Map>> result = InvestigationUtils.getFreeTextInInvestigationSpreadsheets(investigation); ++ ++ return createFlattenedSet(result); ++ } ++ ++ private Set createFlattenedSet(Map>> toFlatten) { ++ ++ Set flattenedSet = new HashSet(); ++ ++ for (Assay assay : toFlatten.keySet()) { ++ Set assayTerms = new HashSet(); ++ for (String columnName : toFlatten.get(assay).keySet()) { ++ assayTerms.addAll(toFlatten.get(assay).get(columnName)); ++ ++ } ++ flattenedSet.addAll(assayTerms); ++ assayToTerms.put(assay, assayTerms); ++ } ++ ++ return flattenedSet; ++ } ++} +diff --git a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java +index fad1e144..cff02a82 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java ++++ b/trunk/src/main/java/org/isatools/isacreator/ontologiser/ui/OntologiserUI.java +@@ -3,6 +3,7 @@ + import org.isatools.isacreator.common.UIHelper; + import org.isatools.isacreator.common.dialog.ConfirmationDialog; + import org.isatools.isacreator.gui.ISAcreator; ++import org.isatools.isacreator.ontologiser.adaptors.ContentAdaptor; + import org.isatools.isacreator.ontologiser.logic.impl.AnnotatorSearchClient; + import org.isatools.isacreator.ontologymanager.bioportal.model.AnnotatorResult; + import org.jdesktop.fuse.InjectedResource; +@@ -16,9 +17,7 @@ + import java.awt.event.MouseEvent; + import java.beans.PropertyChangeEvent; + import java.beans.PropertyChangeListener; +-import java.util.HashSet; + import java.util.Map; +-import java.util.Set; + + /** + * Created by the ISA team +@@ -28,7 +27,7 @@ + * Date: 26/01/2011 + * Time: 11:13 + */ +-public class OntologiserUI extends JFrame { ++public class OntologiserUI extends JDialog { + + public static final int TERM_TAGGER_VIEW = 0; + public static final int HELP = 1; +@@ -58,6 +57,8 @@ public class OntologiserUI extends JFrame { + + private JLabel helpButton; + ++ private ContentAdaptor content; ++ + private int selectedSection = HELP; + + @InjectedResource +@@ -69,11 +70,11 @@ public class OntologiserUI extends JFrame { + private OntologyHelpPane helpPane; + private ConfirmationDialog confirmChoice; + private ISAcreator isacreatorEnvironment; +- private String currentAssay; + +- public OntologiserUI(ISAcreator isacreatorEnvironment, String currentAssay) { ++ ++ public OntologiserUI(ISAcreator isacreatorEnvironment, ContentAdaptor content) { + this.isacreatorEnvironment = isacreatorEnvironment; +- this.currentAssay = currentAssay; ++ this.content = content; + } + + public void createGUI() { +@@ -100,8 +101,6 @@ public void createGUI() { + add(createSouthPanel(), BorderLayout.SOUTH); + + pack(); +- setVisible(true); +- + } + + private Container createTopPanel() { +@@ -133,28 +132,38 @@ public void mousePressed(MouseEvent mouseEvent) { + + Thread performer = new Thread(new Runnable() { + public void run() { +- if (annotationPane == null) { +- // todo call API module to get all unannotated Ontology entries from the spreadsheet + +- annotationPane = new OntologiserAnnotationPane(getTestData()); ++ Map> terms = getTerms(); ++ ++ boolean haveTerms = terms != null; ++ ++ if (haveTerms) { ++ ++ if (annotationPane == null) { ++ ++ annotationPane = new OntologiserAnnotationPane(terms); ++ ++ SwingUtilities.invokeLater(new Runnable() { ++ public void run() { ++ annotationPane.createGUI(); ++ } ++ }); ++ } + + SwingUtilities.invokeLater(new Runnable() { + public void run() { +- annotationPane.createGUI(); ++ swapContainers(annotationPane); ++ ++ termTaggerButton.setIcon(termTaggerIconOver); ++ visualiseButton.setIcon(visualiseIcon); ++ suggestButton.setIcon(suggestIcon); ++ clearAllButton.setIcon(clearAllIcon); + } + }); ++ } else { ++ // todo add info pane saying there are no terms to annotate ++ swapContainers(helpPane); + } +- +- SwingUtilities.invokeLater(new Runnable() { +- public void run() { +- swapContainers(annotationPane); +- +- termTaggerButton.setIcon(termTaggerIconOver); +- visualiseButton.setIcon(visualiseIcon); +- suggestButton.setIcon(suggestIcon); +- clearAllButton.setIcon(clearAllIcon); +- } +- }); + } + + }); +@@ -395,21 +404,18 @@ private void swapContainers(Container newContainer) { + } + } + +- public static void main(String[] args) { +- OntologiserUI ui = new OntologiserUI(null, ""assay""); +- ui.createGUI(); +- } +- +- public Map> getTestData() { ++ public Map> getTerms() { + + AnnotatorSearchClient sc = new AnnotatorSearchClient(); + +- Set testTerms = new HashSet(); +- testTerms.add(""CY3""); +- testTerms.add(""DOSE""); +- testTerms.add(""ASSAY""); ++ if (content != null && content.getTerms().size() > 0) { ++ ++ return sc.searchForTerms(content.getTerms()); ++ ++ } ++ ++ return null; + +- return sc.searchForTerms(testTerms); + } + + +diff --git a/trunk/src/main/java/org/isatools/isacreator/qrcode/utils/QRAPIHook.java b/trunk/src/main/java/org/isatools/isacreator/qrcode/utils/QRAPIHook.java +index 1b48c0c8..8bcb5f5f 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/qrcode/utils/QRAPIHook.java ++++ b/trunk/src/main/java/org/isatools/isacreator/qrcode/utils/QRAPIHook.java +@@ -37,11 +37,11 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + + package org.isatools.isacreator.qrcode.utils; + ++import org.isatools.isacreator.apiutils.SpreadsheetUtils; + import org.isatools.isacreator.formatmappingutility.ui.MappingChoice; + import org.isatools.isacreator.gui.ISAcreator; + import org.isatools.isacreator.model.Investigation; + import org.isatools.isacreator.model.Study; +-import org.isatools.isacreator.spreadsheet.utils.SpreadsheetUtils; + import org.isatools.isacreator.utils.StringProcessing; + + import java.util.*; +diff --git a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/Spreadsheet.java b/trunk/src/main/java/org/isatools/isacreator/spreadsheet/Spreadsheet.java +index eac2f604..813ee863 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/Spreadsheet.java ++++ b/trunk/src/main/java/org/isatools/isacreator/spreadsheet/Spreadsheet.java +@@ -1825,6 +1825,8 @@ public TableConsistencyChecker getTableConsistencyChecker() { + * @param removeEmptyColumns - should empty columns be removed from the submission? + * @throws java.io.FileNotFoundException - never thrown since the file is created if it doesn't exist, and over written if + * it already exists ++ *

    ++ * todo Move this code into a utils class + */ + public boolean exportTable(File f, String separator, boolean removeEmptyColumns) + throws FileNotFoundException { +@@ -1945,6 +1947,8 @@ public boolean exportTable(File f, String separator, boolean removeEmptyColumns) + * in the ISArchive for submission to the index. + * + * @return Set of files defined in the spreadsheet ++ *

    ++ * todo move to spreadsheetutils class + */ + public Set getFilesDefinedInTable + () { +@@ -2015,8 +2019,7 @@ public boolean exportTable(File f, String separator, boolean removeEmptyColumns) + * + * @return Set containing the Ontologies defined in the Spreadsheet. + */ +- public Set getOntologiesDefinedInTable +- () { ++ public Set getOntologiesDefinedInTable() { + Enumeration columns = table.getColumnModel().getColumns(); + + HashSet ontologySources = new HashSet(); +diff --git a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/TableReferenceObject.java b/trunk/src/main/java/org/isatools/isacreator/spreadsheet/TableReferenceObject.java +index da33b4e5..a02142c8 100644 +--- a/trunk/src/main/java/org/isatools/isacreator/spreadsheet/TableReferenceObject.java ++++ b/trunk/src/main/java/org/isatools/isacreator/spreadsheet/TableReferenceObject.java +@@ -254,6 +254,7 @@ public boolean acceptsFileLocations(String colName) { + fieldLookup.get(colName).isAcceptsFileLocations(); + } + ++ + public boolean acceptsMultipleValues(String colName) { + return fieldLookup.get(colName).isAcceptsMultipleValues(); + } +@@ -271,7 +272,7 @@ public void addRowData(String[] headers, String[] rowData) { + int prevValLoc = -1; + + for (int i = 0; i < headers.length; i++) { +- String s; ++ String s; + if (i < rowData.length) { + s = rowData[i]; + } else {" +7bb429c9cde94494cde83b99715149c680c1dae9,intellij-community,external system: add clickable link to log- folder to the project import failure message--,a,https://github.com/JetBrains/intellij-community,"diff --git a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties +index a2d53c3cf6433..1112ae3ca6c40 100644 +--- a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties ++++ b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties +@@ -28,7 +28,8 @@ error.project.undefined=No external project config file is defined + error.project.already.registered=The project is already registered + error.cannot.parse.project=Can not parse {0} project + error.resolve.with.reason={0}\n\nConsult IDE log for more details (Help | Show Log) +-error.resolve.generic=Resolve error ++error.resolve.with.log_link={0}

    Consult IDE log for more details (Show Log) ++error.resolve.generic=Resolve Error + error.resolve.already.running=Another 'refresh project' task is currently running for the project: {0} + + # Tool window +diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java +index 6a3bb5ae28f26..c1e04c1af8627 100644 +--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java ++++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java +@@ -1,6 +1,7 @@ + package com.intellij.openapi.externalSystem.service.project.wizard; + + import com.intellij.ide.util.projectWizard.WizardContext; ++import com.intellij.openapi.application.PathManager; + import com.intellij.openapi.components.PersistentStateComponent; + import com.intellij.openapi.diagnostic.Logger; + import com.intellij.openapi.externalSystem.model.DataNode; +@@ -276,8 +277,9 @@ public void onFailure(@NotNull String errorMessage, @Nullable String errorDetail + if (!StringUtil.isEmpty(errorDetails)) { + LOG.warn(errorDetails); + } +- error.set(new ConfigurationException(ExternalSystemBundle.message(""error.resolve.with.reason"", errorMessage), +- ExternalSystemBundle.message(""error.resolve.generic""))); ++ error.set(new ConfigurationException( ++ ExternalSystemBundle.message(""error.resolve.with.log_link"", errorMessage, PathManager.getLogPath()), ++ ExternalSystemBundle.message(""error.resolve.generic""))); + } + };" +0b3db7cbf5eada6176af266cc6bebfcd1332f115,restlet-framework-java, - Additional WADL refactorings.--,p,https://github.com/restlet/restlet-framework-java,"diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java +index 0752ec6751..0ad154478f 100644 +--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java ++++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/FaultInfo.java +@@ -32,6 +32,7 @@ + import java.util.Iterator; + import java.util.List; + ++import org.restlet.data.MediaType; + import org.restlet.data.Reference; + import org.restlet.data.Status; + import org.restlet.util.XmlWriter; +@@ -47,39 +48,66 @@ public class FaultInfo extends RepresentationInfo { + + /** + * Constructor. ++ * ++ * @param status ++ * The associated status code. + */ +- public FaultInfo() { ++ public FaultInfo(Status status) { + super(); ++ getStatuses().add(status); + } + + /** + * Constructor with a single documentation element. + * ++ * @param status ++ * The associated status code. + * @param documentation + * A single documentation element. + */ +- public FaultInfo(DocumentationInfo documentation) { ++ public FaultInfo(Status status, DocumentationInfo documentation) { + super(documentation); ++ getStatuses().add(status); + } + + /** + * Constructor with a list of documentation elements. + * ++ * @param status ++ * The associated status code. + * @param documentations + * The list of documentation elements. + */ +- public FaultInfo(List documentations) { ++ public FaultInfo(Status status, List documentations) { + super(documentations); ++ getStatuses().add(status); + } + + /** + * Constructor with a single documentation element. + * ++ * @param status ++ * The associated status code. + * @param documentation + * A single documentation element. + */ +- public FaultInfo(String documentation) { +- super(documentation); ++ public FaultInfo(Status status, String documentation) { ++ this(status, new DocumentationInfo(documentation)); ++ } ++ ++ /** ++ * Constructor with a single documentation element. ++ * ++ * @param status ++ * The associated status code. ++ * @param mediaType ++ * The fault representation's media type. ++ * @param documentation ++ * A single documentation element. ++ */ ++ public FaultInfo(Status status, MediaType mediaType, String documentation) { ++ this(status, new DocumentationInfo(documentation)); ++ setMediaType(mediaType); + } + + /** +diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java +index 5ac681ffc5..0aac5ee5ab 100644 +--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java ++++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/MethodInfo.java +@@ -32,8 +32,10 @@ + import java.util.List; + import java.util.Map; + ++import org.restlet.data.MediaType; + import org.restlet.data.Method; + import org.restlet.data.Reference; ++import org.restlet.data.Status; + import org.restlet.resource.Variant; + import org.restlet.util.XmlWriter; + import org.xml.sax.SAXException; +@@ -98,6 +100,24 @@ public MethodInfo(String documentation) { + super(documentation); + } + ++ /** ++ * Adds a new fault to the response. ++ * ++ * @param status ++ * The associated status code. ++ * @param mediaType ++ * The fault representation's media type. ++ * @param documentation ++ * A single documentation element. ++ * @return The created fault description. ++ */ ++ public FaultInfo addFault(Status status, MediaType mediaType, ++ String documentation) { ++ FaultInfo result = new FaultInfo(status, mediaType, documentation); ++ getResponse().getFaults().add(result); ++ return result; ++ } ++ + /** + * Adds a new request parameter. + * +diff --git a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java +index 9eadc8c8c6..d6af850a75 100644 +--- a/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java ++++ b/modules/org.restlet.ext.wadl_1.0/src/org/restlet/ext/wadl/WadlRepresentation.java +@@ -530,7 +530,8 @@ public void startElement(String uri, String localName, String qName, + } + pushState(State.DOCUMENTATION); + } else if (localName.equals(""fault"")) { +- this.currentFault = new FaultInfo(); ++ this.currentFault = new FaultInfo(null); ++ + if (attrs.getIndex(""id"") != -1) { + this.currentFault.setIdentifier(attrs.getValue(""id"")); + }" +504b801ca0e7fd3944872d3214539feb2d614f06,hadoop,HDFS-73. DFSOutputStream does not close all the- sockets. Contributed by Uma Maheswara Rao G--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/trunk@1157232 13f79535-47bb-0310-9956-ffa450edef68-,c,https://github.com/apache/hadoop,"diff --git a/hdfs/CHANGES.txt b/hdfs/CHANGES.txt +index 5148ea243d7e0..02c8864284dd2 100644 +--- a/hdfs/CHANGES.txt ++++ b/hdfs/CHANGES.txt +@@ -964,6 +964,9 @@ Trunk (unreleased changes) + HDFS-2240. Fix a deadlock in LeaseRenewer by enforcing lock acquisition + ordering. (szetszwo) + ++ HDFS-73. DFSOutputStream does not close all the sockets. ++ (Uma Maheswara Rao G via eli) ++ + BREAKDOWN OF HDFS-1073 SUBTASKS + + HDFS-1521. Persist transaction ID on disk between NN restarts. +diff --git a/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java b/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java +index d267bf8a8d4a3..03879338dd273 100644 +--- a/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java ++++ b/hdfs/src/java/org/apache/hadoop/hdfs/DFSOutputStream.java +@@ -36,7 +36,6 @@ + import java.util.List; + import java.util.concurrent.atomic.AtomicBoolean; + +-import org.apache.hadoop.conf.Configuration; + import org.apache.hadoop.fs.CreateFlag; + import org.apache.hadoop.fs.FSOutputSummer; + import org.apache.hadoop.fs.FileAlreadyExistsException; +@@ -63,7 +62,6 @@ + import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status; + import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier; + import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; +-import org.apache.hadoop.hdfs.server.datanode.DataNode; + import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException; + import org.apache.hadoop.hdfs.server.namenode.SafeModeException; + import org.apache.hadoop.io.EnumSetWritable; +@@ -606,6 +604,7 @@ private void closeStream() { + try { + blockStream.close(); + } catch (IOException e) { ++ setLastException(e); + } finally { + blockStream = null; + } +@@ -614,10 +613,20 @@ private void closeStream() { + try { + blockReplyStream.close(); + } catch (IOException e) { ++ setLastException(e); + } finally { + blockReplyStream = null; + } + } ++ if (null != s) { ++ try { ++ s.close(); ++ } catch (IOException e) { ++ setLastException(e); ++ } finally { ++ s = null; ++ } ++ } + } + + // +@@ -1003,16 +1012,20 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, + persistBlocks.set(true); + + boolean result = false; ++ DataOutputStream out = null; + try { ++ assert null == s : ""Previous socket unclosed""; + s = createSocketForPipeline(nodes[0], nodes.length, dfsClient); + long writeTimeout = dfsClient.getDatanodeWriteTimeout(nodes.length); + + // + // Xmit header info to datanode + // +- DataOutputStream out = new DataOutputStream(new BufferedOutputStream( ++ out = new DataOutputStream(new BufferedOutputStream( + NetUtils.getOutputStream(s, writeTimeout), + FSConstants.SMALL_BUFFER_SIZE)); ++ ++ assert null == blockReplyStream : ""Previous blockReplyStream unclosed""; + blockReplyStream = new DataInputStream(NetUtils.getInputStream(s)); + + // send the request +@@ -1038,7 +1051,7 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, + + firstBadLink); + } + } +- ++ assert null == blockStream : ""Previous blockStream unclosed""; + blockStream = out; + result = true; // success + +@@ -1059,12 +1072,15 @@ private boolean createBlockOutputStream(DatanodeInfo[] nodes, long newGS, + } + hasError = true; + setLastException(ie); +- blockReplyStream = null; + result = false; // error + } finally { + if (!result) { + IOUtils.closeSocket(s); + s = null; ++ IOUtils.closeStream(out); ++ out = null; ++ IOUtils.closeStream(blockReplyStream); ++ blockReplyStream = null; + } + } + return result;" +3980e032581824d7241748c7ec56a916fdce6261,orientdb,Improved memory usage and optimized general speed--,p,https://github.com/JetBrains/intellij-community,⚠️ HTTP 404: Not Found +e15a795130250de68c4ea9bf3205c58865732869,Vala,"codegen: Support ""foo is G"" +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +9102b09aeca480dad12bf2edb56266b2d20ccbfb,Vala,"gtk+-2.0: Gtk.MessageDialog:buttons does not have an accessor method + +Fixes bug 607992. +",c,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +be86c7d216202c91a0ba0a43cd7f89b968146d62,drools,JBRULES-1590: fixing problem with shadow proxy- cloning for collections--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@19783 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-compiler/src/test/java/org/drools/MockPersistentSet.java b/drools-compiler/src/test/java/org/drools/MockPersistentSet.java +new file mode 100644 +index 00000000000..24d85fdb07e +--- /dev/null ++++ b/drools-compiler/src/test/java/org/drools/MockPersistentSet.java +@@ -0,0 +1,45 @@ ++package org.drools; ++ ++import java.util.AbstractSet; ++import java.util.Collection; ++import java.util.HashSet; ++import java.util.Iterator; ++import java.util.Set; ++ ++public class MockPersistentSet extends AbstractSet implements Set ++{ ++ ++ private Set set; ++ ++ private boolean exception; ++ ++ public MockPersistentSet() ++ { ++ exception = true; ++ set = new HashSet(); ++ } ++ ++ public MockPersistentSet(boolean exception) ++ { ++ this.exception = exception; ++ set = new HashSet(); ++ } ++ ++ public int size() ++ { ++ return set.size(); ++ } ++ ++ public Iterator iterator() ++ { ++ return set.iterator(); ++ } ++ ++ public boolean addAll(Collection c) ++ { ++ if (exception) ++ throw new MockPersistentSetException(""error message like PersistentSet""); ++ return set.addAll(c); ++ } ++ ++} +diff --git a/drools-compiler/src/test/java/org/drools/MockPersistentSetException.java b/drools-compiler/src/test/java/org/drools/MockPersistentSetException.java +new file mode 100644 +index 00000000000..2b0253fb0d1 +--- /dev/null ++++ b/drools-compiler/src/test/java/org/drools/MockPersistentSetException.java +@@ -0,0 +1,9 @@ ++package org.drools; ++ ++public class MockPersistentSetException extends RuntimeException ++{ ++ public MockPersistentSetException(String message) ++ { ++ super(message); ++ } ++} +diff --git a/drools-compiler/src/test/java/org/drools/ObjectWithSet.java b/drools-compiler/src/test/java/org/drools/ObjectWithSet.java +new file mode 100644 +index 00000000000..806137f4393 +--- /dev/null ++++ b/drools-compiler/src/test/java/org/drools/ObjectWithSet.java +@@ -0,0 +1,35 @@ ++package org.drools; ++ ++import java.util.Set; ++ ++public class ObjectWithSet ++{ ++ private Set set; ++ ++ private String message; ++ ++ public String getMessage() ++ { ++ return message; ++ } ++ ++ public void setMessage(String message) ++ { ++ this.message = message; ++ } ++ ++ public ObjectWithSet() ++ { ++ } ++ ++ public Set getSet() ++ { ++ return set; ++ } ++ ++ public void setSet(Set set) ++ { ++ this.set = set; ++ } ++ ++} +diff --git a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java +index 023d759a24e..943a188f84b 100644 +--- a/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java ++++ b/drools-compiler/src/test/java/org/drools/integrationtests/MiscTest.java +@@ -54,6 +54,8 @@ + import org.drools.IndexedNumber; + import org.drools.InsertedObject; + import org.drools.Message; ++import org.drools.MockPersistentSet; ++import org.drools.ObjectWithSet; + import org.drools.Order; + import org.drools.OrderItem; + import org.drools.OuterClass; +@@ -4418,6 +4420,38 @@ public void testShadowProxyOnCollections() throws Exception { + cheesery.getCheeses().get( 0 ) ); + } + ++ public void testShadowProxyOnCollections2() throws Exception { ++ final PackageBuilder builder = new PackageBuilder(); ++ builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( ""test_ShadowProxyOnCollections2.drl"" ) ) ); ++ final Package pkg = builder.getPackage(); ++ ++ final RuleBase ruleBase = getRuleBase(); ++ ruleBase.addPackage( pkg ); ++ final StatefulSession workingMemory = ruleBase.newStatefulSession(); ++ ++ final List results = new ArrayList(); ++ workingMemory.setGlobal( ""results"", ++ results ); ++ ++ List list = new ArrayList(); ++ list.add( ""example1"" ); ++ list.add( ""example2"" ); ++ ++ MockPersistentSet mockPersistentSet = new MockPersistentSet( false ); ++ mockPersistentSet.addAll( list ); ++ org.drools.ObjectWithSet objectWithSet = new ObjectWithSet(); ++ objectWithSet.setSet( mockPersistentSet ); ++ ++ workingMemory.insert( objectWithSet ); ++ ++ workingMemory.fireAllRules(); ++ ++ assertEquals( 1, ++ results.size() ); ++ assertEquals( ""show"", ++ objectWithSet.getMessage() ); ++ } ++ + public void testQueryWithCollect() throws Exception { + final PackageBuilder builder = new PackageBuilder(); + builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( ""test_Query.drl"" ) ) ); +@@ -4848,30 +4882,31 @@ public void testModifyRetractAndModifyInsert() throws Exception { + + public void testAlphaCompositeConstraints() throws Exception { + final PackageBuilder builder = new PackageBuilder(); +- builder.addPackageFromDrl(new InputStreamReader(getClass() +- .getResourceAsStream(""test_AlphaCompositeConstraints.drl""))); ++ builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( ""test_AlphaCompositeConstraints.drl"" ) ) ); + final Package pkg = builder.getPackage(); + + final RuleBase ruleBase = getRuleBase(); +- ruleBase.addPackage(pkg); ++ ruleBase.addPackage( pkg ); + final WorkingMemory workingMemory = ruleBase.newStatefulSession(); + + final List list = new ArrayList(); +- workingMemory.setGlobal(""results"", list); ++ workingMemory.setGlobal( ""results"", ++ list ); + +- Person bob = new Person( ""bob"", 30 ); ++ Person bob = new Person( ""bob"", ++ 30 ); + +- workingMemory.insert(bob); ++ workingMemory.insert( bob ); + workingMemory.fireAllRules(); + +- assertEquals( 1, list.size()); ++ assertEquals( 1, ++ list.size() ); + } + +- public void testModifyBlock() throws Exception { +- final PackageBuilder builder = new PackageBuilder(); +- builder.addPackageFromDrl(new InputStreamReader(getClass() +- .getResourceAsStream(""test_ModifyBlock.drl""))); +- final Package pkg = builder.getPackage(); ++ public void testModifyBlock() throws Exception { ++ final PackageBuilder builder = new PackageBuilder(); ++ builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( ""test_ModifyBlock.drl"" ) ) ); ++ final Package pkg = builder.getPackage(); + final RuleBase ruleBase = getRuleBase(); + ruleBase.addPackage( pkg ); + final WorkingMemory workingMemory = ruleBase.newStatefulSession(); +@@ -4919,7 +4954,7 @@ public void testJavaModifyBlock() throws Exception { + workingMemory.insert( new Cheese() ); + workingMemory.insert( new OuterClass.InnerClass( 1 ) ); + +- workingMemory.fireAllRules( ); ++ workingMemory.fireAllRules(); + + assertEquals( 2, + list.size() ); +@@ -4928,7 +4963,7 @@ public void testJavaModifyBlock() throws Exception { + assertEquals( 31, + bob.getAge() ); + assertEquals( 2, +- ((OuterClass.InnerClass)list.get( 1 )).getIntAttr() ); ++ ((OuterClass.InnerClass) list.get( 1 )).getIntAttr() ); + } + + public void testOrCE() throws Exception { +diff --git a/drools-compiler/src/test/resources/org/drools/integrationtests/test_ShadowProxyOnCollections2.drl b/drools-compiler/src/test/resources/org/drools/integrationtests/test_ShadowProxyOnCollections2.drl +new file mode 100644 +index 00000000000..22825890c28 +--- /dev/null ++++ b/drools-compiler/src/test/resources/org/drools/integrationtests/test_ShadowProxyOnCollections2.drl +@@ -0,0 +1,14 @@ ++package org.drools; ++ ++import java.util.ArrayList; ++ ++global java.util.List results; ++ ++rule ""shadow proxy on collections2"" ++ when ++ obj:ObjectWithSet( set != null && set.empty == false ) ++ then ++ obj.setMessage(""show""); ++ results.add( ""OK"" ); ++end ++ +diff --git a/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java b/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java +index eae3422325a..3475e97ce5d 100644 +--- a/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java ++++ b/drools-core/src/main/java/org/drools/util/ShadowProxyUtils.java +@@ -53,6 +53,7 @@ public static Object cloneObject(Object original) { + } catch ( Exception e ) { + /* Failed to clone. Don't worry about it, and just return + * the original object. */ ++ clone = null; + } + } + +@@ -82,6 +83,7 @@ public static Object cloneObject(Object original) { + } catch ( Exception e ) { + /* Failed to clone. Don't worry about it, and just return + * the original object. */ ++ clone = null; + } + }" +716aa6974c6c3a0cdfb65e6adbc0e5c59538a289,spring-framework,fixed scheduling tests--,c,https://github.com/spring-projects/spring-framework,"diff --git a/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java b/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java +index 2f7270747e65..207a717a05e1 100644 +--- a/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java ++++ b/org.springframework.context/src/main/java/org/springframework/scheduling/support/ScheduledMethodRunnable.java +@@ -23,12 +23,13 @@ + import org.springframework.util.ReflectionUtils; + + /** +- * Variation of {@link MethodInvokingRunnable} meant to be used for processing ++ * Variant of {@link MethodInvokingRunnable} meant to be used for processing + * of no-arg scheduled methods. Propagates user exceptions to the caller, + * assuming that an error strategy for Runnables is in place. + * + * @author Juergen Hoeller + * @since 3.0.6 ++ * @see org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor + */ + public class ScheduledMethodRunnable implements Runnable { + +@@ -59,6 +60,7 @@ public Method getMethod() { + + public void run() { + try { ++ ReflectionUtils.makeAccessible(this.method); + this.method.invoke(this.target); + } + catch (InvocationTargetException ex) { +diff --git a/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml b/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml +index 9f613201377f..2dc689973c90 100644 +--- a/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml ++++ b/org.springframework.context/src/test/java/org/springframework/scheduling/annotation/taskNamespaceTests.xml +@@ -11,12 +11,20 @@ + + --> + +- ++ ++ ++ ++ ++ + + + + + ++ ++ ++ ++ + + + +diff --git a/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java b/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java +index 52112929038b..295c282ad0d6 100644 +--- a/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java ++++ b/org.springframework.context/src/test/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParserTests.java +@@ -1,5 +1,5 @@ + /* +- * Copyright 2002-2009 the original author or authors. ++ * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the ""License""); + * you may not use this file except in compliance with the License. +@@ -16,19 +16,18 @@ + + package org.springframework.scheduling.config; + +-import static org.junit.Assert.assertEquals; +-import static org.junit.Assert.assertTrue; +- ++import java.lang.reflect.Method; + import java.util.Collection; + import java.util.Map; + ++import static org.junit.Assert.*; + import org.junit.Before; + import org.junit.Test; + + import org.springframework.beans.DirectFieldAccessor; + import org.springframework.context.ApplicationContext; + import org.springframework.context.support.ClassPathXmlApplicationContext; +-import org.springframework.scheduling.support.MethodInvokingRunnable; ++import org.springframework.scheduling.support.ScheduledMethodRunnable; + + /** + * @author Mark Fisher +@@ -64,11 +63,11 @@ public void checkTarget() { + Map tasks = (Map) new DirectFieldAccessor( + this.registrar).getPropertyValue(""fixedRateTasks""); + Runnable runnable = tasks.keySet().iterator().next(); +- assertEquals(MethodInvokingRunnable.class, runnable.getClass()); +- Object targetObject = ((MethodInvokingRunnable) runnable).getTargetObject(); +- String targetMethod = ((MethodInvokingRunnable) runnable).getTargetMethod(); ++ assertEquals(ScheduledMethodRunnable.class, runnable.getClass()); ++ Object targetObject = ((ScheduledMethodRunnable) runnable).getTarget(); ++ Method targetMethod = ((ScheduledMethodRunnable) runnable).getMethod(); + assertEquals(this.testBean, targetObject); +- assertEquals(""test"", targetMethod); ++ assertEquals(""test"", targetMethod.getName()); + } + + @Test" +90f3fc20181932474f371d143cf7b91755df53c4,Vala,"posix: add gettimeofday() and settimeofday() bindings. + +Fixes bug 592189. +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +a3ecc3b910aa3bbc3ede2b8ba1bd040d02a26ca8,hadoop,HDFS-4733. Make HttpFS username pattern- configurable. Contributed by Alejandro Abdelnur.--git-svn-id: https://svn.apache.org/repos/asf/hadoop/common/branches/branch-2@1477241 13f79535-47bb-0310-9956-ffa450edef68-,a,https://github.com/apache/hadoop,"diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java +index d217322b6ae89..1410b8b8cdfce 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSParametersProvider.java +@@ -193,7 +193,7 @@ public static class DoAsParam extends StringParam { + * Constructor. + */ + public DoAsParam() { +- super(NAME, null, UserProvider.USER_PATTERN); ++ super(NAME, null, UserProvider.getUserPattern()); + } + + /** +@@ -248,7 +248,7 @@ public static class GroupParam extends StringParam { + * Constructor. + */ + public GroupParam() { +- super(NAME, null, UserProvider.USER_PATTERN); ++ super(NAME, null, UserProvider.getUserPattern()); + } + + } +@@ -344,7 +344,7 @@ public static class OwnerParam extends StringParam { + * Constructor. + */ + public OwnerParam() { +- super(NAME, null, UserProvider.USER_PATTERN); ++ super(NAME, null, UserProvider.getUserPattern()); + } + + } +diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java +index 440d7c9702b0c..f8e53d4bb3adf 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/HttpFSServerWebApp.java +@@ -24,6 +24,7 @@ + import org.apache.hadoop.lib.server.ServerException; + import org.apache.hadoop.lib.service.FileSystemAccess; + import org.apache.hadoop.lib.servlet.ServerWebApp; ++import org.apache.hadoop.lib.wsrs.UserProvider; + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + +@@ -102,6 +103,9 @@ public void init() throws ServerException { + LOG.info(""Connects to Namenode [{}]"", + get().get(FileSystemAccess.class).getFileSystemConfiguration(). + get(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY)); ++ String userPattern = getConfig().get(UserProvider.USER_PATTERN_KEY, ++ UserProvider.USER_PATTERN_DEFAULT); ++ UserProvider.setUserPattern(userPattern); + } + + /** +diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java +index fd59b19dc3443..cd1cfc7f4ef27 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/UserProvider.java +@@ -41,12 +41,27 @@ public class UserProvider extends AbstractHttpContextInjectable imple + + public static final String USER_NAME_PARAM = ""user.name""; + +- public static final Pattern USER_PATTERN = Pattern.compile(""^[A-Za-z_][A-Za-z0-9._-]*[$]?$""); ++ ++ public static final String USER_PATTERN_KEY ++ = ""httpfs.user.provider.user.pattern""; ++ ++ public static final String USER_PATTERN_DEFAULT ++ = ""^[A-Za-z_][A-Za-z0-9._-]*[$]?$""; ++ ++ private static Pattern userPattern = Pattern.compile(USER_PATTERN_DEFAULT); ++ ++ public static void setUserPattern(String pattern) { ++ userPattern = Pattern.compile(pattern); ++ } ++ ++ public static Pattern getUserPattern() { ++ return userPattern; ++ } + + static class UserParam extends StringParam { + + public UserParam(String user) { +- super(USER_NAME_PARAM, user, USER_PATTERN); ++ super(USER_NAME_PARAM, user, getUserPattern()); + } + + @Override +diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml +index 7171d388fe9ee..87cd73020d151 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/resources/httpfs-default.xml +@@ -226,4 +226,12 @@ + + + ++ ++ httpfs.user.provider.user.pattern ++ ^[A-Za-z_][A-Za-z0-9._-]*[$]?$ ++ ++ Valid pattern for user and group names, it must be a valid java regex. ++ ++ ++ + +diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java +new file mode 100644 +index 0000000000000..e8407fc30cd80 +--- /dev/null ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/fs/http/server/TestHttpFSCustomUserName.java +@@ -0,0 +1,94 @@ ++/** ++ * Licensed to the Apache Software Foundation (ASF) under one ++ * or more contributor license agreements. See the NOTICE file ++ * distributed with this work for additional information ++ * regarding copyright ownership. The ASF licenses this file ++ * to you under the Apache License, Version 2.0 (the ++ * ""License""); you may not use this file except in compliance ++ * with the License. You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an ""AS IS"" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ */ ++package org.apache.hadoop.fs.http.server; ++ ++import org.apache.hadoop.conf.Configuration; ++import org.apache.hadoop.fs.CommonConfigurationKeysPublic; ++import org.apache.hadoop.fs.FileSystem; ++import org.apache.hadoop.fs.Path; ++import org.apache.hadoop.fs.http.client.HttpFSKerberosAuthenticator; ++import org.apache.hadoop.lib.server.Service; ++import org.apache.hadoop.lib.server.ServiceException; ++import org.apache.hadoop.lib.service.Groups; ++import org.apache.hadoop.lib.wsrs.UserProvider; ++import org.apache.hadoop.security.authentication.client.AuthenticatedURL; ++import org.apache.hadoop.security.authentication.server.AuthenticationToken; ++import org.apache.hadoop.security.authentication.util.Signer; ++import org.apache.hadoop.test.HFSTestCase; ++import org.apache.hadoop.test.HadoopUsersConfTestHelper; ++import org.apache.hadoop.test.TestDir; ++import org.apache.hadoop.test.TestDirHelper; ++import org.apache.hadoop.test.TestHdfs; ++import org.apache.hadoop.test.TestHdfsHelper; ++import org.apache.hadoop.test.TestJetty; ++import org.apache.hadoop.test.TestJettyHelper; ++import org.json.simple.JSONObject; ++import org.json.simple.parser.JSONParser; ++import org.junit.Assert; ++import org.junit.Test; ++import org.mortbay.jetty.Server; ++import org.mortbay.jetty.webapp.WebAppContext; ++ ++import java.io.BufferedReader; ++import java.io.File; ++import java.io.FileOutputStream; ++import java.io.FileWriter; ++import java.io.IOException; ++import java.io.InputStream; ++import java.io.InputStreamReader; ++import java.io.OutputStream; ++import java.io.Writer; ++import java.net.HttpURLConnection; ++import java.net.URL; ++import java.text.MessageFormat; ++import java.util.Arrays; ++import java.util.List; ++ ++public class TestHttpFSCustomUserName extends HFSTestCase { ++ ++ @Test ++ @TestDir ++ @TestJetty ++ public void defaultUserName() throws Exception { ++ String dir = TestDirHelper.getTestDir().getAbsolutePath(); ++ ++ Configuration httpfsConf = new Configuration(false); ++ HttpFSServerWebApp server = ++ new HttpFSServerWebApp(dir, dir, dir, dir, httpfsConf); ++ server.init(); ++ Assert.assertEquals(UserProvider.USER_PATTERN_DEFAULT, ++ UserProvider.getUserPattern().pattern()); ++ server.destroy(); ++ } ++ ++ @Test ++ @TestDir ++ @TestJetty ++ public void customUserName() throws Exception { ++ String dir = TestDirHelper.getTestDir().getAbsolutePath(); ++ ++ Configuration httpfsConf = new Configuration(false); ++ httpfsConf.set(UserProvider.USER_PATTERN_KEY, ""1""); ++ HttpFSServerWebApp server = ++ new HttpFSServerWebApp(dir, dir, dir, dir, httpfsConf); ++ server.init(); ++ Assert.assertEquals(""1"", UserProvider.getUserPattern().pattern()); ++ server.destroy(); ++ } ++ ++} +diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java +index 694e8dc3185bd..e8942fbe4ef75 100644 +--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java ++++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/wsrs/TestUserProvider.java +@@ -104,34 +104,39 @@ public void getters() { + @Test + @TestException(exception = IllegalArgumentException.class) + public void userNameEmpty() { +- UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); +- userParam.parseParam(""""); ++ new UserProvider.UserParam(""""); + } + + @Test + @TestException(exception = IllegalArgumentException.class) + public void userNameInvalidStart() { +- UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); +- userParam.parseParam(""1x""); ++ new UserProvider.UserParam(""1x""); + } + + @Test + @TestException(exception = IllegalArgumentException.class) + public void userNameInvalidDollarSign() { +- UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); +- userParam.parseParam(""1$x""); ++ new UserProvider.UserParam(""1$x""); + } + + @Test + public void userNameMinLength() { +- UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); +- assertNotNull(userParam.parseParam(""a"")); ++ new UserProvider.UserParam(""a""); + } + + @Test + public void userNameValidDollarSign() { +- UserProvider.UserParam userParam = new UserProvider.UserParam(""username""); +- assertNotNull(userParam.parseParam(""a$"")); ++ new UserProvider.UserParam(""a$""); ++ } ++ ++ @Test ++ public void customUserPattern() { ++ try { ++ UserProvider.setUserPattern(""1""); ++ new UserProvider.UserParam(""1""); ++ } finally { ++ UserProvider.setUserPattern(UserProvider.USER_PATTERN_DEFAULT); ++ } + } + + }" +415be84340155fa0eb6086149a7de381a41ef480,drools,Fixing NPE--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@6187 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/reteoo/NotNode.java b/drools-core/src/main/java/org/drools/reteoo/NotNode.java +index 62544d106f5..55470f365c5 100644 +--- a/drools-core/src/main/java/org/drools/reteoo/NotNode.java ++++ b/drools-core/src/main/java/org/drools/reteoo/NotNode.java +@@ -242,10 +242,12 @@ public void retractTuple(final ReteTuple leftTuple, + } + + LinkedList list = leftTuple.getLinkedTuples(); +- for ( LinkedListNode node = list.getFirst(); node != null; node = node.getNext() ) { +- ReteTuple tuple = (ReteTuple) ((LinkedListObjectWrapper) node).getObject(); +- tuple.retractTuple( context, +- workingMemory ); ++ if( list != null ) { ++ for ( LinkedListNode node = list.getFirst(); node != null; node = node.getNext() ) { ++ ReteTuple tuple = (ReteTuple) ((LinkedListObjectWrapper) node).getObject(); ++ tuple.retractTuple( context, ++ workingMemory ); ++ } + } + }" +615f760590ecff8d51832aa4988de410b9de4fb5,drools,JBRULES-2339: JBRULES-2440: fixing ruleflow group- management--git-svn-id: https://svn.jboss.org/repos/labs/labs/jbossrules/trunk@32725 c60d74c8-e8f6-0310-9e8f-d4a2fc68ab70-,c,https://github.com/kiegroup/drools,"diff --git a/drools-core/src/main/java/org/drools/common/DefaultAgenda.java b/drools-core/src/main/java/org/drools/common/DefaultAgenda.java +index b6b14756a40..5d9c2502dee 100644 +--- a/drools-core/src/main/java/org/drools/common/DefaultAgenda.java ++++ b/drools-core/src/main/java/org/drools/common/DefaultAgenda.java +@@ -904,8 +904,9 @@ public synchronized void fireActivation(final Activation activation) throws Cons + } + activation.setActivated( false ); + ++ InternalRuleFlowGroup ruleFlowGroup = null; + if ( activation.getActivationNode() != null ) { +- final InternalRuleFlowGroup ruleFlowGroup = (InternalRuleFlowGroup) activation.getActivationNode().getParentContainer(); ++ ruleFlowGroup = (InternalRuleFlowGroup) activation.getActivationNode().getParentContainer(); + // it is possible that the ruleflow group is no longer active if it was + // cleared during execution of this activation + ruleFlowGroup.removeActivation( activation ); +@@ -930,6 +931,10 @@ public synchronized void fireActivation(final Activation activation) throws Cons + throw new RuntimeException( e ); + } + } ++ ++ if( ruleFlowGroup != null ) { ++ ruleFlowGroup.deactivateIfEmpty(); ++ } + + // if the tuple contains expired events + for ( LeftTuple tuple = (LeftTuple) activation.getTuple(); tuple != null; tuple = tuple.getParent() ) { +diff --git a/drools-core/src/main/java/org/drools/common/InternalRuleFlowGroup.java b/drools-core/src/main/java/org/drools/common/InternalRuleFlowGroup.java +index eb56d023dd5..8ed644cd22d 100644 +--- a/drools-core/src/main/java/org/drools/common/InternalRuleFlowGroup.java ++++ b/drools-core/src/main/java/org/drools/common/InternalRuleFlowGroup.java +@@ -17,6 +17,12 @@ public interface InternalRuleFlowGroup extends RuleFlowGroup { + + void clear(); + ++ /** ++ * Checks if this ruleflow group is active and should automatically deactivate. ++ * If the queue is empty, it deactivates the group. ++ */ ++ public void deactivateIfEmpty(); ++ + /** + * Activates or deactivates this RuleFlowGroup. + * When activating, all activations of this RuleFlowGroup are added +diff --git a/drools-core/src/main/java/org/drools/common/RuleFlowGroupImpl.java b/drools-core/src/main/java/org/drools/common/RuleFlowGroupImpl.java +index a744ae0cdfb..40337c80397 100644 +--- a/drools-core/src/main/java/org/drools/common/RuleFlowGroupImpl.java ++++ b/drools-core/src/main/java/org/drools/common/RuleFlowGroupImpl.java +@@ -53,7 +53,7 @@ public class RuleFlowGroupImpl + private InternalWorkingMemory workingMemory; + private String name; + private boolean active = false; +- private boolean autoDeactivate = true; ++ private boolean autoDeactivate = true; + private LinkedList list; + private List listeners; + private Map nodeInstances = new HashMap(); +@@ -72,13 +72,15 @@ public RuleFlowGroupImpl(final String name) { + this.name = name; + this.list = new LinkedList(); + } +- +- public RuleFlowGroupImpl(final String name, final boolean active, final boolean autoDeactivate) { ++ ++ public RuleFlowGroupImpl(final String name, ++ final boolean active, ++ final boolean autoDeactivate) { + this.name = name; + this.active = active; + this.autoDeactivate = autoDeactivate; + this.list = new LinkedList(); +- } ++ } + + public void readExternal(ObjectInput in) throws IOException, + ClassNotFoundException { +@@ -187,7 +189,7 @@ public int size() { + public void addActivation(final Activation activation) { + assert activation.getActivationNode() == null; + final ActivationNode node = new ActivationNode( activation, +- this ); ++ this ); + activation.setActivationNode( node ); + this.list.add( node ); + +@@ -200,12 +202,17 @@ public void removeActivation(final Activation activation) { + final ActivationNode node = activation.getActivationNode(); + this.list.remove( node ); + activation.setActivationNode( null ); +- if ( this.active && this.autoDeactivate ) { +- if ( this.list.isEmpty() ) { +- // deactivate callback +- WorkingMemoryAction action = new DeactivateCallback( this ); +- this.workingMemory.queueWorkingMemoryAction( action ); +- } ++ } ++ ++ /** ++ * Checks if this ruleflow group is active and should automatically deactivate. ++ * If the queue is empty, it deactivates the group. ++ */ ++ public void deactivateIfEmpty() { ++ if ( this.active && this.autoDeactivate && this.list.isEmpty() ) { ++ // deactivate callback ++ WorkingMemoryAction action = new DeactivateCallback( this ); ++ this.workingMemory.queueWorkingMemoryAction( action ); + } + } + +@@ -217,8 +224,8 @@ public void addRuleFlowGroupListener(RuleFlowGroupListener listener) { + } + + public void removeRuleFlowGroupListener(RuleFlowGroupListener listener) { +- if (listeners != null) { +- listeners.remove(listener); ++ if ( listeners != null ) { ++ listeners.remove( listener ); + } + } + +@@ -258,10 +265,12 @@ public int hashCode() { + return this.name.hashCode(); + } + +- public static class DeactivateCallback implements WorkingMemoryAction { +- +- private static final long serialVersionUID = 400L; +- ++ public static class DeactivateCallback ++ implements ++ WorkingMemoryAction { ++ ++ private static final long serialVersionUID = 400L; ++ + private InternalRuleFlowGroup ruleFlowGroup; + + public DeactivateCallback(InternalRuleFlowGroup ruleFlowGroup) { +@@ -269,12 +278,12 @@ public DeactivateCallback(InternalRuleFlowGroup ruleFlowGroup) { + } + + public DeactivateCallback(MarshallerReaderContext context) throws IOException { +- this.ruleFlowGroup = (InternalRuleFlowGroup) context.wm.getAgenda().getRuleFlowGroup(context.readUTF()); ++ this.ruleFlowGroup = (InternalRuleFlowGroup) context.wm.getAgenda().getRuleFlowGroup( context.readUTF() ); + } + + public void write(MarshallerWriteContext context) throws IOException { +- context.writeInt( WorkingMemoryAction.DeactivateCallback ); +- context.writeUTF(ruleFlowGroup.getName()); ++ context.writeInt( WorkingMemoryAction.DeactivateCallback ); ++ context.writeUTF( ruleFlowGroup.getName() ); + } + + public void readExternal(ObjectInput in) throws IOException, +@@ -283,28 +292,32 @@ public void readExternal(ObjectInput in) throws IOException, + } + + public void writeExternal(ObjectOutput out) throws IOException { +- out.writeObject(ruleFlowGroup); ++ out.writeObject( ruleFlowGroup ); + } + + public void execute(InternalWorkingMemory workingMemory) { + // check whether ruleflow group is still empty first +- if (this.ruleFlowGroup.isEmpty()) { ++ if ( this.ruleFlowGroup.isEmpty() ) { + // deactivate ruleflow group +- this.ruleFlowGroup.setActive(false); ++ this.ruleFlowGroup.setActive( false ); + } + } + } +- +- public void addNodeInstance(Long processInstanceId, String nodeInstanceId) { +- nodeInstances.put(processInstanceId, nodeInstanceId); ++ ++ public void addNodeInstance(Long processInstanceId, ++ String nodeInstanceId) { ++ nodeInstances.put( processInstanceId, ++ nodeInstanceId ); + } + +- public void removeNodeInstance(Long processInstanceId, String nodeInstanceId) { +- nodeInstances.put(processInstanceId, nodeInstanceId); ++ public void removeNodeInstance(Long processInstanceId, ++ String nodeInstanceId) { ++ nodeInstances.put( processInstanceId, ++ nodeInstanceId ); + } +- ++ + public Map getNodeInstances() { +- return nodeInstances; ++ return nodeInstances; + } +- ++ + } +diff --git a/drools-core/src/main/java/org/drools/reteoo/RuleTerminalNode.java b/drools-core/src/main/java/org/drools/reteoo/RuleTerminalNode.java +index 07b454c3f87..78ed21b2651 100644 +--- a/drools-core/src/main/java/org/drools/reteoo/RuleTerminalNode.java ++++ b/drools-core/src/main/java/org/drools/reteoo/RuleTerminalNode.java +@@ -298,7 +298,7 @@ public void modifyLeftTuple(LeftTuple leftTuple, + } + + AgendaItem item = (AgendaItem) leftTuple.getActivation(); +- if ( item.isActivated() ) { ++ if ( item != null && item.isActivated() ) { + // already activated, do nothing + return; + } +@@ -314,12 +314,18 @@ public void modifyLeftTuple(LeftTuple leftTuple, + final Timer timer = this.rule.getTimer(); + + if ( timer != null ) { ++ if ( item == null ) { ++ item = agenda.createScheduledAgendaItem( leftTuple, ++ context, ++ this.rule, ++ this.subrule ); ++ } + agenda.scheduleItem( (ScheduledAgendaItem) item, + workingMemory ); + item.setActivated( true ); +-// workingMemory.removeLogicalDependencies( item, +-// context, +-// this.rule ); ++ // workingMemory.removeLogicalDependencies( item, ++ // context, ++ // this.rule ); + + ((EventSupport) workingMemory).getAgendaEventSupport().fireActivationCreated( item, + workingMemory ); +@@ -334,18 +340,32 @@ public void modifyLeftTuple(LeftTuple leftTuple, + } + } + +- item.setSalience( rule.getSalience().getValue( leftTuple, +- workingMemory ) ); // need to re-evaluate salience, as used fields may have changed +- item.setPropagationContext( context ); // update the Propagation Context ++ if ( item == null ) { ++ // ----------------- ++ // Lazy instantiation and addition to the Agenda of AgendGroup ++ // implementations ++ // ---------------- ++ item = agenda.createAgendaItem( leftTuple, ++ rule.getSalience().getValue( leftTuple, ++ workingMemory ), ++ context, ++ this.rule, ++ this.subrule ); ++ item.setSequenence( this.sequence ); ++ } else { ++ item.setSalience( rule.getSalience().getValue( leftTuple, ++ workingMemory ) ); // need to re-evaluate salience, as used fields may have changed ++ item.setPropagationContext( context ); // update the Propagation Context ++ } + + boolean added = agenda.addActivation( item ); + + item.setActivated( added ); + + if ( added ) { +-// workingMemory.removeLogicalDependencies( item, +-// context, +-// this.rule ); ++ // workingMemory.removeLogicalDependencies( item, ++ // context, ++ // this.rule ); + ((EventSupport) workingMemory).getAgendaEventSupport().fireActivationCreated( item, + workingMemory ); + } +@@ -395,7 +415,7 @@ protected void doRemove(final RuleRemovalContext context, + builder, + this, + workingMemories ); +- for( InternalWorkingMemory workingMemory : workingMemories ) { ++ for ( InternalWorkingMemory workingMemory : workingMemories ) { + workingMemory.executeQueuedActions(); + } + context.setCleanupAdapter( adapter ); +@@ -470,19 +490,21 @@ public short getType() { + return NodeTypeEnums.RuleTerminalNode; + } + +- public static class RTNCleanupAdapter implements CleanupAdapter { ++ public static class RTNCleanupAdapter ++ implements ++ CleanupAdapter { + private RuleTerminalNode node; +- ++ + public RTNCleanupAdapter(RuleTerminalNode node) { + this.node = node; + } + + public void cleanUp(final LeftTuple leftTuple, + final InternalWorkingMemory workingMemory) { +- if( leftTuple.getLeftTupleSink() != node ) { ++ if ( leftTuple.getLeftTupleSink() != node ) { + return; + } +- ++ + final Activation activation = leftTuple.getActivation(); + + if ( activation.isActivated() ) {" +736edba1d834a660bb01e9b9704cd7d7b310a097,tapiji,"removes the outdated package namespace `at.ac.tuwien.inso.tapiji`. + +",p,https://github.com/tapiji/tapiji, +c7cbcd3136e0e5a914f6541db0267b9bb93a07ec,isa-tools$isacreator,"Decoupled functionality for creating user profile from the GUI class. +",p,https://github.com/isa-tools/isacreator,"diff --git a/src/main/java/org/isatools/isacreator/api/CreateProfile.java b/src/main/java/org/isatools/isacreator/api/CreateProfile.java +new file mode 100644 +index 00000000..d29bf01b +--- /dev/null ++++ b/src/main/java/org/isatools/isacreator/api/CreateProfile.java +@@ -0,0 +1,70 @@ ++package org.isatools.isacreator.api; ++ ++import org.isatools.isacreator.gui.ISAcreator; ++import org.isatools.isacreator.io.UserProfile; ++import org.isatools.isacreator.managers.ApplicationManager; ++ ++import java.util.regex.Matcher; ++import java.util.regex.Pattern; ++ ++/** ++ * Created by the ISATeam. ++ * User: agbeltran ++ * Date: 22/08/2012 ++ * Time: 12:38 ++ * ++ * Functionality for validating user profile fields and creating user profile ++ * ++ * @author Alejandra Gonzalez-Beltran ++ */ ++public class CreateProfile { ++ ++ private static ISAcreator main = ApplicationManager.getCurrentApplicationInstance(); ++ ++ ++ public static boolean emptyPassword(char[] cpassword){ ++ String password = new String(cpassword); ++ return password.equals(""""); ++ } ++ ++ public static boolean emptyField(String field){ ++ return field.equals(""""); ++ } ++ ++ public static boolean matchingPasswords(char[] cpassword1, char[] cpassword2){ ++ String password1 = new String(cpassword1); ++ String password2 = new String(cpassword2); ++ return password1.equals(password2); ++ } ++ ++ public static boolean validEmail(String email){ ++ Pattern p = Pattern.compile(""[.]*@[.]*""); ++ Matcher m = p.matcher(email); ++ return m.find(); ++ } ++ ++ public static boolean duplicateUser(String username){ ++ for (UserProfile up : main.getUserProfiles()) { ++ if (up.getUsername().equals(username)) { ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ public static void createProfile(String username,char[] password, String firstname, String surname, String institution, String email){ ++ ++ UserProfile newUser = new UserProfile(username, ++ new String(password).hashCode(), ++ firstname, ++ surname, ++ institution, ++ email); ++ ++ main.getUserProfiles().add(newUser); ++ main.setCurrentUser(newUser); ++ main.setUserOntologyHistory(newUser.getUserHistory()); ++ main.saveUserProfiles(); ++ } ++ ++} +diff --git a/src/main/java/org/isatools/isacreator/gui/menu/CreateProfile.java b/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java +similarity index 80% +rename from src/main/java/org/isatools/isacreator/gui/menu/CreateProfile.java +rename to src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java +index 79614ab9..49cbd2bf 100644 +--- a/src/main/java/org/isatools/isacreator/gui/menu/CreateProfile.java ++++ b/src/main/java/org/isatools/isacreator/gui/menu/CreateProfileMenu.java +@@ -5,7 +5,7 @@ ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) + ISAcreator is licensed under the Common Public Attribution License version 1.0 (CPAL) + + EXHIBIT A. CPAL version 1.0 +- ÒThe contents of this file are subject to the CPAL version 1.0 (the ÒLicenseÓ); ++ �The contents of this file are subject to the CPAL version 1.0 (the �License�); + you may not use this file except in compliance with the License. You may obtain a + copy of the License at http://isa-tools.org/licenses/ISAcreator-license.html. + The License is based on the Mozilla Public License version 1.1 but Sections +@@ -13,7 +13,7 @@ ISAcreator is a component of the ISA software suite (http://www.isa-tools.org) + provide for limited attribution for the Original Developer. In addition, Exhibit + A has been modified to be consistent with Exhibit B. + +- Software distributed under the License is distributed on an ÒAS ISÓ basis, ++ Software distributed under the License is distributed on an �AS IS� basis, + WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + the specific language governing rights and limitations under the License. + +@@ -37,9 +37,9 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + + package org.isatools.isacreator.gui.menu; + ++import org.isatools.isacreator.api.CreateProfile; + import org.isatools.isacreator.common.UIHelper; + import org.isatools.isacreator.effects.components.RoundedJPasswordField; +-import org.isatools.isacreator.io.UserProfile; + import org.jdesktop.fuse.InjectedResource; + + import javax.swing.*; +@@ -47,8 +47,7 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + import java.awt.event.ActionEvent; + import java.awt.event.MouseAdapter; + import java.awt.event.MouseEvent; +-import java.util.regex.Matcher; +-import java.util.regex.Pattern; ++ + + /** + * CreateProfileGUI provides interface to allow users to construct a new profile +@@ -59,7 +58,7 @@ The ISA Team and the ISA software suite have been funded by the EU Carcinogenomi + */ + + +-public class CreateProfile extends MenuUIComponent { ++public class CreateProfileMenu extends MenuUIComponent { + @InjectedResource + private ImageIcon createProfileButton, createProfileButtonOver, + backButtonSml, backButtonSmlOver; +@@ -75,7 +74,7 @@ public class CreateProfile extends MenuUIComponent { + private JTextField surnameVal; + private JTextField usernameVal; + +- public CreateProfile(ISAcreatorMenu menu) { ++ public CreateProfileMenu(ISAcreatorMenu menu) { + super(menu); + status = new JLabel("" ""); + status.setForeground(UIHelper.RED_COLOR); +@@ -254,56 +253,30 @@ private void assignKeyActionToComponent(Action action, JComponent field) { + + private void createProfile() { + // check password is not empty and that the password and the confirmation match! +- String password = new String(passwordVal.getPassword()); +- if (!password.equals("""")) { +- String passwordConfirmation = new String(confirmPasswordVal.getPassword()); +- if (!password.equals(passwordConfirmation)) { +- status.setText( +- ""passwords do not match! the password and confirmation must match!""); +- return; +- } +- } else { ++ if (CreateProfile.emptyPassword(passwordVal.getPassword())) { + status.setText( + ""password is required!""); + return; + } ++ if (!CreateProfile.matchingPasswords(passwordVal.getPassword(),confirmPasswordVal.getPassword())){ ++ status.setText( ++ ""passwords do not match! the password and confirmation must match!""); ++ return; ++ }; + + // check the rest of the fields to ensure values have been entered and proceed to creating the + // profile if everything is ok! +- if (!usernameVal.getText().equals("""")) { +- if (!firstnameVal.getText().equals("""")) { +- if (!surnameVal.getText().equals("""")) { +- if (!institutionVal.getText().equals("""")) { +- if (!emailVal.getText().equals("""")) { +- Pattern p = Pattern.compile(""[.]*@[.]*""); +- Matcher m = p.matcher(emailVal.getText()); +- +- if (m.find()) { +- UserProfile newUser = new UserProfile(usernameVal.getText(), +- new String(passwordVal.getPassword()).hashCode(), +- firstnameVal.getText(), +- surnameVal.getText(), +- institutionVal.getText(), +- emailVal.getText()); +- boolean dupUser = false; +- +- for (UserProfile up : menu.getMain().getUserProfiles()) { +- if (up.getUsername() +- .equals(usernameVal.getText())) { +- dupUser = true; +- status.setText( +- ""user name taken! this username is already in use""); +- +- break; +- } +- } +- +- if (!dupUser) { +- menu.getMain().getUserProfiles().add(newUser); +- menu.getMain().setCurrentUser(newUser); +- menu.getMain().setUserOntologyHistory(newUser.getUserHistory()); +- menu.getMain().saveUserProfiles(); +- ++ if (!CreateProfile.emptyField(usernameVal.getText())) { ++ if (!CreateProfile.emptyField(firstnameVal.getText())) { ++ if (!CreateProfile.emptyField(surnameVal.getText())) { ++ if (!CreateProfile.emptyField(institutionVal.getText())) { ++ if (!CreateProfile.emptyField(emailVal.getText())) { ++ if (CreateProfile.validEmail(emailVal.getText())) { ++ if (CreateProfile.duplicateUser(usernameVal.getText())){ ++ status.setText( ++ ""user name taken! this username is already in use""); ++ }else{ ++ CreateProfile.createProfile(usernameVal.getText(), passwordVal.getPassword(),firstnameVal.getText(),surnameVal.getText(),institutionVal.getText(),emailVal.getText()); + menu.changeView(menu.getMainMenuGUI()); + } + } else { +@@ -330,6 +303,6 @@ private void createProfile() { + status.setText( + ""username is required! please enter a username""); + } +- } ++ }//createProfile method + } + +diff --git a/src/main/resources/dependency-injections/gui-package.properties b/src/main/resources/dependency-injections/gui-package.properties +index a7540c70..3f289acf 100644 +--- a/src/main/resources/dependency-injections/gui-package.properties ++++ b/src/main/resources/dependency-injections/gui-package.properties +@@ -99,8 +99,8 @@ SaveAsDialog.saveSubmissionOver=/images/gui/savesubmission_over.png + + # MenuUIComponent images. This class is extended by AuthenticationMenu, CreateISATabMenu, CreateProfie, + # ImportConfiguration, ImportFilesMenu & MainMenu +-MenuUIComponent.backButton={CreateProfile.backButtonSml} +-MenuUIComponent.backButtonOver={CreateProfile.backButtonSmlOver} ++MenuUIComponent.backButton={CreateProfileMenu.backButtonSml} ++MenuUIComponent.backButtonOver={CreateProfileMenu.backButtonSmlOver} + MenuUIComponent.exitButtonSml=/images/gui/menu_new/exit_sml.png + MenuUIComponent.exitButtonSmlOver=/images/gui/menu_new/exit_sml_over.png + MenuUIComponent.createProfileButton=/images/gui/menu_new/create_profile.png +@@ -114,10 +114,10 @@ AuthenticationMenu.createProfileButtonOver={MenuUIComponent.createProfileButtonO + AuthenticationMenu.exitButtonSml={MenuUIComponent.exitButtonSml} + AuthenticationMenu.exitButtonSmlOver={MenuUIComponent.exitButtonSmlOver} + +-CreateProfile.createProfileButton={AuthenticationMenu.createProfileButton} +-CreateProfile.createProfileButtonOver={AuthenticationMenu.createProfileButtonOver} +-CreateProfile.backButtonSml=/images/gui/menu_new/back_sml.png +-CreateProfile.backButtonSmlOver=/images/gui/menu_new/back_sml_over.png ++CreateProfileMenu.createProfileButton={AuthenticationMenu.createProfileButton} ++CreateProfileMenu.createProfileButtonOver={AuthenticationMenu.createProfileButtonOver} ++CreateProfileMenu.backButtonSml=/images/gui/menu_new/back_sml.png ++CreateProfileMenu.backButtonSmlOver=/images/gui/menu_new/back_sml_over.png + + MainMenu.panelHeader=/images/gui/mainmenu.png + MainMenu.createNew=/images/gui/menu_new/create_new.png" +7679e6c2affe21f5179dbd1bedaac4cfa0b00436,Valadoc,"0.20.x: Add support for [GenericAccessors] +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +2daa05f2bd185e3de5c2e85afc86b2bc6194b41b,Valadoc,"gtkdoc: accept % +",a,https://github.com/GNOME/vala/,⚠️ Could not parse repo info +454302cf65c3c617149f28aee819549dd02f3680,Mylyn Reviews,"Move versions-task bridge to reviews +",p,https://github.com/eclipse-mylyn/org.eclipse.mylyn.reviews,"diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.project b/versions/org.eclipse.mylyn.versions.tasks-feature/.project +new file mode 100644 +index 00000000..dfb62cc5 +--- /dev/null ++++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.project +@@ -0,0 +1,17 @@ ++ ++ ++ org.eclipse.mylyn.versions-feature ++ ++ ++ ++ ++ ++ org.eclipse.pde.FeatureBuilder ++ ++ ++ ++ ++ ++ org.eclipse.pde.FeatureNature ++ ++ +diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs +new file mode 100644 +index 00000000..bbaca6d6 +--- /dev/null ++++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.core.prefs +@@ -0,0 +1,357 @@ ++#Wed Mar 02 16:00:06 PST 2011 ++eclipse.preferences.version=1 ++org.eclipse.jdt.core.codeComplete.argumentPrefixes= ++org.eclipse.jdt.core.codeComplete.argumentSuffixes= ++org.eclipse.jdt.core.codeComplete.fieldPrefixes= ++org.eclipse.jdt.core.codeComplete.fieldSuffixes= ++org.eclipse.jdt.core.codeComplete.localPrefixes= ++org.eclipse.jdt.core.codeComplete.localSuffixes= ++org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= ++org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= ++org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled ++org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 ++org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve ++org.eclipse.jdt.core.compiler.compliance=1.5 ++org.eclipse.jdt.core.compiler.debug.lineNumber=generate ++org.eclipse.jdt.core.compiler.debug.localVariable=generate ++org.eclipse.jdt.core.compiler.debug.sourceFile=generate ++org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning ++org.eclipse.jdt.core.compiler.problem.assertIdentifier=error ++org.eclipse.jdt.core.compiler.problem.autoboxing=ignore ++org.eclipse.jdt.core.compiler.problem.deprecation=warning ++org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled ++org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=enabled ++org.eclipse.jdt.core.compiler.problem.discouragedReference=warning ++org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore ++org.eclipse.jdt.core.compiler.problem.enumIdentifier=error ++org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore ++org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled ++org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore ++org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning ++org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning ++org.eclipse.jdt.core.compiler.problem.forbiddenReference=error ++org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning ++org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning ++org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore ++org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore ++org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore ++org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning ++org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore ++org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore ++org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning ++org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning ++org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning ++org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=warning ++org.eclipse.jdt.core.compiler.problem.nullReference=error ++org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning ++org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore ++org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore ++org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning ++org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning ++org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore ++org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore ++org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled ++org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning ++org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled ++org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore ++org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning ++org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning ++org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore ++org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning ++org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore ++org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore ++org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore ++org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore ++org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled ++org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled ++org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled ++org.eclipse.jdt.core.compiler.problem.unusedImport=warning ++org.eclipse.jdt.core.compiler.problem.unusedLabel=warning ++org.eclipse.jdt.core.compiler.problem.unusedLocal=warning ++org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore ++org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled ++org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled ++org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled ++org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning ++org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning ++org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning ++org.eclipse.jdt.core.compiler.source=1.5 ++org.eclipse.jdt.core.compiler.taskCaseSensitive=enabled ++org.eclipse.jdt.core.compiler.taskPriorities=NORMAL,HIGH,NORMAL ++org.eclipse.jdt.core.compiler.taskTags=TODO,FIXME,XXX ++org.eclipse.jdt.core.formatter.align_type_members_on_columns=false ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=16 ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 ++org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 ++org.eclipse.jdt.core.formatter.alignment_for_assignment=0 ++org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 ++org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 ++org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=48 ++org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 ++org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 ++org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 ++org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 ++org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=80 ++org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 ++org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 ++org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 ++org.eclipse.jdt.core.formatter.blank_lines_after_package=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_field=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=0 ++org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_method=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 ++org.eclipse.jdt.core.formatter.blank_lines_before_package=0 ++org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 ++org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 ++org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line ++org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line ++org.eclipse.jdt.core.formatter.comment.clear_blank_lines=false ++org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false ++org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=true ++org.eclipse.jdt.core.formatter.comment.format_block_comments=false ++org.eclipse.jdt.core.formatter.comment.format_comments=true ++org.eclipse.jdt.core.formatter.comment.format_header=false ++org.eclipse.jdt.core.formatter.comment.format_html=true ++org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true ++org.eclipse.jdt.core.formatter.comment.format_line_comments=false ++org.eclipse.jdt.core.formatter.comment.format_source_code=true ++org.eclipse.jdt.core.formatter.comment.indent_parameter_description=true ++org.eclipse.jdt.core.formatter.comment.indent_root_tags=true ++org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert ++org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=insert ++org.eclipse.jdt.core.formatter.comment.line_length=120 ++org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true ++org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true ++org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false ++org.eclipse.jdt.core.formatter.compact_else_if=true ++org.eclipse.jdt.core.formatter.continuation_indentation=2 ++org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=2 ++org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off ++org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on ++org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false ++org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true ++org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true ++org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true ++org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true ++org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true ++org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true ++org.eclipse.jdt.core.formatter.indent_empty_lines=false ++org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true ++org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true ++org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true ++org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=false ++org.eclipse.jdt.core.formatter.indentation.size=4 ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_member=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=do not insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert ++org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert ++org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert ++org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert ++org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert ++org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert ++org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert ++org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert ++org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert ++org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert ++org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert ++org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert ++org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert ++org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert ++org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert ++org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert ++org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert ++org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert ++org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert ++org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert ++org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert ++org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert ++org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert ++org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert ++org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert ++org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert ++org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert ++org.eclipse.jdt.core.formatter.join_lines_in_comments=true ++org.eclipse.jdt.core.formatter.join_wrapped_lines=true ++org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false ++org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false ++org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false ++org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false ++org.eclipse.jdt.core.formatter.lineSplit=120 ++org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=true ++org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=true ++org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 ++org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 ++org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true ++org.eclipse.jdt.core.formatter.tabulation.char=tab ++org.eclipse.jdt.core.formatter.tabulation.size=4 ++org.eclipse.jdt.core.formatter.use_on_off_tags=false ++org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false ++org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true ++org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true +diff --git a/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs +new file mode 100644 +index 00000000..f6c0a161 +--- /dev/null ++++ b/versions/org.eclipse.mylyn.versions.tasks-feature/.settings/org.eclipse.jdt.ui.prefs +@@ -0,0 +1,63 @@ ++#Wed Mar 02 16:00:06 PST 2011 ++cleanup_settings_version=2 ++eclipse.preferences.version=1 ++editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true ++formatter_profile=_Mylyn based on Eclipse ++formatter_settings_version=12 ++internal.default.compliance=default ++org.eclipse.jdt.ui.exception.name=e ++org.eclipse.jdt.ui.gettersetter.use.is=true ++org.eclipse.jdt.ui.javadoc=false ++org.eclipse.jdt.ui.keywordthis=false ++org.eclipse.jdt.ui.overrideannotation=true ++org.eclipse.jdt.ui.text.custom_code_templates=