Home  |  Software Components  |  Examples  |  Books  

Application Examples

Each of these mini applications shows how to use one particular feature of Cedar Spring's TVM Java Bean. They are complete applications, but in order to keep them to a minimum size, they do not have formatting, error checking, and other essentials of production apps. All examples use the TVMu (unsynchronized) version of the bean.

Instructions for running the examples are at the bottom of this page.

 

Example 1. Compute a Property

You can set any four of these TVM properties and then compute the fifth:

  • presentValue
  • futureValue
  • payment
  • interestRate
  • numberOfPeriods

Each property has get, set, and computeProperty() methods.


import java.math.*;
import com.cedarspring.tvm.*;

public class Payments {

  public void calculatePayment() {
    // instantiate a TVM calculator object
    TVMu tvm = new TVMu();

    // set TVM properties. A $100,000 loan at 6% annual 
    // interest rate for 30 years (360 payment periods) 
    tvm.setPresentValue(new BigDecimal("100000"));
    tvm.setInterestRate(new BigDecimal("6.0"));	
    tvm.setNumberOfPeriods(new BigDecimal("360"));

    // compute the payment
    tvm.computePayment();

    // Get the payment and print it.
    System.out.println("Payment: " + tvm.getPayment());
  }

  public static void main(String[] args) {
    Payments e = new Payments();
    e.calculatePayment();
  }

}

Result:
Payment: -599.5505

 

Example 2. Error Events

When an error occurs in the TVM bean, an Error Event is fired instead of throwing an exception to make visual wiring easier. Refer to IBM´s tutorials: "Visual programming tutorial - Visual debugging and error handling" and "Designing beans for visual programming - Handling errors".

Example 1 did not check for input errors. If we had entered -6.0% for the interest rate, TVM would have fired an error event and let the rate set to its original value (0 by default). We can capture these events by:

  • implementing the ErrorListener interface
  • adding an errorOccurred() method that TVM will invoke when an error occurs
  • registering our app with TVM by means of the TVM.addErrorListener(this) method

import java.math.*;
import com.cedarspring.tvm.*;

// 
public class Errors implements ErrorListener {

  public void testErrors() {
    // instantiate a TVM calculator object
    TVMu tvm = new TVMu();

    // register to receive ErrorEvents from TVM
    tvm.addErrorListener(this);

    // set TVM properties. A $100,000 loan at 6% annual 
    // interest rate for 30 years (360 payment periods).
    // The negative rate will cause and error event.
    tvm.setPresentValue(new BigDecimal("100000"));
    tvm.setInterestRate(new BigDecimal("-6.0"));	
    tvm.setNumberOfPeriods(new BigDecimal("360"));

    // compute the payment
    tvm.computePayment();

    // get the payment and print it.
    System.out.println("Payment: " + tvm.getPayment());
  }

  // TVM will invoke the errorOccurred() method of 
  // all objects that have registered to receive ErrorEvents.
  // Print the message and exit.
  public void errorOccurred (ErrorEvent er){
    System.out.println("Error number: " +   er.getErrorNumber());
    System.out.println("Error severity: " + er.getSeverity());
    System.out.println("Error message: " +  er.getMessage());
    System.exit(0);
  }

  public static void main(String[] args) {
    Errors e = new Errors();
    e.testErrors();
  }

}

Result:
Error number: 09
Error severity: 1
Error message: Range is 0 - 999% for interest rate per year

 

Example 3. Property Changes

In Example 2, we asked TVM to notify our application when an error occurs. We can also ask it to notify the application whenever any of its properties change. To do this, we just implement the PropertyChangeListener interface in exactly the same way we did ErrorListener interface.


import java.math.*;
import java.beans.*;
import com.cedarspring.tvm.*;

public class PropertyChanges 
  implements ErrorListener, PropertyChangeListener {

  public void testPropertyChanges() {
    // instantiate a TVM calculator object
    TVMu tvm = new TVMu();

    // register to receive error events
    tvm.addErrorListener(this);

    // register to receive property changes
    tvm.addPropertyChangeListener(this);

    // set TVM properties. A $100,000 loan at 6% annual 
    // interest rate for 30 years (360 payment periods) 
    tvm.setPresentValue(new BigDecimal("100000"));
    tvm.setInterestRate(new BigDecimal("6.0"));	
    tvm.setNumberOfPeriods(new BigDecimal("360"));

    // compute the payment
    tvm.computePayment();

    // get the computed payment and print it.
    System.out.println("Payment: " + tvm.getPayment());
  }

  // when an error occurs, print a message and exit 
  public void errorOccurred (ErrorEvent ee){
    System.out.println("Error number: " +   ee.getErrorNumber());
    System.out.println("Error severity: " + ee.getSeverity());
    System.out.println("Error message: " +  ee.getMessage());
    System.exit(0);
  }

  // when a property changes, print the property name and the 
  // old and new values
  public void propertyChange (PropertyChangeEvent pe) {
    System.out.println("Property: " + pe.getPropertyName());
    System.out.println("Old: " + pe.getOldValue());
    System.out.println("New: " + pe.getNewValue());
  }


  public static void main(String[] args) {
    PropertyChanges e = new PropertyChanges();
    e.testPropertyChanges();
  }

}

Result:
Property: presentValue
Old: 0
New: 100000
Property: interestRate
Old: 0
New: 6.0
Property: numberOfPeriods
Old: 0
New: 360
Property: payment
Old: null
New: -599.5505
Payment: -599.5505

 

Example 4. Amortization

TVM can create a loan amortization schedule that devides each payment into principal and interest and shows the ending balance for the period. It can also sum the interest and principal over a range of periods.


import java.math.*;
import java.beans.*;
import com.cedarspring.tvm.*;

public class Amort implements ErrorListener {

  public void testAmortization() {
    // instantiate a TVM calculator object
    TVMu tvm = new TVMu();

    // register to receive error events
    tvm.addErrorListener(this);

    // set TVM properties. A $100,000 loan at 6% annual 
    // interest rate for 30 years (360 payment periods) 
    tvm.setPresentValue(new BigDecimal("100000"));
    tvm.setInterestRate(new BigDecimal("6.0"));
    tvm.setNumberOfPeriods(new BigDecimal("360"));

    // compute the payment
    tvm.computePayment();

    // get the loan amortization schedule.  The schedule
    // contains a list of amortization objects - one for 
    // each payment period.
    AmortizationSchedule as = tvm.getAmortizationSchedule();
    if (!as.isEmpty()) {
       // print a break out of p & i and the ending balance
       // for each payment. Periods begin with 1!
       for (int i=1; i<=as.getPeriods(); i++) { 
         // get the amortization for period i from the schedule
         Amortization a=as.getAmortization(i);
         // print principal, interest, and balance 
         System.out.println("Payment " + i); 
         System.out.println(" Principal: " + a.getPrincipal()); 
         System.out.println(" Interest: " + a.getInterest()); 
         System.out.println(" Balance: " + a.getBalance()); } 

         // get the total interest paid. 
         Amortization a=as.getAmortization(1,as.getPeriods()); 
         System.out.println("\nTotal Interest paid:" + a.getInterest()); 
       } 
      } 

    // when an error occurs, print a message and exit 
    public void errorOccurred (ErrorEvent ee){ 
      System.out.println("Error number: " + ee.getErrorNumber()); 
      System.out.println("Error severity: " + ee.getSeverity()); 
      System.out.println("Error message: " + ee.getMessage()); 
      System.exit(0); 
    } 

    public static void main(String[] args) { 
      Amort e=new Amort(); 
      e.testAmortization(); 
    } 
 } 


Result:
Payment 1
Principal: -99.5505
Interest: -500.0000
Balance: 99900.4495
Payment 2
Principal: -100.0483
Interest: -499.5022
Balance: 99800.4012
 
[payments 3-359 omitted]
 
Payment 360
Principal: -596.5675
Interest: -2.9830
Balance: 0.0231
Total Interest paid:-115838.2031

 

Example 5. Serialize TVM

The TVM bean can be customized to your specifications without changing the internal code. For example, you may always want to use 2 compounding periods per year instead of the 12 that you get by default. You can open a standard copy of the bean, set your custom values, and then serialize it to create a new version that contains your preferences.


import java.io.*;
import java.math.*;
import com.cedarspring.tvm.*;

public class SerializeTVM 
{
  public void testSerialize() {
    try {

      // instantiate a new TVM object
      TVMu tvm = new TVMu();

      // customize it by setting properties
      tvm.setPresentValue(new BigDecimal("100000"));
      tvm.setInterestRate(new BigDecimal("6.0"));
      tvm.setNumberOfPeriods(new BigDecimal("360"));

      // Serialize it to a flat file (TVM.ser)
      ObjectOutputStream out = new ObjectOutputStream(
	new FileOutputStream("TVM.ser"));
      out.writeObject(tvm);
      out.flush();
    } catch (Exception e) {
        System.out.println("Serialization Exception: " + e);
    }
  }

  public static void main(String[] args) {
    SerializeTVM e = new SerializeTVM();
    e.testSerialize();
  }
}


Result:
A new file named TVM.ser

 

Now you can use this customized version in your applications, but you must use Bean.Instantiate() instead of new. Instantiate will search the classpath for the serialized version (TVM.ser) first. If one is not found it will search again for TVM.class.

 
import java.io.*;
import java.math.*;
import java.beans.*;
import com.cedarspring.tvm.*;

public class DeserializeTVM {
  public void testDeserialize() {
    try {
      // search the classpath for com.cedarspring.tvm.TVM.ser
      // If found, instantiate it. Else, search again for
      // com.cedarspring.tvm.TVM.class
      tvm = (TVMu)Beans.instantiate(null,"TVM");
    } catch (Exception ie) {
        System.out.println("Cannot instantiate TVM. " + ie);
        System.exit(0);
    }
    
    System.out.println(tvm);
  }

  public static void main(String[] args) {
    DeserializeTVM e = new DeserializeTVM();
    e.testDeserialize();
  }

  TVMu tvm;
}


Result:
presentValue : 100000
futureValue : 0
payment : 0
interestRate : 6.0
numberOfPeriods : 360
PaymentsPerYear : 12
CompoundingPerYear : 12
payAtEnd : true
roundUp : true
enterRateAsPercent : true

 

Example 6. Package Versioning

Beginning with TVM Version 1.2.0, you can extract package version information from the jar files. See Sun's Package Versioning Specification for more info.

 
import com.cedarspring.tvm.*;

public class Versioning 
{
  public void testVersioning() {
    TVMu tvm = new TVMu();
    Package p = Package.getPackage("com.cedarspring.tvm");
   if (p != null) {		
      System.out.println("Name: " + p.getName());
      System.out.println("SpecificationTitle: "    
         + p.getSpecificationTitle());
      System.out.println("SpecificationVersion: "  
         + p.getSpecificationVersion());
      System.out.println("SpecificationVendor: "   
         + p.getSpecificationVendor());
      System.out.println("ImplementationTitle: "   
         + p.getImplementationTitle());
      System.out.println("ImplementationVersion: " 
         + p.getImplementationVersion());
      System.out.println("ImplementationVendor: "  
         + p.getImplementationVendor());
    }
  }

  public static void main(String[] args) {
    Versioning e = new Versioning();
    e.testVersioning();
  }
}

  

Result:
Name: com.cedarspring.tvm
SpecificationTitle: TVM
SpecificationVersion: 1.2.2
SpecificationVendor: Cedar Spring Software Inc.
ImplementationTitle: cedarspring.TVM
ImplementationVersion: 1.2.2-u Build 4
ImplementationVendor: Cedar Spring Software Inc.

 

   

Running the Applications

To run the examples using Windows:
  • Create a new directory c:\beans
  • Create a new directory c:\programs.
  • Download the TVMu bean and unzip it into c:/beans
  • Cut and paste one of the examples into notepad and save it to c:\programs with a file name that exactly matches the class name. Use an extention of .java. For instance, save Example #1 as Payments.java. Be sure to use upper and lower case letters that exactly match the class name.
  • Start the Windows Command line interpreter: Start|Run and enter command.com into the input field
  • Compile the program with javac and run it with java:

cd c:\programs 
javac -classpath c:/beans/tvm/TVM.jar Payments.java 
java -classpath .;c:/beans/tvm/TVM.jar Payments


 
Copyright ©1998-2007 Cedar Spring Software, Inc.  All Rights Reserved
Privacy | Legal & Terms of Use | Trademarks | Feedback | About