Home » xmlbeans-2.5.0-src » org.apache.xmlbeans.samples » datetime » [javadoc | source]

    1   /*   Copyright 2004 The Apache Software Foundation
    2    *
    3    *   Licensed under the Apache License, Version 2.0 (the "License");
    4    *   you may not use this file except in compliance with the License.
    5    *   You may obtain a copy of the License at
    6    *
    7    *       http://www.apache.org/licenses/LICENSE-2.0
    8    *
    9    *   Unless required by applicable law or agreed to in writing, software
   10    *   distributed under the License is distributed on an "AS IS" BASIS,
   11    *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   12    *   See the License for the specific language governing permissions and
   13    *  limitations under the License.
   14    */
   15   
   16   package org.apache.xmlbeans.samples.datetime;
   17   
   18   import java.io.File;
   19   import java.io.IOException;
   20   import java.util.Calendar;
   21   import java.util.ArrayList;
   22   
   23   import org.apache.xmlbeans.XmlException;
   24   import org.apache.xmlbeans.XmlOptions;
   25   import org.apache.xmlbeans.XmlError;
   26   import org.apache.xmlbeans.XmlObject;
   27   
   28   import org.apache.xmlbeans.GDuration;
   29   import org.apache.xmlbeans.XmlDate;
   30   import org.apache.xmlbeans.XmlCalendar;
   31   
   32   import java.util.Calendar;
   33   import java.text.SimpleDateFormat;
   34   import java.util.Date;
   35   
   36   import org.apache.xmlbeans.samples.datetime.ImportantDate;
   37   import org.apache.xmlbeans.samples.datetime.DatetimeDocument;
   38   
   39   /**
   40    * The sample illustrates how you can work with XML Schema types date,
   41    * dateTime, time, duration, gDay.
   42    * It parses the XML Document, prints first occurence of <important-date>
   43    * value, creates a new <important-date> element and saves it in a new XML Document.
   44    * This sample illustrates how you can convert XMLBean types to Java types
   45    * (java.util.Date, java.util.Calendar).
   46    * It uses the schema defined in datetime.xsd.
   47    */
   48   public class DateTime {
   49   
   50      /**
   51       * Receives an XML Instance and prints the element values,
   52       * Also creates a new XML Instance.
   53       *
   54       * @param args An array containing
   55       *             (a)Path to the XML Instance conforming to the XML schema in datetime.xsd.
   56       *             (b)Path for creating a new XML Instance.
   57       */
   58      public static void main(String args[]){
   59          // Create an instance of this class to work with.
   60          DateTime dt = new DateTime();
   61   
   62          // Create an instance of a Datetime type based on the received XML's schema
   63          DatetimeDocument doc = dt.parseXml(args[0]);
   64   
   65          // Prints the element values from the XML
   66          dt.printInstance(doc);
   67   
   68          // Creates a new XML and saves the file
   69          dt.createDocument(doc,args[1]);
   70   
   71      }
   72   
   73      /**
   74       * Creates a File from the XML path provided in main arguments, then
   75       * parses the file's contents into a type generated from schema.
   76       */
   77      public DatetimeDocument parseXml(String file){
   78          // Get the XML instance into a file using the path provided.
   79          File xmlfile = new File(file);
   80   
   81          // Create an instance of a type generated from schema to hold the XML.
   82          DatetimeDocument doc = null;
   83   
   84          try {
   85              // Parse the instance into the type generated from the schema.
   86              doc = DatetimeDocument.Factory.parse(xmlfile);
   87          }
   88          catch(XmlException e){
   89              e.printStackTrace();
   90          }
   91          catch(IOException e){
   92              e.printStackTrace();
   93          }
   94          return doc;
   95      }
   96   
   97      /**
   98       * This method prints first occurence of <important-date>
   99       * value. It also prints converted values from  XMLBean types to Java types
  100       * (java.util.Date, java.util.Calendar) and org.apache.xmlbeans.GDate.
  101       */
  102      public void printInstance(DatetimeDocument doc){
  103          // Retrieve the <datetime> element and get an array of
  104          // the <important-date> elements it contains.
  105          DatetimeDocument.Datetime dtelement = doc.getDatetime();
  106          ImportantDate[] impdate = dtelement.getImportantDateArray();
  107   
  108          // Loop through the <important-date> elements, printing the
  109          // values for each.
  110          for (int i=0;i<impdate.length;i++){
  111   
  112              //For purpose of simplicity in output, only first occurrence is printed.
  113              if (i==0){
  114   
  115                  //Retrieving all <holiday> elements within  <important-date> element
  116                  XmlDate[] holiday = impdate[i].xgetHolidayArray();
  117                  System.out.println("Holiday(xs:date): ");
  118   
  119                  for (int j=0;j<holiday.length;j++){
  120                      if (j==0){
  121                          //XmlDate to java.util.Calendar,org.apache.xmlbeans.GDate, java.util.Date
  122                          System.out.println("Calendar:" + holiday[j].getCalendarValue() );
  123                          System.out.println("Date:"+holiday[j].getDateValue() );
  124                          System.out.println("GDate:"+holiday[j].getGDateValue() +"\n");
  125                      }
  126                  }
  127   
  128                  //XmlTime to java.util.Calendar, org.apache.xmlbeans.GDate, java.util.Date
  129                  System.out.println("Fun Begin Time(xs:time): ");
  130                  System.out.println("Calendar:"+impdate[i].getFunBeginTime());
  131                  System.out.println("GDate:"+impdate[i].xgetFunBeginTime().getGDateValue()  );
  132   
  133                  //To convert java.util.Calendar to java.util.Date
  134                  SimpleDateFormat sdf = new SimpleDateFormat("H:mm:ss");
  135                  Date dt = impdate[i].getFunBeginTime().getTime();
  136                  System.out.println("Date:"+ sdf.format(dt) +"\n" );
  137   
  138   
  139                  //XmlDuration to org.apache.xmlbeans.GDuration
  140                  System.out.println("Job Duration(xs:duration): ");
  141                  System.out.println("GDuration:"+impdate[i].getJobDuration() +"\n" );
  142   
  143                  //XmlDate to Calendar,GDate, Date
  144                  System.out.println("Birth DateTime(xs:dateTime): ");
  145                  System.out.println("Calendar:"+impdate[i].getBirthdatetime());
  146                  System.out.println("Date:"+impdate[i].xgetBirthdatetime().getDateValue());
  147                  System.out.println("GDate:"+impdate[i].xgetBirthdatetime().getGDateValue() +"\n" );
  148   
  149   
  150                  //XmlGday to Calendar,GDate, Day - primitive java int
  151                  System.out.println("Pay Day(xs:gDay): ");
  152                  System.out.println("Calendar:"+impdate[i].getPayday());
  153                  System.out.println("GDate:"+impdate[i].xgetPayday().getGDateValue());
  154                  System.out.println("Day:"+ impdate[i].xgetPayday().getGDateValue().getDay() +"\n" );
  155   
  156                  System.out.println("\n\n");
  157              }
  158          }
  159   
  160      }
  161   
  162      /**
  163       * This method creates an new <important-date> element and attaches to the existing XML Instance, and saves the
  164       * new Instance to a file(args[1]).
  165       */
  166      public void createDocument(DatetimeDocument doc , String file){
  167          // Retrieve the <datetime> element and add a new <important-date> element.
  168          DatetimeDocument.Datetime dtelement = doc.getDatetime();
  169   
  170          //
  171          // add an important date using XmlCalendar
  172          //
  173   
  174          ImportantDate impdate = dtelement.addNewImportantDate();
  175   
  176          //Creating value for <holiday> element
  177          Calendar  holiday = new XmlCalendar("2004-07-04");
  178   
  179          //Creating value for <fun-begin-time> element
  180          Calendar  funbegintime = new XmlCalendar("10:30:33");
  181   
  182          //Creating value for <fun-end-time> element
  183          Calendar  funendtime = new XmlCalendar("12:40:12");
  184   
  185          //Creating value for <birthdatetime> element
  186          Calendar  birthdatetime = new XmlCalendar("1977-11-29T10:10:12");
  187   
  188          //Creating value for <job-duration> element
  189          GDuration jobduration =  new GDuration(1,2,4,5,10,12,15,null);
  190   
  191          //Creating value for <payday> element
  192          Calendar payday = new XmlCalendar("---12");
  193   
  194          //Setting all the elements
  195          impdate.addHoliday(holiday);
  196          impdate.setFunBeginTime(funbegintime);
  197          impdate.setFunEndTime(funendtime);
  198          impdate.setJobDuration(jobduration);
  199          impdate.setBirthdatetime(birthdatetime);
  200          impdate.setPayday(payday);
  201          impdate.setDescription("Using XmlCalendar");
  202   
  203   
  204          //
  205          // add another important date using Calendar
  206          //
  207   
  208          impdate = dtelement.addNewImportantDate();
  209   
  210          //Creating value for <holiday> element using XmlCalendar
  211          holiday = new XmlCalendar("2004-07-04");
  212   
  213          //Creating value for <fun-begin-time> element using GregorianCalendar
  214          funbegintime = Calendar.getInstance();
  215          funbegintime.clear();
  216          funbegintime.set(Calendar.AM_PM , Calendar.AM);
  217          funbegintime.set(Calendar.HOUR, 10);
  218          funbegintime.set(Calendar.MINUTE, 30 );
  219          funbegintime.set(Calendar.SECOND, 35 );
  220   
  221          //Creating value for <fun-end-time> element
  222          funendtime = Calendar.getInstance();
  223          funendtime.clear();
  224          funendtime.set(Calendar.AM_PM , Calendar.AM);
  225          funendtime.set(Calendar.HOUR, 12);
  226          funendtime.set(Calendar.MINUTE, 40 );
  227          funendtime.set(Calendar.SECOND, 12 );
  228   
  229          //Creating value for <birthdatetime> element
  230          birthdatetime = Calendar.getInstance();
  231          birthdatetime.clear();
  232          birthdatetime.set(1977,10,29,10,10,12);
  233   
  234          //Creating value for <job-duration> element
  235          jobduration =  new GDuration(1,2,4,5,10,12,15,null);
  236   
  237          //Creating value for <payday> element
  238          payday = Calendar.getInstance();
  239          payday.clear();
  240          payday.set(Calendar.DAY_OF_MONTH,12);
  241   
  242          //Setting all the elements
  243          impdate.addHoliday(holiday);
  244          impdate.setFunBeginTime(funbegintime);
  245          impdate.setFunEndTime(funendtime);
  246          impdate.setJobDuration(jobduration);
  247          impdate.setBirthdatetime(birthdatetime);
  248          impdate.setPayday(payday);
  249          impdate.setDescription("Using Calendar");
  250   
  251          XmlOptions xmlOptions = new XmlOptions();
  252          xmlOptions.setSavePrettyPrint();
  253   
  254          // Validate the new XML
  255          boolean isXmlValid = validateXml(doc);
  256          if (isXmlValid) {
  257              File f = new File(file);
  258   
  259              try{
  260                  //Writing the XML Instance to a file.
  261                  doc.save(f,xmlOptions);
  262              }
  263              catch(IOException e){
  264                  e.printStackTrace();
  265              }
  266              System.out.println("\nXML Instance Document saved at : " + f.getPath());
  267          }
  268      }
  269   
  270      /**
  271       * <p>Validates the XML, printing error messages when the XML is invalid. Note
  272       * that this method will properly validate any instance of a compiled schema
  273       * type because all of these types extend XmlObject.</p>
  274       *
  275       * <p>Note that in actual practice, you'll probably want to use an assertion
  276       * when validating if you want to ensure that your code doesn't pass along
  277       * invalid XML. This sample prints the generated XML whether or not it's
  278       * valid so that you can see the result in both cases.</p>
  279       *
  280       * @param xml The XML to validate.
  281       * @return <code>true</code> if the XML is valid; otherwise, <code>false</code>
  282       */
  283      public boolean validateXml(XmlObject xml)
  284      {
  285          boolean isXmlValid = false;
  286   
  287          // A collection instance to hold validation error messages.
  288          ArrayList validationMessages = new ArrayList();
  289   
  290          // Validate the XML, collecting messages.
  291          isXmlValid = xml.validate(new XmlOptions().setErrorListener(validationMessages));
  292   
  293          if (!isXmlValid)
  294          {
  295              System.out.println("Invalid XML: ");
  296              for (int i = 0; i < validationMessages.size(); i++)
  297              {
  298                  XmlError error = (XmlError) validationMessages.get(i);
  299                  System.out.println(error.getMessage());
  300                  System.out.println(error.getObjectLocation());
  301              }
  302          }
  303          return isXmlValid;
  304      }
  305   
  306   }
  307   
  308   

Home » xmlbeans-2.5.0-src » org.apache.xmlbeans.samples » datetime » [javadoc | source]