GWT Blobstore error calling createUploadUrl() - gwt

I am attempt to use the Blobstore api for appengine using GWT...
I promise you! I had it working for months and suddenly I started
get the following errors.. arfter executing the following line from
a servelet.
public class ImageServiceImpl extends RemoteServiceServlet implements ImageService {
/**
*
*/
private static final long serialVersionUID = 1L;
// init the blog store service
private BlobstoreService blobService = BlobstoreServiceFactory.getBlobstoreService();
//private static final Logger log = Logger.getLogger(ImageServiceImpl.class);
public static final String PATH_TO_DEFAULT_IMAGE = "images/no_photo.jpg";
.
.
.
.
.
// omitted for brevity
}
#Override
public String getUpLoadPath() {
String url = blobService.createUploadUrl("/n5/doimage");
return url;
}
}
Initializing App Engine server
Sep 19, 2011 7:28:45 PM com.google.apphosting.utils.jetty.JettyLogger info
INFO: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
Sep 19, 2011 7:28:45 PM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed C:\development\n5\n5\war\WEB-INF/appengine-web.xml
Sep 19, 2011 7:28:45 PM com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml
INFO: Successfully processed C:\development\n5\n5\war\WEB-INF/web.xml
Sep 19, 2011 3:28:47 PM com.google.appengine.tools.development.DevAppServerImpl start
INFO: The server is running at http://localhost:8888/
Sep 19, 2011 7:34:59 PM com.google.appengine.tools.development.ApiProxyLocalImpl log
SEVERE: javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String com.six.n5.client.service.ImageService.getUpLoadPath()' threw an unexpected exception: java.lang.VerifyError: class com.google.appengine.api.blobstore.BlobstoreServicePb$CreateUploadURLRequest overrides final method isInitialized.()Z
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:385)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:216)
at com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:141)
at com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:93)
at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:63)
at com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:122)
at com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:110)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:35)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:58)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:122)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.apphosting.utils.jetty.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:70)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:351)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.lang.VerifyError: class com.google.appengine.api.blobstore.BlobstoreServicePb$CreateUploadURLRequest overrides final method isInitialized.()Z
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.google.appengine.tools.development.IsolatedAppClassLoader.loadClass(IsolatedAppClassLoader.java:176)
at java.lang.ClassLoader.loadClass(Unknown Source)
at com.google.appengine.api.blobstore.BlobstoreServiceImpl.createUploadUrl(BlobstoreServiceImpl.java:43)
at com.google.appengine.api.blobstore.BlobstoreServiceImpl.createUploadUrl(BlobstoreServiceImpl.java:34)
at com.six.n5.server.ImageServiceImpl.getUpLoadPath(ImageServiceImpl.java:153)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:100)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
... 39 more

I found my own error! as it turn out the reason this was suddenly failing was because the FORM post thought it was cross domain posting. I was testing the web site by calling 127.0.0.1:8888..etc but when the when my Image RPC was called to establish the upload path, it returned to the form setAction the my machine name kmoore-PC:8888..etc instead of the 127.0.0.1:8888... and hence it returned null because it thought it was crossing domains.
To fix, click on the google box in url bar and add your computer name and then test you app using the computer name instead of 127

I tried replacing local host with machine name it didn't help, but it is a cross domain java-script issue so I tried just using the URL pattern assigned in the web xml and I got a String result. The result is my response wrapped with XML and I plan to parse it. if any one has something more elegant please tell me.
here is the response String [it looks a bit different because it affects the stack overflow page]:
pre style="word-wrap: break-word; white-space: pre-wrap;">my response id
Here is the relevant server code
public void doPost(HttpServletRequest request, HttpServletResponse response) throws >ServletException, IOException
{
//Redirect recursively to this servlet (calls doGet)
response.sendRedirect("/blobstoreexample/uploadservice?id=" + >item_image_blob_key);
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("shonka");
//Send the meta-data id back to the client in the HttpServletResponse response
String id = req.getParameter("id");
response.getWriter().write(id);
return;
}
Here is the relevant client code, no need for parsing here is the server side code:
uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
#Override
public void onSubmitComplete(SubmitCompleteEvent event) {
//The submit complete Event Results will contain the unique
//identifier for the picture's meta-data. Trim it to remove
//trailing spaces and line breaks
System.out.println("uploadForm onSubmitComplete() results are: " + event.getResults());
Window.alert(event.getResults());
if(event.getResults() != null)
{
// getPicture(event.getResults().trim());
}
else
{
Window.alert(event.getResults());
}
}
});
Edit I found a more elegant way to deliver a long id
//Redirect recursively to this servlet (calls doGet)
response.sendRedirect("/itemmanager/receive?id=" + item.getKey().getId());
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
System.out.println("entered do post");
//Send the meta-data id back to the client in the HttpServletResponse response
String id = req.getParameter("id");
System.out.println("entered do post id is: " + id);
resp.setHeader("Content-Type", "text/html");
resp.getWriter().println(id);
}

Instead of using the computer name, I simply replace it with the 127 address when in dev mode, like so:
String url = blobstoreService.createUploadUrl("/project/uploadservice");
// change the computer name to standard localhost ip address, if in dev mode
if(SystemProperty.environment.value() == SystemProperty.Environment.Value.Development)
{
url = url.replace("Your-PC-Name", "127.0.0.1");
}

Related

Strange exception using Jersey with embedded Jetty

I have created an embedded Jetty application which utilizes Jersey in order to implement several RESTful services. I am using some standard code as described here in Stack Overflow as well as other websites:
public static void main(String[] args)
{
Server server = new Server(8080);
ServletContextHandler ctx = new ServletContextHandler(
ServletContextHandler.SESSIONS);
ctx.setContextPath("/");
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
holder.setInitOrder(0);
holder.setInitParameter("jersey.config.server.provider.classnames",
RestfulClass.class.getCanonicalName());
server.setHandler(ctx);
try
{
server.start();
server.join();
}
catch(Exception exe)
{
exe.printStackTrace();
}
}
I've used all the recommended jar files, and several other jar files that the various blogs and sites failed to mention. When running the Jetty application, I get the following exception:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer.class
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:86)
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:95)
<several lines omitted for brevty>
Caused by: javax.servlet.UnavailableException: org.glassfish.jersey.servlet.ServletContainer.class
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:102)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:361)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:874)
... 11 more
It is the "UnavailableException" that I do not understand. The ServletContainer class is actually in one of the Jar files (in jersey-container-servlet-core.jar, to be precise), but for some reason it is identified as "unavailable". This is causing a class that is actually in a referenced Jar file to be "not found"!
Can anyone tell me what is causing this UnavailableException and (more importantly) how I can prevent it from being thrown?
Someone please advise...
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
You are using a String for the class name. When doing this, you don't use the .class suffix. That at only when you want to get the actual Class object. You have two options
Remove the .class from the String
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer", "/*");
Remove the "" (double quotes) and just use the Class object1.
ServletHolder holder = ctx.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
1 - See addServlet(Class, String)

Invalid Cursor State - No current row

I am very new to Java, and I am trying to complete one simple task of reading data from a table and passing it to form variables. However, I am getting this frustrating exception:
Invalid cursor state - no current row;
I tried everything but still no luck. I looked into Google but I'm not getting an answer that will fix this issue. Hope you guys can help.
public class MainFrame extends javax.swing.JFrame {
Connection con;
Statement stm;
ResultSet rs;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
DoConnect();
}
public void DoConnect() {
try{
String host = "jdbc:derby:studentinfo;create=true";
String uname = "sudeep";
String upass = "sunny";
con = DriverManager.getConnection(host, uname, upass);
stm = con.createStatement();
String sql = "SELECT * FROM APP.STUDENTID";
rs = stm.executeQuery(sql);
System.out.println("Query executed");
if(rs.next())
{
// This is where the exception is occurring!!!!!!
String id = rs.getString("STUDENTID");
String first = rs.getString("FIRST_NAME");
String second = rs.getString("SECOND_NAME");
ID.setText(id);
fnam1.setText(first);
lnam.setText(second);
System.out.println(id);
}
}
catch ( SQLException err) {
JOptionPane.showMessageDialog(MainFrame.this, err.getMessage());
System.out.println("ERROR GETCONNECTION");}
}
}
Here is the trace generated by the program
run:
[EL Info]: 2013-09-03 21:14:15.732--ServerSession(552364977)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-09-03 21:14:16.299--ServerSession(552364977)--file:/Users/vasundhra_sudeep/NetBeansProjects/StudentForm/build/classes/_jdbc:derby:studentinfo;create=truePU login successful
java.sql.SQLException: Invalid cursor state - no current row.
Invalid cursor state - no current row.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.checkOnRow(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getColumnType(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getString(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getString(Unknown Source)
at studentform.MainFrame.DoConnect(MainFrame.java:57)
at studentform.MainFrame.(MainFrame.java:35)
at studentform.MainFrame$7.run(MainFrame.java:579)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:715)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:676)
at java.awt.EventQueue$2.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:685)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.sql.SQLException: Invalid cursor state - no current row.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 27 more
BUILD SUCCESSFUL (total time: 7 seconds)
It's likely that APP.STUDENTID has no data in it. Insert at least one record (aka row) of data into that table, run your program again, and see if the same exception occurs.

Having trouble mocking an email server using JUnit

I'm trying to mock sending an email (for the purposes of JUnit, v4.8.1, testing) and decided to use Dumbster, which I found through SO. I'm using version 1.6. I have this in my JUnit test …
SimpleSmtpServer server = SimpleSmtpServer.start();
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
server.stop();
and I send an email this way …
public boolean sendEmail(final String toEmail,
final String fromEmail,
final String smtpHost,
final String subject,
final String body)
{
boolean ret = true;
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", smtpHost);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(body);
// Send message
Transport.send(message);
}catch (MessagingException mex) {
ret = false;
LOG.error(mex.getMessage(), mex);
} // try
return ret;
} // sendEmail
This fails with the exception below. Does anyone know what I'm doing wrong or is there an easier way to mock sending an email in a JUnit test?
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
at java.net.ServerSocket.bind(ServerSocket.java:326)
at java.net.ServerSocket.<init>(ServerSocket.java:192)
at java.net.ServerSocket.<init>(ServerSocket.java:104)
at com.dumbster.smtp.SimpleSmtpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:680)
[ERROR]: org.mainco.subco.email.service.EmailServiceImpl - Could not connect to SMTP host: localhost, port: 25
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.mainco.subco.email.service.EmailServiceImpl.sendEmail(EmailServiceImpl.java:62)
at org.mainco.subco.email.service.EmailServiceTest.testSendEmail(EmailServiceTest.java:23)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:527)
at java.net.Socket.connect(Socket.java:476)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
I decided to mock the static call from the Transport class instead, using PowerMock (v.1.5.1).
#RunWith(PowerMockRunner.class)
public class EmailServiceTest
{
#Autowired
private EmailService m_emailSvc = new EmailServiceImpl();
#Test
#PrepareForTest( Transport.class )
public final void testSendEmail()
{
suppress(methodsDeclaredIn(Transport.class));
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
} // testSendEmail
What about wrapping the call to Transport is a mockable object? Inject the mock and verify the call.
What I mean is something like this...
class MyTransport{
public void send(MimeMessage message){
Transport.send(message);
}
}
Then inject an instance of this class into your class above. In your production env you have the same code. However, when doing testing you could pass in a Mock for MyTransport and thereby verify the call to send without the need of a server.

'#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause java.lang.NullPointerException

I googled but can't find a solution for this. It is from Core JSF 3rd.
I did:
1) Included JSF Mojarra in Build path.
2) Included MySQL JDBC driver in Build path.
3) Copied MySQL JDBC driver to Tomcat "lib" folder and "ext" JDK folder.
4) I tested JDBC driver with a small Java app and it succeeded.
CustomerBean from corejsf source code:
public class CustomerBean {
#Resource(name="jdbc/corejsf")
private DataSource source;
public ResultSet getAll() throws SQLException {
Connection conn = source.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM Customers");
// return ResultSupport.toResult(result);
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
// or use an implementation from your database vendor
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
}
Error:
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/DatabaseTest] threw exception [/index.jsp(12,3) '#{customer.all}' Error reading 'all' on type com.corejsf.CustomerBean] with root cause
java.lang.NullPointerException
at com.corejsf.CustomerBean.getAll(CustomerBean.java:18)
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.el.BeanELResolver.getValue(BeanELResolver.java:87)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:67)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at org.apache.el.parser.AstValue.getValue(AstValue.java:169)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:554)
at javax.faces.component.UIData.getDataModel(UIData.java:1248)
at javax.faces.component.UIData.setRowIndex(UIData.java:447)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:823)
at javax.faces.component.UIData.encodeBegin(UIData.java:937)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1611)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.JspViewHandlingStrategy.doRenderView(JspViewHandlingStrategy.java:420)
at com.sun.faces.application.view.JspViewHandlingStrategy.renderView(JspViewHandlingStrategy.java:209)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:317)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:204)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:182)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
You need to configure a JNDI datasource with the name jdbc/corejsf in Tomcat.
I suspect that datasource is not injected, since nothing in your class path interprets the #Resource annotation. As far as I know, #Resource is an EJB annotation, but Tomcat is no EJB container. Try looking up the datasource programatically.

GWT Throwing exception to client

Can someone show to throw exception to client in GWT.
in my serviceasync interface i am doing this as well in my service interface
void ActivateUserAccount(String ActivationCode,AsyncCallback <Boolean> Callback) throws AlreadyActivatedError;
in my serverimpl;
i am doing this to throw an exception
public Boolean ActivateUserAccount(String ActivationCode) throws AlreadyActivatedError
{
....
throw new AlreadyActivatedError();
}
my exception is in the form:
public class AlreadyActivatedError extends Exception implements IsSerializable
{
public AlreadyActivatedError()
{
super();
}
}
Just to make everything clear: you can throw both checked (the ones extending Exception) and unchecked (extending RuntimeException) exceptions from the server to the client - as long as the exception is serializable. It is however recommended to throw checked exceptions, as they
represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files).
In contrast, unchecked exceptions
represent defects in the program (bugs) - often invalid arguments passed to a non-private method.
Source
As the documentation states, the following conditions have to be fulfilled for an exception to be sent to the client:
It has to extend Exception (note that RuntimeException does that).
It has to be serializable. In short: implement Serializable, have a no-args constructor and have all the fields serializable.
In your *Service interface you need to add a throws declaration to the method that can throw the exception. Note that you don't need to add the throws declaration to the *Async interface.
Once you have that set up, you'll be able to handle the exception in the onFailure method in your AsyncCallback.
Some code to show all the pieces together, based on examples from the guide on the GWT site:
DelistedException.java
public class DelistedException extends Exception implements Serializable {
private String symbol;
// Note the no-args constructor
// It can be protected so that only subclasses could use it
// (because if they want to be serializable too, they'll need
// a no-args constructor that calls the superclasses' no-args constructor...)
protected DelistedException() {
}
public DelistedException(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return this.symbol;
}
}
StockPriceService.java
#RemoteServiceRelativePath("stockPrices")
public interface StockPriceService extends RemoteService {
StockPrice[] getPrices(String[] symbols) throws DelistedException;
}
StockPriceServiceAsync.java
public interface StockPriceServiceAsync {
void getPrices(String[] symbols, AsyncCallback<StockPrice[]> callback);
}
On the client side
AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
public void onFailure(Throwable caught) {
if (caught instanceof DelistedException) {
// Do something with it
} else {
// Probably some unchecked exception,
// show some generic error message
}
public void onSuccess(StockPrice[] result) {
// Success!
}
};
stockPriceService.getPrices(symbols, callback);
Not sure why hilal's answer was accepted as it is completely false.
In order for the exceptions to reach the client's browser you must throw a checked exception that is Serializable and defined in the service interfaces.
If your service implementation throws a RuntimeException the web client will receive a generic 500 error messages as follows:
[WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract my.module.shared.Result my.module.client.service.Service.doSomething() throws my.module.shared.exception.MyCheckedException' threw an unexpected exception: my.module.shared.exception.AuthzRuntimeException: some authz message
at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:389)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:324)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: my.module.shared.exception.AuthzRuntimeException: some authz message
at my.module.shared.Authz.doSomeCheck(Authz.java:101)
at my.module.server.ServiceImpl.doSomething(ServiceImpl.java:283)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
... 22 more
[ERROR] 500 - POST /module/userService (127.0.0.1) 57 bytes
Request headers
Host: 127.0.0.1:8888
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://127.0.0.1:8888/foo.html?gwt.codesvr=127.0.0.1:9997
Cookie: worknet=7k8g41ulbl674dp865t180tji5
Connection: keep-alive
Cache-Control: no-cache
X-GWT-Permutation: HostedMode
X-GWT-Module-Base: http://127.0.0.1:8888/module/
Content-Type: text/x-gwt-rpc; charset=utf-8
Content-Length: 1076
Pragma: no-cache
Response headers
Content-Type: text/plain
(RequestCallbackAdapter.java:209) 2013-10-18 13:16:56,966 [WARN ] Fail ""
com.google.gwt.user.client.rpc.StatusCodeException: 500 The call failed on the server; see server log for details
at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:209)
at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
at sun.reflect.GeneratedMethodAccessor40.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:338)
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
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:242)
at sun.reflect.GeneratedMethodAccessor37.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.reactToMessages(BrowserChannelServer.java:293)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
at java.lang.Thread.run(Unknown Source)
GWT can only handle unchecked exceptions(which means sent from server to client) which are not serialized that extends from RuntimeException. I don't know what AlreadyActivatedError is. If it is not RuntimeException it can't be sent to the client(browser)
Maybe also note that if your specific Exception does not have a standard constructor, the generic 500 error message will also be displayed because it is not possible to deserialize the exception. Sadly, the gwt compiler and dev-mode plugin will not always point this problem out explicitly.. (that's how i got here anyway)
So, in combination with what vinnyjames said (the exception must be Serializable and be defined in the (RPC) service's interface), i found that processing exceptions in gwt client code is not too complicated.