Generics - ClassCastException while iterating a ArrayList - java

Following is my code. I am querying the user_group table and getting the result in a List. I want to iterate the List. But getting the exception as follows.
List<Group> list= empDAO.getStudentList();
for(Group o :list){
System.out.println("NAME :"+ o.getFirstName());
}
this is my DAO method
public List<Group> getStudentList() {
System.out.println("INSIDE DAO");
List<Group> groups = new ArrayList<Group>();
List<Group> rows = jdbcTemplate.queryForList("select * from user_group");
return rows;
}
Group.class
public class Group {
public Group() {
// TODO Auto-generated constructor stub
}
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
I am getting the following exception
Aug 3, 2012 9:22:47 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet mvc-dispatcher threw exception
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.common.form.Group
at com.common.controller.HelloWorldController.helloWorld(HelloWorldController.java:28)
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.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:421)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:136)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:326)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:313)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Can anyone please tell how to fix this error?

The line jdbcTemplate.queryForList("select * from user_group"); is returning a list of HashMap, not a list of Group items (your IDE is probably showing a warning on that line).
You might want to read the Spring documentation about the jdbcTemplate and you might want to use a RowMapper to transform each row to a Group object.
I also think that you want to use the method jdbcTemplate.query(String sql, RowMapper rm) for your use case, check the javadoc.

jdbcTemplate.queryForList does not return a List<Group>, it has no idea what a Group is. It returns a List<Map<String,Object>>, a list of rows, each row a map from the column name to its value.
So do this:
for (Map<String,Object> m : jdbcTemplate.queryForList("select * from user_group")) {
for (Map.Entry<String,Object> e : m.entrySet()) {
String columnName = e.key;
Object columnValue = e.value;
...build a Group somehow?...
}
}

Related

getDeclaringClass cause failed to lazily initialize exception

I need to use my own ExclusionStrategy in GSON, so I have created this class:
public class DUExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipField(FieldAttributes f) {
Collection<Annotation> annots = f.getAnnotations();
for(Annotation a : annots) {
if(a.annotationType().equals(Expose.class)) {
return false;
}
}
return (f.getDeclaringClass() == BaseEntityImpl.class && f.getName().equals("creation"))
|| (f.getDeclaringClass() == BaseEntityImpl.class && f.getName().equals("creator"))
|| (f.getDeclaringClass() == BaseEntityImpl.class && f.getName().equals("modification"))
|| (f.getDeclaringClass() == BaseEntityImpl.class && f.getName().equals("modificator"));
}
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
I should not change anything in BaseEntityImpl, and there is this field in this class:
#OneToMany(mappedBy="parent", fetch=FetchType.LAZY) #OrderBy("ordinal")
private Set<T> children = new TreeSet<T>();
And because of calling f.getDeclaringClass() the application is throwing this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: cz.bach.dataframe2.domain.impl.BaseEntityImpl.children, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:124)
at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:95)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.write(CollectionTypeAdapterFactory.java:60)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
at com.google.gson.Gson.toJson(Gson.java:593)
at com.google.gson.Gson.toJson(Gson.java:572)
at com.google.gson.Gson.toJson(Gson.java:527)
at com.google.gson.Gson.toJson(Gson.java:507)
at cz.bach.clients.du.model.service.DUSerializer.serialize(DUSerializer.java:23)
at cz.bach.clients.du.model.service.DURepository.save(DURepository.java:619)
at cz.bach.clients.du.model.service.DURepository.appendChild(DURepository.java:176)
at cz.bach.clients.du.model.service.DURepository.appendChild(DURepository.java:150)
at cz.bach.clients.du.model.service.DURepository$$FastClassByCGLIB$$f2fe0d5d.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at cz.bach.clients.du.model.service.DURepository$$EnhancerByCGLIB$$a27cbe9c.appendChild(<generated>)
at cz.bach.clients.du.ui.perspectives.main.DUDispatcher.add(DUDispatcher.java:261)
at cz.bach.archives.uiframe.actions.CommonAddAction.run(CommonAddAction.java:11)
at cz.bach.clients.du.ui.perspectives.main.DUToolbar$1.buttonClick(DUToolbar.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:164)
at com.vaadin.ui.AbstractComponent.fireEvent(AbstractComponent.java:1219)
at com.vaadin.ui.Button.fireClick(Button.java:567)
at com.vaadin.ui.Button.changeVariables(Button.java:223)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.changeVariables(AbstractCommunicationManager.java:1460)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleVariableBurst(AbstractCommunicationManager.java:1404)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.handleVariables(AbstractCommunicationManager.java:1329)
at com.vaadin.terminal.gwt.server.AbstractCommunicationManager.doHandleUidlRequest(AbstractCommunicationManager.java:761)
at com.vaadin.terminal.gwt.server.CommunicationManager.handleUidlRequest(CommunicationManager.java:325)
at com.vaadin.terminal.gwt.server.AbstractApplicationServlet.service(AbstractApplicationServlet.java:501)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:83)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
Can I solve this by easy and elegant way? I really don't see any reason why getDeclaringClass() should cause full inicialization of BaseEntityImpl ..
Thanks in advance!
In BaseEntityImpl Entity change fetchType Lazy to Eager i.e.
#OneToMany(mappedBy="parent", fetch=FetchType.EAGER)

Null.Pointer.Exception in my web app

I am trying to create a web app that is querying my oracle database and returns a list of menu titles from a table but when i navigate to the page it throws the area shown below.
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.NullPointerException
oracle.DatabaseConnector.selectAllMenus(DatabaseConnector.java:63)
org.apache.jsp.menus_jsp._jspService(menus_jsp.java:113)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.35 logs.
Below is the offending part of the code inside my java class that queries the database. But i am not sure why this would cause the above error? Can someone take a look and see if there is a problem?
public MenuList selectAllMenus(String ordering) {
MenuList list = null;
try {
String strQuery = "SELECT title"
+ " FROM menus"
+ " ORDER BY " + ordering;
PreparedStatement stmt = conn.prepareStatement(strQuery);
results = stmt.executeQuery();
list = new MenuList(results);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
This is what was in the log file:
28-Feb-2012 14:40:57 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
at oracle.DatabaseConnector.selectAllMenus(DatabaseConnector.java:63)
at org.apache.jsp.menus_jsp._jspService(menus_jsp.java:113)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
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.Http11AprProcessor.process(Http11AprProcessor.java:877)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675)
at java.lang.Thread.run(Thread.java:662)
Hope you are using MySQL DB..
Make sure you add the correct MySQL Java Connector as an external library and also add Tomcat as an external server (In the Build Path of the Project in Eclipse).
(You can also copy all the libraries in the lib folder of your $TOMCAT_HOME/$CATALINA_HOME to your build path.
This should resolve this problem.
Thanks.
You can look in your logs : Apache Tomcat/6.0.35 logs
But the error message itself is pretty clear : The db connection is null, probably your connection string/parameters are incorrect.
I assume conn is open.
Instead of printing the stack trace, why don't you print the error message?
line:
PreparedStatement stmt = conn.prepareStatement(strQuery);
"conn" is not being created in any place
try something like this to create a connection:
public class MyConnection {
Connection conn;
String username;
String password;
public Connection getConnection(){
try {
String url = "jdbc:mysql://localhost/yourDBName?";
Class.forName("com.mysql.jdbc.Driver");
try {
conn = (Connection) DriverManager.getConnection(url,username,password);
} catch (Exception e) {
System.out.println(e);
}
} catch (SQLException e) {
System.out.println(e);
}
return conn;
}
}

why do i get this error when trying to get data from a form?

This is the error i get:
14:06:00,355 ERROR [JsonFilter] java.lang.NoSuchMethodException: byte.<init>(java.lang.String)
I have a basic upload form with an input file:
<form method='post' enctype='multipart/form-data'>
<table>
<input type='file' name='logo'>
</table>
</form>
When I submit, it calls a setter servlet, inside the servlet theres an extract() to get the data:
if (fileUp.getContent("compLogo") != null)
{
record.compLogo = fileUp.getContent("compLogo").getData();
} else
System.out.println("logo was null!");
return record;
But the thing, it throws that error before it even got the extact function, i've put many sysouts before it so i will know how the functions are moving around.
15:07:06,915 ERROR [JsonFilter] java.lang.NoSuchMethodException: byte.<init>(java.lang.String)
javax.servlet.ServletException: java.lang.NoSuchMethodException: byte.<init>(java.lang.String)
at com.pinksheets.common.web.req.HttpExtractor.getObject(HttpExtractor.java:160)
at com.pinksheets.common.web.req.HttpExtractor.extract(HttpExtractor.java:88)
at com.pinksheets.common.web.servlet.FetcherServlet.doGet(FetcherServlet.java:52)
at com.pinksheets.common.web.servlet.FetcherServlet.doPost(FetcherServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.pinksheets.common.web.filter.RoleAuthFilter.doFilter(RoleAuthFilter.java:78)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.pinksheets.common.web.filter.UserAuthFilter.doFilter(UserAuthFilter.java:49)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.pinksheets.common.web.filter.JsonFilter.doFilter(JsonFilter.java:81)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.service.session.ClusteredSessionValve.handleRequest(ClusteredSessionValve.java:135)
at org.jboss.web.tomcat.service.session.ClusteredSessionValve.invoke(ClusteredSessionValve.java:94)
at org.jboss.web.tomcat.service.session.LockingValve.invoke(LockingValve.java:62)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoSuchMethodException: byte.<init>(java.lang.String)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at com.pinksheets.common.web.req.HttpExtractor.getObject(HttpExtractor.java:142)
... 37 more
this generates the html codes
EditSplashPageDOM.generate = function (value, callback)
{
var elem, output = document.createElement('form');
output.myValue = value;
output.myCallback = callback;
output.method = 'post';
output.enctype = 'multipart/form-data';
output.onsubmit = function(ev) { callback.handleSubmit(value, this); return false; };
output.appendChild(InputField.genHidden ('id', value.id));
output.appendChild(InputField.genHidden ('name', value.name));
var div, p;
output.appendChild(div = document.createElement('div'));
div.appendChild(p = document.createElement('p'));
p.innerHTML = 'The Splash Page list all the information for the current ad. You may update to change the Splash Page.<br /><span class="footnote">*The info shown are data of the latest ad and the proper format.*</span>';
var table = document.createElement('table');
output.appendChild(table);
table.className = 'detail';
this.createRow(table, 'Company Symbol', 'compSymbol', value.compSymbol, 100, 50);
this.createRow(table, 'Company Sec Id', 'secId', value.secId, 100, 50);
this.createFileRow(table, 'Company Logo', 'compLogo', 100, 47); //this is for input the file
row = table.insertRow (table.rows.length);
cell = row.insertCell(0);
cell.colSpan = 2;
cell.className = 'detailAction'
cell.appendChild(elem = InputField.genSubmit('Submit', 'Insert New Ad'));
return output;
}
this is the submit function
EditSplashPageSimple.prototype.handleSubmit = function(value, form)
{
value.compLogo = form.compLogo.value;
value.compPAL = form.compPAL.value;
value.compUrl = form.compUrl.value;
if(value.compLogo == null)
window.alert("comp logo is null");
else
window.alert("logo is " + value.compLogo);
var me = this;
me.caller.setSplashPage(value);
{
handleRequestData : function(status) {
window.alert('Splash Page is successfully updated with new company ' + value.compSymbol);
// me.callback.handleAddition(value);
},
handleRequestError : function(error) {
// Only deal with validation exceptions.
if (!error.isValidationException) {
window.alert('Sorry, there was an error while trying to add the new information. Please double check the data.');
throw error;
}
window.alert(error.message);
var e;
if (error.field && (e = form.elements[error.field])) {
window.alert('error.field error idk');
e.focus();
}
}
});
}
when submit itll call the servlet
System.out.println("now to extract the content of the file and set it to the logo var");
SplashPage record = (new SplashPageLogoAdapter(request)).extract();
the extract() is the same as i posted
It looks like this com.pinksheets API is assuming a class that it encounters at some point is going to have a constructor that takes a String; when it finds that the class in question is byte (i.e., java.lang.Byte.TYPE, which has no such constructor) you're getting an exception.
I'd want to have a look at the source for com.pinksheets.common.web.req.HttpExtractor.getObject(); that's where you're going to see what's going on.

EOFException when sending data from Applet to a servlet

I am trying to get simple user Details (Name,Phone No, Gender(Option Box)) in an Applet and display the details in an JSP.I put all the three details in an HashMap and send it in a output Stream. The Applet Code is as Follows.
try
{
userUrl = "http://localhost:8080/AppletTest/display.jsp";
/* In the web.xml file I have mapped display.jsp to the Servlet */
testServlet = new URL(userUrl.toString());
servletConnection = testServlet.openConnection();
servletConnection.setDoOutput(true);
servletConnection.setRequestProperty("Content-Type","application/octet-stream");
ObjectOutputStream oos1 = new ObjectOutputStream(servletConnection.getOutputStream());
/* DataMap is the HashMap Containing values */
oos1.writeObject(dataMap);
oos1.flush();
oos1.close();
// Thread.currentThread().sleep(5000);
}
catch(Exception ie)
{
ie.printStackTrace();
}
// Finally call servlet by going to that page.
getAppletContext().showDocument(userUrl, "_self");
While on a servlet i just get the HashMap and forward it to a jsp page to display.
try
{
System.out.println("In Servlet");
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
HashMap<String,String> receievedData = (HashMap<String,String>) inputFromApplet.readObject();
request.setAttribute("dataMap",receievedData);
request.getRequestDispatcher("display1.jsp").forward(request, response);
inputFromApplet.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
As asked in the comments in The Question here ,The Sysout("In Servlet") is printed. But an Exception is thrown
In Servlet
SEVERE: Servlet.service() for servlet jsp threw exception java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream. java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at org.apache.jsp.display1_jsp._jspService(display1_jsp.java:71)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
What am I doing wrong. Please Help.
If I understand correctly you are :
sending a request to the servlet
reading from e input stream of that call
sending a jsp as the response to THAT call
redirecting the user from the applet to that same servlet
this causes a SECOND request, without anything serialized in it
the servlet fails on this second request
This unfortunately canno work. You should use two servlets (or the same one with an optional parameter) to handle the two requests, one will read from the input stream, and write to the session, while the second will retrive from the session and display in a jsp.
I suspect an exception is being thrown by the applet and you haven't detected it in the Java Console yet.

NPE when POSTing Binary data to RESTEasy Service

My environment is JBOSS AS 5.1.0-GA, Struts 2.1.8 and RESTEasy 1.2.GA
When posting to my service I get a NPE on the Block getter which is being called from the #Consumes annotation.
I'm some what at a loss as to what it could be and any help would be greatly appreciated.
Thank you in advance.
Jono
public class MyForm
{
#FormParam("block")
#PartType("application/octet-stream")
private byte[] block;
public MyForm(){}
public byte[] getBlock()
{
return block;
}
public void setBlock(final byte[] block)
{
this.block = block;
}
}
#Path("/service")
public class Service
{
#Consumes("multipart/form-data")
#POST
public Response post(#MultipartForm MyForm form)
{
System.out.println(" recieved form " + form);
......
}
}
Exception
Note, I removed the line numbers as they do not correspond to line numbers in the example.
java.lang.NullPointerException
at MyForm.getBlock(MyForm.java:)
at Service.postFileBlock(Service.java:)
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.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:119)
at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:211)
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:176)
at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:166)
at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:359)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:336)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:103)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:114)
at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.doFilter(StrutsExecuteFilter.java:67)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.doFilter(StrutsPrepareFilter.java:82)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:637)
Please note: This is a cross post from with the resteasy developers mailing list.
The Binary data was a red herring, I had the annotations in the wrong place, they should have been on the setter methods rather than the member variable.
public class MyForm
{
private byte[] block;
public MyForm(){}
public byte[] getBlock()
{
return block;
}
#FormParam("block")
#PartType("application/octet-stream")
public void setBlock(final byte[] block)
{
this.block = block;
}
}
I am not familiar with RestEasy, but your stack suggests that you do not have an instance of MyForm... Since it looks like this is based on reflection, I would suggest you look over your configuration (maybe some type of dependency injection?) to ensure that the object is being instantiated.

Categories