Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

1/26/10

Java Frame

package com.essbase.samples.japi;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.sql.*;
import com.essbase.api.base.*;
import com.essbase.api.session.*;
//import com.essbase.api.datasource.IEssCube;
//import com.essbase.api.datasource.IEssOlapFileObject;
import com.essbase.api.datasource.IEssOlapServer;
import com.essbase.api.domain.*;

public class HypFrame extends JFrame {
/**
*
*/
private JTextField tfname = new JTextField();
private JPasswordField tfpass = new JPasswordField();
private static final int FAILURE_CODE = 1;

void buildConstraints(GridBagConstraints gbc, int gx, int gy,
int gw, int gh, int wx, int wy) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
}

void MainFrame()
{
// String title = (args.length == 0 ? "Main Frame" : args[0]);
JFrame frame= new JFrame("title");
//Container content = frame.getContentPane();
JPanel panel=new JPanel();
JTextArea jt= new JTextArea("Welcome Roseindia",15,29);
frame.add(panel);
//content.add(jt);
JScrollPane rightPane = new JScrollPane(jt);
panel.add(rightPane);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();

buildConstraints(constraints, 0, 0, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn1 = new JButton("button 1");
gridbag.setConstraints(btn1, constraints);
panel.add(btn1);

buildConstraints(constraints, 0, 1, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn2 = new JButton("button 2");
gridbag.setConstraints(btn2, constraints);
panel.add(btn2);

buildConstraints(constraints, 0, 2, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn3 = new JButton("button 3");
gridbag.setConstraints(btn3, constraints);
panel.add(btn3);

buildConstraints(constraints, 1, 0, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn4 = new JButton("button 4");
gridbag.setConstraints(btn4, constraints);
panel.add(btn4);

buildConstraints(constraints, 1, 1, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn5 = new JButton("button 5");
gridbag.setConstraints(btn5, constraints);
panel.add(btn5);

buildConstraints(constraints, 1, 2, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JButton btn6 = new JButton("button 6");
gridbag.setConstraints(btn6, constraints);
panel.add(btn6);

frame.setSize(340,380);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] arguments) {
HypFrame frame = new HypFrame();
frame.setVisible(true);
//.show();
}

void connectEssbase(){
int statusCode = 0; // will set this to FAILURE only if err/exception occurs.
IEssbase ess = null;
String s_provider ="http://localhost:13080/aps/JAPI";
String s_olapSvrName="localhost";
try {
// Create JAPI instance.
ess = IEssbase.Home.create(IEssbase.JAPI_VERSION);
// Sign On to the Provider
IEssDomain dom = ess.signOn(tfname.getText(), tfpass.getText(), false, null, s_provider);
IEssOlapServer olapSvr = dom.getOlapServer(s_olapSvrName);
olapSvr.connect();
System.out.println("Connection to Analyic server '" +olapSvr.getName()+ "' was successful.");
String apiVersion = ess.getApiVersion();
String apiVerDetail = ess.getApiVersionDetail();
System.out.println("API Version :"+apiVersion);
System.out.println("API Version Detail :"+apiVerDetail);
} catch (EssException x) {
System.err.println("Error: " + x.getMessage());
statusCode = FAILURE_CODE;
} finally {
// Sign off.
try {
if (ess != null && ess.isSignedOn() == true)
ess.signOff();
} catch (EssException x) {
System.err.println("Error: " + x.getMessage());
}
}

// Set status to failure only if exception occurs and do abnormal termination
// otherwise, it will by default terminate normally

if (statusCode == FAILURE_CODE) System.exit(FAILURE_CODE);
}
void connectOrcl(){
String data = "jdbc:odbc:orcl";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(data,
tfname.getText(), tfpass.getText());
Statement st = conn.createStatement();
System.out.println("Connected to orcl successfully!");
ResultSet rec = st.executeQuery(
"SELECT * " +
"FROM TBC.Family " +
"WHERE " +
"(FAMILYID='" + 1 + "') " +
"ORDER BY FAMILYID");
System.out.println("FIPS\tCOUNTRY\tYEAR\t" +
"ANTHRACITE PRODUCTION");
while(rec.next()) {
System.out.println(rec.getString(1) + "\t"
+ rec.getString(2) + "\t"
+ rec.getString(3) + "\t"
+ rec.getString(4));
}
st.close();
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString()
+ e.getMessage());
}
}
public HypFrame() {
super("Username and Password");
setSize(290, 110);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel pane = new JPanel();
pane.setLayout(gridbag);
// Name label
buildConstraints(constraints, 0, 0, 1, 1, 10, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JLabel label1 = new JLabel("Username:", JLabel.LEFT);
gridbag.setConstraints(label1, constraints);
pane.add(label1);

// Name text field
buildConstraints(constraints, 1, 0, 1, 1, 90, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
// JTextField tfname = new JTextField();
gridbag.setConstraints(tfname, constraints);
pane.add(tfname);

// password label
buildConstraints(constraints, 0, 1, 1, 1, 0, 40);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JLabel label2 = new JLabel("Password:", JLabel.LEFT);
gridbag.setConstraints(label2, constraints);
pane.add(label2);

// password text field
buildConstraints(constraints, 1, 1, 1, 1, 0, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
tfpass.setEchoChar('*');
gridbag.setConstraints(tfpass, constraints);
pane.add(tfpass);

// OK Button
buildConstraints(constraints, 0, 2, 2, 1, 0, 20);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.CENTER;
JButton btnOk = new JButton("Ok");
gridbag.setConstraints(btnOk, constraints);
btnOk.addActionListener(new ButtonListener());
pane.add(btnOk);

setContentPane(pane);
}
class ButtonListener implements ActionListener {
ButtonListener() {
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Ok")) {
System.out.println("Button Ok has been clicked");
MainFrame();
connectOrcl();
connectEssbase();
}
}
}
}

12/27/09

Java Tips

  • Inheritance is the mechanism that a sub class inherit the behavior and attributes of a super class.
  • An interface is a clollection of methods that indicate a class has some behavior in addition to what it inherits from its superclasses. The methods included in an interface do not define this behavior, that task is left for the classes that implement the inteface. To use an interface, include implements keyword as part of your class definition
    public class AnimationSign extends javax.swing.JApplet
    implements Runable {...}
  • Overriding: the method created in the sub class has the same nane as the super class, this is called overrriding.
  • Package is a way of grouping related classes and interfaces. Such as: java.awt.*,java.lang.*.
  • Literal: A literal is any number,text,or other information that directly represents a value. include: number literal(1,2,3), boolean literal(true,false),character literal(\n,\t),string literal("sss").
  • A reference is an address that indicates where an object's variable and methods are stored.
  • Casting between primitive types enables you to convert the value of one type to another primitive type. such as from int to float. Sample: (int)(x/y),(classname)object,(typename)value.
  • To find out what an object's class is: String name = key.getClass().getName();
  • instanceof operator return true or false: "Texta" instanceof String //true
  • this keyword refer to the current object: t = this.x;
  • Overloading: Methods with the same name but with different number of arguments or/and data type.
  • Constructor mrthod is a method that is called on an object when it is created. The method has the same name as the class. this(arg1,arg2,arg3) can be used to call a constructor method. Constructor can be overloaded too.
  • Use the super keyword to call the original method from inside a method definition:
    void mymethod(String a, String b) {super.mymethod(a,b);}
  • finalizer method is called just before the object is collected for garbage and has its memory reclaimed.
    protected void finalize() throws Throwable {super.finalize();} Finalizer method is used for optimizing the removal of an object. In most cases, you don't need to use finalize(0 at all
  • Applet runs on browser that support Java.
  • Painting is how an applet displays something onscreen. repaint();
  • Java archive is a collection of Java classes and other files packaged into a single file.
    jar cf Animated.jar *.class *.gif
  • Swing is a part of the Java Foundation Classes library, provide a way to offer a graphical user interface. The swing is an extension of awt. javax.swing, javax.swing.JFrame,javax.swing.JWindow. Two other packages that are used with graphical user interface programming are java.awt and java.awt.event
  • Threads are parts od program that are set up to run on their own while the rest of program does something else. This is called multitasking because the program can handle more than one tasks simultaneously.
  • final class cannot be subclassed
  • You can define a class inside a class, as if it were a method or a variable.These classes are called inner classes. Inner class are invisible to all other classes,no need to worry about the name conflicts between it and other classes.
    public class Inner extends javax.swing.Applet {...}
  • Exception catch:
    try{}
    catch (IOExceptio e){}
    catch (ClassNotFoundException e){}
    catch (InterrptedException e){}
    finally{
    }
  • finnally statement is actually useful outside exceptions,you can aalso use it to execute cleanup code after s return,a break,or a continue inside loops.
  • The throw clause: public boolean myMethod(int x,int y) throws AnException {}
  • A digital signiture is an encriped file that accompany a program indicating exactly from whom the files come from. The document that represents this digital signiture is called a certificate.
  • java.io: FileInputStream and FileOutputStream - Byte streams stored in files on disk,CD-ROM,or other storage devices
  • java.io: DataInputStream and DataOutputStream - A filtered byte stream from which data such as integers and floating-point numbers can be read
  • Java handles access to external data via the use of a class of objects called streams. A stream is an object that carries data from one place to another.
  • Object serialization: the capability to reaad and write an object using steams.
  • Objects can be serialized to disk on a single machine or can be serialized across a network.
  • Persistence : the capability of an object to exist and function outside the program that created it. Serialization enables object persistence.
    FileOutputStream disk = new FileOutputStream("SavedObject.dat")
    ObjectOutputStream obj = new ObjectOutputStream(disk)
  • RMI(remote method invocation): creates Java application that can talk to other Java application over a network. RMI allows an application to call methods and access variables inside another application, which might be running in a different Java Envirnment or different OS altogether, and pass objects back and forth over a network connection.
    java.rmi.server, java.rmi.registry, java.rmi.dgc
  • Before code with RMI, use rmic command-line program to generate the Stub and Skeleton layers so that RMI can actually work between the two sides of the process
  • RPC(Remote Procedure calls): sends only procedure calls over the wire, while RMI actually pass the whole object.
  • Socket: Java provides the Socket and ServerSocket classes as an abstraction of standard TCP socket program techniques. The Socket class provides s client side socket interface similar to standard UNIX socket.
    Socket connection = new Socket(hostName, portNum);
    connection.setSoTimeOut(50000);
    BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
    DataInputStream in = new DataInputStream(bis);
    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
    DataOutputStream out = new DataOutputStream(bos);
  • Sever Side sockets work similar to client side sockets, with the exception of the accept() method. The accept() method accepts a connection from that client..
  • JavaBeans is an architecture and platform independent set of classes for crreating and using Java software components. You can drop a JavaBean component directly into an application without writing any code.
  • Java Database connectiion, 2 ways: JDBC-ODBC bridge, or JDBC drivers
    JDBC-ODBC bridge allows JDBC drivers to be used as ODBC drivers by converting JDBC method calls into ODBC function calls. The next is a sample for JDBC-ODBC:
    Connection payday = DriverManager.getConnection("jdbc.odbc:Payroll","Doc","Notnow");
  • The next is a sample for JDBC:
    Connection payday = DriverManager.getConnection("jdbc:JDataConnect://localhost:1150/Presidents","","");
  • Java Data Structure
  • BitSet class implements a group of bits or flags that can be set an cleared individually.
    class Somebits {
        public static final int READABLE = 0;
        public static final int WRITABLE = 1;
        public static final int STREAMABLE = 2;

        public static final int FLEXIBLE = 3;
    }
  • Vectr class implements an extendable array of objects
    Vector v = new Vector();
    v.add("Bob");
  • Stacks are a classic data structure used, last in, first out
    Stack s = new Stack();
    s.push("One");
    s.push("two");
    String s1 = (String)s.pop();
  • Map interface defines a framework for implementing a basic key-mapped data structure.
  • Hashtable class is derived from dictionary, implements the Map interface, and provides a complete implementation of a key-mapped data structure.

12/25/09

Embedded Java API - Hyperion Application Builder

The next picture is a sample that is developed by Hyperion Application Builder:

The Embedded Java Application Programming Interface (JAPI) feature is a simple deployment of the JAPI solution. Enabling this feature will provide the Application Builder for .NET applications to establish connection with the Essbase servers even when Provider Services is not installed, see Figure. The connection protocol between the Application Builder for .NET
applications and the Essbase servers is TCP/IP or HTTPS.

The embedded JAPI deployment for Application Builder for .NET includes .jar files and property files. When you enable the embedded JAPI feature, the Application Programming Interface (API) client will include these .jar files and property files in the Application Builder for .NET application.

Prerequisites
Some of the current Java API customers may require only Java API functionality, and will not require a full installation of the Provider Services product with the extended functionality such as Clustering, High Availability, Connection Pooling, and XMLA provider.

Complete these prerequisites to enable this feature:
● %APS_HOME% should contain both \bin and \data folders
● %APS_HOME%\bin should contain essbase.properties file
● Update the Habnet.properties file.
In \HABNET_HOME\products\Essbase\habnet\Server\lib\, In Habnet.properties file include value EDSUrl=Embedded.
● From Essbase server installation location: HABNET_HOME\products\Essbase\habnet\server\lib copy the Essbase.properties file to %APS_HOME%\bin. Enabling Embedded JAPI
The embedded JAPI feature is available when you install this release of Application Builder for .NET. However, to enable this feature, you must do some updates to the Habnet.properties file. With this feature update to the Application Builder for .NET release, to establish connection between Application Builder for .NET applications and Essbase has a option of using either Provider Services or embedded JAPI depending on the requirement.

This utility is run based on the following assumptions:
● The password information of the Essbase servers are read without any encryption.
● The user ID and password information is used for authentication and this utility will update only the server name information in the domain.db file.
● The utility will read the environment variables APS_HOME and ABNET_HOME to get the location information of the files domain.db and essbase_servers.xml.
➤ To enable the embedded JAPI utility:
1 In the Habnet.properties file, for EDSUrl provide the value Embedded.
2 Save and close the Habnet.properties file.
➤ To revert to Provider Services:
1 In the Habnet.properties file, for EDSUrl provide the value EDSUrl = http://
name>:/aps/JAPI.
2 Save and close the Habnet.properties file.
Managing the Embedded JAPI Feature
This feature offers a utility that gathers the Essbase server information (server name, user ID,and password) from the XML template file essbase_servers.xml and updates the domain.db file. The user has a privilege to add the server information in essbase_servers.xml to "add","delete" and "None" actions to update the domain.db file.
The essbase_servers.xml file must include these server information:
"password">  

"password">


In essbase_servers.xml file the action attribute can have one of the following values:
Add, Delete and None. Add value adds the specified server information to domain.db file.
Delete value deletes the specified server information from the domain.db file. None value means no action performed on the domain.db file. The Application Builder for .NET applications will use this information that is present in the domain.db file to communicate with the Essbase servers. The domain.db file is present in the folder APS_HOME\data.
Running the Embedded JAPI Utility
As prerequisite, the essbase_servers.xml file must be present in the location \HABNET_HOME\products\Essbase\habnet\Server\lib. Once this utility is run, the domain.db file is created in the location APS_HOME\data.
You can run the embedded JAPI utility from the Application Builder for .NET installation directories. The embedded JAPI utilty will update the server information in the domain.db file.
➤ To run the embedded JAPI utility and update the XML template file:
1 For Windows: from %HABNET_HOME%\products\Essbase\habnet\Server\bin\, run command
ESSJapiUtil.bat.
2 For Unix: from $HABNET_HOME/products/Essbase/habnet/Server/bin/, run command
ESSJapiUtil.sh.
You can register or deregister the Essbase servers with or without resetting the password or exporting the Essbase server information.
➤ To register the Essbase servers and reset the Essbase server passwords:
1 For Windows: from %HABNET_HOME%\products\Essbase\habnet\Server\bin\, run command
ESSJapiUtil.bat register.
2 For Unix: from $HABNET_HOME/products/Essbase/habnet/Server/bin/, run command
ESSJapiUtil.sh register.
➤ To export the Essbase server information (This command will not record the password information):
1 In \HABNET_HOME\products\Essbase\habnet\Server\lib create the
essbase_servers_export.xml file.
2 For Windows: from %HABNET_HOME%\products\Essbase\habnet\Server\bin\, run command
ESSJapiUtil.bat export.
 
3 For Unix: from $HABNET_HOME/products/Essbase/habnet/Server/bin/, run command
ESSJapiUtil.sh export.
➤ To register Essbase servers without passwords reset:
1 For Windows: from %HABNET_HOME%\products\Essbase\habnet\Server\bin\, run command
ESSJapiUtil.bat registernoreset.
2 For Unix: from $HABNET_HOME/products/Essbase/habnet/Server/bin/, run command
ESSJapiUtil.sh registernoreset.

Application Builder for .NET

Application Builder for .NET provides a comprehensive set of OLAP-aware classes for data navigation, selection, reporting, and visualization to assist you in building custom analytical applications. These controls provide you with the tools to quickly create and deploy applications in stand-alone, client-server, Web, or distributed processing environments. Application Builder for .NET is a component of the Oracle Enterprise Performance Management system that provides an application development workbench for companies wanting to use the Microsoft .NET Framework to create tailored business performance management solutions. Application Builder for .NET includes the following key features:
● Drag and Drop components for creating OLAP aware applications for Web and Windows using MS Visual Studio.Net
● .NET Framework compatibility
● Web Service -based architecture (SOAP)
Application Builder for .NET provides the following functionality:
● Base classes. These classes contain basic OLAP functionality and encapsulate functionality necessary to connect to and perform operations on Essbase applications and databases.
● Dialog components. These classes encapsulate the functionality of Essbase dialog boxes, including the sign-on and member selection dialog boxes.

To develop Application Builder for .NET applications within Visual Studio for .NET, perform the following steps:
● Install and configure Microsoft Visual Studio for .NET.
● Install Application Builder for .NET and note which directory contains theApplication Builder for .NET assemblies.
● If you are developing an ASP .NET (Active Server Pages) application, install or ensure access to an instance of Microsoft Internet Information Server (IIS).
● If you are developing applications using Microsoft Office Web Components (OWC11), you may need to add Microsoft Office Primary Interop Assemblies and install additional assemblies available from http://www.microsoft.com/.
● Install or ensure access to an Essbase server and application.
This guide assumes that you will be using the Sample application and Basic database installed with Essbase.
● Ensure that the Application Builder for .NET .WAR file has been applied to your Web application server.
● Ensure that Oracle Hyperion Provider Services™ is running, and that your application server can access it.

12/15/09

Java - the package list

com.sqribe.rm.*
          - Hyperion Performance Suite classes
com.essbase.api.*
          - Hyperion Essbase API classes
java.io.*   
          - input, output
java.io.File
          - It is the central class in working with files and directories
java.swing.*
          - an API for providing a graphical user interface (GUI) for Java programs.
java.awt.*
           - Contains all of the classes for creating user interfaces and for painting graphics and images.
java.awt.event.*
           - Provides interfaces and classes for dealing with different types of events fired by AWT components.
java.util.*
           - The package java.util contains a variety of utility classes including the collections framework, 
             internationalization, String utilities, etc
java.lang
            - Provides classes that are fundamental to the design of the Java programming language.

12/14/09

Java-Object Serialization

.Object serialization: the capability to read and write an object using stream.
.Reflection:the capability of one object to learn details about another object
.Remote method invocation: the capability to query another object to investigate its features and call its methods.

A programming concept involved in object serialization is persistence - the capability of an object to exist and function outside the pragram that create it.

An object indicates that it can be used with streams by implementing the Serializable interface. This interface, which is part of the java.io package, differs from other interfaces you have worked withit does not contain any methods that must be included in the classes that implement it. The sole purpose of Serializable is to indicate that objects of that class can be stored an retrieved in serial form.
The following code creates an output stream and an associated object output stream:

FileOutputStream disk = new FileOutputStream("SavedObject.dat");

ObjectOutputStream obj = new ObjectOutputStream(disk);

The object to Disk program:
----------
import java.io.*;

import java.util.*;
public class ObjectToDisk {
public static void main(String[] arguments) {
Message mess = new Message();
String author = "Sam Wainwright, London";
String recipient = "George Bailey, Bedford Falls";
String[] letter = { "Mr. Gower cabled you need cash. Stop.",
"My office instructed to advance you up to twenty-five",
"thousand dollars. Stop. Hee-haw and Merry Christmas." };
Date now = new Date();
mess.writeMessage(author, recipient, now, letter);
try {
FileOutputStream fo = new FileOutputStream("Message.obj");
ObjectOutputStream oo = new ObjectOutputStream(fo);
oo.writeObject(mess);
oo.close();
System.out.println("Object created successfully.");
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
class Message implements Serializable {
int lineCount;
String from, to;
Date when;
String[] text;
void writeMessage(String inFrom,
String inTo,
Date inWhen,
String[] inText) {
text = new String[inText.length];
for (int i = 0; i < inText.length; i++)
text[i] = inText[i];
lineCount = inText.length;
to = inTo;
from = inFrom;
when = inWhen;
}
}
--------------
The object from disk program:
import java.io.*;

import java.util.*;
public class ObjectFromDisk {
public static void main(String[] arguments) {
try {
FileInputStream fi = new FileInputStream("message.obj");
ObjectInputStream oi = new ObjectInputStream(fi);
Message mess = (Message) oi.readObject();
System.out.println("Message:\n");
System.out.println("From: " + mess.from);
System.out.println("To: " + mess.to);
System.out.println("Date: " + mess.when + "\n");
for (int i = 0; i < mess.lineCount; i++)
System.out.println(mess.text[i]);
oi.close();
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
}
}

Java - display all methods in a class

This method can display all metjods inside a class. This will use the Class class, which is part of java.lang package, is used to learn about and create classes,interfaces,and primitive types. To try the below program, enter:
java SeeMethods java.util.Random, and you will get

Method: next()
Modifiers: protected synchronized
Return type: int
Parameters: int

Method: nextDouble()
Modifiers: public
Return type: double
Parameters:
......

--------------------------------
import java.lang.reflect.*;


public class SeeMethods {
public static void main(String[] arguments) {
Class inspect;
try {
if (arguments.length > 0)
inspect = Class.forName(arguments[0]);
else
inspect = Class.forName("SeeMethods");
Method[] methods = inspect.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method methVal = methods[i];
Class returnVal = methVal.getReturnType();
int mods = methVal.getModifiers();
String modVal = Modifier.toString(mods);
Class[] paramVal = methVal.getParameterTypes();
StringBuffer params = new StringBuffer();
for (int j = 0; j < paramVal.length; j++) {
if (j > 0)
params.append(", ");
params.append(paramVal[j].getName());
}
System.out.println("Method: " + methVal.getName() + "()");
System.out.println("Modifiers: " + modVal);
System.out.println("Return Type: " + returnVal.getName());
System.out.println("Parameters: " + params + "\n");
}
} catch (ClassNotFoundException c) {
System.out.println(c.toString());
}
}
}

Java - JDBC connect DB

Use JDBC driver to access DB.

import java.sql.*;

public class Presidents {
public static void main(String[] arguments) {
String data =
try {
Class.forName("JData2_0.sql.$Driver");
Connection conn = DriverManager.getConnection("jdbc:JDataConnect://localhost:1150/Presidents","username","password");
Statement st = conn.createStatement();
ResultSet rec = st.executeQuery(
"SELECT * FROM Contacts ORDER BY NAME");
while(rec.next()) {
System.out.println(rec.getString("NAME") + "\n"
+ rec.getString("ADDRESS1") + "\n"
+ rec.getString("ADDRESS2") + "\n"
+ rec.getString("PHONE") + "\n"
+ rec.getString("E-MAIL") + "\n");
}
st.close();
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
}
}

Java - JDBC-ODBC bridge

JDBC is a set of classes that can be used to develop client/server database applications using Java. JDBC-ODBC bridge allows JDBC drivers to be used as ODBC drivers by coverting JDBC method into ODBC function calls. sun.jdbc.odbc.JdbcOdbcDriver is required.

import java.sql.*;

public class CoalTotals {
public static void main(String[] arguments) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:SampleDataSource", "username", "password");
Statement st = conn.createStatement();
ResultSet rec = st.executeQuery(
"SELECT * " +
"FROM Coal " +
"WHERE " +
"(Country='" + arguments[0] + "') " +
"ORDER BY Year");
System.out.println("FIPS\tCOUNTRY\t\tYEAR\t" +
"ANTHRACITE PRODUCTION");
while(rec.next()) {
System.out.println(rec.getString(1) + "\t"
+ rec.getString(2) + "\t\t"
+ rec.getString(3) + "\t"
+ rec.getString(4));
}
st.close();
} catch (SQLException s) {

System.out.println("SQL Error: " + s.toString() + " "+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString()+ e.getMessage());
}
}
}

12/5/09

Java - Trigger External Event

External Event Based job can be scheduled in Hyperion Portal Server, the key is to trigger the Event when the backend data loading is finished. The next code is about how to trigger the external event using Java method.

import com.sqribe.rm.*;
import java.util.Properties;
/*** example class for triggering an External event */

public class TriggerExternalEvent
{
public TriggerExternalEvent(String [] args)
{
try
{
Session session;
//--------------------------------------------------------------------
// obtain a session connection
//--------------------------------------------------------------------
if (args.length < 5) { throw new IndexOutOfBoundsException(); } else { session = SessionFactory.getInstance(args[0], args[1], args[2], new Integer(args[3]).intValue()); } System.out.println("connection established"); //---------------------------------------------------------------- // trigger external event //---------------------------------------------------------------- try { String EventName = args[4]; Scheduler sch = session.getScheduler(); ExternallyTriggeredEvent MyEvent = null; MyEvent = (ExternallyTriggeredEvent) .getExternallyTriggeredEvent(EventName); System.out.println("Event found..."); MyEvent.triggerETE(); System.out.println("Triggerred Event :: " + EventName); } catch (ReportMartException e) { System.out.println("Event not found"); e.printStackTrace(); } //---------------------------------------------------------------- // close the session when you no longer need it //---------------------------------------------------------------- session.close(); System.out.println("connection closed"); } catch (ReportMartException e) { System.out.println("connection could not be established"); e.printStackTrace(); } } /** * program entry point *


* @param String [] args - command line arguments
*/

public static void main(String [] args)
{
try
{
new TriggerExternalEvent(args);
}
catch (IndexOutOfBoundsException e)
{
System.err.println("usage: TriggerExternalEvent ");
}
}
}

12/2/09

Java - Run Essbase Report Script

/*
RunReport.java
*/
package com.essbase.samples.japi;
import com.essbase.api.base.*;
import com.essbase.api.session.*;
import com.essbase.api.datasource.*;
//import com.essbase.api.dataquery.*;
import com.essbase.api.domain.*;
//import com.essbase.api.metadata.*;
/**RunReport Example does the following: Signs on to essbase domain,
Runs a report and Signs Off.
In order for this sample to work in your environment, make sure to
change the s_* variables to suit your environment.
*/
public class RunReport {
// NOTE: Change the following variables to suit your setup.
private static String s_userName = "admin";
private static String s_password = "password";
private static String s_olapSvrName = "bobpc";
/* Possible values for s_provider:
"Embedded" or "http://localhost:13080/aps/JAPI" */
private static String s_provider = "Embedded"; // Default
private static final int FAILURE_CODE = 1;
public static void main(String[] args) {
int statusCode = 0;
IEssbase ess = null;
IEssOlapServer olapSvr = null;
try {
acceptArgs(args);
// Create JAPI instance.
ess = IEssbase.Home.create(IEssbase.JAPI_VERSION);
// Sign On to the Provider
IEssDomain dom
= ess.signOn(s_userName, s_password, false, null, s_provider);
// Open connection with OLAP server and get the cube.
olapSvr = (IEssOlapServer)dom.getOlapServer(s_olapSvrName);
olapSvr.connect();
IEssCube cube = olapSvr.getApplication("Sample").getCube("Basic");
executeReport(cube);
System.out.println("\nReport Execution Sample Completed.");
} catch (EssException x) {
System.out.println("Error: " + x.getMessage());
statusCode = FAILURE_CODE;
} finally {
// Close OLAP server connection and sign off from the domain.
try {
if (olapSvr != null && olapSvr.isConnected() == true)
olapSvr.disconnect();
} catch (EssException x) {
System.err.println("Error: " + x.getMessage());
}
try {
if (ess != null && ess.isSignedOn() == true)
ess.signOff();
} catch (EssException x) {
System.err.println("Error: " + x.getMessage());
}
}
// Set status to failure only if exception occurs and do abnormal termination
// otherwise, it will by default terminate normally
if (statusCode == FAILURE_CODE) System.exit(FAILURE_CODE);
}
static void executeReport(IEssCube cube) throws EssException {
try {
// Execute a report by passing the specification string.
String repSpec = "{TABDELIMIT}" +
"{SUPALL COLHEADING NAMESON BLOCKHEADERS PAGEHEAD INDENTGEN 2 DECIMALS VARIABLE}" +
"
"
"{INCZEROROWS}" +
"{MISSINGTEXT \"n/a\"}
"
"{ OUTALTNAMES }" +
"
System.out.println("Executing a report by passing the specification string....");
System.out.println("\n\nReport Output for spec: "+repSpec+"\n----------------"+
"------------------------------------------------------------");
String output = cube.report(repSpec, true, false);
System.out.println(output);
// Execute a report by passing file name in the server.
String reportFile = "Top";
System.out.println("\nExecuting a report by passing file name in the server....");
System.out.println("\n\nReport Output for file: " + reportFile +
"\n-----------------------------");
output = cube.report(true, false, reportFile, false);
System.out.println(output);
// Copy a report file from server to JAPI client, and execute the
// report by passing this client file name.
reportFile = System.getProperty("java.io.tmpdir")+"Bottom.rep";
cube.copyOlapFileObjectFromServer(IEssOlapFileObject.TYPE_REPORT,
"Bottom", reportFile, false);
System.out.println("\n\nReport Output for file: " + reportFile +
"\n-----------------------------");
output = cube.report(true, false, reportFile, true);
System.out.println(output);
// Execute a report and get the output as an iterator. This is
// useful when report returns large resultset.
reportFile = "Asym";
System.out.println("\nExecuting a report to get output as an iterator....");
System.out.println("\n\nReport Output for file: " + reportFile +
"\n-----------------------------");
IEssSequentialIterator iterator = cube.report(reportFile, true, false,
true, false);
while ((iterator.isEndOfData() == false) &&
((output = iterator.getNextString()) != null))
System.out.println(output);
} catch (EssException x) {
System.err.println("Error: " + x.getMessage());
}
}
static void acceptArgs(String[] args) throws EssException {
if (args.length >= 4) {
s_userName = args[0];
s_password = args[1];
s_olapSvrName = args[2];
s_provider = args[3]; //PROVIDER
} else if (args.length != 0) {
System.err.println("ERROR: Incorrect Usage of this sample.");
System.err.println(
"Usage: java " + RunReport.class.getName() + " ");
System.exit(1); // Simply end
}
}
}

11/28/09

Java - backup Essbase

We can create Java procedure that will automatically backup the Essbase database, and even recover the essbase database when necessary.
package com.essbase.samples.japi;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.io.File;

import com.essbase.api.base.EssException;
import com.essbase.api.datasource.EssSEQID;
import com.essbase.api.datasource.EssTRANSACTION;
import com.essbase.api.datasource.EssTRANSACTION_REPLAY;
import com.essbase.api.datasource.IEssCube;
import com.essbase.api.datasource.IEssOlapFileObject;
import com.essbase.api.datasource.IEssOlapServer;
import com.essbase.api.domain.IEssDomain;
import com.essbase.api.session.IEssbase;

/**
* Signs on to essbase domain,
* creates a App and Cube, backups the database(cube) and then restores it.
* In order for this sample to work in your environment, make sure to
* change the s_* variables to suit your environment.
*
* @author
* @version
*/
public class BackupAndRestoreDatabase {
// NOTE: Change the following variables to suit your setup.
private static String s_userName = "system";
private static String s_password = "password";
private static String s_olapSvrName = "localhost";
/* Possible values for s_provider:
"Embedded" or "http://localhost:13080/aps/JAPI" */
private static String s_provider = "Embedded"; // Default
private static final int FAILURE_CODE = 1;
public static void main(String[] args) {
int statusCode = 0;
IEssbase ess = null;
IEssOlapServer olapSvr = null;
try {
acceptArgs(args);
// Create JAPI instance.
ess = IEssbase.Home.create(IEssbase.JAPI_VERSION);
// Sign On to the Provider
IEssDomain dom = ess.signOn(s_userName, s_password, false, null,s_provider);
// Open connection with OLAP server and get the cube.
olapSvr = (IEssOlapServer) dom.getOlapServer(s_olapSvrName);
olapSvr.connect();
try {
// Delete the App if it already exists
olapSvr.getApplication("BackUp").delete();
} catch (EssException x) {
// Ignore Error
}
// Create a new Application/Cube : BackUp/Basic - Copy of Sample/Basic
olapSvr.createApplication("BackUp");
dom.copyCube(s_olapSvrName, "Sample", "Basic", s_olapSvrName, "BackUp","Basic");
olapSvr.disconnect();

olapSvr.connect();
IEssCube cube = olapSvr.getApplication("BackUp").getCube("Basic");
BackUpAndRestore(cube);

System.out.println("Cube Archive and Restore Sample completed.");
// Transaction logging requires the below essbase property to be set in essbase.cfg. Choose one
// of the below ways to set it.
// TransactionLogLocation AppName DbName LogLocation NATIVE ENABLE|DISABLE
// TransactionLogLocation AppName LogLocation NATIVE ENABLE
// TransactionLogLocation LogLocation NATIVE ENABLE
// Ex: TransactionLogLocation Sample Basic D:\Hyperion\AnalyticServices-950\app\Sample\Basic NATVIE ENABLE
// TransactionLoggingAndReplay(cube);

// Delete newly created Application.
olapSvr.getApplication("BackUp").delete();

} catch (EssException x) {
System.out.println("Error: " + x.getMessage());
statusCode = FAILURE_CODE;
} finally {
// Close OLAP server connection and sign off from the domain.
try {
if (olapSvr != null && olapSvr.isConnected() == true)
olapSvr.disconnect();
} catch (EssException x) {
System.out.println("Error: " + x.getMessage());
}

try {
if (ess != null && ess.isSignedOn() == true)
ess.signOff();
} catch (EssException x) {
System.out.println("Error: " + x.getMessage());
}
}
// Set status to failure only if exception occurs and do abnormal termination
// otherwise, it will by default terminate normally
if (statusCode == FAILURE_CODE)
System.exit(FAILURE_CODE);
}

static void TransactionLoggingAndReplay(IEssCube cube) throws EssException {

Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, -2);
cal.getTimeInMillis();
SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy:HH:mm:ss");
String date = fmt.format(cal.getTime());
System.out.println("From Date specified for Transactions is :"+ date);
EssTRANSACTION[] list = cube.listTransactions((short)1, date, IEssCube.ESS_LIST_TRANSACTIONS_TOCLIENT, "");
if (list == null || list.length ==0) {
System.out.println("\nNo transactions to List or Replay since "+ date +".\n"
+"Please comment out the BackUpAndRestore(cube) function call in this sample and\n ensure you have executed a transaction like loaddata prior to running this sample.");

return;
}
for (int i = 0; i < list.length; i++) { System.out.println(list[i] +"\n"); } System.out.println("List transactions complete"); EssTRANSACTION_REPLAY replayTran = new EssTRANSACTION_REPLAY((byte)2, date, 1); EssSEQID[] seqIds = new EssSEQID[1]; seqIds[0] = new EssSEQID(list[0].getSeq_id(), list[0].getSeq_id_upper(), 1, list[0].getSeq_id_upper()); cube.replayTransactions(replayTran, seqIds); System.out.println("Relplay transactions complete"); } static void BackUpAndRestore(IEssCube cube) throws EssException { cube.loadData(true, false, "Product Market Actual Sales Jan 4469\n" + "Product Market Actual Sales Feb 42494"); String ArchiveFile = System.getProperty("java.io.tmpdir") + "demobasic.arc"; cube.archiveDatabase(ArchiveFile, "", true); // Take backup. cube.loadData(IEssOlapFileObject.TYPE_RULES, null, IEssOlapFileObject.TYPE_TEXT, "Calcdat", false); String[] Src = null; String[] Dest = null; // Unload Database before restoring. do { try { Thread.sleep(5000); cube.stop(); break; } catch(EssException x){ // If error occurs in unloading database because database is in use(Error #1013113), // wait for 5 sec. and try again. if(x.getNativeCode() == 1013113) continue; else break; } catch (Exception x) { break; } } while (true); cube.restoreDatabase(ArchiveFile, false, Src, Dest); // Restore database. (new File (ArchiveFile)).delete(); } static void acceptArgs(String[] args) throws EssException { if (args.length >= 4) {
s_userName = args[0];
s_password = args[1];
s_olapSvrName = args[2];
s_provider = args[3]; //PROVIDER
} else if (args.length != 0) {
System.err.println("ERROR: Incorrect Usage of this sample.");
System.err.println("Usage: java " + BackupAndRestoreDatabase.class.getName()
+ " ");
System.exit(1); // Simply end
}
}
}

11/25/09

Java Customized Calc Function

The essbase already have many functions for calculation. We can create customized calculation functions by Java. Steps:
1. Create a Java function,CalcFunc.java
public class CalcFunc {
public static double sum (double[] data) {
int i, n = data.length;
double sum = 0.0d;
for (i=0; i< n ; i++)
{
double d = data [i];
sum = sum + d;
}
return sum;
}
}
2. compile,run with javac CalcFunc.java, and generate CalcFunc.class
javac CalcFunc.java
C:\app\bob\product\11.1.0\db_1\jdk\bin\javac.exe C:\Hyperion\CustJava\CalcFunc.java
3. Put the class file in the jar file
jar cf jar_filename class_filename
jar cf CalcFunc.jar CalcFunc.class
4.On the computer running Essbase Server, copy the .jar file to one of the following directories (if the directory does not exist, create it):
For .jar files containing global custom-defined functions:
ARBORPATH/java/udf/
C:\Hyperion\products\Essbase\EssbaseServer\java\udf
For .jar files to be used only with specific applications:
ARBORPATH/app/AppName/udf/
5. Register
create function Sample.'@JSUM'
as 'CalcFunc.sum'
spec '@JSUM(memberRange)'
comment 'adds list of input members';