Cooldown is not working [Minecraft Bukkit plugin] - plugins

so I got a problem with the cooldown in my command. The command work perfectly but when I try to put a cooldown, it's not working. In the chat this error message is send: An internal error occurred while attempting to perform this command. In the console, it's say that:
> [14:50:33 INFO]: EvilestVirus7 issued server command: /rtpPlayer
> [14:50:33 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'rtpplayer' in plugin RandomTP v1.0
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.dispatchCommand(CraftServer.java:641) ~[spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PlayerConnection.handleCommand(PlayerConnection.java:1162) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PlayerConnection.chat(PlayerConnection.java:1078) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer.chat(CraftPlayer.java:237) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at can.evilestvirus.randomtp.MenuHandler.onMenuClick(MenuHandler.java:20) [RandomTpPlugin.jar:git-Spigot-21fe707-e1ebe52]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_212]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_212]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_212]
at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_212]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:502) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:487) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PlayerConnection.a(PlayerConnection.java:1630) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PacketPlayInWindowClick.a(SourceFile:31) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PacketPlayInWindowClick.a(SourceFile:9) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.PlayerConnectionUtils$1.run(SourceFile:13) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_212]
at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_212]
at net.minecraft.server.v1_8_R3.SystemUtils.a(SourceFile:44) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:715) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_212]
Caused by: java.lang.NullPointerException
at can.evilestvirus.randomtp.CooldownManager.checkCooldowns(CooldownManager.java:26) ~[?:?]
at can.evilestvirus.randomtp.CommandRtpPlayer.onCommand(CommandRtpPlayer.java:22) ~[?:?]
at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot1.8.8.jar:git-Spigot-21fe707-e1ebe52]
... 26 more
This is my main class:
package can.evilestvirus.randomtp;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin{
#Override
public void onEnable() {
getCommand("rtpplayer").setExecutor(new CommandRtpPlayer());
getCommand("rtp").setExecutor(new CommandRtp());
Bukkit.getPluginManager().registerEvents(new MenuHandler(), this);
}
}
There the cooldownManager class:
package can.evilestvirus.randomtp;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.UUID;
public class CooldownManager {
public static HashMap<UUID, Double> cooldowns;
public static void setupCooldown(){
cooldowns = new HashMap<>();
}
public static void setCooldowns(Player player, int secondes){
double delay = System.currentTimeMillis() + (secondes * 1000);
cooldowns.put(player.getUniqueId(), delay);
}
public static int getCooldowns(Player player){
return Math.toIntExact(Math.round((cooldowns.get(player.getUniqueId()) - System.currentTimeMillis()/1000)));
}
public static boolean checkCooldowns(Player player){
if(!cooldowns.containsKey(player.getUniqueId()) || cooldowns.get(player.getUniqueId()) <= System.currentTimeMillis()){
return true;
}
return false;
}
}
And this is the command class:
package can.evilestvirus.randomtp;
import java.util.HashMap;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
public class CommandRtpPlayer implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if(CooldownManager.checkCooldowns(player.getPlayer())){
CooldownManager.setCooldowns(player.getPlayer(), 10);
Location rtp, rtp2, rtp3, rtp4, rtp5;
Random random = new Random();
int nbrandom = (int) (Math.random() * 4.0D) + 1;
switch (nbrandom) {
case 1:
rtp = new Location(player.getWorld(), random.nextInt(2500), 90.0D,
random.nextInt(2500), 1.8F, 7.4F);
player.teleport(rtp);
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 99));
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 99));
break;
case 2:
rtp2 = new Location(player.getWorld(), -random.nextInt(2500), 90.0D,
-random.nextInt(2500), 1.8F, 7.4F);
player.teleport(rtp2);
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 99));
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 99));
break;
case 3:
rtp3 = new Location(player.getWorld(), -random.nextInt(2500), 90.0D,
random.nextInt(2500), 1.8F, 7.4F);
player.teleport(rtp3);
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 99));
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 99));
break;
case 4:
rtp4 = new Location(player.getWorld(), random.nextInt(2500), 90.0D,
-random.nextInt(2500), 1.8F, 7.4F);
player.teleport(rtp4);
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 99));
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 99));
break;
default:
rtp5 = new Location(player.getWorld(), random.nextInt(2500), 90.0D,
-random.nextInt(2500), 1.8F, 7.4F);
player.teleport(rtp5);
player.addPotionEffect(new PotionEffect(PotionEffectType.REGENERATION, 200, 99));
player.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 200, 99));
break;
}
player.sendMessage("§a§lVous venez d'être téléporté aléatoirement!");
}else{
player.getPlayer().sendMessage("Vous pourez utiliser la commandes dans " + CooldownManager.getCooldowns(player.getPlayer()) + " seconds");
}
}
return true;
}
}

You never run the setupCooldowns() method you have inside your CooldownManager class. I would recommend you remove this method anyways and simply instantiate the cooldown using Map<UUID, Double> cooldowns = new HashMap<>();
The reason you’re getting a NullPointerException is because your HashMap has not been instantiated (does not exist)

Related

Proxy for MongoDB Client-Side Field Level Encrytion AWS KMS Connection

We have implemented a Client-Side Field Level Encryption on a Spring Boot application, using AWS KMS to save the master key.
I followed the tutorial created by Visweshwar Ganesh and everything works perfectly.
MongoDB Client-Side Field Level Encryption using Java-Spring
The problem is that we need to connect to the AWS KMS through a proxy, and I can't find any documentation to inject proxy configs for MongoEncription.
Does anyone know how to solve this?
Regards!
Edit:
We are using: spring-boot-starter-data-mongodb-2.2.4.RELEASE which uses mongodb-driver 3.11.2
And this is the official MongoDB Documentation
We want to proxy the call to retrieve the CMK from Thrid-Party KMS (AWS) to Encrypt and Decrypt data:
When application starts it creates a mongoClient with the encryption settings and validates if alteady exists a vault with encrypton keys, if not tries to create one, and for that needs to have the CMK stored on AWS KMS
It's on this call that occurs on buildOrValidateVault() method that we want to inject the proxy.
PS: This application is running on a kubernetes container.
MongoEncryptionConfig
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.BsonDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.AutoEncryptionSettings;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoDriverInformation;
import com.mongodb.client.MongoClient;
import com.mongodb.client.internal.MongoClientImpl;
import com.mongodb.internal.build.MongoDriverVersion;
#Configuration
public class MongoEncryptionConfig extends AbstractMongoClientConfiguration {
#Value(value = "${mongodb.student.name}")
private String dbDatabase;
#Value(value = "${mongodb.student.uri}")
private String dbConnection;
#Value(value = "${encryption.schema-path}")
private String schemaPath;
#Autowired
private KmsHandlerAws kmsHandler;
private static Logger logger = LogManager.getLogger("MongoEncryptionConfig");
private MongoDriverInformation getMongoDriverInfo() {
return MongoDriverInformation.builder()
.driverName(MongoDriverVersion.NAME)
.driverVersion(MongoDriverVersion.VERSION)
.driverPlatform(java.lang.String.format("Java/%s/%s", java.lang.System.getProperty("java.vendor", "unknown-vendor"),
java.lang.System.getProperty("java.runtime.version", "unknown-version")))
.build();
}
private MongoClientSettings getAutoEncryptMongoClientSettings() {
return MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(dbConnection))
.autoEncryptionSettings(autoEncryptionSettings())
.build();
}
private AutoEncryptionSettings autoEncryptionSettings() {
return AutoEncryptionSettings.builder()
.keyVaultNamespace(kmsHandler.getEncryptionCollectionName())
.kmsProviders(kmsHandler.getKmsProvider())
.extraOptions(kmsHandler.getExtraOptsMap())
.schemaMap(buildOrValidateVault())
.build();
}
private Map<String, BsonDocument> buildOrValidateVault() {
try {
ObjectMapper objectMapper = new ObjectMapper();
for (Path path : loadSchemasPaths(this.schemaPath)) {
logger.debug("Path being iterated: " + path.getFileName().toString());
String encryptKey = this.kmsHandler.buildOrValidateVault();
JsonNode jsonDocument = objectMapper.readTree(Files.readString(path));
return Collections.singletonMap(
this.dbDatabase + "." + jsonDocument.get("metadata").get("collection").asText(),
BsonDocument.parse(String.format(objectMapper.writeValueAsString(jsonDocument.get("schema")), encryptKey)));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
private List<Path> loadSchemasPaths(String encryptionPath) throws IOException {
List<Path> paths = new ArrayList<>();
logger.debug("Encryption Path: " + encryptionPath);
Files.list(Paths.get(encryptionPath))
.forEach(path -> {
logger.debug("Path trying to be add: " + path.getFileName());
if (path.getFileName().toString().endsWith(".json")) {
logger.debug(path.getFileName() + " ends with .json! Yes!");
paths.add(path);
} else {
logger.debug(path.getFileName() + " Doesn't end with .json :(");
}
});
return paths;
}
#Override
public MongoClient mongoClient() {
return new MongoClientImpl(getAutoEncryptMongoClientSettings(), getMongoDriverInfo());
}
#Override
protected String getDatabaseName() {
return dbDatabase;
}
}
KMSHandler
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bson.BsonBinary;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
public abstract class KmsHandler {
Logger logger = LoggerFactory.getLogger(KmsHandler.class);
#Value(value = "${mongodb.student.uri}")
String dbConnection;
#Value(value = "${encryption.vault.database}")
String encryptionVaultDatabase;
#Value(value = "${encryption.vault.collection}")
String encryptionVaultCollection;
#Value(value = "${encryption.vault.name}")
String encryptionVaultName;
private String encryptionKeyBase64;
private UUID encryptionKeyUuid;
public String getEncryptionKeyBase64() {
return encryptionKeyBase64;
}
public void setEncryptionKeyBase64(String encryptionKeyBase64) {
this.encryptionKeyBase64 = encryptionKeyBase64;
}
public UUID getEncryptionKeyUuid() {
return encryptionKeyUuid;
}
public void setEncryptionKeyUuid(UUID encryptionKeyUuid) {
this.encryptionKeyUuid = encryptionKeyUuid;
}
public String getEncryptionCollectionName() {
return encryptionVaultDatabase + "." + encryptionVaultCollection;
}
public Map<String, Object> getExtraOptsMap() {
Map<String, Object> extraOps = new HashMap<>();
//extraOps.put("mongocryptdBypassSpawn", true);
//extraOps.put("mongocryptdURI", "mongodb://localhost:27020");
return extraOps;
}
/**
* Check in database if encryption was already created
* dd
*
* #return true or false
*/
protected String doesEncryptionKeyExist() {
MongoClient mongoClient = MongoClients.create(dbConnection);
MongoCollection<Document> collection = mongoClient.getDatabase(encryptionVaultDatabase).getCollection(encryptionVaultCollection);
Document doc = collection.find(Filters.in("keyAltNames", encryptionVaultName)).first();
if (doc != null) {
return Base64.getEncoder().encodeToString(new BsonBinary((UUID) doc.get("_id")).getData());
} else {
return null;
}
}
}
KMSHandlerAWS
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.bson.BsonBinary;
import org.bson.BsonDocument;
import org.bson.BsonString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.mongodb.ClientEncryptionSettings;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.model.vault.DataKeyOptions;
import com.mongodb.client.vault.ClientEncryption;
import com.mongodb.client.vault.ClientEncryptions;
#Component
public class KmsHandlerAws extends KmsHandler implements IKmsHandler {
#Value(value = "${encryption.kms.aws.region}")
private String encryptionKmsRegion;
#Value(value = "${encryption.kms.aws.key}")
private String encryptionKmsKey;
#Value(value = "${encryption.kms.aws.iam.accessKeyId}")
private String encryptionKmsIamAccessKey;
#Value(value = "${encryption.kms.aws.iam.secretAccessKey}")
private String encryptionKmsIamSecretAccessKey;
public String buildOrValidateVault() {
try {
// Check if encryption key exists
String encryptKey = doesEncryptionKeyExist();
if (encryptKey != null) {
return encryptKey;
}
// Create Encryption Key
BsonBinary dataKeyId = getClientEncryption().createDataKey("aws", this.getDataKeyOptions());
// Save key in instance
this.setEncryptionKeyUuid(dataKeyId.asUuid());
logger.debug("DataKeyID [UUID]{}", dataKeyId.asUuid());
System.out.println("DataKeyID [UUID]: " + dataKeyId.asUuid());
String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());
this.setEncryptionKeyBase64(base64DataKeyId);
logger.debug("DataKeyID [base64]: {}", base64DataKeyId);
System.out.println("DataKeyID [base64]: " + base64DataKeyId);
return super.getEncryptionKeyBase64();
} catch (Exception ex) {
String exceptionMessage = "Exception at buildOrValidateVault(): " + ex.getMessage();
System.out.println(exceptionMessage);
ex.printStackTrace();
return exceptionMessage;
}
}
public Map<String, Map<String, Object>> getKmsProvider() {
Map<String, Object> providerDetails = new HashMap<>();
providerDetails.put("accessKeyId", new BsonString(this.encryptionKmsIamAccessKey).getValue());
providerDetails.put("secretAccessKey", new BsonString(this.encryptionKmsIamSecretAccessKey).getValue());
Map<String, Map<String, Object>> kmsProviders = new HashMap<>();
kmsProviders.put("aws", providerDetails);
return kmsProviders;
}
public ClientEncryption getClientEncryption() {
return ClientEncryptions.create(ClientEncryptionSettings.builder()
.keyVaultMongoClientSettings(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(this.dbConnection))
.build())
.keyVaultNamespace(this.encryptionVaultDatabase + "." + this.encryptionVaultCollection)
.kmsProviders(this.getKmsProvider())
.build());
}
public DataKeyOptions getDataKeyOptions() {
return new DataKeyOptions().masterKey(
new BsonDocument()
.append("region", new BsonString(this.encryptionKmsRegion))
.append("key", new BsonString(this.encryptionKmsKey))
)
.keyAltNames(Collections.singletonList(this.encryptionVaultName));
}
}
Log Error:
Exception at buildOrValidateVault(): Exception opening connection to Key Management Service
com.mongodb.MongoSocketOpenException: Exception opening connection to Key Management Service
at com.mongodb.client.internal.KeyManagementService.stream(KeyManagementService.java:57)
at com.mongodb.client.internal.Crypt.decryptKey(Crypt.java:299)
at com.mongodb.client.internal.Crypt.decryptKeys(Crypt.java:289)
at com.mongodb.client.internal.Crypt.executeStateMachine(Crypt.java:242)
at com.mongodb.client.internal.Crypt.createDataKey(Crypt.java:155)
at com.mongodb.client.internal.ClientEncryptionImpl.createDataKey(ClientEncryptionImpl.java:50)
at com.example.student.nosql.config.kms.KmsHandlerAws.buildOrValidateVault(KmsHandlerAws.java:40)
at com.example.student.nosql.config.MongoEncryptionConfig.buildOrValidateVault(MongoEncryptionConfig.java:77)
at com.example.student.nosql.config.MongoEncryptionConfig.autoEncryptionSettings(MongoEncryptionConfig.java:68)
at com.example.student.nosql.config.MongoEncryptionConfig.getAutoEncryptMongoClientSettings(MongoEncryptionConfig.java:59)
at com.example.student.nosql.config.MongoEncryptionConfig.mongoClient(MongoEncryptionConfig.java:110)
at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d.CGLIB$mongoDbFactory$3(<generated>)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d$$FastClassBySpringCGLIB$$6e240ce0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d.mongoDbFactory(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d.mongoDbFactory(<generated>)
at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d.CGLIB$mongoTemplate$2(<generated>)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d$$FastClassBySpringCGLIB$$6e240ce0.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
at com.example.student.nosql.config.MongoEncryptionConfig$$EnhancerBySpringCGLIB$$acc0967d.mongoTemplate(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:330)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1699)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1444)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:207)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:454)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:543)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:513)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:653)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:224)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$172/0x00000000b0807980.getObject(Unknown Source)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
at com.example.student.StudentApplication.main(StudentApplication.java:16)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
at org.springframework.boot.loader.Launcher.launch(Launcher.java:51)
at org.springframework.boot.loader.PropertiesLauncher.main(PropertiesLauncher.java:597)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.base/java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.base/java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.base/java.net.SocksSocketImpl.connect(Unknown Source)
at java.base/java.net.Socket.connect(Unknown Source)
at java.base/sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at com.mongodb.client.internal.KeyManagementService.stream(KeyManagementService.java:54)
... 131 more
I don't think this is supported.
The contents of the KMS request is constructed by libmongocrypt; the request itself is performed by the driver. The payload being sent is opaque to the driver. This is described under MONGOCRYPT_CTX_NEED_KMS state in https://github.com/mongodb/libmongocrypt/blob/master/integrating.md.
I find it unlikely that you would be able to use a proxy with the described integration flow because:
The payload must be correctly constructed by libmongocrypt to account for the request being proxied (for example, to use the full URL including the protocol and host in the HTTP URI).
The driver needs to be told about the proxy. To my knowledge there isn't any such guidance across drivers. Generally speaking, proxy configuration in different environments is different.
The language as written doesn't (to me) have any indicators that the proxy use case was considered.
Looking at the Ruby driver implementation of this flow (https://github.com/mongodb/mongo-ruby-driver/blob/master/lib/mongo/crypt/encryption_io.rb feed_kms method), the driver creates a socket directly to the requested host/port. There is no provision for using proxies.
If you are a paying customer I suggest submitting this request through official support channels. Otherwise I suggest adding it to https://feedback.mongodb.com/.

How to use multiple Zookeeper with distributed state machine?

I'm trying to use distributed states in my application with zookeeper just like in the Spring document, with only one difference. My application works fine with one zookeeper but I need multiple zookeeper address. Here is my configuration:
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.data.jpa.JpaPersistingStateMachineInterceptor;
import org.springframework.statemachine.data.jpa.JpaStateMachineRepository;
import org.springframework.statemachine.ensemble.StateMachineEnsemble;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.persist.StateMachineRuntimePersister;
import org.springframework.statemachine.service.DefaultStateMachineService;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.zookeeper.ZookeeperStateMachineEnsemble;
import java.util.EnumSet;
#Slf4j
#Configuration
#EnableStateMachineFactory
public class JpaPersistStateMachineConfiguration extends StateMachineConfigurerAdapter<States, Events> {
#Autowired
public JpaStateMachineRepository jpaStateMachineRepository;
private Logger logger = LoggerFactory.getLogger(JpaPersistStateMachineConfiguration.class);
#Override
public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception{
states
.withStates()
.initial(States.ORDERED)
.end(States.PAYED)
.end(States.CANCELLED)
.states(EnumSet.allOf(States.class));
}
#Override
public void configure(StateMachineTransitionConfigurer<States,Events> transitions) throws Exception {
transitions
.withExternal().source(States.ORDERED).target(States.ASSEMBLED).event(Events.assemble).and()
.withExternal().source(States.ASSEMBLED).target(States.DELIVERED).event(Events.deliver).and()
.withExternal().source(States.DELIVERED).target(States.PAYED).event(Events.payment_received).and()
.withExternal().source(States.ORDERED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.ASSEMBLED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.DELIVERED).target(States.CANCELLED).event(Events.cancel);
}
#Override
public void configure(StateMachineConfigurationConfigurer<States,Events> config) throws Exception{
config
.withDistributed()
.ensemble(stateMachineEnsemble())
.and()
.withPersistence()
.runtimePersister(stateMachineRuntimePersister())
.and()
.withConfiguration()
.autoStartup(true);
}
#Bean
public StateMachineEnsemble<States, Events> stateMachineEnsemble() throws Exception {
return new ZookeeperStateMachineEnsemble<States, Events>(curatorClient(), "/app");
}
#Bean
public CuratorFramework curatorClient() throws Exception {
CuratorFramework client = CuratorFrameworkFactory
.builder()
.defaultData(new byte[0])
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.connectString("localhost:2181,localhost:2182,localhost:2183")
.build();
client.start();
return client;
}
#Bean
public StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister(){
return new JpaPersistingStateMachineInterceptor<>(jpaStateMachineRepository);
}
#Bean
public StateMachineService<States,Events> stateMachineService (
StateMachineFactory<States,Events> stateMachineFactory,
StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister){
return new DefaultStateMachineService<>(stateMachineFactory, stateMachineRuntimePersister);
}
#Bean
public StateMachineListener<States, Events> listener() {
return new StateMachineListenerAdapter<States, Events>() {
#Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
logger.info("*** listener: in state changed");
if (from == null) logger.info("*** state machine initialised in state {}", to.getId());
else logger.info("*** state changed from {} to {}", from.getId(), to.getId());
}
};
}
}
And my REST Controller class is:
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
#RestController
#RequestMapping("/jpapersist")
public class RestServiceController {
#Autowired
public StateMachineService<States, Events> stateMachineService;
#Autowired
public StateMachineListener listener;
public StateMachine<States, Events> stateMachine;
public Logger logger = LoggerFactory.getLogger(RestServiceController.class);
#RequestMapping(value="/init", method= RequestMethod.POST)
public void init(#RequestBody Map<String,String> parameters){
logger.info("\n*** inside of state machine controller : INIT ");
try {
stateMachine = getStateMachine(parameters.get("guid"));
} catch (Exception e) {
e.printStackTrace();
}
logger.info("\n*** state machine initialized to state: {}", stateMachine.getState().getId().name());
}
/***
Synchronized method to obtain persisted state machine from database.
*/
public synchronized StateMachine<States,Events> getStateMachine(String machineId) throws Exception {
if (stateMachine == null) {
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
} else if (!ObjectUtils.nullSafeEquals(stateMachine.getId(), machineId)) {
stateMachineService.releaseStateMachine(stateMachine.getId());
stateMachine.stop();
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
}
return stateMachine;
}
}
When I send a request for initialize a state machine, getting an error like:
Unable to persist stateMachineContext
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): org.springframework.statemachine.data.jpa.JpaRepositoryStateMachine
at org.hibernate.id.Assigned.generate(Assigned.java:33) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:800) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:309) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:535) ~[spring-data-jpa-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 111 common frames omitted
The state of the machine seems to changed, but could not persist on db. As I said, the problem is my curator configuration. Because it works fine when I define connectString with single Zookeeper like
.connectString("localhost:2181")
I'm new to Zookeeper and Curator, and open to any help. Thanks in advance.
The problem is with this configuration:
.withConfiguration()
.autoStartup(true);
Because it tries to start the machine, before having a machine id.

Unable to load module entry point in GWT/GXT Project

I am working on GWT/GXT
I trying to create radar Chart
Here is the Code
public class Test implements EntryPoint {
public static boolean isExplorer() {
String test = Window.Location.getPath();
if (test.indexOf("pages") != -1) {
return false;
}
return true;
}
#Override
public void onModuleLoad() {
RootPanel.get().add(new ChartExmaple());
}
}
public class ChartExmaple extends LayoutContainer {
private ChartModelExample example = new RadarChart();
private Command updateCmd;
#Override
protected void onRender(Element parent, int index) {
super.onRender(parent, index);
ContentPanel cp = new ContentPanel();
cp.setHeading("Charts Gallery");
cp.setFrame(true);
cp.setSize(700, 350);
cp.setLayout(new BorderLayout());
BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
centerData.setMargins(new Margins(0, 5, 0, 0));
cp.add(getChart(), centerData);
add(cp, new MarginData(20));
}
private LayoutContainer getChart() {
FieldSet fs = new FieldSet();
fs.setHeading("Opera Star");
fs.setLayout(new FitLayout());
String url = !Test.isExplorer() ? "../../" : "";
url += "gxt/chart/open-flash-chart.swf";
final Chart chart = new Chart(url);
chart.setBorders(true);
fs.add(chart, new FitData(0, 0, 20, 0));
updateCmd = new Command() {
public void execute() {
chart.setChartModel(example.getChartModel(5));
}
};
return fs;
}
}
RadarChart.Java
public class RadarChart implements ChartModelExample {
#Override
public ChartModel getChartModel(int segments) {
ChartModel cm = new ChartModel("Popularity",
"font-size: 12px; text-align: left;");
cm.setBackgroundColour("#f0f0f0");
RadarAxis ra = new RadarAxis();
ra.setMax(segments + 1);
ra.setStroke(2);
ra.setColour("#A1D4B5");
ra.setGridColour("#C0DEBF");
ra.setSpokeLabels("Ext", "Web", "Java", "AJAX", "PHP");
cm.setRadarAxis(ra);
AreaChart area = new AreaChart();
area.setFillAlpha(0.3f);
area.setColour("#ff9900");
area.setFillColour("#ff6600");
area.setLoop(true);
area.addValues(segments);
area.addValues(Random.nextInt(segments + 1));
area.addValues(Random.nextInt(segments + 1));
area.addValues(Random.nextInt(segments + 1));
area.addValues(Random.nextInt(segments + 1));
cm.addChartConfig(area);
return cm;
}
}
Error
[ERROR] [test] - Unable to load module entry point class test.client.Test (see associated exception for details)
[ERROR] [test] - Failed to load module 'test' from user agent 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36' at 127.0.0.1:58087
19:10:32.887 [ERROR] [test] Unable to load module entry point class test.client.Test (see associated exception for details)
com.google.gwt.core.client.JavaScriptException: (TypeError) #com.extjs.gxt.ui.client.widget.ComponentHelper::doAttachNative(Lcom/google/gwt/user/client/ui/Widget;)([Java object: com.extjs.gxt.ui.client.widget.ContentPanel#676012820]): Cannot read property 'embedSWF' of undefined
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:249)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeVoid(ModuleSpace.java:299)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeVoid(JavaScriptHost.java:107)
at com.extjs.gxt.ui.client.widget.ComponentHelper.doAttachNative(ComponentHelper.java)
at com.extjs.gxt.ui.client.widget.ComponentHelper.doAttach(ComponentHelper.java:21)
at com.extjs.gxt.ui.client.widget.Container.attachChildren(Container.java:635)
at com.extjs.gxt.ui.client.widget.Container.onLayoutExcecuted(Container.java:497)
at com.extjs.gxt.ui.client.widget.Container$1.handleEvent(Container.java:586)
at com.extjs.gxt.ui.client.widget.Container$1.handleEvent(Container.java:1)
at com.extjs.gxt.ui.client.event.BaseObservable.callListener(BaseObservable.java:178)
at com.extjs.gxt.ui.client.event.BaseObservable.fireEvent(BaseObservable.java:86)
at com.extjs.gxt.ui.client.widget.Layout.layout(Layout.java:116)
at com.extjs.gxt.ui.client.widget.Container.doLayout(Container.java:351)
at com.extjs.gxt.ui.client.widget.Container.layout(Container.java:443)
at com.extjs.gxt.ui.client.widget.LayoutContainer.layout(LayoutContainer.java:246)
at com.extjs.gxt.ui.client.widget.Container.layout(Container.java:426)
at com.extjs.gxt.ui.client.widget.LayoutContainer.layout(LayoutContainer.java:241)
at com.extjs.gxt.ui.client.widget.Container.onAttach(Container.java:479)
at com.google.gwt.user.client.ui.Widget.setParent(Widget.java:475)
at com.google.gwt.user.client.ui.Panel.adopt(Panel.java:127)
at com.google.gwt.user.client.ui.ComplexPanel.add(ComplexPanel.java:97)
at com.google.gwt.user.client.ui.AbsolutePanel.add(AbsolutePanel.java:97)
at test.client.Test.onModuleLoad(Test.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:406)
at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:200)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:526)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
Edited
public interface ChartModelExample {
public ChartModel getChartModel(int segments);
}
I have included swfobject.js in my HTML page and the error is gone.
I have downloaded it from gxt/samples/public/flash/swfobject.js
Make sure you have included the swfobject.js and the location of open-flash-chart.swf is correct.
For more info follow this link till the last section.

CompileError in File uploading

List<?> items =upload.parseRequest(request);
The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments (HttpServletRequest)
When i Run as Server...it gives error on console
May 13, 2012 7:47:49 PM org.apache.tomcat.util.digester.Digester startElement
SEVERE: Begin event threw error
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
java.lang.NoSuchMethodError: org.apache.tomcat.util.ExceptionUtils.unwrapInvocationTargetException(Ljava/lang/Throwable;)Ljava/lang/Throwable;
at org.apache.catalina.core.AprLifecycleListener.init(AprLifecycleListener.java:185)
at org.apache.catalina.core.AprLifecycleListener.isAprAvailable(AprLifecycleListener.java:84)
at org.apache.catalina.connector.Connector.setProtocol(Connector.java:577)
at org.apache.catalina.connector.Connector.(Connector.java:69)
at org.apache.catalina.startup.ConnectorCreateRule.begin(ConnectorCreateRule.java:62)
at org.apache.tomcat.util.digester.Digester.startElement(Digester.java:1356)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:506)
at com.sun.org.apache.xerces.internal.parsers.AbstractXMLDocumentParser.emptyElement(AbstractXMLDocumentParser.java:182)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1302)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2715)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:488)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at org.apache.tomcat.util.digester.Digester.parse(Digester.java:1642)
at org.apache.catalina.startup.Catalina.load(Catalina.java:576)
at org.apache.catalina.startup.Catalina.load(Catalina.java:619)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.load(Bootstrap.java:281)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:449)
This is my code in this code
List<?> items =upload.parseRequest(request); Got error as The method parseRequest(HttpServletRequest, int, long, String) in the type DiskFileUpload is not applicable for the arguments
(HttpServletRequest)
package br.com.ecommerce.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.disk.*;
import org.apache.tomcat.util.http.fileupload.servlet.*;
import org.apache.tomcat.util.http.fileupload.util.*;
import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import br.com.ecommerce.bean.Produtos;
import br.com.ecommerce.controller.ExceptionController;
import br.com.ecommerce.dao.CategoriasDao;
import br.com.ecommerce.dao.ProdutosDao;
class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
Produtos produto = new Produtos();
String caminhoTemp = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String pasta = new String("C:\\Users\\vaio\\workspace\\ecommerce\\WebContent\\images\\upload");
String caminho = new String("images\\upload\\");
if (ServletFileUpload.isMultipartContent( request)){
DiskFileUpload upload = new DiskFileUpload();
upload.setRepositoryPath(caminhoTemp);
try{
List<?> items =upload.parseRequest(request);//In this line i got error..why?..Pls help
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
if(item.getFieldName().equals("nome")){
produto.setProdNome(item.getString().toUpperCase());
}
else if (item.getFieldName().equals("categoria")){
produto.setCategorias(new CategoriasDao().findByPK(Integer.valueOf(item.getString())));
}
else if (item.getFieldName().equals("preco")){
produto.setPreco(Double.valueOf(item.getString()));
Double preco = 0d;
preco = Double.valueOf(item.getString());
preco += 10.00;
System.out.println(preco);
}
else if (item.getFieldName().equals("descp")){
produto.setDescPeq(item.getString());
}
else if (item.getFieldName().equals("descg")){
produto.setDescGd(item.getString());
}
else if (item.getFieldName().equals("espec")){
produto.setEspecificacoes(item.getString());
}
else if (item.getFieldName().equals("itens")){
produto.setItensInclusos(item.getString());
}
produto.setPromocao(0);
produto.setDestaque(0);
}
if (!item.isFormField()) {
String nome = item.getName().toString();
String nomeArquivo = nome.substring(nome.lastIndexOf("\\")+1);
File arquivo = new File(pasta + "\\" + nomeArquivo);
produto.setImagem(caminho + nomeArquivo);
item.write(arquivo);
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
new ProdutosDao().insert(produto);
} catch (ExceptionController e) {
e.printStackTrace();
}
response.sendRedirect("/ecommerce/admin/gerenciarProdutos.jsp");
}
}
enter code here
Are you trying to use the DiskFileUpload class from Commons FileUpload? If so, make sure your class is importing org.apache.commons.fileupload.DiskFileUpload, and not some other class called DiskFileUpload.

GWT Uncaught exception escaped

I have created a new google application using GWT, and it runs fine. But when i click a button that is responsible for performing some action with the server side, it throws an unusual error. Please could someone offer some help? Thank you in advance :(
Here is the code:
package com.ukstudentfeedback.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.ukstudentfeedback.shared.FieldVerifier;
import com.ukstudentfeedback.client.MailClient;
import com.ukstudentfeedback.client.MailClientAsync;
public class Ukstudentfeedback implements EntryPoint{
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final MailClientAsync sendMessage = GWT
.create(MailClient.class);
// ...
public void onModuleLoad()
{
java.lang.System.out.println("I finally worked!");
final Button sendButton;
final TextBox toField, fromField, subjectField, messageField;
final Label errorLabel = new Label();
sendButton = new Button("Send");
toField = new TextBox();
fromField = new TextBox();
subjectField = new TextBox();
messageField = new TextBox();
sendButton.addStyleName("sendButton");
toField.setText("Testing");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("sendButton").add(sendButton);
RootPanel.get("To").add(toField);
RootPanel.get("From").add(fromField);
RootPanel.get("Subject").add(subjectField);
RootPanel.get("Message").add(messageField);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the to field when the app loads
toField.setFocus(true);
toField.selectAll();
//sendButton.setEnabled(true);
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Message Sent");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Message Sent:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler{
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
java.lang.System.out.println("I have been clicked");
sendMessageToServer();
}
public void sendMessageToServer()
{
errorLabel.setText("");
String to = toField.getText();
String from = fromField.getText();
String subject = subjectField.getText();
String message = messageField.getText();
if (!FieldVerifier.isValidName(to, from, subject, message)) {
errorLabel.setText("Please enter at least four characters");
return;
}
sendButton.setEnabled(false);
textToServerLabel.setText("Hello");
serverResponseLabel.setText("");
sendMessage.sendMessage(to, from, subject, message, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
dialogBox
.setText("Message sending Failed");
serverResponseLabel
.addStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(SERVER_ERROR);
dialogBox.center();
closeButton.setFocus(true);
}
public void onSuccess(String result) {
dialogBox.setText("Message Sent");
serverResponseLabel
.removeStyleName("serverResponseLabelError");
serverResponseLabel.setHTML(result);
dialogBox.center();
closeButton.setFocus(true);
}
});
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
}
}
Server side:
package com.ukstudentfeedback.server;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ukstudentfeedback.shared.FieldVerifier;
#SuppressWarnings("serial")
public class MailServerImpl extends RemoteServiceServlet{
public void sendMessage(String to, String from, String subject, String message) throws IllegalArgumentException
{
// Verify that no input is null.
if (!FieldVerifier.isValidName(to, from, subject, message)) {
// If the input is not valid, throw an IllegalArgumentException back to
// the client.
throw new IllegalArgumentException(
"Name must be at least 4 characters long");
}
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, "Admin"));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(to, "Mr. User"));
msg.setSubject(subject);
msg.setText(message);
Transport.send(msg);
}
catch (AddressException e)
{
// ...
e.printStackTrace();
} catch (MessagingException e)
{
// ...
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Error Stack:
23:26:55.817 [ERROR] [ukstudentfeedback] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: One or more exceptions caught, see full set in UmbrellaException#getCauses
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Thread.java:680)
Caused by: com.google.gwt.user.client.rpc.ServiceDefTarget$NoServiceEntryPointSpecifiedException: Service implementation URL not specified
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.doPrepareRequestBuilderImpl(RemoteServiceProxy.java:430)
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy.doInvoke(RemoteServiceProxy.java:368)
at com.google.gwt.user.client.rpc.impl.RemoteServiceProxy$ServiceHelper.finish(RemoteServiceProxy.java:74)
at com.ukstudentfeedback.client.MailClient_Proxy.sendMessage(MailClient_Proxy.java:38)
at com.ukstudentfeedback.client.Ukstudentfeedback$1MyHandler.sendMessageToServer(Ukstudentfeedback.java:118)
at com.ukstudentfeedback.client.Ukstudentfeedback$1MyHandler.onClick(Ukstudentfeedback.java:98)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:54)
at com.google.gwt.event.dom.client.ClickEvent.dispatch(ClickEvent.java:1)
at com.google.gwt.event.shared.GwtEvent.dispatch(GwtEvent.java:1)
at com.google.web.bindery.event.shared.EventBus.dispatchEvent(EventBus.java:40)
at com.google.web.bindery.event.shared.SimpleEventBus.doFire(SimpleEventBus.java:193)
at com.google.web.bindery.event.shared.SimpleEventBus.fireEvent(SimpleEventBus.java:88)
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:127)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
at com.google.gwt.user.client.DOM.dispatchEvent(DOM.java:1307)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:337)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:218)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:213)
at sun.reflect.GeneratedMethodAccessor27.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:292)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:546)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:363)
at java.lang.Thread.run(Thread.java:680)
To find the cause of an UmbrellaException look for "Caused by":
Caused by:
com.google.gwt.user.client.rpc.ServiceDefTarget$NoServiceEntryPointSpecifiedException:
Service implementation URL not specified
Specify the remote service URL by doing either of the following:
Adding a RemoteServiceRelativePath annotation to your MailClientAsync interface.
Calling ServiceDefTarget#setServiceEntryPoint:
((ServiceDefTarget)sendMessage).
setServiceEntryPoint("http://www.example.com/service");