ClassCastException on arraylist?

Code:
package soft.lit3.dev.AI.parsers;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import soft.lit3.dev.AI.Types.Template;
public class TemplateParser {
     private Node n;
     Document a;
     public TemplateParser(Document d, Node n) {
          super();
          this.n = n;
          a = d;
          parse();
      * for (int b = 0; b != la.getLength(); b++) { Node g = la.item(b); if
      * (g.getNodeName().equals("get")) { Element nodeE = (Element) g;
      * get(nodeE); } else if (g.getNodeName() .equals("set")) {
      * Element nodeE = (Element) g; set(nodeE); }else{ } }
     public Template parse() {
          ArrayList<Node> responsesA = new ArrayList<Node>();
          ArrayList<Node> inputA = new ArrayList<Node>();
          Template t = null;
          NodeList nl = n.getChildNodes();
          for (int i = 0; i != nl.getLength(); i++) {
          Node node = nl.item(i);
          if (!node.getNodeName().contains("#text")) {
               if (node.getNodeName().equals("input")) {
                    inputA.add(node);
                    } else if (node.getNodeName().equals("response")) {
                    if (node.getChildNodes().item(0) != null) {
                         NodeList li = node.getChildNodes();
                         for (int x = 0; x != li.getLength(); x++) {
                              Node list = li.item(x);
                              if (!list.getNodeName().equals("#text")) {
                                   if (list.getNodeName().equals("redirect")) {
                                        NodeList al = a.getChildNodes();
                                        for (int r = 0; r != al.getLength(); r++) {
                                             Node z = al.item(r);
                                             NodeList lol = z.getChildNodes();
                                             for (int w = 0; w != lol.getLength(); w++) {
                                                  Node op = lol.item(w);
                                                  Node cdsaa = null;
                                                  NodeList rp = op.getChildNodes();
                                                  for(int t45 = 0; t45 != rp.getLength(); t45++){
                                                       Node n = rp.item(t45);
                                                       if(!n.getNodeName().equals("#text")){
                                                            if(n.getTextContent().equals(list.getTextContent())){
                                                                 cdsaa = op;
                                                                 break;
                                                  if(cdsaa != null){
                                                       ArrayList<Node> input_Temp = new ArrayList<Node>();
                                                       ArrayList<Node> r_Temp = new ArrayList<Node>();
                                                       log(cdsaa.getNodeName());
                                                       NodeList il = cdsaa.getChildNodes();
                                                            for(int yol = 0; yol != il.getLength();yol++){
                                                                 Node pop = il.item(yol);
                                                                 if(!pop.getNodeName().equals("#text")){
                                                                      if(pop.getNodeName().equals("input")){
                                                                           input_Temp.add(pop);
                                                                      if(pop.getNodeName().equals("response")){
                                                                           NodeList re = pop.getChildNodes();
                                                                           for(int ry = 0; ry != re.getLength(); ry++){
                                                                                Node list5 = re.item(ry);
                                                                                r_Temp.add(list5);
                                                            //TODO Add all the other template Responses here.
                                        } else if (list.getNodeName().equals("li")) {
                                             responsesA.add(list);
          for(Node node:(Node[]) responsesA.toArray()){
               log(node.getTextContent());
          return new Template((Node[]) inputA.toArray(), (Node[]) responsesA.toArray());
     public void get(Element e) {
          if (e.getAttribute("bot_prefs") != null) {
               log(e.getAttributeNode("bot_prefs").getNodeName());
               log(e.getAttributeNode("bot_prefs").getNodeValue());
     public void set(Element e) {
     public static void log(String a) {
          System.out.println(a);
     public void log(NodeList nl) {
          for (int i = 0; i != nl.getLength(); i++) {
               Node n = nl.item(i);
               if (!n.getNodeName().equals("#text")) {
                    log(n.getNodeName());
     public void log(Node nl) {
          Node n = nl;
          if (!n.getNodeName().equals("#text")) {
               log(n.getNodeName());
}Exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lorg.w3c.dom.Node;
     at soft.lit3.dev.AI.parsers.TemplateParser.parse(TemplateParser.java:99)
     at soft.lit3.dev.AI.parsers.TemplateParser.<init>(TemplateParser.java:20)
     at soft.lit3.dev.AI.Main.Parser.<init>(Parser.java:33)
     at soft.lit3.dev.AI.Main.Main.main(Main.java:35)Why do i get this? I cannot seem to get this to work :(

if (!node.getNodeName().contains("#text")) {
               if (node.getNodeName().equals("input")) {
                    inputA.add(node);
                    } else if (node.getNodeName().equals("response")) {
                    if (node.getChildNodes().item(0) != null) {
                         NodeList li = node.getChildNodes();
                         for (int x = 0; x != li.getLength(); x++) {
                              Node list = li.item(x);
                              if (!list.getNodeName().equals("#text")) {
                                   if (list.getNodeName().equals("redirect")) {
                                        NodeList al = a.getChildNodes();
                                        for (int r = 0;
// and on and on and onOh my friggin lord. Time to refactor!

Similar Messages

  • Error: java.lang.ClassCastException: java.util.Arrays$ArrayList

    Hi,
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj;
    Please help how to solve this problem.
    Thanks,
    cmbl

    cmbl wrote:
    How to solve this error?
    I get the error at this line of code in my program.
    java.util.ArrayList list= (java.util.ArrayList)obj; Don't do this cast.
    Why are you doing this cast anyway? I think you need to show a small bit of compilable code (or almost compilable except perhaps for this error) and some more explanation.

  • Java.lang.ClassCastException

    My class CDRack is almost ready, but in the last method
    sortAlphabetically() there
    comes java.lang.ClassCastException. I found in the net
    http://java.sun.com/docs/books/tutorial/collections/algorithms/
    that with method Collections.sort(l) I can sort alphabetically.
    The code compiles, but when I run it with a tester program, it stops
    to ClassCastException in the almost last row.
    Something is wrong with Collections.sort(l) ?
    /** Class CDRack represents collections of compact discs. Discs are
    located in the rack in slots numbered from zero upwards. The discs are
    represented by Record objects and empty slots by null values. */
    public class CDRack extends Object {
      private Record[] mRecords;
      private int size;
    /**Creates a new, empty CD rack.
    Parameters:
    size - the size of the new rack, i.e. the number of slots it has */
          public CDRack(int size) {
              mRecords = new Record[size];
              this.size = size;
    /** "Organizes" the discs in the rack so that they will be located in
    consecutive slots starting at slot number zero, and any and all empty
    slots will be at the "end of the rack". After calling this method, the
    discs are in an undefined (i.e. arbitrary) order - the only thing this
    method guarantees is that there aren't any empty slots in between full
    ones.
          public void organize() {
              // Turn array into a list - more flexible
              List l = Arrays.asList(aanilevyt);
              // Remove all nulls from a copy of the list which supports  removal.
              l = new ArrayList(l);
              while (l.remove(null)) /*do nothing*/;
              // Clear the original array.
              for (int i = 0; i < mRecords.length; i++){
                   mRecords[i] = null;
              } // Put the non-nulls back.
              l.toArray(mRecords);
    /**"Organizes" the discs in the rack to the beginning of the rack (see
    the method organize) and sorts them in alphabetical order. Recordings
    by the same artist are placed in alphabetical order by disc name. */
        public void sortAlphabetically() {
              // Turn array into a list - more flexible
              List l = Arrays.asList(aanilevyt);
              // Remove all nulls from a copy of the list which supports  removal.
              l = new ArrayList(l);
              while (l.remove(null)) /*do nothing*/;
              // Clear the original array.
              for (int i = 0; i < mRecords.length; i++){
                   mRecords[i] = null;
              } // Put the non-nulls back.
              l.toArray(mRecords);
              Collections.sort(l);   // alphabetical order. THERE IS CLASSCASTEXCEPTION 
    }

    I have thought and thought but the sorting alphabetically doesnt work.
    I can't use Collections.sort and class Record doesnt implement Comparable(and I can't change it).
    One suggestion was that I could make my own class which implements Comparator. Could it be like this
    import java.util.*;
    public class AlphabeticComparator
    implements Comparator{
      public int compare(Object o1, Object o2) {
        String s1 = (String)o1;
        String s2 = (String)o2;
        return s1.toLowerCase().compareTo(
          s2.toLowerCase());
    }      But how an earth can I tell to CDRack class that it would
    use the class AlphabeticComparator?
    Somebody please save my Christmas!
    /** Class CDRack represents collections of compact discs. Discs are
    located in the rack in slots numbered from zero upwards. The discs are
    represented by Record objects and empty slots by null values. */
    public class CDRack extends Object {
      private Record[] mRecords;
      private int size;
    /**Creates a new, empty CD rack.
    Parameters:
    size - the size of the new rack, i.e. the number of slots it has */
          public CDRack(int size) {
              mRecords = new Record[size];
              this.size = size;
    /** "Organizes" the discs in the rack so that they will be located in
    consecutive slots starting at slot number zero, and any and all empty
    slots will be at the "end of the rack". After calling this method, the
    discs are in an undefined (i.e. arbitrary) order - the only thing this
    method guarantees is that there aren't any empty slots in between full
    ones.
          public void organize() {
              // Turn array into a list - more flexible
              List l = Arrays.asList(aanilevyt);
              // Remove all nulls from a copy of the list which supports  removal.
              l = new ArrayList(l);
              while (l.remove(null)) /*do nothing*/;
              // Clear the original array.
              for (int i = 0; i < mRecords.length; i++){
                   mRecords<i> = null;
              } // Put the non-nulls back.
              l.toArray(mRecords);
    /**"Organizes" the discs in the rack to the beginning of the rack (see
    the method organize) and sorts them in alphabetical order. Recordings
    by the same artist are placed in alphabetical order by disc name. */
        public void sortAlphabetically() {

  • Why do I get a ClassCastException?

    Hello!
    I'm playing around with hibernate, axis2 and Weblogic 8.1.6 and I got I really tricky problem.
    My Weblogic 8.1.6 got consist of 3 servers.
    1 Adminserver (myserver)
    1 Managedserver (ejbserver)
    1 Managedserver (webserviceserver)
    My play_around_example is built around a database called names in a mysql-databas.
    To access data I got a package called nameshibernate.jar, that works fine used from an standalone application called namesjavaapplication.jar.
    (namesjavaapplication->nameshibernate->database)
    I also got an ejb in a packaged called namesejb.jar that uses the nameshibernate.jar. The namesejb.jar is deployed under "Ejb Modules" and the target is "ejbserver". If I call the ejb from my standalone application called namesjavaapplication.jar it works fine.
    (namesjavaapplication->namesejb->nameshibernate->database)
    I also got an webserviceapplication that uses axis2 in a aar-file called nameswebservice.aar. This application uses the namesejb.jar. The Axis2-server is deployed in the server under "Web Application Modules" and the target is "webserviceserver". In this Axis2-server the nameswebservice.aar is deployed. This i supposed to work like:
    (namesjavaapplication->nameswebservice->namesejb->nameshibernate->database)
    If I call the webservice from my standalone application called namesjavaapplication.jar I get a calsscast exception:
    java.lang.ClassCastException: Cannot narrow remote object to namesejb.client.NameManagerEJBHome
    I really can not find out the problem since it works fine if I go directly to the ejb like:
    (namesjavaapplication->namesejb->nameshibernate->database)
    Below is the method inside my standalone application that calls the ejb directly.
    This is the code that works:
    (namesjavaapplication->namesejb->nameshibernate->database)
         public void getNamesEJB() throws Exception
              try
                   System.out.println("getNamesEJB start");
                   Context context = getWebLogicInitialContext();
                   Object object = context.lookup("namesejb/client/NameManagerEJBHome");
                   System.out.println("\t1: " + object.getClass().getName());
                   Class c = Class.forName("namesejb.client.NameManagerEJBHome");
                   System.out.println("\t2: " + c.getName());
                   System.out.println("\t3: " + NameManagerEJBHome.class.getName());
                   System.out.println("\t4: " + (object instanceof NameManagerEJBHome));
                   System.out.println("\tjava.class.version: " + System.getProperty("java.class.version"));
                   System.out.println("\tjava.class.path: " + System.getProperty("java.class.path"));
                   System.out.println("\tjava.library.path: " + System.getProperty("java.library.path"));
                   System.out.println("\tjava.compiler: " + System.getProperty("java.compiler"));
                   System.out.println("\tjava.ext.dirs: " + System.getProperty("java.ext.dirs"));
                   System.out.println("\tuser.dir: " + System.getProperty("user.dir"));
                   System.out.println("\tjava.home: " + System.getProperty("java.home"));
                   if(object instanceof namesejb.server.NameManagerSessionBean)
                        System.out.println("\t"+ ((namesejb.server.NameManagerSessionBean)object).getSerialVersionUID() );
                   else
                        System.out.println("\tNOT instanceof NameManagerSessionBean");
                   NameManagerEJBHome nameManagerEJBHome = (NameManagerEJBHome)PortableRemoteObject.narrow(object, NameManagerEJBHome.class);
                   NameManangerEJBObject nameManangerEJBObject = nameManagerEJBHome.create();
         String nameString = "";
                   List names = nameManangerEJBObject.getNames();
         for (int i = 0; i < names.size(); i++)
         Name theName = (Name) names.get(i);
         nameString = nameString + "\n" + theName.getName();
         textAreaEJB.setText(nameString);
              catch(RemoteException e)
                   e.printStackTrace();
              catch(NamingException e)
                   e.printStackTrace();
              catch(Exception e)
                   e.printStackTrace();
    From this I get this output:
    getNamesEJB start
    1: namesejb.server.NameManagerSessionBean_o0oo54_HomeImpl_816_WLStub
    2: namesejb.client.NameManagerEJBHome
    3: namesejb.client.NameManagerEJBHome
    4: true
    java.class.version: 50.0
    java.class.path: namesjavaapplication.jar
    java.library.path: /home/fredrik/Applications/Java/Java_ee_sdk_5-04/jd k/jre/lib/i386/server:/home/fredrik/Applications/Java/Java_ee_sdk_5-04 /jdk/jre/lib/i386:/home/fredrik/Applications/Java/Java_ee_sdk_5-04/jdk /jre/../lib/i386:/usr/java/packages/lib/i386:/lib:/usr/lib
    java.compiler: null
    java.ext.dirs: /home/fredrik/Applications/Java/Java_ee_sdk_5-04/jdk/jr e/lib/ext:/usr/java/packages/lib/ext
    user.dir: /home/fredrik/eclipse_workspace/namesjavaapplication
    java.home: /home/fredrik/Applications/Java/Java_ee_sdk_5-04/jdk/jre
    NOT instanceof NameManagerSessionBean
    Below is my methods inside the ejb:
         public void ejbCreate()
              try
                   Class c = Class.forName("namesejb.client.NameManagerEJBHome");
                   System.out.println("1: " + c.getName());
                   System.out.println("2: " + NameManagerEJBHome.class.getName());
                   System.out.println("java.class.version: " + System.getProperty("java.class.version"));
                   System.out.println("java.class.path: " + System.getProperty("java.class.path"));
                   System.out.println("java.library.path: " + System.getProperty("java.library.path"));
                   System.out.println("java.compiler: " + System.getProperty("java.compiler"));
                   System.out.println("java.ext.dirs: " + System.getProperty("java.ext.dirs"));
                   System.out.println("user.dir: " + System.getProperty("user.dir"));
              catch(Exception e)
                   System.out.println(e.getMessage());
                   e.printStackTrace();
         public ArrayList getNames() throws Exception {
              Class c = Class.forName("namesejb.client.NameManagerEJBHome");
              System.out.println("4 " + c.getName());
              NameManager nameManager = new NameManager();
              return nameManager.getNames();
    From these methods I get this output from the ejbserver:
    1: namesejb.client.NameManagerEJBHome
    2: namesejb.client.NameManagerEJBHome
    java.class.version: 48.0
    java.class.path:/home/fredrik/Applications/bea/jrockit81sp6_142_10/lib/tools.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/weblogic_sp.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/weblogic.jar::/home/fredrik/Applications/bea/weblogic81/common/eval/pointbase/lib/pbserver44.jar:/home/fredrik/Applications/bea/weblogic81/common/eval/pointbase/lib/pbclient44.jar:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/rt.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/webservices.jr:
    java.library.path:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/i386/jrockit:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/i386:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/../lib/i386:/home/fredrik/Applications/bea/weblogic81/server/lib/linux/i686:/home/fredrik/Applications/bea/weblogic81/server/lib/linux/i686/oci920_8
    java.compiler: null
    java.ext.dirs: /home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/ext
    user.dir: /home/fredrik/Applications/bea/user_projects/domains/mydomain
    4 namesejb.client.NameManagerEJBHome
    THIS WORKS FINE
    Below is the method inside my webservice that calls the ejb directly.
    This is the code that throws the Exception:
    (namesjavaapplication->nameswebservice->namesejb->nameshibernate->database)
         public String getNamesWSEJB() throws Exception
              String errorMessage = "Error: ";
              try
                   System.out.println("getNamesWSEJB start");
                   Context context = getWebLogicInitialContext();
                   Object object = context.lookup("namesejb/client/NameManagerEJBHome");
                   System.out.println("\t1: " + object.getClass().getName());
                   Class c = Class.forName("namesejb.client.NameManagerEJBHome");
                   System.out.println("\t2: " + c.getName());
                   System.out.println("\t3: " + NameManagerEJBHome.class.getName());
                   System.out.println("\t4: " + (object instanceof NameManagerEJBHome));
                   System.out.println("\tjava.class.version: " + System.getProperty("java.class.version"));
                   System.out.println("\tjava.class.path: " + System.getProperty("java.class.path"));
                   System.out.println("\tjava.library.path: " + System.getProperty("java.library.path"));
                   System.out.println("\tjava.compiler: " + System.getProperty("java.compiler"));
                   System.out.println("\tjava.ext.dirs: " + System.getProperty("java.ext.dirs"));
                   System.out.println("\tuser.dir: " + System.getProperty("user.dir"));
                   System.out.println("java.home: " + System.getProperty("java.home"));
                   if(object instanceof namesejb.server.NameManagerSessionBean)
                        System.out.println("\t"+ ((namesejb.server.NameManagerSessionBean)object).getSerialVersionUID() );
                   else
                        System.out.println("\tNOT instanceof NameManagerSessionBean");
                   NameManagerEJBHome nameManagerEJBHome = (NameManagerEJBHome)PortableRemoteObject.narrow(object, NameManagerEJBHome.class);
                   NameManangerEJBObject nameManangerEJBObject = nameManagerEJBHome.create();
         String nameString = "";
                   List names = nameManangerEJBObject.getNames();
                   for (int i = 0; i < names.size(); i++)
                        Name theName = (Name) names.get(i);
                        nameString = nameString + "\n" + theName.getName();
                   return nameString;
              catch(RemoteException e)
                   errorMessage = errorMessage + e.getMessage();
                   e.printStackTrace();
              catch(NamingException e)
                   errorMessage = errorMessage + e.getMessage();
                   e.printStackTrace();
              catch(Exception e)
                   errorMessage = errorMessage + e.getMessage();
                   e.printStackTrace();
              return errorMessage;
    1: namesejb.server.NameManagerSessionBean_o0oo54_HomeImpl_816_WLStub
    2: namesejb.client.NameManagerEJBHome
    3: namesejb.client.NameManagerEJBHome
    4: false
    java.class.version: 48.0
    java.class.path:/home/fredrik/Applications/axis2-1.3/lib/jalopy-1.5rc3.jar:/home/fredrik/Applications/bea/jrockit81sp6_142_10/lib/tools.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/weblogic_sp.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/weblogic.jar::/home/fredrik/Applications/bea/weblogic81/common/eval/pointbase/lib/pbserver44.jar:/home/fredrik/Applications/bea/weblogic81/common/eval/pointbase/lib/pbclient44.jar:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/rt.jar:/home/fredrik/Applications/bea/weblogic81/server/lib/webservices.jar:
    java.library.path: /home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/i386/jrockit:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/i386:/home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/../lib/i386:/home/fredrik/Applications/bea/weblogic81/server/lib/linux/i686:/home/fredrik/Applications/bea/weblogic81/server/lib/linux/i686/oci920_8
    java.compiler: null
    java.ext.dirs: /home/fredrik/Applications/bea/jrockit81sp6_142_10/jre/lib/ext
    user.dir: /home/fredrik/Applications/bea/user_projects/domains/mydomain
         NOT instanceof NameManagerSessionBean
    java.lang.ClassCastException: Cannot narrow remote object to namesejb.client.NameManagerEJBHome
    at weblogic.iiop.PortableRemoteObjectDelegateImpl.narrow(PortableRemoteObjectDelegateImpl.java:242)
    at javax.rmi.PortableRemoteObject.narrow(PortableRemoteObject.java:134)
    at nameswebservices.NamesWebService.getNamesWSEJB(NamesWebService.java:49)
    at jrockit.reflect.VirtualNativeMethodInvoker.invoke(Ljava.lang.Object;[Ljava.lang.Object;)Ljava.lang.Object;(Unknown Source)
            at java.lang.reflect.Method.invoke(Ljava.lang.Object;[Ljava.lang.Object;I)Ljava.lang.Object;(Unknown Source)
            at org.apache.axis2.rpc.receivers.RPCUtil.invokeServiceClass(RPCUtil.java:165)
            at org.apache.axis2.rpc.receivers.RPCMessageReceiver.invokeBusinessLogic(RPCMessageReceiver.java:98)
            at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:40)
            at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:96)
            at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:145)
            at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275)
            at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:120)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
            at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:1077)
            at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:465)
            at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:348)
            at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:7047)
            at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
            at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
            at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3902)
            at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2773)
            at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:224)
            at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:183)
    I really can not find out what might be the problem since it works to call tje ejb from a standalone application.
    The "same" code executed from a webservice throws the exception.
    One strange thing that I notice is that from the standalone the java.class.version gets 50.0 and from the webserver it gets 48.0 But the standalone uses 1.6 when I run it and the Weblogic uses 1.4. (I do not think that weblogic can run with 1.6)
    Pretty long thread but I hope for some mercy!
    Best regards
    Fredrik                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hello Thok, this code is from a quistion in a studybook for preparation of the SCJP 5.0 exam.
    When i compile i get this warning:
    Shapes.java:13: warning: [unchecked] unchecked cast
    found   : java.util.ArrayList
    required: java.util.ArrayList<generics.Rectangle>
            ArrayList <Rectangle> c = (ArrayList<Rectangle>) b;
                                                             ^
    1 warningWhen running this line causes an exception:
                for ( Rectangle o : c){My questions are
    How do i re-write the code so that i will get an warning and exception free program?
    Tnx Auke

  • A problem with ArrayLists

    Hello
    I'm pretty new to Java, and sometimes all those objects, instances, classes, data types etc confuse me. I'm having some kind of a problem with ArrayLists (tried with vectors too, didn't work) . I'm writing a program which takes float numbers from user input and does stuff to them. No syntax error in my code, but I get a java.lang.ClassCastException when I run it.
    I insert stuff to the ArrayList like this:
    luku.add(new Float(syotettyLuku));no problem
    I'm trying to access information from the list like this inside a while loop
    float lukui = new Float((String)luku.get(i)) .floatValue();but the exception comes when the programme hits that line, no matter which value i has.
    Tried this too, said that types are incompatible:
    float lukui = ((float)luku.get(i)) .floatValue();What am I doing wrong? I couldn't find any good tutorials about using lists, so i'm really lost here.
    I'll post the whole code here, if it helps. Sorry about the Finnish variable and method names, but you get the idea :)
    package esa;
    import java.io.*;
    import java.util.*;
    public class Esa {
    static final int maxLukuja = 100;
    static BufferedReader syote = new BufferedReader(new InputStreamReader(System.in));
    static String rivi;
    static String lopetuskasky = "exit";
    static double keskiarvo;
    static ArrayList luku = new ArrayList();
    static int lukuja;
    static float summa = 0;
    // M��ritell��n pari metodia, joiden avulla voidaan tarkastaa onko tarkasteltava muuttuja liukuluku
    static Float formatFloat(String rivi) {
        if (rivi == null) {
            return null;
        try {
            return new Float(rivi);
        catch(NumberFormatException e) {
            return null;
    static boolean isFloat(String rivi) {
        return (formatFloat(rivi) != null);
    // Luetaan luvut k�ytt�j�lt� ja tallnnetaan ne luku-taulukkoon
    static void lueLuvut() throws IOException{
        int i = 0;
        float syotettyLuku;
        while(i < maxLukuja) {
            System.out.println("Anna luku kerrallaan ja paina enter. Kun halaut lopettaa, n�pp�ile exit");
            rivi = syote.readLine();
            boolean onkoLiukuluku = isFloat(rivi);
            if (onkoLiukuluku) {
                syotettyLuku = Float.parseFloat(rivi);
                if (syotettyLuku == 0) {
                    lukuja = luku.size();              
                    break;
                }  // if syotettyluku
                else {
                    luku.add(new Float(syotettyLuku));
                    i++;
                } // else
            } // if onkoLiukuluku
            else {
               System.out.println("Antamasi luku ei ole oikeaa muotoa, yrit� uudelleen.");
               System.out.println("");
            } // else
        } // while i < maxlukuja
    // lueLuvut
    static void laskeKeskiarvo() {
        int i = 0;
        while(i < lukuja) {
            float lukui = ((float)luku.get(i)) .floatValue();
            System.out.println(lukui);
            summa = summa + lukui;
        }   i++;
        keskiarvo = (summa / lukuja);
    } // laskeKeskiarvo
    public static void main(String args[]) throws IOException {
    lueLuvut();
    laskeKeskiarvo();
    } // main
    } // class

    Thanks! Now it's functioning.
    As I mentioned, I tried this:
    float lukui = ((float)luku.get(i))
    .floatValue();And your reply was:
    float lukui =
    ((Float)luku.get(i)).floatValue So the problem really was the spelling, it should
    have been Float with a capital F.
    From what I understand, Float refers to the Float
    class, Correct. And float refers to the float primitive type. Objects and primitives are not interchangeable. You need to take explicit steps to convert between them. Although, in 1.5/5.0, autoboxing/unboxing hide some of this for you.
    so why isn't just a regular float datatype
    doing the job here, like with the variable lukui?Not entirely sure what you're asking.
    Collections take objects, not primitives, and since you put an object in, you get an object out. You then have to take the extra step to get a primitive representation of that object. You can't just cast between objects and primitives.
    Again, autoboxing will relieve some of this drudgery. I haven't used it myself yet, so I can't comment on how good or bad it is.

  • [svn] 949: Bug: BLZ-96 - When sending a HttpService request from ActionScript with multiple headers with the same name , it causes a ClassCastException in the server

    Revision: 949
    Author: [email protected]
    Date: 2008-03-27 07:12:59 -0700 (Thu, 27 Mar 2008)
    Log Message:
    Bug: BLZ-96 - When sending a HttpService request from ActionScript with multiple headers with the same name, it causes a ClassCastException in the server
    QA: Yes - try again with legacy-collection true and false.
    Doc: No
    Checkintests: Pass
    Details: Another try in fixing this bug. When legacy-collection is false, Actionscript Array on the client becomes Java Array on the server and my fix yesterday assumed this case. However, when legacy-collection is true, Actionscript Array becomes Java ArrayList on the server. So added code to handle this case.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/BLZ-96
    Modified Paths:
    blazeds/branches/3.0.x/modules/proxy/src/java/flex/messaging/services/http/proxy/RequestF ilter.java

    Hi all!
    Just to post the solution to this if anyone ever runs accross this thread...
    For some reason i had it bad the first time, don't have time right now to see why but here is what worked for me:
    HashMap primaryFile = new HashMap();
    primaryFile.put("fileContent", bFile);
    primaryFile.put("fileName", uploadedFile.getFilename());
    operationBinding.getParamsMap().put("primaryFile", primaryFile);
    HashMap customDocMetadata = new HashMap();
    HashMap [] properties = new HashMap[1];
    HashMap customMetadataPropertyRoom = new HashMap();
    customMetadataPropertyRoom.put("name", "xRoom");
    customMetadataPropertyRoom.put("value", "SOME ROOM");
    properties[0] = customMetadataPropertyRoom;
    customDocMetadata.put("property", properties);
    operationBinding.getParamsMap().put("CustomDocMetaData", customDocMetadata);
    Basically an unbounded wsdl type is an array of objects (HashMaps), makes sense, i thought i had it like this before, must have messed up somewhere...
    Good luck all!

  • ClassCastException error problem

    Hi all,
    I am relatively new to java and confused with the following problem. The below code compilers but returns a ClassCastException error when run.
    private List<TableOne> query = new ArrayList<TableOne>();
           private TableTwo tableTwo;
    //create an array of values
            for (Double value : array) {
              query = ..result from sql query (needs to be list using hibernate)
             for (TableOne queryValue :  query ) {
             //something
    public List<TableOne> getTableOne() {
            return query;
        public List getQuery()
            return this.Query;
               The ClassCastException error occurs on the second for loop? Is this because the wo objects are not of the same type? Any suggetions would be great, thanks in advance

    Hi,
    look, List<TableOne> should mean that You have a list of TableOne objects. It seems like logic mistake. In addition, You are already have instance of query why do You need to assign it once more?
    Now about ex. You sayed it is in the second loop and put almost nothing there. It seems like You have a mistake in //something ;)

  • Problem in calling arraylist from client

    Hi
    I am trying to execute a webservice program and facing some problems in the
    client side ,am trying to pass arraylist from client in weblogic8.1
    this is my client code and the error i am getting on the serverside all the files
    are getting generated properly,am i missing something.
    i have webserviceclient.jar in the classpath also,
    package examples.webservices.basic.statelessSession;
    import weblogic.utils.Debug;
    import java.util.ArrayList;
    import java.util.Collection;
    import javax.xml.soap.SOAPConstants;
    import javax.xml.namespace.QName;
    import javax.xml.rpc.Service;
    import javax.xml.rpc.encoding.TypeMapping;
    import javax.xml.rpc.encoding.TypeMappingRegistry;
    import weblogic.xml.schema.binding.internal.builtin.JavaUtilArrayListCodec;
    import weblogic.xml.schema.binding.internal.builtin.JavaUtilCollectionCodec;
    public final class Client {
    private final static boolean debug = true;
    private final static boolean verbose = true;
    public Client() {}
    public static void main(String[] argv)
    throws Exception
    HelloWorldEJB_Impl ws = new HelloWorldEJB_Impl(argv[0]);
    HelloWorldEJBPort port = ws.getHelloWorldEJBPort();
    TypeMappingRegistry registry = ((Service)port).getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
    mapping.register(
    ArrayList.class,
    new QName("java:language_builtins.util", "ArrayList"),
    new JavaUtilArrayListCodec(),
    new JavaUtilArrayListCodec()
    mapping.register(
    Collection.class,
    new QName("java:language_builtins.util", "Collection"),
    new JavaUtilCollectionCodec(),
    new JavaUtilCollectionCodec()
    ArrayList arrList = new ArrayList(1);
    arrList.add("ccc");
    arrList.add("bbb");
    port.sayHelloList(arrList);
    The error i am getting while compiling with ant is
    [javac] C:\bea\weblogic81\samples\server\examples\src\examples\webservices\b
    asic\statelessSession\Client.java:92: sayHelloList(java.lang.Object[]) in exampl
    es.webservices.basic.statelessSession.HelloWorldEJBPort cannot be applied to (ja
    va.util.ArrayList)
    [javac] port.sayHelloList(arrList);
    [javac] ^
    [javac] 1 error
    Kindly reply at the soonest
    Sindhu

    Hi
    I tried object[] that was working fine but the requirement for the project
    is that we should use arraylists.i found a solution like i overwrote the xml in
    client.jar but again looks like i have to regenrate the stubs.
    Is there any way to regenerate except using the clientgen
    this time i got
    run:
    [java] java.rmi.RemoteException: null; nested exception is:
    [java] java.lang.ClassCastException
    [java] at examples.webservices.basic.statelessSession.HelloWorldEJBPort
    Stub.sayHelloList(HelloWorldEJBPortStub.java:32)
    [java] at examples.webservices.basic.statelessSession.Client.main(Clien
    t.java:75)
    [java] Caused by: java.lang.ClassCastException
    [java] at weblogic.xml.schema.binding.internal.builtin.JavaUtilCollecti
    onCodec.serializeOneDimArray(JavaUtilCollectionCodec.java:90)
    [java] at weblogic.xml.schema.binding.SoapArrayCodecBase.gatherContents
    (SoapArrayCodecBase.java:442)
    [java] at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase
    .java:279)
    [java] at weblogic.xml.schema.binding.CodecBase.serialize_internal(Code
    cBase.java:216)
    [java] at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.jav
    a:178)
    [java] at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(Ru
    ntimeUtils.java:188)
    [java] at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(Ru
    ntimeUtils.java:174)
    [java] at weblogic.webservice.core.DefaultPart.invokeSerializer(Default
    Part.java:324)
    [java] at weblogic.webservice.core.DefaultPart.toXML(DefaultPart.java:2
    97)
    [java] at weblogic.webservice.core.DefaultMessage.toXML(DefaultMessage.
    java:619)
    [java] at weblogic.webservice.core.ClientDispatcher.send(ClientDispatch
    er.java:206)
    [java] at weblogic.webservice.core.ClientDispatcher.dispatch(ClientDisp
    atcher.java:143)
    [java] at weblogic.webservice.core.DefaultOperation.invoke(DefaultOpera
    tion.java:444)
    [java] at weblogic.webservice.core.DefaultOperation.invoke(DefaultOpera
    tion.java:430)
    [java] at weblogic.webservice.core.rpc.StubImpl._invoke(StubImpl.java:2
    70)
    [java] at examples.webservices.basic.statelessSession.HelloWorldEJBPort
    Stub.sayHelloList(HelloWorldEJBPortStub.java:26)
    and my xml i changed this way
    <wsdd:type-mapping xmlns:wsdd="http://www.bea.com/servers/wls70"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">
    <wsdd:type-mapping-entry xmlns:p1="java:language_builtins.util"
    type="p1:ArrayList"
    class-name="java.util.ArrayList"
    serializer="weblogic.xml.schema.binding.internal.builtin.JavaUtilArrayListCodec"
    deserializer="weblogic.xml.schema.binding.internal.builtin.JavaUtilArrayListCodec">
    </wsdd:type-mapping-entry>
    </wsdd:type-mapping>
    Sindhu
    "jas" <[email protected]> wrote:
    >
    If you haven't already ... please see the thread below .. This might
    be of sokme
    use
    http://newsgroups.bea.com/cgi-bin/dnewsweb?cmd=article&group=weblogic.developer.interest.webservices&item=4378&utag=
    cheers
    jas
    "sindhu" <[email protected]> wrote:
    Hi
    I am trying to execute a webservice program and facing some problems
    in the
    client side ,am trying to pass arraylist from client in weblogic8.1
    this is my client code and the error i am getting on the serversideall
    the files
    are getting generated properly,am i missing something.
    i have webserviceclient.jar in the classpath also,
    package examples.webservices.basic.statelessSession;
    import weblogic.utils.Debug;
    import java.util.ArrayList;
    import java.util.Collection;
    import javax.xml.soap.SOAPConstants;
    import javax.xml.namespace.QName;
    import javax.xml.rpc.Service;
    import javax.xml.rpc.encoding.TypeMapping;
    import javax.xml.rpc.encoding.TypeMappingRegistry;
    import weblogic.xml.schema.binding.internal.builtin.JavaUtilArrayListCodec;
    import weblogic.xml.schema.binding.internal.builtin.JavaUtilCollectionCodec;
    public final class Client {
    private final static boolean debug = true;
    private final static boolean verbose = true;
    public Client() {}
    public static void main(String[] argv)
    throws Exception
    HelloWorldEJB_Impl ws = new HelloWorldEJB_Impl(argv[0]);
    HelloWorldEJBPort port = ws.getHelloWorldEJBPort();
    TypeMappingRegistry registry = ((Service)port).getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping(SOAPConstants.URI_NS_SOAP_ENCODING
    mapping.register(
    ArrayList.class,
    new QName("java:language_builtins.util", "ArrayList"),
    new JavaUtilArrayListCodec(),
    new JavaUtilArrayListCodec()
    mapping.register(
    Collection.class,
    new QName("java:language_builtins.util", "Collection"),
    new JavaUtilCollectionCodec(),
    new JavaUtilCollectionCodec()
    ArrayList arrList = new ArrayList(1);
    arrList.add("ccc");
    arrList.add("bbb");
    port.sayHelloList(arrList);
    The error i am getting while compiling with ant is
    [javac] C:\bea\weblogic81\samples\server\examples\src\examples\webservices\b
    asic\statelessSession\Client.java:92: sayHelloList(java.lang.Object[])
    in exampl
    es.webservices.basic.statelessSession.HelloWorldEJBPort cannot be applied
    to (ja
    va.util.ArrayList)
    [javac] port.sayHelloList(arrList);
    [javac] ^
    [javac] 1 error
    Kindly reply at the soonest
    Sindhu

  • Error processing WSDL document: java.lang.ClassCastException: java.util.Ar

    Hi
    Program is giving unpredictable behaviour.
    Am trying to consume webservice using Axis Client.
    When running as stand alone Java programs its working fine.
    But when deployed on OC4J its giving problem
    Error processing WSDL document: java.lang.ClassCastException: java.util.ArrayList
    Could you please give some hint
    Regards
    Bajarang

    Here is the program
    QName serviceQN = new QName(targetNamespace,serviceName );
    System.out.println("After serviceQN "+ serviceQN);
    QName portQN = new QName( targetNamespace, portName );
    System.out.println("After port "+ portQN);
    // This Call object will be used the invocation
    Service service = new Service(implURI,serviceQN);
    System.out.println("After service "+ service);
    Call call = (Call) service.createCall();
    System.out.println("After call "+ call);
    // Now make the call...
    System.out.println("Invoking service>> " + serviceName + " <<...");
    call.setOperation(portQN,operationName);
    call.invoke( inputParams );
    System.out.println("Result returned from call to "+ serviceName+" ");
    Error while execution
    javax.xml.rpc.ServiceException: Error processing WSDL document:
    java.lang.ClassCastException: java.util.ArrayList

  • ClassCastException in InvocableMap.ParallelAwareAggregator

    I am using InvocableMap.ParallelAwareAggregator to sort results set on cache server side. But I'm keep getting ClassCastException like below :
    2008-02-14 17:33:28.603 Oracle Coherence DC 3.3.1/389p1 <Info> (thread=main, member=n/a): Connected to 10.5.235.162:9096
    Exception in thread "main" com.tangosol.io.pof.PortableException (Remote: An exception occurred while processing a AggregateFilterRequest) (Wrapped: Failed request execution for DistributedService service on Member(Id=10, Timestamp=2008-02-14 17:21:38.86, Address=10.5.235.162:8089, MachineId=58530, Location=machine:docqa4,member:dvCache2)) java.lang.ClassCastException
    at com.docview.test.SortByServerAggregator$SortingParallelAggregator.sortByDate(SortByServerAggregator.java:188)
    at com.docview.test.SortByServerAggregator$SortingParallelAggregator.sortEntries(SortByServerAggregator.java:151)
    at com.docview.test.SortByServerAggregator$SortingParallelAggregator.aggregate(SortByServerAggregator.java:133)
    at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache.onAggregateFilterRequest(DistributedCache.CDB:74)
    at com.tangosol.coherence.component.util.daemon.queueProcessor.service.DistributedCache$AggregateFilterRequest.run(DistributedCache.CDB:1)
    at com.tangosol.coherence.component.util.DaemonPool$WrapperTask.run(DaemonPool.CDB:24)
    at com.tangosol.coherence.component.util.DaemonPool$Daemon.onNotify(DaemonPool.CDB:49)
    at com.tangosol.coherence.component.util.Daemon.run(Daemon.CDB:35)
    at java.lang.Thread.run(Thread.java:534)
    Any ideas ? I can see the messages in cache server logs which indicate the sorting is done and size of sorted entries on each cache server instance. But if trying to print out each entry, I will get ClassCastException.
    Attached please see my codes as below :
    ==================================================
    import java.io.DataInput;
    import java.io.DataOutput;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    import java.util.Set;
    import java.util.List;
    import java.util.TreeSet;
    import java.util.HashSet;
    import java.util.ArrayList;
    import com.tangosol.io.ExternalizableLite;
    import com.tangosol.util.ExternalizableHelper;
    import com.tangosol.util.InvocableMap;
    import com.tangosol.util.ValueExtractor;
    import com.tangosol.util.InvocableMap.Entry;
    import com.tangosol.util.InvocableMap.EntryAggregator;
    import com.tangosol.util.InvocableMap.ParallelAwareAggregator;
    import com.tangosol.util.extractor.ReflectionExtractor;
    import com.docview.query.Cache_Query_Constants;
    import com.docview.util.SortUtils;
    import com.docview.cache.MultiTagPubSearchCacheKey;
    import com.docview.entity.MultiTagPubSearchCacheEntity;
    public class SortByServerAggregator implements ParallelAwareAggregator, ExternalizableLite {
         private String sortFlag;
         private String ascDescFlag;
         public SortByServerAggregator(String sortFlag, String ascDescFlag) {
              this.sortFlag = sortFlag;
              this.ascDescFlag = ascDescFlag;
         public SortByServerAggregator() {
              super();
         public Object aggregate(Set entries) {
              return new SortingParallelAggregator(sortFlag, ascDescFlag).aggregate(entries);
         public Object aggregateResults(Collection resultObjects) {
              return mergeMultipleResults(resultObjects);
         public EntryAggregator getParallelAggregator() {
              return new SortingParallelAggregator(sortFlag, ascDescFlag);
         public void readExternal(DataInput input) throws IOException {
              sortFlag = ExternalizableHelper.readSafeUTF(input);
              ascDescFlag = ExternalizableHelper.readSafeUTF(input);
         public void writeExternal(DataOutput output) throws IOException {
              ExternalizableHelper.writeSafeUTF(output, sortFlag);
              ExternalizableHelper.writeSafeUTF(output, ascDescFlag);
         private List mergeMultipleResults(Collection resultObjects) {
              ArrayList list = new ArrayList();
              Iterator iter = resultObjects.iterator();
              while (iter.hasNext()) {
                   ParallelResultObject result = (ParallelResultObject)iter.next();
                   list.addAll(result.generateResultList());
              return list;
         public static class ParallelResultObject implements ExternalizableLite {
              private MultiTagPubSearchCacheEntity[] entries;
              public ParallelResultObject() {}
              public ParallelResultObject(MultiTagPubSearchCacheEntity[] entries) {
                   this.entries = entries;
              public List generateResultList() {
                   ArrayList l = new ArrayList();
                   for(int i=0;i<entries.length;i++) {
                        l.add(entries);
                   return l;
              public void readExternal(DataInput input) throws IOException {
                   int numEntries = ExternalizableHelper.readInt(input);
                   if(numEntries >0) {
                        entries = new MultiTagPubSearchCacheEntity[numEntries];
                        for(int i=0;i<numEntries;i++) {
                             entries[i] = (MultiTagPubSearchCacheEntity)ExternalizableHelper.readObject(input);     
              public void writeExternal(DataOutput output) throws IOException {
                   int numEntries = entries.length;
                   if(numEntries >0) {
                        ExternalizableHelper.writeInt(output, numEntries);
                        for(int i=0;i<numEntries;i++) {
                             ExternalizableHelper.writeObject(output, entries[i]);     
         public static class SortingParallelAggregator implements ExternalizableLite, EntryAggregator {
              private String sortFlag;
              private String ascDescFlag;
              public SortingParallelAggregator() {
                   super();
              public SortingParallelAggregator(String sortFlag, String ascDescFlag) {
                   super();
                   this.sortFlag = sortFlag;
                   this.ascDescFlag = ascDescFlag;
              public Object aggregate(Set entries) {
                   return sortEntries(entries, sortFlag, ascDescFlag);
              public void readExternal(DataInput input) throws IOException {
                   sortFlag = ExternalizableHelper.readSafeUTF(input);
                   ascDescFlag = ExternalizableHelper.readSafeUTF(input);
              public void writeExternal(DataOutput output) throws IOException {
                   ExternalizableHelper.writeSafeUTF(output, sortFlag);
                   ExternalizableHelper.writeSafeUTF(output, ascDescFlag);
              private ParallelResultObject sortEntries(Set entries, String sortFlag, String ascDescFlag) {
                   ArrayList sortedList;
                   ArrayList arrayList = new ArrayList(entries);     
                   if ( sortFlag != null && !"".equals(sortFlag.trim()) ) {
         if ( Cache_Query_Constants.DATE_SORT_FLAG.equals(sortFlag.trim().toUpperCase()) ) {
                             sortedList = sortByDate(arrayList, ascDescFlag);
         } else {
         sortedList = arrayList;
         } else {
         sortedList = arrayList;
                   return new ParallelResultObject(convertListToArray(sortedList));
              private ArrayList sortByDate(ArrayList arrayList, String ascDescFlag) {
                   if("DESC".equals(ascDescFlag.trim().toUpperCase())) {
                        System.out.println("Start sort by DATE DESC");
                        Collections.sort(arrayList, new Comparator() {
                             public int compare(Object o1, Object o2) {
                                  int rc = 0;
                                  if((o1 instanceof MultiTagPubSearchCacheEntity) && (o2 instanceof MultiTagPubSearchCacheEntity))
                                       System.out.println("Sorting by MultiTagPubSearchCacheEntity ...");
                                       MultiTagPubSearchCacheEntity p1 = (MultiTagPubSearchCacheEntity) o1;
                                       MultiTagPubSearchCacheEntity p2 = (MultiTagPubSearchCacheEntity) o2;
                                       rc = p1.getPub_Date() - p2.getPub_Date();
                                       if ( rc == 0 ) {
                                            rc = p2.getTitle().compareTo(p1.getTitle());
                                  return rc;
                        Collections.reverse(arrayList);
                        System.out.println("Done sort by DATE DESC");
                   System.out.println("Size of sorted result : " + arrayList.size());
                   Iterator iter = arrayList.iterator();
                   while(iter.hasNext()) {
         MultiTagPubSearchCacheEntity e = (MultiTagPubSearchCacheEntity)iter.next();
         System.out.println("### Sorted Entries : " + e.toString());
                   return arrayList;
              private MultiTagPubSearchCacheEntity[] convertListToArray(ArrayList sortedList) {
                   MultiTagPubSearchCacheEntity[] entries = new MultiTagPubSearchCacheEntity[sortedList.size()];
                   Iterator iter = sortedList.iterator();
                   int idx = 0;
                   while(iter.hasNext()) {
                        entries[idx] = (MultiTagPubSearchCacheEntity)iter.next();     
                        idx++;
                   return entries;
    ==================================================
    Thanks,
    Bing

    Hi, Gene
    I'm getting another ClassCastException during the client call as below :
    public class SortByServerFactory
            // sortFlag
            public static MultiTagPubSearchCacheEntity[] filterAndSortByServer(String cacheName, String sortFlag, String ascDescFlag, Filter filter)
                    InvocableMap cache = CacheFactory.getCache(cacheName);
                    return (MultiTagPubSearchCacheEntity[])cache.aggregate(filter, new SortByServerAggregator(sortFlag, ascDescFlag));
    }2008-02-15 15:11:41.850 Oracle Coherence DC 3.3.1/389p1 <Info> (thread=main, member=n/a): Connected to 10.56.32.91:9098
    Exception in thread "main" java.lang.ClassCastException
    at com.docview.test.SortByServerFactory.filterAndSortByServer(SortByServerFactory.java:16)
    at com.docview.test.TestRegSectorAnalystCacheQueryInvocationSVC.main(TestRegSectorAnalystCacheQueryInvocationSVC.java:83)
    Attached please find my updated "SortByServerAggregator" class also :
    The method "aggregateResults(Collection resultObjects)" within SortByServerAggregator class will return "MultiTagPubSearchCacheEntity[]"
    Would you please help me to point out where is problem ?
    Maybe I'm still not fully understand how ParallelAwareAggregator works, and what should be done for aggregate(Set entries), aggregateResults(Collection resultObjects) and getParallelAggregator() .
    Many thanks for your help.
    Bing
    =========================================================
    public class SortByServerAggregator implements ParallelAwareAggregator, ExternalizableLite {
         private String sortFlag;
         private String ascDescFlag;
         public SortByServerAggregator(String sortFlag, String ascDescFlag) {
              this.sortFlag = sortFlag;
              this.ascDescFlag = ascDescFlag;
         public SortByServerAggregator() {
              super();
         public Object aggregate(Set entries) {
              return new SortingParallelAggregator(sortFlag, ascDescFlag).aggregate(entries);
         public Object aggregateResults(Collection resultObjects) {
              return mergeMultipleResults(resultObjects);
         public EntryAggregator getParallelAggregator() {
              return new SortingParallelAggregator(sortFlag, ascDescFlag);
         public void readExternal(DataInput input) throws IOException {
              sortFlag = ExternalizableHelper.readSafeUTF(input);
              ascDescFlag = ExternalizableHelper.readSafeUTF(input);
         public void writeExternal(DataOutput output) throws IOException {
              ExternalizableHelper.writeSafeUTF(output, sortFlag);
              ExternalizableHelper.writeSafeUTF(output, ascDescFlag);
         private MultiTagPubSearchCacheEntity[] mergeMultipleResults(Collection resultObjects) {
              HashSet tmpSet = new HashSet();
              Iterator iter = resultObjects.iterator();
              while (iter.hasNext()) {
                   ParallelResultObject result = (ParallelResultObject)iter.next();
                   int numEntries = result.getNumEntries();
                   if(numEntries > 0) {
                        MultiTagPubSearchCacheEntity[] entries = result.getEntries();
                        for(int i=0;i<numEntries;i++) {
                             tmpSet.add(entries);     
              return toEntityArray(tmpSet);
         private MultiTagPubSearchCacheEntity[] toEntityArray(HashSet s) {
              MultiTagPubSearchCacheEntity[] entries = new MultiTagPubSearchCacheEntity[s.size()];
              int idx = 0;
              Iterator iter = s.iterator();
              while (iter.hasNext()) {
                   MultiTagPubSearchCacheEntity e = (MultiTagPubSearchCacheEntity)iter.next();
                   entries[idx] = e;
                   idx++;
              return entries;
         public static class ParallelResultObject implements ExternalizableLite {
              private MultiTagPubSearchCacheEntity[] entries;
              private int numEntries;
              public ParallelResultObject() {}
              public ParallelResultObject(MultiTagPubSearchCacheEntity[] entries, int numEntries) {
                   this.entries = entries;
                   this.numEntries = numEntries;
              public List generateResultList() {
                   ArrayList l = new ArrayList();
                   if(entries != null) {
                        for(int i=0;i<entries.length;i++) {
                             l.add(entries[i]);
                   return l;
              public MultiTagPubSearchCacheEntity[] getEntries() {
                   return entries;
              public int getNumEntries() {
                   return numEntries;
              public void readExternal(DataInput input) throws IOException {
                   int numEntries = ExternalizableHelper.readInt(input);
                   if(numEntries >0) {
                        MultiTagPubSearchCacheEntity[] entries = new MultiTagPubSearchCacheEntity[numEntries];
                        for(int i=0;i<numEntries;i++) {
                             entries[i] = (MultiTagPubSearchCacheEntity)ExternalizableHelper.readObject(input);     
                   this.entries = entries;
              public void writeExternal(DataOutput output) throws IOException {
                   if(numEntries >0) {
                        ExternalizableHelper.writeInt(output, numEntries);
                        for(int i=0;i<numEntries;i++) {
                             ExternalizableHelper.writeObject(output, entries[i]);     
                   } else {
                        ExternalizableHelper.writeInt(output, 0);
         public static class SortingParallelAggregator implements ExternalizableLite, EntryAggregator {
              private String sortFlag;
              private String ascDescFlag;
              public SortingParallelAggregator() {
                   super();
              public SortingParallelAggregator(String sortFlag, String ascDescFlag) {
                   super();
                   this.sortFlag = sortFlag;
                   this.ascDescFlag = ascDescFlag;
              public Object aggregate(Set entries) {
                   return sortEntries(entries, sortFlag, ascDescFlag);
              public void readExternal(DataInput input) throws IOException {
                   sortFlag = ExternalizableHelper.readSafeUTF(input);
                   ascDescFlag = ExternalizableHelper.readSafeUTF(input);
              public void writeExternal(DataOutput output) throws IOException {
                   ExternalizableHelper.writeSafeUTF(output, sortFlag);
                   ExternalizableHelper.writeSafeUTF(output, ascDescFlag);
              private ParallelResultObject sortEntries(Set entries, String sortFlag, String ascDescFlag) {
                   ArrayList sortedList;
                   ArrayList arrayList = new ArrayList(entries);     
                   if ( sortFlag != null && !"".equals(sortFlag.trim()) ) {
         if ( Cache_Query_Constants.DATE_SORT_FLAG.equals(sortFlag.trim().toUpperCase()) ) {
                             sortedList = sortByDate(arrayList, ascDescFlag);
         } else {
         sortedList = arrayList;
         } else {
         sortedList = arrayList;
                   return new ParallelResultObject(convertListToArray(sortedList), sortedList.size());
              private ArrayList sortByDate(ArrayList arrayList, String ascDescFlag) {
                   if("DESC".equals(ascDescFlag.trim().toUpperCase())) {
                        System.out.println("Start sort by DATE DESC");
                        Collections.sort(arrayList, new Comparator() {
                             public int compare(Object o1, Object o2) {
                                  int rc = 0;
                                  if((o1 instanceof MultiTagPubSearchCacheEntity) && (o2 instanceof MultiTagPubSearchCacheEntity))
                                       System.out.println("Sorting by MultiTagPubSearchCacheEntity ...");
                                       MultiTagPubSearchCacheEntity p1 = (MultiTagPubSearchCacheEntity) o1;
                                       MultiTagPubSearchCacheEntity p2 = (MultiTagPubSearchCacheEntity) o2;
                                       rc = p1.getPub_Date() - p2.getPub_Date();
                                       if ( rc == 0 ) {
                                            rc = p2.getTitle().compareTo(p1.getTitle());
                                  return rc;
                        Collections.reverse(arrayList);
                        System.out.println("Done sort by DATE DESC");
                   System.out.println("Size of sorted result : " + arrayList.size());
                   Iterator iter = arrayList.iterator();
                   while(iter.hasNext()) {
         InvocableMap.Entry entry = (InvocableMap.Entry)iter.next();
                        MultiTagPubSearchCacheEntity e = (MultiTagPubSearchCacheEntity)entry.getValue();     
         System.out.println("### Sorted Entries : " + e.toString());
                   return arrayList;
              private MultiTagPubSearchCacheEntity[] convertListToArray(ArrayList sortedList) {
                   MultiTagPubSearchCacheEntity[] entries = new MultiTagPubSearchCacheEntity[sortedList.size()];
                   Iterator iter = sortedList.iterator();
                   int idx = 0;
                   while(iter.hasNext()) {
                        InvocableMap.Entry e = (InvocableMap.Entry)iter.next();
                        entries[idx] = (MultiTagPubSearchCacheEntity)e.getValue();
                        idx++;
                   return entries;
    =========================================================

  • Can't convert an ArrayList into a Double

    I have this TXT file with some data that i read and insert it to an arraylist then i want to pass the data in to several variables but i keep getting an error when i convert it to double.
    TXT file:
    volvo
    200000
    0.7
    2000
    Mercedes
    500000
    1.0
    1000
    Fiat
    100000
    0.5
    5000
    Code:
    class Register{
    private ArrayList bilar = new ArrayList();
    private BufferedReader indata =     new BufferedReader(new InputStreamReader(System.in));
    //Read the information from .txt"
    public void läsInRegister() throws IOException{
    try
    FileReader file = new FileReader("C:/Users/Kelly/workspace/cla…
    BufferedReader buf = new BufferedReader(file);
    String in = buf.readLine();
    while (in != null && !in.equals(""))
    bilar.add(in);
    in = buf.readLine();
    System.out.println(bilar+ "\n" );
    catch (Exception e){
    public void set(){
    for(int i=0; i< bilar.size(); i++) {
    String str = bilar.get(i).toString();
    String modell = str;
    i=i++;
    str="";
    str = bilar.get(i).toString();
    // until here everything is allright
    // Now i have try with this ways but still nothing
    double inköpspris = Double.parseDouble(str);
    i=i++;
    double bränsleförbrukning = (double) bilar.get(i);
    i=i++;
    double underhåll = (double) bilar.get(i);
    i=i++;     
    double bränsleförbrukning = Double.parseDouble((String) bilar.get(i));
    i can convert it to string there is no problem there, so i tried to convert the string str to double but still keeps getting the same error
    the error is:
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at examples.Register.sortera(Bilkostnad.jav…
    at examples.Bilkostnad.main(Bilkostnad.java…

    They're not doubles, they are Strings, resulting from readLine() calls. You have to parse them into doubles. Your already doing that with one of them, just do it to the others. A trivial problem that you had already solved.

  • Java.lang.ClassCastException in Custom VO

    I have created custom VO and made as such that it will display the Text Box “Carrier Charge” . Now I am extending the Controller of this region as such the value that is been entered in this text field needs to stored in the Database. For this, we need to know the line id and so with that line id we can store the carrier charge in database. For taking the current line id, I am referring the XXPosViewLinesVORowImpl.java.
    I have coded my custom java file also to take from the region” PosOrderLines”. My coding is below.
    public void processFormRequest(OAPageContext oapagecontext, OAWebBean oawebbean)
    throws OAException
    //super.processFormRequest(oapagecontext, oawebbean);
    OADBTransaction oadbtransaction = getApplicationModule(oapagecontext, oawebbean).getOADBTransaction();
    OATableBean oatablebean = (OATableBean)oawebbean.findChildRecursive("PosOrderLines");
    int x= 0;
    int y= 0;
    int z= 0;
    String s5 = null;
    if(oatablebean != null)
    OAInnerDataObjectEnumerator oainnerdataobjectenumerator = new OAInnerDataObjectEnumerator(oapagecontext, oatablebean);
    for(int k = 0; oainnerdataobjectenumerator.hasMoreElements(); k++)
    RowSet rowset = (RowSet)oainnerdataobjectenumerator.nextElement();
    if(rowset != null)
    y++;
    XXPosViewLinesVORowImpl posviewlinesvorowimpl = (XXPosViewLinesVORowImpl)rowset.first(); //It shows castException here……..
    if(posviewlinesvorowimpl != null)
    try
    storeAttribute16(posviewlinesvorowimpl,oadbtransaction);
    // String firstAttribute16 = PosServerUtil.replaceNull(posviewlinesvorowimpl.getAttribute("Attribute16"));
    catch(Exception e)
    e.printStackTrace();
    for(int i1 = 0; rowset.hasNext() && i1 < rowset.getFetchedRowCount(); i1++)
    z++;
    XXPosViewLinesVORowImpl posviewlinesvorowimpl1 = (XXPosViewLinesVORowImpl)rowset.next();
    if(posviewlinesvorowimpl1 != null)
    try
    storeAttribute16(posviewlinesvorowimpl1,oadbtransaction);
    // String nextAttribute16 = PosServerUtil.replaceNull(posviewlinesvorowimpl1.getAttribute("Attribute16"));
    catch(Exception e)
    e.printStackTrace();
    throw new OAException(y+" Times "+z+" Times"+z+" Times"+" "+s5, OAException.INFORMATION);
    ====
    In my file it shows error in the line marked. ClassCastException is shows. I have only created custom VO and haven’t created custom AM. Whether it may be the reason for this error.
    oracle.apps.fnd.framework.OAException: java.lang.ClassCastException
    at oracle.apps.fnd.framework.OAException.wrapperException(OAException.java:891)
    at oracle.apps.fnd.framework.webui.OAPageErrorHandler.prepareException(OAPageErrorHandler.java:1145)
    at oracle.apps.fnd.framework.webui.OAPageErrorHandler.processErrors(OAPageErrorHandler.java:1408)
    at oracle.apps.fnd.framework.webui.OAPageBean.processFormRequest(OAPageBean.java:2679)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:1682)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:508)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:429)
    at oa_html._OA._jspService(_OA.java:85)
    at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java:119)
    at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java:417)
    at oracle.jsp.JspServlet.doDispatch(JspServlet.java:267)
    at oracle.jsp.JspServlet.internalService(JspServlet.java:186)
    at oracle.jsp.JspServlet.service(JspServlet.java:156)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
    at org.apache.jserv.JServConnection.processRequest(JServConnection.java:456)
    at org.apache.jserv.JServConnection.run(JServConnection.java:294)
    at java.lang.Thread.run(Thread.java:534)
    ## Detail 0 ##
    java.lang.ClassCastException
    at oracle.apps.xxpos.changeorder.server.XXViewOrderPGCO.processFormRequest(XXViewOrderPGCO.java:101)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequest(OAWebBeanHelper.java:810)
    at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processFormRequest(OAWebBeanContainerHelper.java:363)
    at oracle.apps.fnd.framework.webui.beans.layout.OAStackLayoutBean.processFormRequest(OAStackLayoutBean.java:370)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:1022)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:988)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequest(OAWebBeanHelper.java:843)
    at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processFormRequest(OAWebBeanContainerHelper.java:363)
    at oracle.apps.fnd.framework.webui.beans.layout.OAStackLayoutBean.processFormRequest(OAStackLayoutBean.java:370)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:1022)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:988)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequest(OAWebBeanHelper.java:843)
    at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processFormRequest(OAWebBeanContainerHelper.java:363)
    at oracle.apps.fnd.framework.webui.OAPageLayoutHelper.processFormRequest(OAPageLayoutHelper.java:1159)
    at oracle.apps.fnd.framework.webui.beans.layout.OAPageLayoutBean.processFormRequest(OAPageLayoutBean.java:1579)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:1022)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:988)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequest(OAWebBeanHelper.java:843)
    at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processFormRequest(OAWebBeanContainerHelper.java:363)
    at oracle.apps.fnd.framework.webui.beans.form.OAFormBean.processFormRequest(OAFormBean.java:395)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:1022)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequestChildren(OAWebBeanHelper.java:988)
    at oracle.apps.fnd.framework.webui.OAWebBeanHelper.processFormRequest(OAWebBeanHelper.java:843)
    at oracle.apps.fnd.framework.webui.OAWebBeanContainerHelper.processFormRequest(OAWebBeanContainerHelper.java:363)
    at oracle.apps.fnd.framework.webui.beans.OABodyBean.processFormRequest(OABodyBean.java:363)
    at oracle.apps.fnd.framework.webui.OAPageBean.processFormRequest(OAPageBean.java:2675)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:1682)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:508)
    at oracle.apps.fnd.framework.webui.OAPageBean.preparePage(OAPageBean.java:429)
    at oa_html._OA._jspService(_OA.java:85)
    at oracle.jsp.runtime.HttpJsp.service(HttpJsp.java:119)
    at oracle.jsp.app.JspApplication.dispatchRequest(JspApplication.java:417)
    at oracle.jsp.JspServlet.doDispatch(JspServlet.java:267)
    at oracle.jsp.JspServlet.internalService(JspServlet.java:186)
    at oracle.jsp.JspServlet.service(JspServlet.java:156)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:588)
    at org.apache.jserv.JServConnection.processRequest(JServConnection.java:456)
    at org.apache.jserv.JServConnection.run(JServConnection.java:294)
    at java.lang.Thread.run(Thread.java:534)
    java.lang.ClassCastException
    at oracle.apps.xxpos.changeorder.server.XXViewOrderPGCO.processFormRequest(XXViewOrderPGCO.java:101)
    Please help me to solve this, is there any other way to get the attributes from the RowImpl.java?
    Thank you,
    Rajarajan.A

    Also i have seen this code in some java file,
    ====
    PosViewLinesVOImpl posviewlinesvoimpl = getPosViewLinesVO();
    RowSetIterator rowsetiterator1 = posviewlinesvoimpl.findRowSetIterator("lines");
    if(rowsetiterator1 == null)
    rowsetiterator1 = posviewlinesvoimpl.createRowSetIterator("lines");
    if(posviewlinesvoimpl.isPreparedForExecution())
    while(rowsetiterator1.hasNext())
    PosViewLinesVORowImpl posviewlinesvorowimpl = (PosViewLinesVORowImpl)rowsetiterator1.next();
    ArrayList arraylist2 = posviewlinesvorowimpl.getExceptions();
    if(arraylist2 != null)
    arraylist1.addAll(arraylist2);
    if(posviewlinesvorowimpl.isDirty())
    Object aobj2[] = new Object[51];
    getLineChanges(s, s1, s2, s3, posviewlinesvorowimpl, arraylist, aobj2);
    rowsetiterator1.closeRowSetIterator();
    =====
    Here i think that they are fetching the row attributes from the VO PosViewLinesVOImpl.java....
    Can i use similar code for my case, if its possible, what is this?
    posviewlinesvoimpl.createRowSetIterator("lines");........... In this line they are separating the lines. what for they have hardcoded like this "lines". is its for gettign the lines, can i do similar like this.......
    I am not familiar in OAF and this is my first component in this!!!!
    Please reply me.....
    Thank you,

  • "ClassCastException" for items in List after serialization

    consider this code:
    public class MyClass implements Serializable {
      public double price = -1;
      public double volume = -1;
    List list = new ArrayList<MyClass>();
    while(!endOfData) {
      MyClass mc = new MyClass();
      mc.price = x;
      mc.volume = y;
      list.add(mc);
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(list);----
    and then the receiver-side:
    ObjectInputStream ois = new ObjectInputStream(in);
    List list = (List) ois.readObject();
    MyClass mc = (MyClass) list.get(2);
    ..... error ... error ...
    Exception in thread "Thread-1" java.lang.ClassCastException: MyClass
    note: using a Double instead of MyClass works ok.
    also please notice:
    ObjectInputStream ois = new ObjectInputStream(in);
    List list = (List) ois.readObject();
    Object mc = (Object) list.get(4);
    System.out.println("this is what i am --> " + mc.getClass().getCanonicalName());
    output: "this is what i am --> MyClass"
    thanks.
    Message was edited by:
    suppon

    the MyClass objects are not
    initially loaded in the receiver's JVM.Make a custom class as:
    public class CustomObjectInputStream extends ObjectInputStream {
        private ClassLoader classLoader;
        /** Creates a new instance of CustomObjectInputStream */
        public CustomObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
            super(in);
            this.classLoader = classLoader;
        protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
            return Class.forName(desc.getName(), false, classLoader);
    }and use an instance of this class instead of the standard object inputstream to deserialize your object. You should pass the url class loader as an argument to the constructor of the custom object input stream. The reason is that the standard object inputstream only recognises classes that are "statically defined in the JAVA class path". (I quote the last text because I am not sure if I am using the right terminology, but I hope you understand what I mean.)
    why do i get
    "ClassCastExceptions" ??
    and not
    "ClassNotFoundException"
    ??This must be because somehow you have a "static" class definition for MyClass anyway, otherwise you wouldn't be able to write the following code and have it compile:
    MyClass item = (MyClass) class1.cast(list.get(7));Apparently your "static" MyClass definition does not correspond with the MyClass definition in your .jar file.
    You can only access a deserialized object of which the class definition is in a .jar file through reflection, unless you can cast it to an interface with a "static" definition.

  • Glassfish v3 ClassCastException for same class, at a List.get() command.

    Hello everyone,
    I am in the process of developing a small web application with JSF 2.0 and JPA, both of which I am not entirely familiar with. But thanks to Google and a lot of very dedicated experts, the Java and JSF forums have helped me with creating a basic form for entering and storing data. I am using Netbeans 6.8 which has glassfish V3 for the app server. However I have a problem where the auto-deploy in glass fish ends up giving me a ClassCastException for the same class, which after a bit of research on the net, seems to be a classloader problem.
    A related link http://72.5.124.102/thread.jspa?messageID=10119180 probably confirms the cause as a hot-deploy issue.
    My JSF page is created dynamically in the constructor of the managed bean, and it is here that I get the exception occasionally. A restart of the server solves the issue. Nevertheless, I would like to know if there is any other way to solve the classloader problem other than using a build.xml file as suggested in the forum link given above.
    I am posting a part of my code as well, so that if you think there a classloader problem in my code, you can let me know, so I can fix it.
    @ManagedBean(name = "CustomFields")
    @RequestScoped
    public class CustomFields {
        private String tableName;
        private List<UiSetup> dispFieldsList = new ArrayList();
        private HtmlPanelGrid customPanelSec = new HtmlPanelGrid();
        public HtmlPanelGrid getCustomPanelSec() {
            return customPanelSec;
        public void setCustomPanelSec(HtmlPanelGrid customPanelSec) {
            this.customPanelSec = customPanelSec;
        public String getTableName() {
            return tableName;
        public void setTableName(String tableName) {
            this.tableName = tableName;
        public CustomFields() {
            System.out.println("Invoked customFields backing bean");
            String callerBean = "";
            FacesContext context = FacesContext.getCurrentInstance();
            Application application = context.getApplication();
            tableName = context.getExternalContext().getRequestParameterMap().get("callerPage");
            callerBean = context.getExternalContext().getRequestParameterMap().get("backingBean");
            // This is a JPA contoller class for an entity that defines the custom fields that have to be enabled for this page.
            UiSetupJpaController fldsToShow = new UiSetupJpaController();
            dispFieldsList.clear();
            System.out.println("Did this1");
            // This function getDisplayFields gets the fields that have to be shown on the page.
            this.dispFieldsList = fldsToShow.getDisplayFields(tableName);
            System.out.println("Did this2");
            int totFields = this.dispFieldsList.size();
            System.out.println("Did this3");
            UiSetup us = this.dispFieldsList.get(totFields - 1);// This is where the error is thrown always.
            System.out.println("Did this4");
            customPanelSec.getChildren().clear();
            for (int i = 0; i < totFields; i++) {
                try {
                    HtmlPanelGrid fldLblGroup = new HtmlPanelGrid();
                    HtmlOutputLabel customLabel = (HtmlOutputLabel) application.createComponent(HtmlOutputLabel.COMPONENT_TYPE);
                    String labelName = dispFieldsList.get(i).getDisplayName();
                    customLabel.setValue(labelName);
                    String fieldName = dispFieldsList.get(i).getFieldName();
                    HtmlPanelGroup customField = (HtmlPanelGroup) application.createComponent(HtmlPanelGroup.COMPONENT_TYPE);
                    HtmlInputText customText = new HtmlInputText();
                    String valExp = "#{" + callerBean + "." + fieldName + "}";
                    customText.setId(fieldName);
                    customText.setValueExpression("value", createValueExpr(valExp, BigDecimal.class, context));
                    customField.getChildren().clear();
                    customField.getChildren().add(customText);
                    customPanelSec.getChildren().add(customLabel);
                    customPanelSec.getChildren().add(customField);
                }catch (Exception e) {
                    System.out.println(e.getMessage());
        private ValueExpression createValueExpr(String valexp, Class cls, FacesContext fcs) {
            return fcs.getApplication().getExpressionFactory().createValueExpression(fcs.getELContext(), valexp, cls);
    }The error message is as follows
    com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: karma.com.managedbeans.master.CustomFields.
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:405)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:267)
    Caused by: java.lang.ClassCastException: karma.com.model.ui.UiSetup cannot be cast to karma.com.model.ui.UiSetup
    at karma.com.managedbeans.master.CustomFields.<init>(CustomFields.java:397)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    ... 82 moreRegards,
    Swati

    Thanks very much for your reply. I have implemented your suggestion of using a PostConstruct method with the @ManagedProperty to inject the values into the tableName and the callerBean properties. The good news is that the page is rendered correctly and I haven't encountered the exception the few times that I invoked the page.
    However, I can't be sure the issue is resolved, since, like I mentioned, the error is seemingly erratic and I don't quite know if it is not seen because of a genuine fix or because, well, its currently not in a mood to show up.
    There is just one more thing I would like to mention. I have said that the code fails at the List.get() line. However, its not happening because the list is empty. In fact the earlier lines are giving expected outputs and totFields value is set all right. Maybe this has nothing to do with the error, but I thought I will mention it all the same, in case it triggers another idea altogether.
    Thanks very much
    Regards
    Swati

  • Sorting a arraylist user defined object

    I'm curious as to how I would go about sorting an object that I created. I would like to sort the object by the name variable in the Employee class. I tried just doing Collections.sort(staff);, but that throws the 'ClassCastException' exception. Here is the code that I was working with.
    import java.util.*;
    import java.util.Collections.*;
    public class ArrayListTest {
         public static void main (String args[]) {
              ArrayList staff = new ArrayList();
              staff.add(new Employee("Harry Cracker", 50000, 1989, 10, 1));
              staff.add(new Employee("Tony Cracker", 40000, 1990, 3, 15));
              staff.add(new Employee("carl Cracker", 75000, 1987, 12, 15));
              for (int i=0; i<staff.size(); i++) {
                   Employee e = (Employee)staff.get(i);
                   e.raiseSalary(5);
              try {
                   Collections.sort(staff);
              catch (ClassCastException e) {
                   //e.printStackTrace();
                   System.out.println("got here1");
              catch (UnsupportedOperationException e) {
                   //e.printStackTrace();
                   System.out.println("got here1");
              for (int i=0; i<staff.size(); i++) {
                   Employee e = (Employee)staff.get(i);
                   System.out.println("name=" + e.getName() + "salary=" + e.getSalary() + ",hireDay=" + e.getHireDay());
    class Employee {
         public Employee(String n, double s, int year, int month, int day) {
              name = n;
              salary = s;
              GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
              hireDay = calendar.getTime();
         public String getName() {
              return name;
         public double getSalary() {
              return salary;
         public Date getHireDay() {
              return hireDay;
         public void raiseSalary(double byPercent) {
              double raise = salary * byPercent / 100;
              salary += raise;
         private String name;
         private double salary;
         private Date hireDay;
    }WHile I'm on this example if someone could explain what the Employee class is, shouldn't that be defined in a seperate file? It's not a inner class because it's not defined inside another class, but what would it be called and how come it works that way. If I go and put a private/public statement in front of it I get an error message. Thanks for the help.

    It doesn't know how to sort Employee, you have to implement Comparable or create a Comparator. You could change your Collections.sort() method to something like this: (remove the try and catch also)Collections.sort(staff, new Comparator()
        public int compare(Object o, Object o2)
            String s = ((Employee)o).getName();
            String s2 = ((Employee)o2).getName();
            return String.CASE_INSENSITIVE_ORDER.compare(s, s2);
    });That's at least one way.

Maybe you are looking for

  • Fix the old or buy the new?

    Hey everybody, I'm new to this board but I've had an iPod (5th gen) since about March of 2005. About a couple of days ago, my headphone jack broke. Also, my battery is losing power faster than before. It still holds a good charge, but it can get anno

  • Education upgrade

    Is it really not possible to upgrade my educational version from Studio 8 to Studio 9? I bought Logic Studio for my home computer to see if we wanted it for my school lab. Got the educational discount. We ordered it for school but by the time the ord

  • Putting Playlists into Itunes

    Hi all- Can you put playslists from my ipod nano into itunes.  I switched computers (pc to a mac).  Thanks, Larry

  • Command-F search results aren't sorted by category

    I recently upgraded from Tiger to Leopard. I'm running 10.5.3 on a MacBook. Under Tiger, whenever I did a command-F search, the results were displayed in neat little categories ("Folders," "PDF Documents," "HTML," "Images," "Other'). Using Leopard, t

  • WOW, Prescott CPU Temp drop

    Well my system, Prescott 3.0 not overclocked, was running 45 at idle. I didnt like that. So I went the cheap route and got a CoolerMaster Aero 4. My system at idle is now at 34, as reported by speed fan!  :biggthumbsup:WOW that is a huge drop I think