Spring Integration | DSL - java

I am trying to send a file to Remote SFTP server. I have created a factory and an outboundFlow for the same.
UploaderSftpConnectionFactoryBuilder
#Configuration
public class UploaderSftpConnectionFactoryBuilder {
#Value("${report-uploader.sftp-factory.host}")
private String host = null;
#Value("${report-uploader.sftp-factory.port}")
private Integer port = null;
#Value("classpath:${report-uploader.sftp-factory.privateKey}")
private Resource privateKey = null;
#Value("${report-uploader.sftp-factory.privateKeyPassphrase}")
private String privateKeyPassphrase = null;
#Value("${report-uploader.sftp-factory.maxConnections}")
private String maxConnections = null;
#Value("${report-uploader.sftp-factory.user}")
private String user = null;
#Value("${report-uploader.sftp-factory.poolSize}")
private Integer poolSize = null;
#Value("${report-uploader.sftp-factory.sessionWaitTimeout}")
private Long sessionWaitTimeout = null;
//#Bean(name = "cachedSftpSessionFactory")
public DefaultSftpSessionFactory getSftpSessionFactory() {
DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
Optional.ofNullable(this.getHost()).ifPresent(value -> defaultSftpSessionFactory.setHost(value));
Optional.ofNullable(this.getPort()).ifPresent(value -> defaultSftpSessionFactory.setPort(port));
Optional.ofNullable(this.getPrivateKey()).ifPresent(
value -> defaultSftpSessionFactory.setPrivateKey(privateKey));
Optional.ofNullable(this.getPrivateKeyPassphrase()).ifPresent(
value -> defaultSftpSessionFactory.setPrivateKeyPassphrase(value));
Optional.ofNullable(this.getUser()).ifPresent(value -> defaultSftpSessionFactory.setUser(value));
return defaultSftpSessionFactory;
}
#Bean(name = "cachedSftpSessionFactory")
public CachingSessionFactory<LsEntry> getCachedSftpSessionFactory() {
CachingSessionFactory<LsEntry> cachedFtpSessionFactory = new CachingSessionFactory<LsEntry>(
getSftpSessionFactory());
cachedFtpSessionFactory.setPoolSize(poolSize);
cachedFtpSessionFactory.setSessionWaitTimeout(sessionWaitTimeout);
return cachedFtpSessionFactory;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Resource getPrivateKey() {
return privateKey;
}
public void setPrivateKey(Resource privateKey) {
this.privateKey = privateKey;
}
public String getPrivateKeyPassphrase() {
return privateKeyPassphrase;
}
public void setPrivateKeyPassphrase(String privateKeyPassphrase) {
this.privateKeyPassphrase = privateKeyPassphrase;
}
public String getMaxConnections() {
return maxConnections;
}
public void setMaxConnections(String maxConnections) {
this.maxConnections = maxConnections;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
Now i want to test the outbound flow using an integration test. For that i have created below testContext:
TestContextConfiguration
#Configuration
public class TestContextConfiguration {
#Configuration
#Import({ FakeSftpServer.class, JmxAutoConfiguration.class, IntegrationAutoConfiguration.class,
UploaderSftpConnectionFactoryBuilder.class })
#IntegrationComponentScan
public static class ContextConfiguration {
#Value("${report-uploader.reportingServer.fileEncoding}")
private String fileEncoding;
#Autowired
private FakeSftpServer fakeSftpServer;
#Autowired
#Qualifier("cachedSftpSessionFactory")
//CachingSessionFactory<LsEntry> cachedSftpSessionFactory;
DefaultSftpSessionFactory cachedSftpSessionFactory;
#Bean
public IntegrationFlow sftpOutboundFlow() {
return IntegrationFlows
.from("toSftpChannel")
.handle(Sftp.outboundAdapter(this.cachedSftpSessionFactory, FileExistsMode.REPLACE)
.charset(Charset.forName(fileEncoding)).remoteFileSeparator("\\")
.remoteDirectory(this.fakeSftpServer.getTargetSftpDirectory().getPath())
.fileNameExpression("payload.getName()").autoCreateDirectory(true)
.useTemporaryFileName(true).temporaryFileSuffix(".tranferring")
).get();
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
I have also created a fake sftp server as suggested # https://github.com/spring-projects/spring-integration-java-dsl/blob/master/src/test/java/org/springframework/integration/dsl/test/sftp/TestSftpServer.java
Below is my fake server:
FakeSftpServer
#Configuration("fakeSftpServer")
public class FakeSftpServer implements InitializingBean, DisposableBean {
private final SshServer server = SshServer.setUpDefaultServer();
private final int port = SocketUtils.findAvailableTcpPort();
private final TemporaryFolder sftpFolder;
private final TemporaryFolder localFolder;
private volatile File sftpRootFolder;
private volatile File sourceSftpDirectory;
private volatile File targetSftpDirectory;
private volatile File sourceLocalDirectory;
private volatile File targetLocalDirectory;
public FakeSftpServer() {
this.sftpFolder = new TemporaryFolder() {
#Override
public void create() throws IOException {
super.create();
sftpRootFolder = this.newFolder("sftpTest");
targetSftpDirectory = new File(sftpRootFolder, "sftpTarget");
targetSftpDirectory.mkdir();
}
};
this.localFolder = new TemporaryFolder() {
#Override
public void create() throws IOException {
super.create();
File rootFolder = this.newFolder("sftpTest");
sourceLocalDirectory = new File(rootFolder, "localSource");
sourceLocalDirectory.mkdirs();
File file = new File(sourceLocalDirectory, "localSource1.txt");
file.createNewFile();
file = new File(sourceLocalDirectory, "localSource2.txt");
file.createNewFile();
File subSourceLocalDirectory = new File(sourceLocalDirectory, "subLocalSource");
subSourceLocalDirectory.mkdir();
file = new File(subSourceLocalDirectory, "subLocalSource1.txt");
file.createNewFile();
}
};
}
#Override
public void afterPropertiesSet() throws Exception {
this.sftpFolder.create();
this.localFolder.create();
this.server.setPasswordAuthenticator((username, password, session) -> true);
this.server.setPort(this.port);
this.server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("src/test/resources/hostkey.ser")));
this.server.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
this.server.setFileSystemFactory(new VirtualFileSystemFactory(sftpRootFolder.toPath()));
this.server.start();
}
#Override
public void destroy() throws Exception {
this.server.stop();
this.sftpFolder.delete();
this.localFolder.delete();
}
public File getSourceLocalDirectory() {
return this.sourceLocalDirectory;
}
public File getTargetLocalDirectory() {
return this.targetLocalDirectory;
}
public String getTargetLocalDirectoryName() {
return this.targetLocalDirectory.getAbsolutePath() + File.separator;
}
public File getTargetSftpDirectory() {
return this.targetSftpDirectory;
}
public void recursiveDelete(File file) {
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
recursiveDelete(each);
}
}
if (!(file.equals(this.targetSftpDirectory) || file.equals(this.targetLocalDirectory))) {
file.delete();
}
}
}
Finally below is my test class
TestConnectionFactory
#ContextConfiguration(classes = { TestContextConfiguration.class }, initializers = {ConfigFileApplicationContextInitializer.class})
#RunWith(SpringJUnit4ClassRunner.class)
#DirtiesContext
public class TestConnectionFactory {
#Autowired
#Qualifier("cachedSftpSessionFactory")
CachingSessionFactory<LsEntry> cachedSftpSessionFactory;
//DefaultSftpSessionFactory cachedSftpSessionFactory;
#Autowired
FakeSftpServer fakeSftpServer;
#Autowired
#Qualifier("toSftpChannel")
private MessageChannel toSftpChannel;
#After
public void setupRemoteFileServers() {
this.fakeSftpServer.recursiveDelete(this.fakeSftpServer.getSourceLocalDirectory());
this.fakeSftpServer.recursiveDelete(this.fakeSftpServer.getTargetSftpDirectory());
}
#Test
public void testSftpOutboundFlow() {
boolean status = this.toSftpChannel.send(MessageBuilder.withPayload(new File(this.fakeSftpServer.getSourceLocalDirectory() + "\\" + "localSource1.txt")).build());
RemoteFileTemplate<ChannelSftp.LsEntry> template = new RemoteFileTemplate<>(this.cachedSftpSessionFactory);
ChannelSftp.LsEntry[] files = template.execute(session ->
session.list(this.fakeSftpServer.getTargetSftpDirectory() + "\\" + "localSource1.txt"));
assertEquals(1, files.length);
//assertEquals(3, files[0].getAttrs().getSize());
}
}
Now when i am running this test, I am getting the below exception:
org.springframework.messaging.MessagingException: ; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.dispatcher.AbstractDispatcher.wrapExceptionIfNecessary(AbstractDispatcher.java:133)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:120)
at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:101)
at org.springframework.integration.dispatcher.UnicastingDispatcher.dispatch(UnicastingDispatcher.java:97)
at org.springframework.integration.channel.AbstractSubscribableChannel.doSend(AbstractSubscribableChannel.java:77)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:286)
at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:245)
at com.sapient.lufthansa.reportuploader.config.TestConnectionFactory.testSftpOutboundFlow(TestConnectionFactory.java:66)
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.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:345)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:211)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:201)
at org.springframework.integration.file.remote.RemoteFileTemplate.send(RemoteFileTemplate.java:193)
at org.springframework.integration.file.remote.handler.FileTransferringMessageHandler.handleMessageInternal(FileTransferringMessageHandler.java:110)
at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:78)
at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
... 36 more
Caused by: java.lang.IllegalStateException: failed to create SFTP Session
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:355)
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:49)
at org.springframework.integration.file.remote.RemoteFileTemplate.execute(RemoteFileTemplate.java:334)
... 42 more
Caused by: java.lang.IllegalStateException: failed to connect
at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:272)
at org.springframework.integration.sftp.session.DefaultSftpSessionFactory.getSession(DefaultSftpSessionFactory.java:350)
... 44 more
Caused by: com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
at com.jcraft.jsch.Util.createSocket(Util.java:349)
at com.jcraft.jsch.Session.connect(Session.java:215)
at com.jcraft.jsch.Session.connect(Session.java:183)
at org.springframework.integration.sftp.session.SftpSession.connect(SftpSession.java:263)
... 45 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.jcraft.jsch.Util.createSocket(Util.java:343)
... 48 more
which i am not able to resolve it and stuck on it for quite a time now. I am a beginner with spring-integration-dsl and any help woul be really appreciated.

Caused by: java.net.ConnectException: Connection refused: connect
You are connecting to the wrong port.
The test connection factory listens on a random port - you need to use the same port.

Related

instance is null after renaming project

I'm working in IntelliJ and I attempted to rename my Project! After doing so, and renaming everything, which I believe I did correctly, I'm unable to actually start my application.
Error:
org.bukkit.plugin.InvalidPluginException: java.lang.NullPointerException
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:133) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:326) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:248) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.loadPlugins(CraftServer.java:302) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:205) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:544) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]
Caused by: java.lang.NullPointerException
at me.craftblock.MochaMessages.Config.<init>(Config.java:7) ~[?:?]
at me.craftblock.MochaMessages.MochaMessages.<init>(MochaMessages.java:18) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_121]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_121]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_121]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_121]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_121]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:129) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
... 6 more
The error points to my Config class, however I'm not sure why:
public class Config {
private MochaMessages instance = MochaMessages.getInstance();
private FileConfiguration config = instance.getConfig();
public Config() {
}
public String get(String node) {
System.out.println("Fetching: " + node);
return config.getString(node);
}
public void set(String node, String value) {
config.set(node, value);
}
public boolean getBoolean(String node) {
System.out.println("Fetching: " + node);
return config.getBoolean(node);
}
}
Which is being called via my MochaMessages class:
Here's the related method:
private static MochaMessages instance;
private Config config = new Config();
public void onEnable() {
instance = this;
createConfig();
te = getTokenEnchant();
if (!config.getBoolean("database.enabled")) {
disablePlugin("Enable MySQL!");
} else if (config.get("mocha.currency").equalsIgnoreCase("TokenEnchant")) {
if (te == null) {
disablePlugin("Unable to access TokenEnchant. Disabling Plugin!");
}
} else {
Bukkit.getServer().getPluginManager().registerEvents(new MochaListener(), this);
new MochaModel().createTable();
new CommandHandler();
}
}
I believe it's because instance is returning null even though it shouldn't be. This worked perfectly before the rename!
What's going on?

EasyMock unexpected method call

I can't work out how to setup the expectation of a call to a mock class. Here is the JUnit test:
public class AfkTest extends TestCase {
private AfkPlayerManager manager;
private Player player;
private Set<AfkPlayer> afkPlayers;
public void setUp() throws Exception {
super.setUp();
manager = new AfkPlayerManager();
player = EasyMock.createMock(Player.class);
afkPlayers = new HashSet<AfkPlayer>();
}
public void tearDown() {
}
public void testNotifyOfAfkPlayerSuccess() {
AfkPlayer afkPlayer = new AfkPlayer();
afkPlayer.setPlayer(player);
afkPlayer.setReason("TEST REASON");
afkPlayers.add(afkPlayer);
List<Player> onlinePlayers = new ArrayList<Player>();
onlinePlayers.add(player);
onlinePlayers.add(player);
EasyMock.expect(player.getDisplayName()).andReturn("TEST PLAYER");
player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]");
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(player);
assertTrue(manager.notifyOfAfkPlayer(onlinePlayers, afkPlayer));
//verify call to sendMessage is made or not
EasyMock.verify(player);
}
}
And the method that I am testing:
public class AfkPlayerManager implements Manager {
public boolean notifyOfAfkPlayer(Collection<Player> onlinePlayers, AfkPlayer afkPlayer) {
if (afkPlayer == null) {
return false;
}
String message = ChatColor.BLUE + afkPlayer.getPlayer().getDisplayName();
message += ChatColor.AQUA + " is AFK.";
if (afkPlayer.getReason().length() > 0) {
message += " [" + afkPlayer.getReason() + "]";
}
if (onlinePlayers != null && onlinePlayers.size() > 1) {
int notified = 0;
for (Player onlinePlayer : onlinePlayers) {
onlinePlayer.sendMessage(message);
notified++;
}
if (notified > 0) {
return true;
}
}
return false;
}
}
Why is this giving me the AssertionError:
java.lang.AssertionError: Unexpected method call
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"):
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"): expected: 1, actual: 0 at
org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at
org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy3.sendMessage(Unknown Source) at
crm.afk.AfkPlayerManager.notifyOfAfkPlayer(AfkPlayerManager.java:33)
at crm.test.AfkTest.testNotifyOfAfkPlayerSuccess(AfkTest.java:84) 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
junit.framework.TestCase.runTest(TestCase.java:176) at
junit.framework.TestCase.runBare(TestCase.java:141) at
junit.framework.TestResult$1.protect(TestResult.java:122) at
junit.framework.TestResult.runProtected(TestResult.java:142) at
junit.framework.TestResult.run(TestResult.java:125) at
junit.framework.TestCase.run(TestCase.java:129) at
junit.framework.TestSuite.runTest(TestSuite.java:252) at
junit.framework.TestSuite.run(TestSuite.java:247) at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The expected and actual are different.
Expected: §9TEST PLAYER§b is AFK. [TEST REASON]
Actual: §9TEST PLAYER§b is AFK. [TEST REASON]
The  at the beginning is missing. So it fails as it should.

Vaadin with Grails Database error

I am using vaadin7 with grails i have created model and service and trying to access it when click on login button to check login details.
I search a lot but no relevant result, i am new to grails framework.
i am getting below error when trying to access service class:-
java.lang.NullPointerException
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:130)
at org.codehaus.groovy.grails.orm.support.GrailsTransactionTemplate.execute(GrailsTransactionTemplate.groovy:85)
at com.xfuel.web.services.PeopleService.checkLogin(PeopleService.groovy)
at com.xfuel.web.services.PeopleService$checkLogin.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at test.Test$2.buttonClick(Test.groovy:60)
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:606)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1270)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:508)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:198)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:161)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:984)
at com.vaadin.ui.Button.fireClick(Button.java:393)
at com.vaadin.ui.Button$1.click(Button.java:57)
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:606)
My Vaadincode is below :-
class Test extends UI {
public Test() {
// TODO Auto-generated constructor stub
}
#Override
protected void init(VaadinRequest request) {
HorizontalLayout fields = new HorizontalLayout();
fields.setSpacing(true);
fields.setMargin(true);
fields.addStyleName("fields");
final TextField username = new TextField("Username");
username.focus();
fields.addComponent(username);
final PasswordField password = new PasswordField("Password");
fields.addComponent(password);
final Button signin = new Button("Sign In");
signin.addStyleName("default");
fields.addComponent(signin);
fields.setComponentAlignment(signin, Alignment.BOTTOM_LEFT);
final ShortcutListener enter = new ShortcutListener("Sign In",
KeyCode.ENTER, null) {
#Override
public void handleAction(Object sender, Object target) {
signin.click();
}
};
signin.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
if (username.getValue() != null
&& username.getValue().equals("")
&& password.getValue() != null
&& password.getValue().equals("")) {
signin.removeShortcutListener(enter);
PeopleService p1 = new PeopleService();
p1.checkLogin("", "");
// iPeopleService.checkLogin(username.getValue(), password.getValue());
buildMainView();
} else {
}
}
});
signin.addShortcutListener(enter);
setContent(fields);
}
}
And domain class :-
class People {
String name;
String apppassword;
static constraints = {
}
}
and Grails services code :-
#Transactional
class PeopleService {
def serviceMethod() {
}
public People checkLogin(String username, String password) {
def query = People.where{
peopleID == username &&
apppassword == password &&
visible == true
}
return people = query.find()
}
i below is the datasource :-
development {
dataSource {
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/sample"
username = "root"
password = "root"
loggingSql = true
}
}
i did not understand the reason of this error. Can someone please help me?
Thanks

ibi.telnet.api.TnDriverException: Connection is closed

I'm trying to connect to a mainframe via java using iway telnet, this is the connection code:
public static Session conexion(String nodo,int port) throws TnDriverException {
TnDriver driver = new TnDriver();
driver.setHost(nodo);
driver.setPort(port);
driver.setEmulation(Terminal.TN_3270);
driver.setTraceOn(false);
driver.setExtendedAttributes(true);
driver.setLanguage("Cp037");
driver.setTimerTimeout(25);
driver.setTimerOn(true);
session = driver.getSession();
logger.info("CONNECTED TO MAINFRAME.");
return session;
}
During the process of connecting to the mainframe I'm getting the next exception in the first screen:
ibi.telnet.api.TnDriverException: Connection is closed...
at ibi.telnet.api.Session.waitFor(Session.java:453)
at ibi.telnet.api.Session.waitFor(Session.java:393)
at ibi.telnet.api.Session.waitFor(Session.java:312)
at
tn3270.GestionPantallas.identificaPantalla(GestionPantallas.java:73)
at
tn3270.CertificacionSindo.getTransaccion(CertificacionSindo.java:67)
at
ws.Pensiones.obtenerCertificacion(Pensiones.java:41)
at sun.reflect.GeneratedMethodAccessor486.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at weblogic.wsee.component.pojo.JavaClassComponent.invoke(JavaClassComponent.java:99)
at weblogic.wsee.ws.dispatch.server.ComponentHandler.handleRequest(ComponentHandler.java:64)
at weblogic.wsee.handler.HandlerIterator.handleRequest(HandlerIterator.java:137)
at weblogic.wsee.ws.dispatch.server.ServerDispatcher.dispatch(ServerDispatcher.java:109)
at weblogic.wsee.ws.WsSkel.invoke(WsSkel.java:80)
at weblogic.wsee.server.servlet.SoapProcessor.handlePost(SoapProcessor.java:66)
at weblogic.wsee.server.servlet.SoapProcessor.process(SoapProcessor.java:44)
at weblogic.wsee.server.servlet.BaseWSServlet$AuthorizedInvoke.run(BaseWSServlet.java:257)
at weblogic.wsee.server.servlet.BaseWSServlet.service(BaseWSServlet.java:156)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3395)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2140)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2046)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
And this is the method identificaPantalla in the class GestionPantallas, where the conexion method is.
public static int identificaPantalla(ScreenDesc[] pantallas) throws TnDriverException {
int result = -1;
try {
result = session.waitFor(pantallas);
}
catch(TnDriverException e) {
throw e;
}
return result;
}
Any idea about this issue?

Jetty Websocket servlet InstantiationException problems

I'm having problems to make the websocket example of jetty work
public class App {
public static void main(String[] args) {
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(MyEchoServlet.class, "/test/*");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyEchoServlet extends WebSocketServlet {
#Override
public void configure(WebSocketServletFactory factory) {
//factory.getPolicy().setIdleTimeout(10000);
factory.register(MyEchoSocket.class);
}
}
#WebSocket(maxMessageSize = 64 * 1024)
public class MyEchoSocket {
Session session;
#OnWebSocketConnect
public void onConnect(Session session){
this.session = session;
System.out.println("init "+session.getUpgradeRequest().getRequestURI().getPath() );
}
#OnWebSocketMessage
public void onText(String msg) {
System.out.println("rec "+msg );
try {
session.getRemote().sendString(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
#OnWebSocketClose
public void onClose(int statusCode, String reason) {
System.out.println("MyWebSocket.onClose()");
}
}
}
gives the following error as soon as I try to create a Websocket from javascript:
var ws = new WebSocket("ws://localhost:8080/test/");
server error:
2013-09-14 15:57:04.076 INFO Server - jetty-9.0.5.v20130815
2013-09-14 15:57:04.122 INFO ServerConnector - Started ServerConnector#1a51ce0{HTTP/1.1}{0.0.0.0:8080}
2013-09-14 15:57:11.700 WARN ContextHandler - unavailable
java.lang.InstantiationException: app.App$MyEchoServlet
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:979)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:523)
at org.eclipse.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:424)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:505)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:434)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Unknown Source)
2013-09-14 15:57:11.706 WARN ServletHandler -
javax.servlet.ServletException: app.App$MyEchoServlet-4598284#e19c6ca5==app.App$MyEchoServlet,-1,false
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:563)
at org.eclipse.jetty.servlet.ServletHolder.getServlet(ServletHolder.java:424)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:671)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:505)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:434)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:445)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:268)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:229)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.InstantiationException: app.App$MyEchoServlet
at java.lang.Class.newInstance(Unknown Source)
at org.eclipse.jetty.servlet.ServletHolder.newInstance(ServletHolder.java:979)
at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:523)
... 13 more
jetty version: 9.0.5v20130815 (from maven eclipse.jetty repo)
Since you have that declared both your servlet and socket as inner classes, change the following 2 lines of your code ...
// From
public class MyEchoServlet extends WebSocketServlet {
// To
public static class MyEchoServlet extends WebSocketServlet {
// From
public class MyEchoSocket {
// To
public static class MyEchoSocket {
This is because Java cannot just instantiate a non-static inner class.
Try this from your main() method and you'll see ...
Servlet test = new MyEchoServlet();

Categories