Passing JAVA objects to different methods

As you can see that
"public static IntervalCategoryDataset createDataset()" want to get the data and attributes from storeStartDate and storeEndDate methods. i have class files, StartDate and EndDate that contains all the accessor methods. after i have store the relevant attributes, i want to call it out in the "public static IntervalCategoryDataset createDataset()" method to manipulate it.
i hope that my question doesn't confuse you all. hope that you all can guide me on this. Thank you
package ericTest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Calendar;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.IntervalCategoryDataset;
import org.jfree.data.gantt.Task;
import org.jfree.data.gantt.TaskSeries;
import org.jfree.data.gantt.TaskSeriesCollection;
import org.jfree.data.time.SimpleTimePeriod;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import Gantt.Chart;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
public class GanttDemo3 extends ApplicationFrame {
     private static ObjectContainer db;
     private static String day;
     private static String month;
     private static String year;
     private static String task;
     private static String startDate;
     private static String endDate;
     private static String startDay;
     private static String startMonth;
     private static String startYear;
     public static int startDay1;
     public static int startMonth1;
     public static int startYear1;
     public static int startDay2;
     public static int startMonth2;
     public static int startYear2;
     public static String endDay;
     public static String endMonth;
     public static String endYear;
     public static int endDay1;
     public static int endMonth1;
     public static int endYear1;
     public static int endDay2;
     public static int endMonth2;
     public static int endYear2;
     DataInputStream dis = null;
     String fileRecord = null;
   public GanttDemo3(final String title) {
        super(title);
        final IntervalCategoryDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        // add the chart to a panel...
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
        setContentPane(chartPanel);
         public final static String filename = "C:\\KLGCC Mock Up.yap";
         public void storeData() throws IOException{
              new File(filename).delete();
              db = Db4o.openFile(filename);
                   File f = new File("C:\\KLGCC Mock Up.txt");
                   FileReader fis = new FileReader(f);
                   BufferedReader bis = new BufferedReader(fis);
                   while((fileRecord = bis.readLine()) != null){
                             StringTokenizer st = new StringTokenizer(fileRecord,",");
                             task = st.nextToken();
                             startDate = st.nextToken();
                             endDate = st.nextToken();
                             Country c = new Country(task, startDate, endDate);
                             db.set(c);               
                   db.close();
         public void storeStartDate() throws ParseException{
              db = Db4o.openFile(filename);
              Country c = new Country();
              ObjectSet result = db.get(c);
              while(result.hasNext()){
                   Country obj = (Country)result.next();
                   String sDate = obj.getStartDate();
                   StringTokenizer str = new StringTokenizer(sDate, "/");
                   startMonth = str.nextToken();
                   startDay = str.nextToken();
                   startYear = str.nextToken();
                   int startMonth1 = Integer.parseInt(startMonth);
                   int startDay1 = Integer.parseInt(startDay);
                   int startYear1 = Integer.parseInt(startYear);
                   StartDate sd = new StartDate(startDay1, startMonth1, startYear1);
                   ArrayList<Integer> startDay2 = new ArrayList<Integer>();
                   startDay2.add(startDay1);
                   ArrayList<Integer> startMonth2 = new ArrayList<Integer>();
                   startMonth2.add(startMonth1);
                   ArrayList<Integer> startYear2 = new ArrayList<Integer>();
                   startYear2.add(startYear1);                 
              db.close();          
    public void storeEndDate() throws ParseException{
              db = Db4o.openFile(filename);
              Country c = new Country();
              ObjectSet result = db.get(c);
              while(result.hasNext()){
                   Country obj = (Country)result.next();
                   String sEndDate = obj.getEndDate();
                   StringTokenizer str1 = new StringTokenizer(sEndDate, "/");
                   endMonth = str1.nextToken();
                   endDay = str1.nextToken();
                   endYear = str1.nextToken();
                   int endMonth1 = Integer.parseInt(endMonth);
                   int endDay1 = Integer.parseInt(endDay);
                   int endYear1 = Integer.parseInt(endYear);
                   EndDate ed = new EndDate(endDay1, endMonth1, endYear1);
                   ArrayList<Integer> endDay2 = new ArrayList<Integer>();
                   endDay2.add(startDay1);
                   ArrayList<Integer> endMonth2 = new ArrayList<Integer>();
                   endMonth2.add(endMonth1);
                   ArrayList<Integer> endYear2 = new ArrayList<Integer>();
                   endYear2.add(endYear1);
              db.close();
public static IntervalCategoryDataset createDataset() {
         final TaskSeries s1 = new TaskSeries("Scheduled");
         StartDate sd = new StartDate(startDay1, startMonth1, startYear1);
         EndDate ed = new EndDate(endDay1, endMonth1, endYear1);
        s1.add(new Task(task,
               new SimpleTimePeriod(date(sd.getStartDay1(),sd.getStartDay1(), sd.getStartYear1()),
                                    date(ed.getEndDay1(), ed.getEndMonth1(), ed.getendYear1()))));
        System.out.println("dumb");
                final TaskSeriesCollection collection = new TaskSeriesCollection();
        collection.add(s1);
        return collection;
     * Utility method for creating <code>Date</code> objects.
     * @param day  the date.
     * @param month  the month.
     * @param year  the year.
     * @return a date.
    private static Date date(final int startDay2, final int startMonth2, final int startYear2) {
        System.out.println("sdojsodj");
         final Calendar calendar = Calendar.getInstance();
        calendar.set(startYear2, startMonth2, startDay2);
        final Date result = calendar.getTime();
        return result;
     * Creates a chart.
     * @param dataset  the dataset.
     * @return The chart.
    private JFreeChart createChart(final IntervalCategoryDataset dataset) {
        final JFreeChart chart = ChartFactory.createGanttChart(
            "Gantt Chart Demo",  // chart title
            "Task",              // domain axis label
            "Date",              // range axis label
            dataset,             // data
            true,                // include legend
            true,                // tooltips
            false                // urls
//        chart.getCategoryPlot().getDomainAxis().setMaxCategoryLabelWidthRatio(10.0f);
        return chart;   
    public static void main(final String[] args) throws IOException, ParseException
        final GanttDemo3 demo = new GanttDemo3("Gantt Chart Demo 1");
        demo.storeData();
        demo.storeStartDate();
        //demo.storeEndDate();
        //demo.pack();
        //RefineryUtilities.centerFrameOnScreen(demo);
        //demo.setVisible(true);
}

the error that came out in eclipse is
Exception in thread "main" java.lang.IllegalArgumentException: Null 'description' argument.
     at org.jfree.data.gantt.Task.<init>(Task.java:87)
     at ericTest.GanttDemo3.createDataset(GanttDemo3.java:191)
     at ericTest.GanttDemo3.<init>(GanttDemo3.java:78)
     at ericTest.GanttDemo3.main(GanttDemo3.java:248)and if i replace this
public static IntervalCategoryDataset createDataset() {
         final TaskSeries s1 = new TaskSeries("Scheduled");
         StartDate sd = new StartDate(startDay1, startMonth1, startYear1);
         EndDate ed = new EndDate(endDay1, endMonth1, endYear1);
        s1.add(new Task(task,
               new SimpleTimePeriod(date(sd.getStartDay1(),sd.getStartDay1(), sd.getStartYear1()),
                                    date(ed.getEndDay1(), ed.getEndMonth1(), ed.getendYear1()))));
        System.out.println("dumb");
                final TaskSeriesCollection collection = new TaskSeriesCollection();
        collection.add(s1);
        return collection;
    }with
public static IntervalCategoryDataset createDataset() {
         final TaskSeries s1 = new TaskSeries("Scheduled");
         Chart chart = new Chart();
        s1.add(new Task(chart.getTitle(),
               new SimpleTimePeriod(date(chart.getStartDay(), chart.getStartMonth(), chart.getStartYear()),
                                    date(chart.getEndDay(), chart.getEndMonth(), chart.getEndYear()))));
System.out.println("dumb");
                final TaskSeriesCollection collection = new TaskSeriesCollection();
        collection.add(s1);
        return collection;
    }the chart class file has all the accessor methods and all the values is hard code. so the graph can be generated. the problem now is if i want to get the values from the StartDate and EndDate methods to get the dates so that i can put it into the createDataset method to add the values needed for the graph.
can anyone help me on this? thanks alot

Similar Messages

  • How to create new java objects in native methods?

    Hello,
    Is it possible to create java objects and return the same to the java code from a native method?
    Also is it possible to pass java objects other than String objects (for example, Vector objects) as parameters to native methods and is it possible to return such objects back to the java code?
    If so how can I access those objects (say for example, accessing Vector elements) inside the native code?
    What should I do in order to achieve them?
    Regards,
    Satish

    bschauwe is correct in that constructing Java objects and calling methods on Java objects from native code is tough and takes some study. While you're at it, you might want to check out Jace, http://jace.reyelts.com/jace. It's a free open-source toolkit that really takes the nastiness out of doing this sort of stuff. For example,/**
    * A C++ function that takes a java.util.Vector and plays around with it.
    public void useVector( java::util::Vector& vector ) {
      // Print out all the contents of the vector
      for ( Iterator it = vector.iterator(); it.hasNext(); ) {
        cout << it.next();
      // Add some new elements to the vector
      vector.addElement( "Hello" );
      vector.addElement( "world" );
    } All this code just results in calls to standard JNI functions like FindClass, NewObject, GetMethodID, NewStringUTF, CallObjectMethod, etc...
    God bless,
    -Toby Reyelts

  • How to Pass Java Objects between Web Dynpro and Java SAP iViews

    Basically I have an SAP web dynpro iView that I do stuff with and I want to pass an object to another iView which is just a regular Java iView. From what I've read and tried, I can't just stick something in the session object and hope that the Java iView can pull it down the other end. I had a dream that it was possible (seriously).
    Anyway, are there any possible solutions around? Please advice and share you throughts. I will try to dream about it again tonight and see if its really gonna work this time.
    thanks for your help in advance

    There is no easy way you can pass objects other than those supported by express such as String, map, list etc.
    Though not advised, you can create a class with static variables to handle the storage of such java objects during transition between form and workflow. You will need to somehow identify the objects uniquely .

  • How do u pass an object into a method

    I want to create a method getData that takes an object of type Helper and returns an object of the same type.
    how do u pass objects into a method and how do u get objects as returns im a bit confused

    That will just allow you to pass a parameter. If you want to return a helper object
    Helper paramHelper = new Helper();
    Helper someHelper = callMethod(paramHelper);
    public Helper callMethod(Helper hobj) {
        //<some code>
        Helper retHelper = new Helper();
        //<blah, blah>
        return retHelper;

  • Passing variables/objects to different classes

    I need to get the balance of bank accounts for the method "total" .
    Problem is I haven't written the class "Account" and therefore don't get to grips with it...
    Any ideas how I can get it to work?
    Thanks a lot
    class Account
        private double theBalance    = 0.00;   // Balance of account
        private String theName       = "";
        public Account( String name, double openingBalance )
          theBalance = openingBalance;
          theName    = name;
        public double getBalance()
          // assert theBalance >= 0.00;
          return theBalance;
        public String getName()
          return theName;
        public double withdraw( final double money )
          // assert theBalance >= 0.00;
          if ( theBalance >= money  )
            theBalance = theBalance - money;
            return money;
          } else {
            return 0.00;
        public void deposit( final double money )
          // assert theBalance >= 0.00;
          theBalance = theBalance + money;
      class BankStats {
           private Account accounts[];
          public BankStats(Account[] acc) {
               accounts = acc ;
          public double total (double ammount) {
               double bal = Account.getBalance(accounts);
         }

    Problem is I haven't written the class "Account" and therefore don't get to grips with it...Sorry, what's that stuff "class Account"? What do you mean you haven't written it? It's right there!
    Any ideas how I can get it to work?You haven't written Account in a such a way that you'll get the answer you want, but that's different.
    I do have an idea, but I'm not going to write it for you. Have a look at your total method. Does the compiler complain when you try to compile this? Something about static methods? Might want to read about that, and think about what that array of Accounts is really for. Maybe BankStats should loop over the array of Accounts and get their respective balances.
    When is your homework due?
    MOD

  • Printing java object in the method

    How to print the object that has called the method in the method itself.
    class abc{
    public method1()
    S.o.p("Print the object that has called this method")
    psvm(string a[])
    abc aa=new abc();
    aa.method1();
    Thanks
    Sir

    Or make a new exception and parse the stack trace.
    This has a performance penalty, though.That wont get the object that's making the call (the 'this' of the method that's making the call), but only the class and the method

  • Empty strings when passing a Java object to a Stored Procedure

    Hi,
    I'm using the interface SQLData to pass Java objects to StoredProcedures. All the object's attributes 'arrive' to the Stored Procedure ok, except the strings, which are empty.
    Here is my Oracle object:
    TYPE OBJ_ASJFF_OBJ1 IS OBJECT (
    ARG1 CHAR(3),
    ARG2 NUMBER(4),
    ARG3 CHAR(4),
    ARG4 NUMBER(7),
    ARG5 NUMBER(13,2),
    ARG6 CHAR(1));
    The nested table of that object:
    TYPE TAB_ASJFF_OBJ1 AS TABLE OF OBJ_ASJFF_OBJ1;
    The procedure declaration:
    PROCEDURE Pup_Instaura_Processo (                              x_crCert IN TAB_ASJFF_OBJ1,
    x_cResult OUT CHAR(4)
    My SQLData implementation:
    public void writeSQL(SQLOutput stream) throws SQLException {
                   stream.writeString(getArg1());     
                   stream.writeInt(getArg2().intValue());
                   stream.writeString(getArg3());          
                   stream.writeLong(getArg4().longValue());     
                   stream.writeBigDecimal(getArg5());
                   stream.writeString(getArg6());
    Can anybody help me?
    Thanks in advance
    Rui Gonçalves

    not exactly what you wanted but ingredients can be found at
    - JPublisher's docuemntation (especially "Type Mapping Support Through PL/SQL Conversion Functions")
    - http://otn.oracle.com/sample_code/tech/java/jsp/Oracle9iJSPSamples.html (Best Hotels PL/SQL Sample )
    - http://otn.oracle.com/tech/xml/xdk_sample/xdksample_093001i.html
    hope this helps
    Kuassi
    I have a Java Stored procedure which takes an instance of a different java object as its parameter.
    I need to do this from a pl/sql package - can anyone point me to a sample etc (looked on the website but don't see one) ?
    Andrew

  • How to pass an object as method parameter

    Hi Guys
    I was testing a simple program and was trying to pass an object to a method but it didnt seem to work and I couldnt find out WHY.
    I am posting the code so please let me know who can i make my method ADD_EMPLOYEE work so that when i pass an object of LCL_EMPLOYEE, it updates I_EMPLOYEE_LIST.
    *& Report:  ZOO_HR_SAMPLE_1
    *& Author:  Avinash Pandey
    *& Date:    25.03.2009
    *& Description: Concepts of OO in ABAP
    REPORT  zoo_hr_sample_1.
    *&       Class LCL_EMPLOYEE
           Local class
    CLASS lcl_employee DEFINITION.
    Public section
      PUBLIC SECTION.
    Data type
        TYPES:
          BEGIN OF t_employee,
            no  TYPE i,
            name TYPE string,
            wage TYPE i,
         END OF t_employee.
    Method
        METHODS:
          constructor
            IMPORTING im_employee_no TYPE i
                      im_employee_name TYPE string
                      im_wage TYPE i,
            add_employee
             IMPORTING im_employee TYPE REF TO lcl_employee,
           display_employee_list,
           display_employee,
           get_no EXPORTING ex_no TYPE i,
           get_name EXPORTING ex_name TYPE string,
           get_wage EXPORTING ex_wage TYPE i.
      Class methods are global for all instances
        CLASS-METHODS: display_no_of_employees.
    Protected section
      PROTECTED SECTION.
      Class data are global for all instances
        CLASS-DATA: g_no_of_employees TYPE i.
        CLASS-DATA: i_employee_list TYPE TABLE OF t_employee.
    Private section
      PRIVATE SECTION.
       CLASS-DATA: i_employee_list TYPE TABLE OF t_employee.
        DATA: g_employee TYPE t_employee.
    ENDCLASS.               "LCL_EMPLOYEE
    *&       Class (Implementation)  LCL_EMPLOYEE
           Text
    CLASS lcl_employee IMPLEMENTATION.
    Class constructor method
      METHOD constructor.
        g_employee-no = im_employee_no.
        g_employee-name = im_employee_name.
        g_employee-wage = im_wage.
        g_no_of_employees = g_no_of_employees + 1.
      ENDMETHOD.                    "constructor
    Method
      METHOD display_employee.
        WRITE:/ 'Employee', g_employee-no, g_employee-name.
      ENDMETHOD.                    "display_employee
    Method
      METHOD get_no.
        ex_no = g_employee-no.
      ENDMETHOD.                    "get_no
    Method
      METHOD get_name.
        ex_name = g_employee-name.
        WRITE: / 'Name is:' , ex_name.
      ENDMETHOD.                    "get_no
    Method
      METHOD get_wage.
        ex_wage = g_employee-wage.
      ENDMETHOD.                    "get_no
    Method
      METHOD add_employee.
      Adds a new employee to the list of employees
        DATA: l_employee TYPE t_employee.
        l_employee-no = im_employee->get_no.
        l_employee-name = im_employee->get_name.
        l_employee-wage = im_employee->get_wage.
        APPEND l_employee TO i_employee_list.
      ENDMETHOD.                    "add_employee
    Method
      METHOD display_employee_list.
      Displays all employees and there wage
        DATA: l_employee TYPE t_employee.
        WRITE: / 'List of Employees'.
        LOOP AT i_employee_list INTO l_employee.
          WRITE: / l_employee-no, l_employee-name, l_employee-wage.
        ENDLOOP.
      ENDMETHOD.                    "display_employee_list
    Class method
      METHOD display_no_of_employees.
        WRITE: / 'Number of employees is:', g_no_of_employees.
      ENDMETHOD.                    "display_no_of_employees
    ENDCLASS.               "LCL_EMPLOYEE
    REPORT
    DATA: g_employee1 TYPE REF TO lcl_employee,
          g_employee2 TYPE REF TO lcl_employee.
    START-OF-SELECTION.
    Create class instances
      CREATE OBJECT g_employee1
        EXPORTING
          im_employee_no   = 1
          im_employee_name = 'John Jones'
          im_wage          = 20000.
      CREATE OBJECT g_employee2
        EXPORTING
          im_employee_no   = 2
          im_employee_name = 'Sally Summer'
          im_wage          = 28000.
    Call methods
      CALL METHOD g_employee1->display_employee.
      CALL METHOD g_employee1->add_employee
        EXPORTING
          im_employee = g_employee1.
      CALL METHOD g_employee1->get_name.
      CALL METHOD g_employee2->display_employee.
      CALL METHOD g_employee2->display_no_of_employees.
    The error I am getting is:
    Field GET_NO/GET_NAME/GET_WAGE is unknown.
    Please help me out on this.
    Thanks a lot you people

    hi.
    The following parts of your program were changed.
    The result is OK?.
    *(1)change
    CLASS lcl_employee DEFINITION.
    Public section
    PUBLIC SECTION.
    display_employee,
    *get_no EXPORTING ex_no TYPE i,
    *get_name EXPORTING ex_name TYPE string,
    *get_wage EXPORTING ex_wage TYPE i.
    get_no returning value(ex_no) TYPE i,
    get_name returning value(ex_name) TYPE string,
    get_wage returning value(ex_wage) TYPE i.
    *(2)change
    CLASS lcl_employee IMPLEMENTATION.
    Method
    METHOD add_employee.
    Adds a new employee to the list of employees
    DATA: l_employee TYPE t_employee.
    *l_employee-no = im_employee->get_no.
    *l_employee-name = im_employee->get_name.
    *l_employee-wage = im_employee->get_wage.
    l_employee-no   = im_employee->get_no( ).
    l_employee-name = im_employee->get_name( ).
    l_employee-wage = im_employee->get_wage( ).
    APPEND l_employee TO i_employee_list.
    ENDMETHOD. "add_employee
    Result List
    Employee          1  John Jones
    Name is: John Jones
    Name is: John Jones
    Employee          2  Sally Summer
    Number of employees is:          2

  • 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.

  • Passing complex object from bpel process to web service

    I have deployed my web service on apache axis.The wsdl file looks like as follows,
    <?xml version="1.0" encoding="UTF-8" ?>
    - <wsdl:definitions targetNamespace="http://bpel.jmetro.actiontech.com" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://bpel.jmetro.actiontech.com" xmlns:intf="http://bpel.jmetro.actiontech.com" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    - <wsdl:types>
    - <schema targetNamespace="http://bpel.jmetro.actiontech.com" xmlns="http://www.w3.org/2001/XMLSchema">
    <import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
    - <complexType name="ADLevelBpelWS">
    - <sequence>
    <element name="adLevelStr" nillable="true" type="xsd:string" />
    <element name="id" type="xsd:int" />
    </sequence>
    </complexType>
    - <complexType name="TransResultWS">
    - <sequence>
    <element name="description" nillable="true" type="xsd:string" />
    <element name="id" type="xsd:long" />
    <element name="responseType" type="xsd:int" />
    <element name="status" type="xsd:boolean" />
    </sequence>
    </complexType>
    - <complexType name="NamespaceDataImplBpelWS">
    - <sequence>
    <element name="ADLevel" nillable="true" type="impl:ADLevelBpelWS" />
    <element name="appdataDef" nillable="true" type="apachesoap:Map" />
    <element name="description" nillable="true" type="xsd:string" />
    <element name="name" nillable="true" type="xsd:string" />
    </sequence>
    </complexType>
    - <complexType name="CreateSharedNamespaceBpelWS">
    - <sequence>
    <element name="actor" nillable="true" type="xsd:string" />
    <element name="comment" nillable="true" type="xsd:string" />
    <element name="from" nillable="true" type="xsd:string" />
    <element name="namespaceData" nillable="true" type="impl:NamespaceDataImplBpelWS" />
    <element name="priority" type="xsd:int" />
    <element name="processAtTime" nillable="true" type="xsd:dateTime" />
    <element name="replyTo" nillable="true" type="xsd:string" />
    <element name="responseRequired" type="xsd:boolean" />
    </sequence>
    </complexType>
    </schema>
    - <schema targetNamespace="http://xml.apache.org/xml-soap" xmlns="http://www.w3.org/2001/XMLSchema">
    <import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
    - <complexType name="mapItem">
    - <sequence>
    <element name="key" nillable="true" type="xsd:string" />
    <element name="value" nillable="true" type="xsd:string" />
    </sequence>
    </complexType>
    - <complexType name="Map">
    - <sequence>
    <element maxOccurs="unbounded" minOccurs="0" name="item" type="apachesoap:mapItem" />
    </sequence>
    </complexType>
    </schema>
    </wsdl:types>
    + <wsdl:message name="createNamespaceRequest">
    <wsdl:part name="createNs" type="impl:CreateSharedNamespaceBpelWS" />
    </wsdl:message>
    - <wsdl:message name="createNamespaceResponse">
    <wsdl:part name="createNamespaceReturn" type="impl:TransResultWS" />
    </wsdl:message>
    - <wsdl:portType name="JMetroWebService">
    - <wsdl:operation name="createNamespace" parameterOrder="createNs">
    <wsdl:input message="impl:createNamespaceRequest" name="createNamespaceRequest" />
    <wsdl:output message="impl:createNamespaceResponse" name="createNamespaceResponse" />
    </wsdl:operation>
    </wsdl:portType>
    - <wsdl:binding name="NAMESPACEWITHMAPSoapBinding" type="impl:JMetroWebService">
    <wsdlsoap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
    - <wsdl:operation name="createNamespace">
    <wsdlsoap:operation soapAction="" />
    - <wsdl:input name="createNamespaceRequest">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://bpel.jmetro.actiontech.com" use="encoded" />
    </wsdl:input>
    - <wsdl:output name="createNamespaceResponse">
    <wsdlsoap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="http://bpel.jmetro.actiontech.com" use="encoded" />
    </wsdl:output>
    </wsdl:operation>
    </wsdl:binding>
    - <wsdl:service name="JMetroWebServiceService">
    - <wsdl:port binding="impl:NAMESPACEWITHMAPSoapBinding" name="NAMESPACEWITHMAP">
    <wsdlsoap:address location="http://localhost:7001/axis/services/NAMESPACEWITHMAP" />
    </wsdl:port>
    </wsdl:service>
    </wsdl:definitions>
    My NamespaceDataObjectImplBpelWS object contains element appDataDef which is of type java.util.Map.My bpel wsdl file is as below,
    <?xml version="1.0"?>
    <definitions name="NsWithMap"
    targetNamespace="http://bpel.jmetro.actiontech.com"
    xmlns:tns="http://bpel.jmetro.actiontech.com"
    xmlns:plnk="http://schemas.xmlsoap.org/ws/2003/05/partner-link/"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
    xmlns:apachesoap="http://xml.apache.org/xml-soap"
    >
    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    TYPE DEFINITION - List of services participating in this BPEL process
    The default output of the BPEL designer uses strings as input and
    output to the BPEL Process. But you can define or import any XML
    Schema type and us them as part of the message types.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <types>
         <schema targetNamespace="http://bpel.jmetro.actiontech.com" xmlns="http://www.w3.org/2001/XMLSchema">
         <import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
              <element name="createNamespace" type="tns:CreateSharedNamespaceBpelWS"/>
              <element name="transResult" type="tns:TransResultWS"/>
              <complexType name="TransResultWS">
                   <sequence>
                        <element name="description" type="string" />
                        <element name="id" type="long" />
                        <element name="responseType" type="int" />
                        <element name="status" type="boolean" />
              </sequence>
              </complexType>
              <complexType name="ADLevelBpelWS">
                   <sequence>
                        <element name="adLevelStr" type="string" />
                        <element name="id" type="int" />
                   </sequence>
              </complexType>
              <complexType name="NamespaceDataImplBpelWS">
                   <sequence>
                        <element name="ADLevel" type="tns:ADLevelBpelWS" />
                        <element name="description" type="string" />
                        <element name="name" type="string" />
                        <element name="appdataDef" type="apachesoap:Map" />
                   </sequence>
              </complexType>
              <complexType name="CreateSharedNamespaceBpelWS">
                   <sequence>
                        <element name="namespaceData" type="tns:NamespaceDataImplBpelWS" />
              </sequence>
              </complexType>
         <element name="desc" type="string"/>
         </schema>
         <schema targetNamespace="http://xml.apache.org/xml-soap" xmlns="http://www.w3.org/2001/XMLSchema">
                   <import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
                        <complexType name="mapItem">
                             <sequence>
                                  <element name="key" type="string" />
                                  <element name="value" type="string" />
                        </sequence>
                        </complexType>
                        <complexType name="Map">
                             <sequence>
                             <element maxOccurs="unbounded" minOccurs="0" name="item" type="apachesoap:mapItem" />
                             </sequence>
                        </complexType>
              </schema>
    </types>
    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    MESSAGE TYPE DEFINITION - Definition of the message types used as
    part of the port type defintions
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <message name="NsWithMapRequestMessage">
    <part name="payload" element="tns:createNamespace"/>
    </message>
    <message name="NsWithMapResponseMessage">
    <part name="payload" element="tns:transResult"/>
    </message>
    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PORT TYPE DEFINITION - A port type groups a set of operations into
    a logical service unit.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <!-- portType implemented by the NsWithMap BPEL process -->
    <portType name="NsWithMap">
    <operation name="initiate">
    <input message="tns:NsWithMapRequestMessage"/>
    </operation>
    </portType>
    <!-- portType implemented by the requester of NsWithMap BPEL process
    for asynchronous callback purposes
    -->
    <portType name="NsWithMapCallback">
    <operation name="onResult">
    <input message="tns:NsWithMapResponseMessage"/>
    </operation>
    </portType>
    <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    PARTNER LINK TYPE DEFINITION
    the NsWithMap partnerLinkType binds the provider and
    requester portType into an asynchronous conversation.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <plnk:partnerLinkType name="NsWithMap">
    <plnk:role name="NsWithMapProvider">
    <plnk:portType name="tns:NsWithMap"/>
    </plnk:role>
    <plnk:role name="NsWithMapRequester">
    <plnk:portType name="tns:NsWithMapCallback"/>
    </plnk:role>
    </plnk:partnerLinkType>
    </definitions>
    I am trying to set this map data using java code ,
         HashMap procADMap1 = new HashMap(5);
                   PropertyTypeWS pType = new PropertyTypeWS();
                   pType.setTypeIndex(2);     
              AppdataDefImplWS appData1 = new AppdataDefImplWS();
              appData1.setName("Project");
              appData1.setType(pType);
              appData1.setMaxSize(400);
              appData1.setLOB(false);
         appData1.setDefaultValue("Project Default value");
              procADMap1.put(appData1.getName(), appData1);
              setVariableData("request","createNs","/createNs/namespaceData/appdataDef",procADMap1);     
    Then I am passing request object to the method which I want to invoke from bpel process.
    I am able to deploy the application but when I do post message I am getting following exception,
    NamespaceWithMap (createNamespace) (faulted)
    [2004/09/09 18:35:54] "{http://schemas.oracle.com/bpel/extension}bindingFault" has been thrown. Less
    faultName: {{http://schemas.oracle.com/bpel/extension}bindingFault}
    messageType: {{http://schemas.oracle.com/bpel/extension}RuntimeFaultMessage}
    code: {Server.userException}
    summary: {org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.}
    detail: {null}
    Is there any other way to handle Map type in bpel process?
    Thanks in advance,
    Sanjay

    Thanks for the quick reply.Actually the web service is already deployed on the server.What I want to do is use existing wsdl file of the deployed web service and invoke the method of the same using oracle PM.
    If I remove element which uses apachesoap:Map type it just works fine also I am getting the complex object returned by the web service method.But when I try to set appDataDef which is of type apachesoap:Map(Axis conversion for java.util.Map and it uses namespace xmlns:apachesoap="http://xml.apache.org/xml-soap") I am getting the error.
    Can you give me some direction to use this exising wsdl file to set map object or it is not possible.

  • Over technologies rather than RMI to pass remote objects

    Hi,
    Just a general question about remote objects. Currently I am familiar with RMI, IIOP and JMS to pass remote objects. What other technologies are available? in particular, technologies for passing remote objects between different software systems?
    Just a simple response detailing the names would be great, gives me something to research then.
    thanks

    ofcourse passing over socket is always an option. Sure in that case you will have to serialize the object yourself or make a mini-protocol of some kind.
    In our project we also use XML to pass object between C++ and Java world, instead of using CORBA.

  • Newbie Help: Java Object to create an image

    Hi there.
    I'm trying to create a Java class that I can call from Coldfusion that will build a GIF file based on parameters.
    The idea is, the Java object opens a "background" gif file and then writes some text onto it and saves the whole thing out as a GIF.
    Bearing in mind this class will be used directly by Coldfusion, and so isn't an applet or an application...can anyone tell me what is wrong with this code as I get a null pointer exception on the getGraphics() line:
    // Methods available to Coldfusion
    public String CreateOverlay( String imageFile, String outPath, String overlayText, int x, int y, String fontFace, int PointSize)
    try{
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image im = tk.getImage(imageFile);
    Gif89Encoder enc = new Gif89Encoder();
    OutputStream out = new BufferedOutputStream(
    new FileOutputStream(outPath)
    Image newimg = createImage(100,50);
    ***** Graphics g = newimg.getGraphics();
    g.drawImage(im, 0, 0, 100, 50, this);
    g.drawLine(0,0,50,50);
    enc.addFrame( newimg );
    enc.encode(out);
    out.close();
    catch (Exception e) {
    System.out.println("Error...");
    e.printStackTrace();
    return "Dont care at the moment";
    Any help to this troubled newbie would be appreciated.

    Hi Kurt,
    You must call "setVisible(true)" on your Frame before
    creating the image.But, the thing is, this object doesnt have (or need) a GUI. Its just an object that sits on the server and its methods are called to generate an image on disk. Basically what happens is Coldfusion receives information from a user and it loads the java object, calls a method which then generates a new GIF file that is made up of a simple button background and some text (entered by the user)....it then returns the name of this file to Coldfusion and Coldfusion stores it in a database for later retrieval.
    In simple terms:
    COLDFUSION===========
    1. Creates an instance of the JAVA Object
    2. Call the generateGif method passing an image filename and some text eg:
    newFile=c.GenerateGif( "simplebutton.gif", "Some text for button");
    JAVA OBJECT========= (GenerateGif method)
    1. Load the GIF simplebutton.gif
    2. Create a new blank image
    3. Draw the loaded GIF onto the blank one
    4. Write the Text ("some text for button") onto the image
    5. Take the image and encode it to GIF format
    6. Write this GIF to disk
    7. Return the filename of the new GIF image just created
    8. Finish
    As you can see, I dont want or need a GUI.....
    Is this possible ?
    Thanks in Advance,
    Tony Johnson

  • Passing Opaque Objects from Oracle to Java

    Hi all
    I am trying to write a stored procedure that needs to be called from different triggers. Each triggers needs to pass a different set of data to the stored procedure. Now the problem is that i need to pack the different set of data into one opaque object type that i can pass onto java. Is there any way of doing this. I am using Oracle 9i running on Linux 2.4.9. I tried using the Object datatype in Oracle 9i. But am not able to pass a object datatype to java directly.

    Didn't know that. Guess the way this API handles the struct is it puts it on the heap, since this idea (with passing a 32-bit var back and forth with a memory location) worked.
    My next problem - I can't figure out a way to destroy a jstring: whenever I do an env->GetStringUTF((char*)charBuff), it seems to simply copy the bytes from the buffer
    into the same String object up the length of the buff (so I get the extra bytes from the previous String if it was longer at the end).
    Here's how it works: I have a loop in C code that parses tags inside a file, then depending on what tag it is, I create a new jobject and call a Java method to do stuff
    to that object. As one of the parameters in the constructor I pass in a String that I create (as you can see above) from a character array, however I am getting
    massive artifacts when I print out that String inside the Java method.
    Thoughts? :(

  • Trying to pass and object variable to a method

    I have yet another question. I'm trying to display my output in succession using a next button. The button works and I get what I want using test results, however what I really want to do is pass it a variable instead of using a set number.
    I want to be able to pass the object variables myProduct, myOfficeSupplies, and maxNumber to method actionPerformed so they can be in-turn passed to the displayResults method which is called in the actionPerformed method. Since there is no direct call to actionPerformed because it is called within one of the built in methods, I can't tell it to receive and pass those variables. Is there a way to do it without having to pass them through the built-in methods?
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.net.URL;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Panel extends JPanel implements ActionListener
         protected JTextArea myTextArea;
         protected String newline = "\n";
         static final private String FIRST = "first";
         static final private String PREVIOUS = "previous";
         static final private String NEXT = "next";
         public Panel( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 super(new BorderLayout());
              int counter = 0;
                 //Create the toolbar.
                 JToolBar myToolBar = new JToolBar( "Still draggable" );
                 addButtons( myToolBar );
                 //Create the text area used for output.
                 myTextArea = new JTextArea( 450, 190 );
                 myTextArea.setEditable( false );
                 JScrollPane scrollPane = new JScrollPane( myTextArea );
                 //Lay out the main panel.
                 setPreferredSize(new Dimension( 450, 190 ));
                 add( myToolBar, BorderLayout.PAGE_START );
                 add( scrollPane, BorderLayout.CENTER );
              myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) );
              setCounter( counter );
         } // End Constructor
         protected void addButtons( JToolBar myToolBar )
                 JButton myButton = null;
                 //first button
                 myButton = makeNavigationButton( FIRST, "Display first record", "First" );
                 myToolBar.add(myButton);
                 //second button
                 myButton = makeNavigationButton( PREVIOUS, "Display previous record", "Previous" );
                 myToolBar.add(myButton);
                 //third button
                 myButton = makeNavigationButton( NEXT, "Display next record", "Next" );
                 myToolBar.add(myButton);
         } //End method addButtons
         protected JButton makeNavigationButton( String actionCommand, String toolTipText, String altText )
                 //Create and initialize the button.
                 JButton myButton = new JButton();
                     myButton.setActionCommand( actionCommand );
                 myButton.setToolTipText( toolTipText );
                 myButton.addActionListener( this );
                   myButton.setText( altText );
                 return myButton;
         } // End makeNavigationButton method
             public void actionPerformed( ActionEvent e )
                 String cmd = e.getActionCommand();
                 // Handle each button.
              if (FIRST.equals(cmd))
              { // first button clicked
                          int counter = 0;
                   setCounter( counter );
                 else if (PREVIOUS.equals(cmd))
              { // second button clicked
                   counter = getCounter();
                      if ( counter == 0 )
                        counter = 5;  // 5 would be replaced with variable maxNumber
                        setCounter( counter );
                   else
                        counter = getCounter() - 1;
                        setCounter( counter );
              else if (NEXT.equals(cmd))
              { // third button clicked
                   counter = getCounter();
                   if ( counter == 5 )  // 5 would be replaced with variable maxNumber
                        counter = 0;
                        setCounter( counter );
                      else
                        counter = getCounter() + 1;
                        setCounter( counter );
                 displayResult( counter );
         } // End method actionPerformed
         private int counter;
         public void setCounter( int number ) // Declare setCounter method
              counter = number; // stores the counter
         } // End setCounter method
         public int getCounter()  // Declares getCounter method
              return counter;
         } // End method getCounter
         protected void displayResult( int counter )
              //Test statement
    //                 myTextArea.setText( String.format( "%d", counter ) );
              // How can I carry the myProduct and myOfficeSupplies variables into this method?
              myTextArea.setText( packageData( product, officeSupplies, counter ) );
                 myTextArea.setCaretPosition(myTextArea.getDocument().getLength());
             } // End method displayResult
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event dispatch thread.
         public void createAndShowGUI( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 //Create and set up the window.
                 JFrame frame = new JFrame("Products");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new Panel( myProduct, myOfficeSupplies, maxNumber ));
                 //Display the window.
                 frame.pack();
                 frame.setVisible( true );
             } // End method createAndShowGUI
         public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
              JTextArea myTextArea = new JTextArea(); // textarea to display output
              JFrame JFrame = new JFrame( "Products" );
              // For loop to display data array in a single Window
              for ( int counter = 0; counter < maxNumber; counter++ )  // Loop for displaying each product
                   myTextArea.append( packageData( myProduct, myOfficeSupplies, counter ) + "\n\n" );
                   JFrame.add( myTextArea ); // add textarea to JFrame
              } // End For Loop
              JScrollPane scrollPane = new JScrollPane( myTextArea ); //Creates the JScrollPane
              JFrame.setPreferredSize(new Dimension(350, 170)); // Sets the pane size
              JFrame.add(scrollPane, BorderLayout.CENTER); // adds scrollpane to JFrame
              JFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Sets program to exit on close
              JFrame.setSize( 350, 170 ); // set frame size
              JFrame.setVisible( true ); // display frame
         } // End method displayData
         public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
              return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
              "Product Number", myOfficeSupplies.getProductNumber( counter ),
              "Product Name", myOfficeSupplies.getProductName( counter ),
              "Product Brand",myProduct.getProductBrand( counter ),
              "Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
              "Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
              "Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
              "Restock charge for this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
              "Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
                   myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
         } // end method packageData
    } //End Class Panel

    multarnc wrote:
    My instructor has not been very forthcoming with assistance to her students leaving us to figure it out on our own.Aren't they all the same! Makes one wonder why they are called instructors. <sarcasm/>
    Of course it's highly likely that enough information was imparted for any sincere, reasonably intelligent student to actually figure it out, and learn the subject in the process.
    And if everything were spoonfed, how would one grade the performance of the students? Have them recite from memory
    public class HelloWorld left-brace
    indent public static void main left-parenthesis String left-bracket right-bracket args right-parenthesis left-brace
    And everywhere that Mary went
    The lamb was sure to go
    db

  • How to pass the java object into the spring controller

    Hi Friends
    When I hit the url at the first time my call goes to the spring controller and sets the userDetails objects in the modelAndView.addObject("userDetails", userDetails.getUserDetails()) and returns the userDetails.html page. if I click any link in the same page i want to pass same (userDetails) object thru javascript or jquery and calls the another(controller) method and returns the same (userDetails.html) page.
    It means how can i pass the java object thru javascript or jquery and calls the controller. if i get the same object in my controller i can avoid calling the db again. please help me out to resolve this issue. i am tired of fixing this issue.
    Regards
    Sherin Pooja

    If you want to avoid calling the database again then cache the data.
    However before you do that make sure that calling the database, in the context of YOUR system, is going to be an actual problem.
    For example there is absolutely no point in caching a  User object when only one user an hour is actually using the system.

Maybe you are looking for