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:
*/
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 extends Script> 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 extends T> 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 extends T> 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 extends T> 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 extends ShellCommand> commandManager;
+ final AbstractClassManager extends ShellCommand> commandManager;
/** . */
- final ClassManager extends GroovyScript> scriptManager;
+ final AbstractClassManager extends GroovyScript> scriptManager;
/** . */
final PluginContext context;
@@ -55,7 +54,7 @@ public CRaSH(PluginContext context) throws NullPointerException {
);
}
- public CRaSH(PluginContext context, ClassManager commandManager, ClassManager extends GroovyScript> scriptManager) {
+ public CRaSH(PluginContext context, AbstractClassManager commandManager, AbstractClassManager extends GroovyScript> 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 extends Script> baseScriptClass) {
- CompilerConfiguration config = new CompilerConfiguration();
- config.setRecompileGroovySource(true);
- config.setScriptBaseClass(baseScriptClass.getName());
+ public ClassManager(PluginContext context, ResourceKind kind, Class baseClass, Class extends Script> baseScriptClass) {
+ super(context, baseClass, baseScriptClass);
//
this.context = context;
- this.config = config;
- this.baseClass = baseClass;
this.kind = kind;
}
- Class extends T> 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 extends T> 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 extends T> 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 name
- *
Class name
- *
Description
- *
- *
- *
org.restlet.http.headers
- *
org.restlet.data.Form
- *
Server 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.clientCertificates
- *
List
- *
For 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 name
+ *
Class name
+ *
Description
+ *
+ *
+ *
org.restlet.http.headers
+ *
org.restlet.data.Form
+ *
Server 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.clientCertificates
+ *
List
+ *
For 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