JAAS exception null username and password - java

I followed this tutorial to learn JAAS. That example worked for me, so I created my own version (I'm using Tomcat 6 and Java 6), but I can not get it to work (exception on the bottom of the post).
(I can't put online the sources in a ZIP because the proxy. Sorry.)
This is the JAAS:
TestJAAS {
test.auth.MyModule required debug=true;
};
This is the user Principal:
public class MyUser implements Principal {
private String name;
public MyUser(String name) {
super();
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
This is the role Principal:
public final class MyRole implements Principal {
public String getName() {
return "Superman";
}
}
This is the login module:
public class MyModule implements LoginModule {
private CallbackHandler handler;
private Subject subject;
private MyUser user;
private final MyRole ROLE = new MyRole();
#Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.handler = callbackHandler;
this.subject = subject;
}
public boolean login() throws LoginException {
NameCallback nc = new NameCallback("login");
PasswordCallback pc = new PasswordCallback("password", false);
String name = nc.getName();
String pass = String.valueOf(pc.getPassword());
try {
handler.handle(new Callback[]{nc, pc});
} catch (Exception ex) {
throw new LoginException(ex.getMessage());
}
if ("123".equals(name) && "secret".equals(pass)) {
user = new MyUser(name);
return true;
}
throw new LoginException();
}
public boolean commit() throws LoginException {
subject.getPrincipals().add(user);
subject.getPrincipals().add(ROLE);
return true;
}
public boolean abort() throws LoginException {
return false;
}
public boolean logout() throws LoginException {
subject.getPrincipals().remove(user);
subject.getPrincipals().remove(ROLE);
return true;
}
}
This is the context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Realm className="org.apache.catalina.realm.JAASRealm" appName="TestJAAS"
userClassNames="test.auth.MyUser" roleClassNames="test.auth.MyRole" />
</Context>
And this is the web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>MyProtectedResources</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>Superman</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>Superman</role-name>
</security-role>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>MyProtectedResources</realm-name>
</login-config>
And this is the exception when I try to log in on http://localhost:8080/TestJAAS/admin/admin.html:
5-dic-2013 10.07.29 org.apache.catalina.realm.JAASRealm authenticate
AVVERTENZA: Login exception authenticating username "123"
javax.security.auth.login.LoginException: java.lang.NullPointerException
at java.lang.String.<init>(String.java:177)
at java.lang.String.valueOf(String.java:2840)
at test.auth.MyModule.login(MyModule.java:33)
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 javax.security.auth.login.LoginContext.invoke(LoginContext.java:769)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
at javax.security.auth.login.LoginContext.login(LoginContext.java:579)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:409)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:334)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:181)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
at javax.security.auth.login.LoginContext.invoke(LoginContext.java:872)
at javax.security.auth.login.LoginContext.access$000(LoginContext.java:186)
at javax.security.auth.login.LoginContext$4.run(LoginContext.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
at javax.security.auth.login.LoginContext.login(LoginContext.java:579)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:409)
at org.apache.catalina.realm.JAASRealm.authenticate(JAASRealm.java:334)
at org.apache.catalina.authenticator.BasicAuthenticator.authenticate(BasicAuthenticator.java:181)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
The config file is loaded correctly. Why my username and password are null? Thanks in advance.

You have at least one error, located in this code:
String name = nc.getName();
String pass = String.valueOf(pc.getPassword());
try {
handler.handle(new Callback[]{nc, pc});
} catch (Exception ex) {
throw new LoginException(ex.getMessage());
}
You read the name/password from the callbacks, before they are filled by the callback handler!!!
You will need to put the String name=...;String pass=... part after handler.handle(...). The example you linked does this too.

Related

javax.security.auth.login.LoginException When consume WCF web service with java client using apache cxf

I have a simple wcf in website hosted on iis and I try to call it from java client web application on
wildfly 10
I used apache cxf to implement web service client as below :
#WebServiceClient
(name="BankService",targetNamespace="http://tempuri.org/",
wsdlLocation="http://khalil/BankService-15-7-2016/Service.svc?wsdl")
public class BankService extends Service
{
private final static URL BANKSERVICE_WSDL_LOCATION;
private final static WebServiceException BANKSERVICE_EXCEPTION;
private final static QName BANKSERVICE_QNAME = new QName("http://tempuri.org/", "BankService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("http://khalil/BankService-15-7-2016/Service.svc?wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
BANKSERVICE_WSDL_LOCATION = url;
BANKSERVICE_EXCEPTION = e;
}
public BankService() {
super(__getWsdlLocation(), BANKSERVICE_QNAME);
}
public BankService(WebServiceFeature... features) {
super(__getWsdlLocation(), BANKSERVICE_QNAME, features);
}
public BankService(URL wsdlLocation) {
super(wsdlLocation, BANKSERVICE_QNAME);
}
public BankService(URL wsdlLocation, WebServiceFeature... features) {
super(wsdlLocation, BANKSERVICE_QNAME, features);
}
public BankService(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public BankService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
super(wsdlLocation, serviceName, features);
}
#WebEndpoint(name = "WSHttpBinding_IBankService")
public IBankService getWSHttpBindingIBankService() {
return super.getPort(new QNam("http://tempuri.org/","WSHttpBinding_IBankService"),IBankService.class);
}
#WebEndpoint(name = "WSHttpBinding_IBankService")
public IBankService getWSHttpBindingIBankService(WebServiceFeature... features) {
return super.getPort(new QName("http://tempuri.org/", "WSHttpBinding_IBankService"),
IBankService.class, features);
}
private static URL __getWsdlLocation() {
if (BANKSERVICE_EXCEPTION!= null) {
throw BANKSERVICE_EXCEPTION;
}
return BANKSERVICE_WSDL_LOCATION;
}
}
and I call ws operation as below :
BankService bank_service = new BankService();
IBankService bank_port = bank_service.getWSHttpBindingIBankService();
double b = bank_port.getBalance(123456L);
and this exeption is thrown :
12:55:15,226 ERROR [stderr] (default task-21) An error occurred in trying to obtain a TGT: Invalid null input:
name
12:55:15,227 SEVERE [com.controller.DSMCEcontroller] (default task-21) null:
javax.xml.ws.soap.SOAPFaultException: An error occurred in trying to obtain a TGT: Invalid null input: name
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
at com.sun.proxy.$Proxy169.getBalance(Unknown Source)
at com.controller.DSMCEcontroller.PurchaceOrder(DSMCEcontroller.java:83)
at com.controller.RegisterController.prepareCreate(RegisterController.java:135)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.el.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:181)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at javax.faces.event.MethodExpressionActionListener.processAction
(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIData.broadcast(UIData.java:1108)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest
(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest
(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest
(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest
(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest
(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest
(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest
(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest
(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest
(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest
(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest
(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest
(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest
(ServletInitialHandler.java:284)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:263)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:174)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:793)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
In IIS manager I set anonymous authentication to enable but same result
also I try to provide username and passowrd in client application like that
BindingProvider prov = (BindingProvider) port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "ComputerName\\MyUSERNAME");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "MYPASSWORD");
also not work .
Can anyone help me with it please?

Spring Integration | DSL

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.

java.lang.ClassCastException: com.sun.proxy.$Proxy is thrown when casting an EJB

I am having trouble using remote EJB objects. JNDI look-up succeeds but casting to an object and later usage fails. The EJB interface and implementation are as follows:
UserViewBeanRemote.java
package books.pointejb;
import java.util.List;
import javax.ejb.Remote;
import books.pointejb.User;
import books.pointejb.Book;
#Remote
public interface UserViewBeanRemote {
public boolean register(User user);
// A user can delete his/her account, note that two users with the same username cannot exist
public void delete(User user);
public boolean login(User user);
public boolean logout(User user);
// Search only by book titles
public List<Book> search(String title);
}
UserViewBean.java
package books.pointejb;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateful;
import javax.management.Query;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
// import javax.ejb.Remote;
import books.pointejb.User;
import books.pointejb.Book;
/**
* Session Bean implementation class UserView
*/
#Stateful
// #Remote(UserViewBeanRemote.class)
public class UserViewBean implements UserViewBeanRemote {
#PersistenceContext
private EntityManager entityManager;
/**
* Default constructor.
*/
public UserViewBean() {
// TODO Auto-generated constructor stub
}
public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
List<T> r = new ArrayList<T>(c.size());
for(Object o: c)
r.add(clazz.cast(o));
return r;
}
#Override
public boolean register(User user) {
// We have servlets that validate these fields, so we don't validate anything here
// We check to see whether there is already a user with the same user name or not
Query query = (Query) entityManager.createQuery("SELECT u FROM users u WHERE u.username=:userName");
((javax.persistence.Query) query).setParameter("userName", user.getUsername());
// We check each returned value. If we find anything than we do not add the user
List<User> users = castList(User.class, ((javax.persistence.Query) query).getResultList());
if(users.isEmpty()) {
// The user is not present. Add this user
entityManager.persist(user);
// return "Welcome to BooksPoint " + user.getUsername() + "!";
return true;
} else {
// return "Cannot create " + user.getUsername() + ". A user with this name already exists";
return false;
}
}
#Override
public void delete(User user) {
// The account automatically exists since the user is already logged in
Query query = (Query) entityManager.createQuery("DELETE FROM users u WHERE u.username=:userName");
((javax.persistence.Query) query).setParameter("userName", user.getUsername());
// return "Your account " + user.getUsername() + " has been removed successfully!";
}
#Override
public boolean login(User user) {
// Check if we have a valid user/pass pair
Query query = (Query) entityManager.createQuery("SELECT u FROM users u WHERE u.username=:userName AND u.password=:password");
((javax.persistence.Query) query).setParameter("userName", user.getUsername());
((javax.persistence.Query) query).setParameter("password", user.getPassword());
List<User> users = castList(User.class, ((javax.persistence.Query) query).getResultList());
if(!users.isEmpty()) {
// return "Welcome " + user.getUsername() + "!";
return true;
} else {
// return "Username or password are not valid";
return false;
}
}
#Override
public boolean logout(User user) {
// This can be done in the jsp/servlet. Simply erase the session variables associated with the current user
return false;
}
#Override
public List<Book> search(String title) {
// Check all entries for names similar to title
Query query = (Query) entityManager.createQuery("SELECT * FROM books WHERE title LIKE '%:title%'");
((javax.persistence.Query) query).setParameter("title", title);
List<Book> books = castList(Book.class, ((javax.persistence.Query) query).getResultList());
// Return the books now leave the rest to the jsp
return books;
}
}
Uncommenting #Remote(UserViewBeanRemote.class) doesn't change this behavior.
The lookup is done in the following file:
Lookup.java
package books.point;
import javax.naming.Context;
import javax.naming.NamingException;
import books.point.clientutility.ClientUtility;
import books.pointejb.CartBean;
import books.pointejb.CartBeanRemote;
import books.pointejb.UserViewBean;
import books.pointejb.UserViewBeanRemote;
public class Lookup {
private static final String MODULE_NAME = "BooksPointEJB";
public static UserViewBean doLookupUser() {
Context context = null;
UserViewBean bean = null;
try {
// 1. Obtaining Context
context = ClientUtility.getInitialContext();
// 2. Generate JNDI Lookup name
String lookupName = getLookupNameUser();
// 3. Lookup and cast
bean = (UserViewBean) context.lookup(lookupName); // <== Exception is thrown here
} catch (NamingException e) {
e.printStackTrace();
}
return bean;
}
public static String getLookupNameUser() {
/*
* The app name is the EAR name of the deployed EJB without .ear suffix.
* Since we haven't deployed the application as a .ear, the app name for
* us will be an empty string
*/
String appName = "";
/*
* The module name is the JAR name of the deployed EJB without the .jar
* suffix.
*/
String moduleName = MODULE_NAME;
/*
* AS7 allows each deployment to have an (optional) distinct name. This
* can be an empty string if distinct name is not specified.
*/
String distinctName = "";
// The EJB bean implementation class name
String beanName = UserViewBean.class.getSimpleName();
// Fully qualified remote interface name
final String interfaceName = UserViewBeanRemote.class.getName();
// Create a look up string name
// Be very careful about the stateful flag at the end
String name = "ejb:" + appName + "/" + moduleName + "/" + distinctName
+ "/" + beanName + "!" + interfaceName + "?stateful";
// User looked up name: ejb:/BooksPointEJB//UserViewBean!books.pointejb.UserViewBeanRemote?stateful
System.out.println("User Lookup name is: " + name);
return name;
}
...
}
The EJB deployment log is:
12:10:22,897 INFO [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-5) JNDI bindings for session bean named UserViewBean in deployment unit deployment "BooksPoint.war" are as follows:
java:global/BooksPoint/UserViewBean!books.pointejb.UserViewBeanRemote
java:app/BooksPoint/UserViewBean!books.pointejb.UserViewBeanRemote
java:module/UserViewBean!books.pointejb.UserViewBeanRemote
java:jboss/exported/BooksPoint/UserViewBean!books.pointejb.UserViewBeanRemote
java:global/BooksPoint/UserViewBean
java:app/BooksPoint/UserViewBean
java:module/UserViewBean
I am using jboss-as-7.1.1.Final. Why is this exception thrown?
12:10:52,973 INFO [org.jboss.ejb.client] (http-localhost-127.0.0.1-8080-1) JBoss EJB Client version 1.0.5.Final
12:10:53,043 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/BooksPoint].[books.point.Register]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet books.point.Register threw exception: java.lang.ClassCastException: com.sun.proxy.$Proxy22 cannot be cast to books.pointejb.UserViewBean
at books.point.Lookup.doLookupUser(Lookup.java:24) [classes:]
at books.point.Register.doPost(Register.java:263) [classes:]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.7.0_45]
When you do a JNDI lookup, you lookup the remote Interface.
so changing your cast to
bean = (UserViewBeanRemote) context.lookup(lookupName);
should do the trick.

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();

Unable to find root cause of error (GWT-Umbrella Exception)

I'm building a login application.I'm getting Umbrella Exception everytime, after clicking the Button....unable to find the root cause. Im providing the code and the error list. Please provide me with the fix. Using GWT-RPC
CLIENT SIDE
1. VinLog.java
package com.login.vinayak.client;
import com.google.gwt.core.client.EntryPoint;
public class VinLog implements EntryPoint {
private GreetingServiceAsync GreetingService = (GreetingServiceAsync) GWT.create(GreetingService.class);
public void onModuleLoad() {
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
Window.alert("uncaught: " +e.getMessage());
Window.alert("uncaught: " + e.getMessage());
String s = buildStackTrace(e, "RuntimeExceotion:\n");
Window.alert(s);
e.printStackTrace();
System.out.println(e.getCause());
}
});
RootPanel rootPanel = RootPanel.get();
SimplePanel simplePanel = new SimplePanel();
rootPanel.add(simplePanel, 0, 0);
simplePanel.setSize("450px", "19px");
Label lblLoginForm = new Label("LOGIN");
lblLoginForm.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
simplePanel.setWidget(lblLoginForm);
lblLoginForm.setSize("544px", "41px");
Label lblUserName = new Label("User Name");
rootPanel.add(lblUserName, 10, 124);
Label lblPassword = new Label("Password");
rootPanel.add(lblPassword, 10, 183);
final TextBox textBox = new TextBox();
textBox.setAlignment(TextAlignment.CENTER);
rootPanel.add(textBox, 112, 114);
textBox.setSize("139px", "18px");
final PasswordTextBox passwordTextBox = new PasswordTextBox();
rootPanel.add(passwordTextBox, 112, 173);
passwordTextBox.setSize("139px", "18px");
Button btnClickToEnter = new Button("Click to Enter");
btnClickToEnter.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String j=textBox.getText();
String k=passwordTextBox.getText();
GreetingService.loginuser(j, k, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
Window.alert("welcome");
}
public void onSuccess(String result) {
Window.alert("try again");
}
});
}
});
rootPanel.add(btnClickToEnter, 10, 229);
final ListBox comboBox = new ListBox();
comboBox.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent event) {
Object ob=comboBox.getElement();
if(ob=="Guest") {
Window.alert("Username and Passowrd is: Guest007");
}
}
});
comboBox.addItem("User");
comboBox.addItem("Admin");
comboBox.addItem("Guest");
rootPanel.add(comboBox, 10, 51);
comboBox.setSize("85px", "22px");
Image image = new Image("home.gif");
rootPanel.add(image, 310, 98);
image.setSize("182px", "155px");
}
protected String buildStackTrace(Throwable t, String log) {
if (t != null) {
log += t.getClass().toString();
log += t.getMessage();
StackTraceElement[] stackTrace = t.getStackTrace();
if (stackTrace != null) {
StringBuffer trace = new StringBuffer();
for (int i = 0; i < stackTrace.length; i++) {
trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "("
+ stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber());
}
log += trace.toString();
}
Throwable cause = t.getCause();
if (cause != null && cause != t) {
log += buildStackTrace(cause, "CausedBy:\n");
}
}
return log;
}
}
2.GreetingService.java
package com.login.vinayak.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#SuppressWarnings("unused")
public interface GreetingService extends RemoteService {
public String loginuser(String username, String password);
}
3.GreetinServiceAsync.java
package com.login.vinayak.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GreetingServiceAsync {
public void loginuser(String username, String password, AsyncCallback<String> callback);
}
SERVER SIDE ==> GreetingServiceImpl.java
package com.login.vinayak.server;
import com.login.vinayak.client.GreetingService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.google.gwt.dev.generator.ast.Statement;
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService{
private static final long serialVersionUID = 1L;
public String loginuser(String username,String password) {
try {
java.sql.Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "SA", "");
Statement st=(Statement) con.createStatement();
ResultSet rs=((java.sql.Statement) st).executeQuery("select username,password from lgfrm");
String user=rs.getString(1);
String pass=rs.getString(2);
boolean b1=username.equals(user);
boolean b2= password.equals(pass);
if(b1==b2==true) {
return "success";
}
}
catch (Exception ae) {}
return "Success";
}
}
web.xml
> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC
> "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
> "http://java.sun.com/dtd/web-app_2_3.dtd">
>
> <web-app> <servlet>
> <servlet-name>GreetingServiceImpl</servlet-name>
> <servlet-class>com.login.vinayak.server.GreetingServiceImpl</servlet-class>
> </servlet> <servlet-mapping>
> <servlet-name>GreetingServiceImpl</servlet-name>
> <url-pattern>/Login</url-pattern> </servlet-mapping> <!-- Default page to serve --> <welcome-file-list>
> <welcome-file>VinLog.html</welcome-file> </welcome-file-list>
>
> </web-app>
ERROR LIST
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.GeneratedMethodAccessor33.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) 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.GeneratedMethodAccessor31.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) 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)
**********ADDITIONAL ERROR-CAUSE LIST**********
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.login.vinayak.client.GreetingService_Proxy.loginuser(GreetingService_Proxy.java:34)
at com.login.vinayak.client.VinLog$2.onClick(VinLog.java:82) 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)
KINDLY PROVIDE ME WITH THE FIX...TY
...And there you have it: Service implementation URL not specified...
You need to somehow tell GWT where on the backend the RPC call should go. You may do that with the annotation #RemoteServiceRelativePath on the service interface or programmatically on the ServiceDefTarget instance (which is effectively your async service instance).
Cheers,

Categories