Get / Cast a Java Object

Does anybody know how to get (or Cast) a Java Object returned from a Java method call ?
Example:
<cfset someList = object1.method1(someString, JavaCast("float",someNumber),...)>
This method returns a list of Java object of type "Object2". ie. it returns List<Object2>
Now I attempted to loop thru each objects from the returned list, and invoke some method on them, using code similar to below,
<cfset var="#someList[index]#"/>
but ColdFusion does not seem to understand the object "var" as Java "Object2". Is there any way I can cast the "var" to "Object2"?
Thanks in advance.
Xiaoling

"var" is a reserved keyword! You can initialize variables with "var" in the beginning of a component, but do not use it as a variables name:
<cfset var someVar = "#someList[index]#">

Similar Messages

  • How to get xml into java object

    yo
    i want to get the xml doc into some object like Document
    i have downloaded code:
    public class Echo extends org.xml.sax.helpers.DefaultHandler
    this class compiles fine but when i instantiate the class in code i get:
    "Exception in thread 'main' java.lang.NoClassDefFoundError: org/xml/sax/helpers/DefaultHandler"
    Please, what does this mean and how do i get this to recognise that i want to use a specific parser
    thanks a lot

    You are probably not specifying the XML jar files (xalan.jar & xerces.jar) on the run line. What is the command you are using?
    Actually, which "jars" you use is dependent on which version of the XML Java release you downloaded (Winter or Fall).

  • Java Object Cache have wired behaviour

    HI,
    I am trying to get my Oracle Java Object Cache working but I am observing some really stange behaviour which has stop it working. So any help will be really useful (10.1.3 and 10.1.2.0.2). I will explain:
    Progammaticly I have setup a parent region call 'DatabaseDataCache' and a sub-region call 'country'. In this region I have defined my object call countriesDto' with a Attribuite that has a CaheLoader attached. In my cache loader I connects to a Entity EJB that loads a bunch of DTOs into the cache.
    What is strange is that when i run the unit test on the code (cactus). The cache seems to call the cache loader 3 times consequtively before the EJB will load the data (i know this due to debuging messages)
    Then in the actual implmentation I have the cache setup code of the in the init() of the servlet but again the cache loader doesn't seem to able to call the ejb it requires. Ones the cache is access it trys to call the cache loader and of course the ejb dosn't get called and is returning me a NullPointerError as I am trying to acces the local interface (in the cache loader). This is strange as in the cactus test it actually calls the ejb ok bit only on the third attemp.
    I am abit puzzled with this so any help will be much appreciated.
    Charlie

    I think I have got what you need. The following is the cactus test class that test the getCountries method in my session ejb:
    public class WebinUtilTest extends ServletTestCase {
    private CacheAccess globParCache;
    public void setUp() throws Exception {
    CacheAccess.defineRegion("DatabaseDataCache");
    globParCache = CacheAccess.getAccess("DatabaseDataCache");
    globParCache.defineSubRegion("country");
    Attributes cAtt = new Attributes();
    cAtt.setLoader(new CountryCacheLoader());
    CacheAccess globCountCache = globParCache.getSubRegion("country");
    globCountCache.defineObject("countriesDto", cAtt);
    globCountCache.preLoad("countriesDto");
    globCountCache.close();
    globParCache.close();
    public void testGetCountries() throws Exception{
    WebinUtilLocal wuLoc = HomeFactory.getWebinUtilLocalHome().create();
    String[] countries = wuLoc.getCountries();
    assertTrue(countries.length >0);
    public void tearDown() throws Exception {
    if (globParCache != null){
    CacheAccess gCache = CacheAccess.getAccess("DatabaseDataCache");
    gCache.destroy();
    When I run this test here is the stack trace I am getting (in order):
    06/01/05 15:54:14 load entred for country cache loader: Thu Jan 05 15:54:14 GMT 2006
    06/01/05 15:54:14 java.lang.Exception: Stack trace
    06/01/05 15:54:14 at java.lang.Thread.dumpStack(Thread.java:1064)
    06/01/05 15:54:14 at uk.ac.ebi.submission.util.CountryCacheLoader.load(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheLoader.callLoad(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheHandle.findObject(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheHandle.asyncLoad(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.Task.execute(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.WorkerThread.run(Unknown Source)
    06/01/05 15:54:14 WebinUtil Session Started: Thu Jan 05 15:54:14 GMT 2006
    06/01/05 15:54:14 load entred for country cache loader Thu Jan 05 15:54:14 GMT 2006
    06/01/05 15:54:14 java.lang.Exception: Stack trace
    06/01/05 15:54:14 at java.lang.Thread.dumpStack(Thread.java:1064)
    06/01/05 15:54:14 at uk.ac.ebi.submission.util.CountryCacheLoader.load(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheLoader.callLoad(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheHandle.findObject(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheHandle.locateObject(Unknown Source)
    06/01/05 15:54:14 at oracle.ias.cache.CacheAccess.get(Unknown Source)
    06/01/05 15:54:14 at uk.ac.ebi.submission.ejb.session.WebinUtilBean.getCountries(Unknown Source)
    06/01/05 15:54:14 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    06/01/05 15:54:14 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    06/01/05 15:54:14 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    06/01/05 15:54:14 at java.lang.reflect.Method.invoke(Method.java:324)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.EJBJoinPointImpl.invoke(EJBJoinPointImpl.java:39)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:45)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:62)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.JAASInterceptor$1.run(JAASInterceptor.java:32)
    06/01/05 15:54:14 at java.security.AccessController.doPrivileged(Native Method)
    06/01/05 15:54:14 at javax.security.auth.Subject.doAs(Subject.java:379)
    06/01/05 15:54:14 at com.evermind.server.ThreadState.runAs(ThreadState.java:637)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.JAASInterceptor.invoke(JAASInterceptor.java:36)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.TxRequiredInterceptor.invoke(TxRequiredInterceptor.java:56)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.SecurityRoleInterceptor.invoke(SecurityRoleInterceptor.java:46)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.DMSInterceptor.invoke(DMSInterceptor.java:62)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.system.RunningStateInterceptor.invoke(RunningStateInterceptor.java:28)
    06/01/05 15:54:14 at com.evermind.server.ejb.interceptor.InvocationContextImpl.proceed(InvocationContextImpl.java:43)
    06/01/05 15:54:14 at com.evermind.server.ejb.StatelessSessionEJBObject.OC4J_invokeMethod(StatelessSessionEJBObject.java:106)
    06/01/05 15:54:14 at WebinUtilLocal_StatelessSessionBeanWrapper50.getCountries(WebinUtilLocal_StatelessSessionBeanWrapper50.java: 310)
    06/01/05 15:54:14 at uk.ac.ebi.submission.cactus.session.WebinUtilTest.testGetCountries(Unknown Source)
    06/01/05 15:54:14 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    06/01/05 15:54:14 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    06/01/05 15:54:14 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    06/01/05 15:54:14 at java.lang.reflect.Method.invoke(Method.java:324)
    06/01/05 15:54:14 at junit.framework.TestCase.runTest(TestCase.java:154)
    06/01/05 15:54:14 at junit.framework.TestCase.runBare(TestCase.java:127)
    06/01/05 15:54:14 at org.apache.cactus.internal.AbstractCactusTestCase.runBareServer(AbstractCactusTestCase.java:153)
    06/01/05 15:54:14 at org.apache.cactus.internal.server.AbstractWebTestCaller.doTest(AbstractWebTestCaller.java:119)
    06/01/05 15:54:14 at org.apache.cactus.internal.server.AbstractWebTestController.handleRequest_aroundBody0(AbstractWebTestControl ler.java:93)
    06/01/05 15:54:14 at org.apache.cactus.internal.server.AbstractWebTestController.handleRequest_aroundBody1$advice(AbstractWebTest Controller.java:224)
    06/01/05 15:54:14 at org.apache.cactus.internal.server.AbstractWebTestController.handleRequest(AbstractWebTestController.java)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doPost_aroundBody2(ServletTestRedirector.java:101)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doPost_aroundBody3$advice(ServletTestRedirector.java:224)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doPost(ServletTestRedirector.java)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doGet_aroundBody0(ServletTestRedirector.java:72)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doGet_aroundBody1$advice(ServletTestRedirector.java:224)
    06/01/05 15:54:14 at org.apache.cactus.server.ServletTestRedirector.doGet(ServletTestRedirector.java)
    06/01/05 15:54:14 at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
    06/01/05 15:54:14 at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
    06/01/05 15:54:14 at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:64)
    06/01/05 15:54:14 at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:382)
    06/01/05 15:54:14 at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:701)
    06/01/05 15:54:14 at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:397)
    06/01/05 15:54:14 at com.evermind.server.http.HttpRequestHandler.doProcessRequest(HttpRequestHandler.java:833)
    06/01/05 15:54:14 at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:430)
    06/01/05 15:54:14 at com.evermind.server.http.HttpRequestHandler.serveOneRequest(HttpRequestHandler.java:216)
    06/01/05 15:54:14 at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:119)
    06/01/05 15:54:14 at com.evermind.server.http.HttpRequestHandler.run(HttpRequestHandler.java:112)
    06/01/05 15:54:14 at oracle.oc4j.network.ServerSocketReadHandler$SafeRunnable.run(ServerSocketReadHandler.java:215)
    06/01/05 15:54:14 at oracle.oc4j.network.ServerSocketAcceptHandler.procClientSocket(ServerSocketAcceptHandler.java:232)
    06/01/05 15:54:14 at oracle.oc4j.network.ServerSocketAcceptHandler.access$1000(ServerSocketAcceptHandler.java:35)
    06/01/05 15:54:14 at oracle.oc4j.network.ServerSocketAcceptHandler$AcceptHandlerHorse.run(ServerSocketAcceptHandler.java:819)
    06/01/05 15:54:14 at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:303)
    06/01/05 15:54:14 at java.lang.Thread.run(Thread.java:534)
    Hope this is enough information.
    Thanks
    Charlie

  • How to get the owning bean given a java object

    Hi, is there any way - for a just-created bean instance - to know on behalf of which bean this object has been created ?
    In other words, going back from the java object to the bean symbolic name, as described in a faces-config managed-bean chunk (just the opposite of resolveVariable) ?

    You want to get the definied managed bean name inside the backing bean?
    If so, call this inside the backing bean: private String getManagedBeanName() {
        String managedBeanName = null;
        HttpServletRequest request =
            (HttpServletRequest) FacesContext
                .getCurrentInstance()
                    .getExternalContext()
                        .getRequest();
        // Lookup bean in request scope.
        Enumeration requestAttributeNames = request.getAttributeNames();
        while (requestAttributeNames.hasMoreElements()) {
            String requestAttribute = (String) requestAttributeNames.nextElement();
            Object object = request.getAttribute(requestAttribute);
            if (this.equals(object)) {
                managedBeanName = requestAttribute;
                break;
        if (managedBeanName == null) {
            // Bean is not in the request scope. Lookup it in session scope.
            Enumeration sessionAttributeNames = request.getSession().getAttributeNames();
            while (sessionAttributeNames.hasMoreElements()) {
                String sessionAttribute = (String) sessionAttributeNames.nextElement();
                Object object = request.getSession().getAttribute(sessionAttribute);
                if (this.equals(object)) {
                    managedBeanName = sessionAttribute;
                    break;
        return managedBeanName;
    }

  • Getting invalid packages when installing support for stored java objects

    I am getting invalid packages notices when installing support for stored java objects in Forms 9i that can with the Oracle 9iDS Suite. In the post installation notes it says to locate a few SQL files, PLB files and a JAR file and run them. On executing the SQL package that will install the rest , I am logged in as SYSTEM as the instructions stated, I get an error when it tries to load the PLB files ( which are encrypted from Oracle). Any one else have this problem or know of a solution?
    If you need more information please let me know and I will try to respond promptly.
    Thanks
    Chad Leath

    The PLB package is called ORA_DE_REFLECTION. I forgot to mention this in the previous post.

  • Getting Error:::oracle.jbo.domain.Date cannot be cast to java.lang.String

    Hi Friends,
    I have simple req'.
    i have one date filed in OAF page...if user has change the date filed..means if he incresed by 2 days..then i need to call one procedure..if not no need to call....
    first am picking that date field to by uusing prepared stmt and putting in to one variable..like below
    try {
    ps1 = am.getOADBTransaction().getJdbcConnection().prepareStatement("SELECT -------");
    ResultSet rs2 = ps1.executeQuery();
    while (rs2.next()) {
    schDate = rs2.getString(1);//storing the value
    } catch (Exception e) {
    throw OAException.wrapperException(e);
    Next..am picking the current value like this(user can change the value) like below...
    OAViewObject viewObj = (OAViewObject)am.findViewObject("simpleVO");
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");
    java.text.SimpleDateFormat dtFormat = new java.text.SimpleDateFormat ("MM/dd/yyyy");
    StringBuilder date = new StringBuilder(dtFormat.format(currSchDate));
    Then am comparing the values like below..
    if (schDate.equals(date)) {
    String outParamValue = "";
    String secondOutParamValue = "";
    but am geting the below error
    ## Detail 0 ##
    java.lang.ClassCastException: oracle.jbo.domain.Date cannot be cast to java.lang.String
         at xxuss.oracle.apps.abc.webui.xxPGCO15.processFormRequest(xxGCO15.java:594)
    Appriciate any help...its very urgent
    Regards
    Harry

    Instead of :
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");Try
    String currSchDate = viewObj.getCurrentRow().getAttribute("iDate").toString();
    -Anand

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

  • Getting information about an object from JList

    Hi
    I have created a movie application and i have a JList displaying all registered movies, it uses a DefaultListModel to display these.
    I want to be able to click on an element in the JList and then push a button called "Show movie details" to display all information about the selected movie.'.
    Every new movie is added to the DefaultListModel as an object with "Titlle", "Genere" etc. If someone click on a movie, what do i do to get information about which object that was clicked. All i can see is that integers can be returned with the getSelectedIndex/Value methods. If i use one of these methods to get the object from the DefaultListModel, that would work i guess, but what when someone deletes a movie in the middle of the JList, then the indexes wouldnt match.
    Can someone help me out here? :)

    I get a big fat exception when trying to cast the returned object to a Movie object which im using.
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.S
    tring cannot be cast to Movie
    ...sure that this is the way to do it? If so, what am i doing wrong..

  • JAXB : ClassCastException while using generated java objects

    Hi,
    I am using JAXB for unmarshalling my xml to set of java objects. It is working but when i use one child object and cast it i am getting ClassCastException.
    java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to com.xyz.base.EmployeeType
    My XSD
    ======
    <xsd:complexType name="EmployeeType">
    </xsd:complexType>
    <xsd:complexType name="EmployeeList">
         <xsd:sequence>
              <xsd:element name="Employee" type="base:EmployeeType" maxOccurs="unbounded"/>
         </xsd:sequence>
    </xsd:complexType>
    JAXB Binding
    ==========
    In Binding i am direct schema compiler to use ArrayList for EmployeeList.. as i want to use this as ArrayList.
    <jxb:bindings node="//xs:complexType[@name='EmployeeList']">
              <jxb:class ref="java.util.ArrayList"/>
    </jxb:bindings>
    Everything works well but when i extract element from EmployeeList (i.e. ArrayList) and try to type cast it to EmployeeType, getting following exception:
    java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.ElementNSImpl cannot be cast to com.xyz.base.EmployeeType
    so at the time of unmarshalling how jaxb will know about the type of child element and use accordingly.
    Any help would be greatly appreciated.

    Hi,
    Could you try outputting the class type of the object you are trying to cast?
    Check the class of the object. Say use object.class.getName().
    I used jaxb quite a long time ago but I believe it resolves the classes correctly.

  • Setting workflow payload as Java object

    Hello,
    The documentation for CQ workflows indicates that a Java object can be passed as the payload data for a workflow process.  I have a Java class that implements the WorkflowProcess interface and have hooked it up so I can invoke it programmatically.
    However the documentation does not give any insight on the "payload type" options other than "JCR_PATH".  If I use JCR_PATH then it expects the Object passed to be a string (a node path obviously).  Passing anything else will cause a class cast exception. Using any payload type other than JCR_PATH results in the log message "com.day.cq.workflow.impl.jcr.WorkflowManager No payload set" and the process does not get invoked correctly.  They show up in the Workflow instances UI as RUNNING and have no payload (basically stuck).
    Any help?

    That's a reasonable limitation of the implementation behind the interface. Just serialize your payload into a JCR node (or a node structure) and then add this node as payload to the workflow. The WF steps then process this node.
    A possible explanation for this: A workflow is guaranteed to be executed exactly once. So at the end of every workflow step the payload must be serialized to the repository to ensure that the next step can be repeated if it fails for any reason. So you can either serialize it yourself and upfront (the workflow then just updates this node struecture) or you would need some OR mapper here, which does this job for you. I prefer the first approach :-)
    kind regards,
    Jörg

  • Generation of XML file from Java objects using castor

    I have the following java file(Customer.java).
    public class Customer
         private String ID;
         private FirstName firstName;
         private MiddleName middleName;
         private LastName lastName;
         private ArrayList address;
         public ArrayList getAddress() {
              return address;
         public void setAddress(ArrayList address) {
              this.address = address;
         public FirstName getFirstName() {
              return firstName;
         public void setFirstName(FirstName firstName) {
              this.firstName = firstName;
         public String getID() {
              return ID;
         public void setID(String id) {
              ID = id;
         public LastName getLastName() {
              return lastName;
         public void setLastName(LastName lastName) {
              this.lastName = lastName;
         public MiddleName getMiddleName() {
              return middleName;
         public void setMiddleName(MiddleName middleName) {
              this.middleName = middleName;
    Using castor i have created an xml file(customer.xml) which has the following format.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    - <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    </customer>
    I have used a mapping file to get this output.Is there a way where i can get the output xml in the following format without changing the Java object structure.If yes then please suggest how this can be done.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    </customer>
    <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    I mean the output xml file should have the address as a separate tag not withing the root tag customer.

    Hello,
    Castor's own discussion groups might be able to point you to the solution you're looking for (if this use case is possible using Castor).
    Oracle has its own object-to-XML mapping tool that is part of the TopLink product. It allows you to map existing objects to an existing XML Schema. This can be done visually using the TopLink Workbench, or programmatically using the TopLink APIs. TopLink OXM also supports the JAXB specification.
    Using TopLink OXM to get the desired XML result I would recommend the following. Map the Customer and Address classes to XML, but don't map the relationship between Customer and Address. Then make the calls to the marshaller something like the following:
    marshaller.marshal(aCustomer, System.out);
    for(int x=0; x<aCustomer.getAddress().size(); x++) {
         marshal(aCustomer.getAddress().get(x), System.out);
    Example - Using TopLink OXM to map an existing object model to an existing XML Schema:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/howto/ox/index.htm
    For more information on TopLink object-to-XML mapping:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/objectxml/index.html
    -Blaise

  • How do I get to the request object in a webflow.

    How do I get to the request object in a webflow.
    I created a input process and one function it needs to do is create a cookie.
    Problem is I don't have a response object.
    How do I create/get the response object so I can create a cookie.
    Thanks
    Michael C Ford
    ------------------ Code Line ------------------------------------
    public Object process(HttpServletRequest req, Object requestContext)
    throws ProcessingException
    // get the pipeline and namespace info for the process
    PipelineSession pSession = null;
    String namespace = null;
    String username = req.getRemoteUser();
    pSession = getPipelineSession(req);
    namespace = getCurrentNamespace(pSession);
    /* ***** DO THE INITIAL CREATE OF THE BEAN *** */
         try {
              Properties props = new Properties();
              props.put(
                   Context.INITIAL_CONTEXT_FACTORY,
                   "weblogic.jndi.WLInitialContextFactory");
              Context ctx = new InitialContext(props);
              Object homeObject = ctx.lookup("com.??.??PortalMgr");
              SeechangePortalMgrHome seechangePortalMgrHome =
              (SeechangePortalMgrHome) javax.rmi.PortableRemoteObject.narrow(
                                                      homeObject,
                                                      SeechangePortalMgrHome.class);
              SeechangePortalMgr portalMgr = seechangePortalMgrHome.create();
    /* Set the initail user */
    portalMgr.setUser(username);          
              UserRuntime userRuntime = (UserRuntime)portalMgr.getRuntimeObject();
              System.out.print("Run Time User is " + userRuntime.getUserName());
              System.out.print("Run Time User is " + userRuntime.getOrgSeq());
    // ** cookies for Actuate XXX=(customer sequence ID), YYY=ZZZ is a dummy per
    their requirement
              Cookie cCustSeqNumber = new Cookie("XXX",userRuntime.getOrgSeq());
              Cookie cPassword = new Cookie("YYY","ZZZ");
              cCustSeqNumber.setPath("/");
              cPassword.setPath("/");
              ??response.addCookie(cCustSeqNumber);
              ??response.addCookie(cPassword);          
         } catch (Exception ee) {
              System.out.print("Unable to create Portal Manager" + ee);
    // at this point we add the logic to produce the bean
    return "success";

    Thanks
    Just what I needed, except I needed to caste response.
    Michael C
    "Daniel Selman" <[email protected]> wrote:
    Michael,
    // get the HttpServletResponse from the HttpServletRequest
    HttpServletResponse response =
    equest.getAttribute( WebflowConstants.HTTP_SERVLET_RESPONSE );
    Cookie cPassword = new Cookie("YYY","ZZZ");
    cCustSeqNumber.setPath("/");
    cPassword.setPath("/");
    response.addCookie(cCustSeqNumber);
    response.addCookie(cPassword);
    You HAVE the HttpServletRequest...
    public Object process(HttpServletRequest req, ObjectrequestContext)
    throws ProcessingExceptionMake sense?
    Dan
    "michael C Ford" <[email protected]> wrote in message
    news:[email protected]...
    How can I get to the response this way ?
    this just stored the response as an attribute did it now ?
    If I don't have it, how can I use it in a setAttribute ?
    Sorry just a little slow
    I can't do this can I ?
    request.setAttribute(WebflowConstants.HTTP_SERVLET_RESPONSE,response);
    Cookie cPassword = new Cookie("YYY","ZZZ");
    cCustSeqNumber.setPath("/");
    cPassword.setPath("/");
    response.addCookie(cCustSeqNumber);
    response.addCookie(cPassword);
    "Daniel Selman" <[email protected]> wrote:
    Michael,
    I found this handy snippet in our code:
    // Put the httpServletResponse into the request, this is done
    in
    case IPs want to
    // use the response to deposit cookies. The IPs maynot howeverwrite
    // anything to the response as this will cause an
    IllegalStateException
    request.setAttribute(WebflowConstants.HTTP_SERVLET_RESPONSE,
    response);
    So, the HttpServletResponse is bound into the HttpServletRequest usingthe
    key, WebflowConstants.HTTP_SERVLET_RESPONSE.
    Magic!
    Sincerely,
    Daniel Selman
    "michael C Ford" <[email protected]> wrote in message
    news:[email protected]...
    How do I get to the request object in a webflow.
    I created a input process and one function it needs to do is create
    a
    cookie.
    Problem is I don't have a response object.
    How do I create/get the response object so I can create a cookie.
    Thanks
    Michael C Ford
    ------------------ Code Line ------------------------------------
    public Object process(HttpServletRequest req, Object
    requestContext)
    throws ProcessingException
    // get the pipeline and namespace info for the process
    PipelineSession pSession = null;
    String namespace = null;
    String username = req.getRemoteUser();
    pSession = getPipelineSession(req);
    namespace = getCurrentNamespace(pSession);
    /* ***** DO THE INITIAL CREATE OF THE BEAN *** */
    try {
    Properties props = new Properties();
    props.put(
    Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    Context ctx = new InitialContext(props);
    Object homeObject = ctx.lookup("com.??.??PortalMgr");
    SeechangePortalMgrHome seechangePortalMgrHome =
    (SeechangePortalMgrHome) javax.rmi.PortableRemoteObject.narrow(
    homeObject,
    SeechangePortalMgrHome.class);
    SeechangePortalMgr portalMgr = seechangePortalMgrHome.create();
    /* Set the initail user */
    portalMgr.setUser(username);
    UserRuntime userRuntime = (UserRuntime)portalMgr.getRuntimeObject();
    System.out.print("Run Time User is " + userRuntime.getUserName());
    System.out.print("Run Time User is " + userRuntime.getOrgSeq());
    // ** cookies for Actuate XXX=(customer sequence ID), YYY=ZZZ isa
    dummy per
    their requirement
    Cookie cCustSeqNumber = new
    Cookie("XXX",userRuntime.getOrgSeq());
    Cookie cPassword = new Cookie("YYY","ZZZ");
    cCustSeqNumber.setPath("/");
    cPassword.setPath("/");
    ??response.addCookie(cCustSeqNumber);
    ??response.addCookie(cPassword);
    } catch (Exception ee) {
    System.out.print("Unable to create Portal Manager" + ee);
    // at this point we add the logic to produce the bean
    return "success";

  • How can I use XStream to persist complicated Java Object  to XML & backward

    Dear Sir:
    I met a problem as demo in my code below when i use XTream to persist my Java Object;
    How can I use XStream to persist complicated Java Object to XML & backward??
    See
    [1] main code
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    public class PhoneList {
         ArrayList<PhoneNumber> phones;
         ArrayList<Person> person;
         private PhoneList myphonelist ;
         private LocationTest location;
         private PhoneList(String name) {
         phones = new ArrayList<PhoneNumber>();
         person = new ArrayList<Person>();
         public ArrayList<PhoneNumber> getphones() {
              return phones;
         public ArrayList<Person> getperson() {
              return person;
         public void addPhoneNumber(PhoneNumber b1) {
              this.phones.add(b1);
         public void removePhoneNumber(PhoneNumber b1) {
              this.phones.remove(b1);
         public void addPerson(Person p1) {
              this.person.add(p1);
         public void removePerson(Person p1) {
              this.person.remove(p1);
         public void BuildList(){
              location = new LocationTest();
              XStream xstream = new XStream();
              myphonelist = new PhoneList("PhoneList");
              Person joe = new Person("Joe, Wallace");
              joe.setPhone(new PhoneNumber(123, "1234-456"));
              joe.setFax(new PhoneNumber(123, "9999-999"));
              Person geo= new Person("George Nixson");
              geo.setPhone(new PhoneNumber(925, "228-9999"));
              geo.getPhone().setLocationTest(location);          
              myphonelist.addPerson(joe);
              myphonelist.addPerson(geo);
         public PhoneList(){
              XStream xstream = new XStream();
              BuildList();
              saveStringToFile("C:\\temp\\test\\PhoneList.xml",convertToXML(myphonelist));
         public void saveStringToFile(String fileName, String saveString) {
              BufferedWriter bw = null;
              try {
                   bw = new BufferedWriter(
                             new FileWriter(fileName));
                   try {
                        bw.write(saveString);
                   finally {
                        bw.close();
              catch (IOException ex) {
                   ex.printStackTrace();
              //return saved;
         public String getStringFromFile(String fileName) {
              BufferedReader br = null;
              StringBuilder sb = new StringBuilder();
              try {
                   br = new BufferedReader(
                             new FileReader(fileName));
                   try {
                        String s;
                        while ((s = br.readLine()) != null) {
                             // add linefeed (\n) back since stripped by readline()
                             sb.append(s + "\n");
                   finally {
                        br.close();
              catch (Exception ex) {
                   ex.printStackTrace();
              return sb.toString();
         public  String convertToXML(PhoneList phonelist) {
              XStream xstream = new  XStream(new DomDriver());
              xstream.setMode(xstream.ID_REFERENCES) ;
              return xstream.toXML(phonelist);
         public static void main(String[] args) {
              new PhoneList();
    }[2].
    import java.io.Serializable;
    import javax.swing.JFrame;
    public class PhoneNumber implements Serializable{
           private      String      phone;
           private      String      fax;
           private      int      code;
           private      String      number;
           private      String      address;
           private      String      school;
           private      LocationTest      location;
           public PhoneNumber(int i, String str) {
                setCode(i);
                setNumber(str);
                address = "4256, Washington DC, USA";
                school = "Washington State University";
         public Object getPerson() {
              return null;
         public void setPhone(String phone) {
              this.phone = phone;
         public String getPhone() {
              return phone;
         public void setFax(String fax) {
              this.fax = fax;
         public String getFax() {
              return fax;
         public void setCode(int code) {
              this.code = code;
         public int getCode() {
              return code;
         public void setNumber(String number) {
              this.number = number;
         public String getNumber() {
              return number;
         public void setLocationTest(LocationTest bd) {
              this.location = bd;
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(location);
            f.getContentPane().add(location.getControls(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
         public LocationTest getLocationTest() {
              return location;
         }[3].
    package test.temp;
    import java.io.Serializable;
    public class Person implements Serializable{
         private String           fullname;
           @SuppressWarnings("unused")
         private PhoneNumber      phone;
           @SuppressWarnings("unused")
         private PhoneNumber      fax;
         public Person(){
         public Person(String fname){
                fullname=fname;           
         public void setPhone(PhoneNumber phoneNumber) {
              phone = phoneNumber;
         public void setFax(PhoneNumber phoneNumber) {
              fax = phoneNumber;
         public PhoneNumber getPhone() {
              return phone ;
         public PhoneNumber getFax() {
              return fax;
        public String getName() {
            return fullname ;
        public void setName(String name) {
            this.fullname      = name;
        public String toString() {
            return getName();
    }[4]. LocationTest.java
    package test.temp;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class LocationTest extends JPanel implements ChangeListener
        Ellipse2D.Double ball;
        Line2D.Double    line;
        JSlider          translate;
        double           lastTheta = 0;
        public void stateChanged(ChangeEvent e)
            JSlider slider = (JSlider)e.getSource();
            String name = slider.getName();
            int value = slider.getValue();
            if(name.equals("rotation"))
                tilt(Math.toRadians(value));
            else if(name.equals("translate"))
                moveBall(value);
            repaint();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(ball == null)
                initGeom();
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.red);
            g2.fill(ball);
        private void initGeom()
            int w = getWidth();
            int h = getHeight();
            int DIA = 30;
            int padFromEnd = 5;
            line = new Line2D.Double(w/4, h*15/16, w*3/4, h*15/16);
            double x = line.x2 - padFromEnd - DIA;
            double y = line.y2 - DIA;
            ball = new Ellipse2D.Double(x, y, DIA, DIA);
            // update translate slider values
            int max = (int)line.getP1().distance(line.getP2());
            translate.setMaximum(max);
            translate.setValue(max-padFromEnd);
        private void tilt(double theta)
            // rotate line from left end
            Point2D pivot = line.getP1();
            double lineLength = pivot.distance(line.getP2());
            Point2D.Double p2 = new Point2D.Double();
            p2.x = pivot.getX() + lineLength*Math.cos(theta);
            p2.y = pivot.getY() + lineLength*Math.sin(theta);
            line.setLine(pivot, p2);
            // find angle from pivot to ball center relative to line
            // ie, ball center -> pivot -> line end
            double cx = ball.getCenterX();
            double cy = ball.getCenterY();
            double pivotToCenter = pivot.distance(cx, cy);
            // angle of ball to horizon
            double dy = cy - pivot.getY();
            double dx = cx - pivot.getX();
            // relative angle phi = ball_to_horizon - last line_to_horizon
            double phi = Math.atan2(dy, dx) - lastTheta;
            // rotate ball from pivot
            double x = pivot.getX() + pivotToCenter*Math.cos(theta+phi);
            double y = pivot.getY() + pivotToCenter*Math.sin(theta+phi);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
            lastTheta = theta;  // save theta for next time
        private void moveBall(int distance)
            Point2D pivot = line.getP1();
            // ball touches line at distance from pivot
            double contactX = pivot.getX() + distance*Math.cos(lastTheta);
            double contactY = pivot.getY() + distance*Math.sin(lastTheta);
            // find new center location of ball
            // angle lambda = lastTheta - 90 degrees (anti-clockwise)
            double lambda = lastTheta - Math.PI/2;
            double x = contactX + (ball.width/2)*Math.cos(lambda);
            double y = contactY + (ball.height/2)*Math.sin(lambda);
            ball.setFrameFromCenter(x, y, x+ball.width/2, y+ball.height/2);
        JPanel getControls()
            JSlider rotate = getSlider("rotation angle", "rotation", -90, 0, 0, 5, 15);
            translate = getSlider("distance from end",  "translate", 0, 100, 100,25, 50);
            JPanel panel = new JPanel(new GridLayout(0,1));
            panel.add(rotate);
            panel.add(translate);
            return panel;
        private JSlider getSlider(String title, String name, int min, int max,
                                  int value, int minorSpace, int majorSpace)
            JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, value);
            slider.setBorder(BorderFactory.createTitledBorder(title));
            slider.setName(name);
            slider.setPaintTicks(true);
            slider.setMinorTickSpacing(minorSpace);
            slider.setMajorTickSpacing(majorSpace);
            slider.setPaintLabels(true);
            slider.addChangeListener(this);
            return slider;
    }OK, My questions are:
    [1]. what I generated XML by XSTream is very complicated, especially for object LocationTest, Can we make it as simple as others such as Person object??
    [2]. after I run it, LocationTest will popup and a red ball in a panel will dsiplay, after I change red ball's position, I hope to persist it to xml, then when I read it back, I hope to get same picture, ie, red ball stiil in old position, How to do that??
    Thanks a lot!!

    Positive feedback? Then please take this in a positive way: if you want to work on persisting Java objects into XML, then GUI programming is irrelevant to that goal. The 1,000 lines of code you posted there appeared to me to have a whole lot of GUI code in it. You should produce a smaller (much smaller) example of what you want to do. Calling the working code from your GUI program should come later.

  • Generating an XML representation of arbitrary Java objects

    Hi. Just for fun, I'm attempting to write some code which creates an XML representation of an arbitrary java object using reflection. The idea is that only properties with get/set methods should come through in the XML.
    Here is the code:
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Node;
    import java.util.Stack;
    public class XMLDAO {
         public static String getXMLWithHeader(Object obj){
              return "<?xml version=\"0\"?>" + getXML(obj);
          * Returns an XML representation of an arbitrary object
         public static String getXML(Object obj){
              StringBuffer buffer = new StringBuffer();
              AccessorMethod[] accessorMethods = getAccessorMethods(obj);
              buffer.append("<" + obj.getClass().getName() + ">\n");
              //List
              if(obj instanceof List){
                   List objList = (List)obj;
                   Iterator iterator = objList.iterator();
                   while(iterator.hasNext()){                              
                        buffer.append(getXML(iterator.next()));
              else{
                   for(int i = 0; i < accessorMethods.length; i++){
                        Object fieldObj = null;
                        try{
                             fieldObj = accessorMethods.invoke();
                             1. Primitive Wrapper or String(base case)
                             if(fieldObj instanceof Integer || fieldObj instanceof Float || fieldObj instanceof Double
                                  || fieldObj instanceof Long || fieldObj instanceof String){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">");
                                  buffer.append(accessorMethods[i].invoke());
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                             else if(fieldObj instanceof Object[]){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">\n");
                                  Object[] fieldArray = (Object[])fieldObj;
                                  for(int j = 0; j < fieldArray.length; j++)
                                       buffer.append(getXML(fieldArray[i]));
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                        }catch(Exception e){
                             System.out.println("Couldn't invoke method: " + accessorMethods[i].getName());
              buffer.append("</" + obj.getClass().getName() + ">\n");
              return buffer.toString();
         * Returns the Object representation for the XML - used to rebuild Java objects
         * converted to XML by XMLDAO.getXML().
         public static Object getObject(String xmlString) throws ParserConfigurationException,
              SAXException, IOException{
              //the root element is the class name
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(xmlString);
              Stack objectStack = new Stack();
              return getObject(document);
         private static Object getObject(Node n){
              //every document is either an object or a bean property
              //all bean properties have values
              //no object has a value, it can only have bean properties
              //the base case occurs when the document has a value
              String nodeName = n.getNodeName();
              if(n.getNodeValue() == null){
                   System.out.println("node " + nodeName + " is an object");
              else{
                   System.out.println("node " + nodeName + " is a bean property");
              return null;
         * Returns all of the "getter" methods for the given object
         private static AccessorMethod[] getAccessorMethods(Object obj){
              Class theClass = obj.getClass();
              Method[] objMethods = theClass.getMethods();
              ArrayList methodList = new ArrayList();
              for(int i = 0; i < objMethods.length; i++){
                   try{
                        methodList.add(new AccessorMethod(obj, objMethods[i]));
                   }catch(IllegalArgumentException e){}
              return (AccessorMethod[])methodList.toArray(new AccessorMethod[methodList.size()]);
         * Invokes the specified "getter" method and returns the result as an Object
         private Object invokeAccessorMethod(Object obj, Method m) throws IllegalAccessException,
              InvocationTargetException{
              return m.invoke(obj, null);
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    * Represents an AccessorMethod (i.e. getField()) on an Object
    public class AccessorMethod{
         private Object obj;
         private Method m;
         private String accessorFieldName;
         * Constructor for AccessorMethod
         public AccessorMethod(Object obj, Method m) throws IllegalArgumentException{
              1. Method name starts with get
              2. Method name does not equal get
              3. Method takes no arguments
              4. Method return type is not void
              String methodName = m.getName();
              if(methodName.indexOf("get") != 0 || methodName.length() == 3 &&
                   m.getParameterTypes().length != 0 && m.getReturnType() != null){
                   throw new IllegalArgumentException("Not a valid getter method " + methodName);
              this.obj = obj;
              this.m = m;
              String tempName = m.getName().substring(3, m.getName().length());
              this.accessorFieldName = Character.toLowerCase(tempName.charAt(0)) + tempName.substring(1, tempName.length());
         public Object invoke() throws IllegalAccessException, InvocationTargetException{
              return m.invoke(obj, null);
         * Gets the m
         * @return Returns a Method
         public Method getM() {
              return m;
         * Sets the m
         * @param m The m to set
         public void setM(Method m) {
              this.m = m;
         * Gets the accessorFieldName
         * @return Returns a String
         public String getAccessorFieldName() {
              return accessorFieldName;
         * Sets the accessorFieldName
         * @param accessorFieldName The accessorFieldName to set
         public void setAccessorFieldName(String accessorFieldName) {
              this.accessorFieldName = accessorFieldName;
         * Gets the obj
         * @return Returns a Object
         public Object getObj() {
              return obj;
         * Sets the obj
         * @param obj The obj to set
         public void setObj(Object obj) {
              this.obj = obj;
         public String getName(){
              return this.m.getName();
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

    I think the end of my post got cut off:
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

  • Getting compilation error: java.util.Set is an interface. This interface is not supported.

    Hi Folks,
    Is there a limitation in BEA's web services implementation? I have a simple web
    service that returns an array of java objects. However I am calling another middle
    tier API that returns a Set. I convert this Set into array of object and return
    it via the web service.
    However the .jws file that implements the webservice does not compile. I get the
    following error message:
    java.util.Set is an interface. This interface is not supported.
    Is there a limitation on using Collections within the .jws file? If that is the
    case it is a severe limitation.
    Note my Web Service API returns an array of java objects with no collections in
    them.
    Sanjay

    Hello,
    Generic java collections can only be handled in a very generic, weakly
    typed manner.
    Take a look at the
    http://workshop.bea.com/xmlbeans/guide/conXMLBeansSupportBuiltInSchemaTypes.html
    and also
    http://workshop.bea.com/xmlbeans/guide/conJavaTypesGeneratedFromUserDerived.html
    You might also ask your question to the XMLBeans newsgroup:
    http://newsgroups.bea.com/cgi-bin/dnewsweb?cmd=xover&group=weblogic.developer.interest.xmlbeans
    Regards,
    Bruce
    Sanjay wrote:
    >
    Hi Folks,
    Is there a limitation in BEA's web services implementation? I have a simple web
    service that returns an array of java objects. However I am calling another middle
    tier API that returns a Set. I convert this Set into array of object and return
    it via the web service.
    However the .jws file that implements the webservice does not compile. I get the
    following error message:
    java.util.Set is an interface. This interface is not supported.
    Is there a limitation on using Collections within the .jws file? If that is the
    case it is a severe limitation.
    Note my Web Service API returns an array of java objects with no collections in
    them.
    Sanjay

Maybe you are looking for

  • Dynamic columns in report... NON ALV REPORT

    Hey Guys, I have a internal table which has abt 50 columns now i wanna show only the columns that have any value in it... Now this is not an ALV report... this is a basic report.... So anyideas as to where i can start  on this.... i dont want to writ

  • Letters change when creating PDF

    I am using Acrobat Professional 6 and creating PDFs with the "Adobe PDF" icon it created when installed. Some documents from the Bloomberg system are converted by a sort of substitution cypher to gibberish. Capital letters are affected, but not lower

  • How do I turn off 'All' the photo stills in iMovie 11 without having to turn off each one?

    How do I turn off 'All' the photos in iMovie 11 without having to turn off each one?

  • Why is the Image in Canvas Square?

    I have about a dozen video clips in my Sequence - they are all DV/DVCPRO - NTSC, 720x480. The sequence settings are 720x480 NTSC DV (3:2), Pixel Aspect Ratio NTSC - CCIR 601 - DV 720/480 and the Compressor DV/DVCPRO - NTSC. Question: Why is the image

  • Widescreen DV, full quality export to .mov?

    Hi, I'm working on a short iMovie project in widescreen dv mode, and I'd like to export it in full quality to a .mov file rather than a .dv file. Is this possible? Thanks! Macbook Core 2 Duo   Mac OS X (10.4.8)