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");
Related
Just wondering what's causing this. I have no idea!
I am trying to make a queue plugin. I am using paper spigot. Please ignore all the holes in my plugins code as I'm simply testing it at the moment. If you have anything that you think I should change however I'd be glad to here it. Here is my error message spat out by the terminal.
[19:29:52 ERROR]: Could not load 'plugins\anarchyqueuet3.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.NoClassDefFoundError: redis/clients/jedis/Jedis
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:329) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.loadPlugins(CraftServer.java:318) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:222) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:616) ~[patched_1.12.2.jar:git-Paper-1618]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_241]
Caused by: java.lang.NoClassDefFoundError: redis/clients/jedis/Jedis
at com.Package.AnarchyQueue.<init>(AnarchyQueue.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_241]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:94) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:127) ~[patched_1.12.2.jar:git-Paper-1618]
... 6 more
Caused by: java.lang.ClassNotFoundException: redis.clients.jedis.Jedis
at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:156) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:104) ~[patched_1.12.2.jar:git-Paper-1618]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_241]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_241]
at com.Package.AnarchyQueue.<init>(AnarchyQueue.java:19) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_241]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_241]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_241]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:94) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:127) ~[patched_1.12.2.jar:git-Paper-1618]
... 6 more
And here's my code:
package com.Package;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import redis.clients.jedis.Jedis;
import java.util.ArrayList;
import java.util.logging.Logger;
public class AnarchyQueue extends JavaPlugin {
//list of players in queue
private ArrayList<Player> players = new ArrayList<Player>();
//jedis object to communicate with other server
private Jedis jedis = new Jedis("localhost");
private int playerCount = 0;
static int maxPlayerCount = 10;
#Override
public void onEnable() {
onEnablePri();
}
#Override
public void onDisable() {
onDisablePri();
}
public void onPlayerJoin(PlayerJoinEvent event)
{
onPlayerJoinPri(event);
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
onCommandPri(sender,command,label,args);
return true;
}
//--------------------private methods--------------------
private void onEnablePri() {
log("Server test: "+jedis.ping(),1);
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this, new Runnable() {
#Override
public void run() {
runPri();
}
}, 0L, 10L);;
}
private void runPri() {
try {
playerCount=Integer.parseInt(jedis.get("anarchy-player-count"));
} catch (Exception e) {
log("Player count get failed",1);
}
if(playerCount<maxPlayerCount)
{
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF("anarchy");
players.get(0).sendPluginMessage(this, "BungeeCord", out.toByteArray());
players.remove(0);
}
}
private void onDisablePri() {
//disable code
}
private void onPlayerJoinPri(PlayerJoinEvent event)
{
players.add(event.getPlayer());
}
private void onCommandPri(CommandSender sender, Command command, String label, String[] args) {
if(command.getName().equalsIgnoreCase("setmaxplayercount"))
{
jedis.set("anarchy-player-count",args[0]);
}
/*if (command.getName().equalsIgnoreCase("players")) {
if (!(sender instanceof Player)) {
sender.sendMessage("You must be in game!");
}
else {
getCount();
}
} */
}
//private void getCount() {
//}
private void log(String str, int i)
{
if(i==0)
{
Logger.getLogger("Minecraft").info(str);
}
else
{
if(i!=1)
{
System.out.println("NUMBER NOT RECOGNISED: ");
}
System.out.println(str);
}
}
}
And finally here's my plugin.yml (in case this is wrong)
main: com.Package.AnarchyQueue
name: AnarchyQueue
version: '1.0'
description: The queue plugin for Ed_Silver's anarchy server.
load: postworld
author: Ed_Silver
prefix: AnarchyQueue
commands:
setmaxplayercount:
description: Sets max player count
usage: /setmaxplayercount [int]
I saw a post that spoke about needing to add a dependency using a pom.xml but I don't know if that applies to me.
Thanks in advance,
If you need anything just ask,
Edward
You are trying to import redis.clients.jedis.Jedis; but Minecraft cant find Jedis, you have to add Jedis to your maven or gradle project.
According to https://github.com/xetorthio/jedis :
https://github.com/xetorthio/jedis#how-do-i-use-it
Hopefully this helped, I am here to answer any more questions you have!
UPD: Problem was solved. Thanks.
https://github.com/CyberdyneCC/Thermos/issues/498#issuecomment-247083549
Please, help me with this problem.
I compile minecraft bukkit plugin for version 1.7.10 named Spark. Compilation is successful but i can`t load this.
Server core: Thermos 1.7.10.
Full stacktrace:
org.bukkit.plugin.InvalidPluginException: Cannot find main class `me.lucko.spark.bukkit.BukkitSparkPlugin'
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:191) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:145) ~[JavaPluginLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:334) ~[SimplePluginManager.class:1.7.10-1614.58]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:256) [SimplePluginManager.class:1.7.10-1614.58]
at org.bukkit.craftbukkit.v1_7_R4.CraftServer.loadPlugins(CraftServer.java:343) [CraftServer.class:1.7.10-1614.58]
at net.minecraft.world.storage.SaveHandler.initBukkitData(SaveHandler.java:462) [ayq.class:?]
at net.minecraft.world.storage.SaveHandler.func_75757_d(SaveHandler.java:138) [ayq.class:?]
at net.minecraft.world.World.<init>(World.java:374) [ahb.class:?]
at net.minecraft.world.WorldServer.<init>(WorldServer.java:162) [mt.class:?]
at net.minecraft.server.MinecraftServer.func_71247_a(MinecraftServer.java:375) [MinecraftServer.class:?]
at net.minecraft.server.dedicated.DedicatedServer.func_71197_b(DedicatedServer.java:337) [lt.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:643) [MinecraftServer.class:?]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_211]
Caused by: java.lang.ClassNotFoundException: Failed to remap class me.lucko.spark.bukkit.BukkitSparkPlugin
at org.bukkit.plugin.java.PluginClassLoader.remappedFindClass(PluginClassLoader.java:534) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:455) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:211) ~[PluginClassLoader.class:1.7.10-1614.58]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_211]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_211]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:189) ~[PluginClassLoader.class:1.7.10-1614.58]
... 12 more
Caused by: java.lang.IllegalArgumentException: INVOKESPECIAL/STATIC on interfaces require ASM 5
at org.objectweb.asm.MethodVisitor.visitMethodInsn(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.a(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.b(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.accept(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at org.objectweb.asm.ClassReader.accept(Unknown Source) ~[asm-all-5.0.3.jar:5.0.3]
at net.md_5.specialsource.JarRemapper.remapClassFile(JarRemapper.java:246) ~[JarRemapper.class:?]
at net.md_5.specialsource.JarRemapper.remapClassFile(JarRemapper.java:232) ~[JarRemapper.class:?]
at org.bukkit.plugin.java.PluginClassLoader.remappedFindClass(PluginClassLoader.java:499) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:455) ~[PluginClassLoader.class:1.7.10-1614.58]
at org.bukkit.plugin.java.PluginClassLoader.findClass(PluginClassLoader.java:211) ~[PluginClassLoader.class:1.7.10-1614.58]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_211]
at java.lang.Class.forName0(Native Method) ~[?:1.8.0_211]
at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_211]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:189) ~[PluginClassLoader.class:1.7.10-1614.58]
... 12 more
Compilation was with using Eclipse IDE.
Class me.lucko.spark.bukkit.BukkitSparkPlugin source:
package me.lucko.spark.bukkit;
import me.lucko.spark.bukkit.placeholder.SparkMVdWPlaceholders;
import me.lucko.spark.bukkit.placeholder.SparkPlaceholderApi;
import me.lucko.spark.common.SparkPlatform;
import me.lucko.spark.common.SparkPlugin;
import me.lucko.spark.common.sampler.ThreadDumper;
import me.lucko.spark.common.sampler.TickCounter;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
public class BukkitSparkPlugin extends JavaPlugin implements SparkPlugin {
private CommandExecutor tpsCommand = null;
private SparkPlatform platform;
#Override
public void onEnable() {
this.platform = new SparkPlatform(this);
this.platform.enable();
// override Spigot's TPS command with our own.
if (getConfig().getBoolean("override-tps-command", true)) {
this.tpsCommand = (sender, command, label, args) -> {
if (!sender.hasPermission("spark") && !sender.hasPermission("spark.tps") && !sender.hasPermission("bukkit.command.tps")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return true;
}
BukkitCommandSender s = new BukkitCommandSender(sender) {
#Override
public boolean hasPermission(String permission) {
return true;
}
};
this.platform.executeCommand(s, new String[]{"tps"});
return true;
};
CommandMapUtil.registerCommand(this, this.tpsCommand, "tps");
}
if (getServer().getPluginManager().isPluginEnabled("PlaceholderAPI")) {
new SparkPlaceholderApi(this, this.platform);
getLogger().info("Registered PlaceholderAPI placeholders");
}
if (getServer().getPluginManager().isPluginEnabled("MVdWPlaceholderAPI")) {
new SparkMVdWPlaceholders(this, this.platform);
getLogger().info("Registered MVdWPlaceholderAPI placeholders");
}
}
#Override
public void onDisable() {
this.platform.disable();
if (this.tpsCommand != null) {
CommandMapUtil.unregisterCommand(this.tpsCommand);
}
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
this.platform.executeCommand(new BukkitCommandSender(sender), args);
return true;
}
#Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return this.platform.tabCompleteCommand(new BukkitCommandSender(sender), args);
}
#Override
public String getVersion() {
return getDescription().getVersion();
}
#Override
public Path getPluginDirectory() {
return getDataFolder().toPath();
}
#Override
public String getCommandName() {
return "spark";
}
#Override
public Stream<BukkitCommandSender> getSendersWithPermission(String permission) {
return Stream.concat(
getServer().getOnlinePlayers().stream().filter(player -> player.hasPermission(permission)),
Stream.of(getServer().getConsoleSender())
).map(BukkitCommandSender::new);
}
#Override
public void executeAsync(Runnable task) {
getServer().getScheduler().runTaskAsynchronously(BukkitSparkPlugin.this, task);
}
#Override
public ThreadDumper getDefaultThreadDumper() {
return new ThreadDumper.Specific(new long[]{Thread.currentThread().getId()});
}
#Override
public TickCounter createTickCounter() {
return new BukkitTickCounter(this);
}
}
What could be the problem and how to solve it?
Thanks.
Probably the problem is on your plugin.yml file. On this file you must specify the main class of your plugin so that then Bukkit/Spigot/Paper know where to point when the plugin is enabled. Could you please post the plugin.yml file?
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.
I am learning unit testing. I have implemented unit test for the spring boot controller in my sample project. When I run the test class, every time it returns 400 status (Expected 200). After i did a research and I have found that if(entity.getStatusCode().equals(HttpStatus.OK)) { is line which gives exception. It might be because it uses return of Service2.
However, code is working fine without running test cases. I have attached MyController and MyControllerTest classes.
My Controller
#RestController
#RequestMapping("/user")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserManagementService userManageService;
#Autowired
private AdminManagementService adminManageService;
#Autowired
private AuthenticateManagementService authService;
#PutMapping("/change-password")
public ResponseEntity<?> changePassword(#RequestHeader("Authorization") String token,
#RequestBody PasswordChangeRequestDTO passwordChangeRequestDTO) {
ResponseDTO finalResponse = new ResponseDTO();
try {
LOGGER.info("Changing user password.");
KeycloakLoginResponseDTO keycloakResponse = authService.auhtenticate(passwordChangeRequestDTO.getLoginRequestDTO());
ResponseEntity<?> logoutEntity = authService.logout(token, keycloakResponse.getSession_state());
if(logoutEntity.getStatusCode().equals(HttpStatus.OK)) {
LOGGER.info("User password matched");
}
String userId = adminManageService.getUserByName(token, passwordChangeRequestDTO.getLoginRequestDTO().getUsername());
ResponseEntity<?> entity = userManageService.changePassword(token, passwordChangeRequestDTO, userId);
LOGGER.info("USER : " + "" +"has successfully changed password.");
finalResponse.setMessageCode(HttpStatus.OK);
finalResponse.setMessage("Password changed successfully");
finalResponse.setError(false);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.ok().body(finalResponse);
return finalEntity;
}catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error has occured while changing password of USER : " + "" + ".");
finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
finalResponse.setMessage("Oops! Looks like you have entered the wrong password in the 'Old Password' field");
finalResponse.setMessageDetail(e.getMessage());
finalResponse.setError(true);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.badRequest().body(finalResponse);
return finalEntity;
}
}
}
Controller Unit test class
#RunWith(SpringRunner.class)
#WebMvcTest(UserController.class)
public class UserControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private UserManagementService userManageService;
#MockBean
private AdminManagementService adminManageService;
#MockBean
private AuthenticateManagementService authService;
#InjectMocks
private UserController userController;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testChangePasswordhappyPath() throws Exception {
PasswordChangeRequestDTO passwordChangeRequestDTO = new PasswordChangeRequestDTO();
LoginRequestDTO loginRequestDTO = new LoginRequestDTO();
loginRequestDTO.setClient_id("test_client");
loginRequestDTO.setGrant_type("test_grant_type");
loginRequestDTO.setPassword("test_password");
loginRequestDTO.setUsername("test_user");
CredentialsRequestDTO credentialsRequestDTO = new CredentialsRequestDTO();
credentialsRequestDTO.setTemporary(false);
credentialsRequestDTO.setType("password");
credentialsRequestDTO.setValue("test_password");
passwordChangeRequestDTO.setLoginRequestDTO(loginRequestDTO);
passwordChangeRequestDTO.setCredentialsRequestDTO(credentialsRequestDTO);
ResponseEntity<String> mockResponse = new ResponseEntity<String>("", HttpStatus.OK);
when(userManageService.changePassword("Token", passwordChangeRequestDTO, "UserId")).thenReturn(mockResponse);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(passwordChangeRequestDTO);
mockMvc.perform(put("/user/change-password", passwordChangeRequestDTO)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Token")
.content(json)
.characterEncoding("utf-8"))
.andExpect(status().isOk()).andReturn();
}
}
What am i doing wrong here. Is there anything to add to my MyControllerTest class or How can i cover this test case. Any help would be grateful.
UPDATED
I have also added e.printStackTrace()
java.lang.NullPointerException
at com.mycode.controller.UserController.changePassword(UserController.java:39)
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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:919)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.mycode.controller.UserControllerTest.testChangePasswordhappyPath(UserControllerTest.java:71)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
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.