Frequent Database Access through  Java Mapping ?

I have to implement a Java Mapping Program which will require frequent database Access to compare and read table data from some other  data base .
What is the most optimum procedure to  implement it ?
Should i make a jdbc  call every time from the code or should i use EJB(Session beans + Entity beans)...
or  any other process besides these 2 to acheive maximum performance
Please Suggest
regards
Nilesh Taunk.

Hi Nilesh,
I would suggest you to use XI DB Lookup API's for accessing Database.  Eventhough it will not give you maximum performance, it will be very easy to change the configuration parameters in JDBC Adapter (No need for hardcoding user id/password/Driver details etc.) and you can refer the same in your  Lookup API's.
Please refer the link: <a href="/people/siva.maranani/blog/2005/08/23/lookup146s-in-xi-made-simpler Weblog</a>
Regards,
Ananth

Similar Messages

  • Database Access in Java (Count field incorrect)

    Was given a stock tracking application to be edited for use as a Student/Admin login application which accesses a database and adds/deletes/edits student information. When I try to login, I get the following error: [Microsoft][OBDC Microsoft Access Driver]Count Field Incorrect
    The driver was set up in the Admin tools in Windows XP.
    The columns exist in the database.
    //makeDB.java
      import java.sql.*;
      import java.io.*;
      public class MakeDB
        public static void main(String[] args) throws Exception
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              String url = "jdbc:odbc:saad";
              Connection con = DriverManager.getConnection(url);
             Statement stmt = con.createStatement();
              // The following code deletes each index and table, if they exist.
              // If they do not exist, a message is displayed and execution continues.
              System.out.println("Dropping indexes & tables ...");
            try
                   stmt.executeUpdate("DROP INDEX PK_StudentUserBridge ON StudentUserBridge");
             catch (Exception e)
                   System.out.println("Could not drop primary key on saad table: "
                                     + e.getMessage());
            try
                     stmt.executeUpdate("DROP TABLE Student");
             catch (Exception e)
                   System.out.println("Could not drop Student table: "
                                     + e.getMessage());
            try
                     stmt.executeUpdate("DROP TABLE Users");
             catch (Exception e)
                   System.out.println("Could not drop Users table: "
                                     + e.getMessage());
            try
                     stmt.executeUpdate("DROP TABLE StudentUserBridge");
             catch (Exception e)
                   System.out.println("Could not drop StudentUserBridge table: "
                                     + e.getMessage());
              ///////// Create the database tables /////////////
              System.out.println("\nCreating tables ............");
              // Create Stocks table with primary key index
            try
                   System.out.println("Creating Student table with primary key index...");
                   stmt.executeUpdate("CREATE TABLE Student ("
                                     +"IDNumber TEXT(8) NOT NULL "
                                     +"CONSTRAINT PK_Student PRIMARY KEY, "
                                     +"FirstName TEXT(50), "
                                     +"LastName TEXT(50)"
                                     +")");
             catch (Exception e)
                   System.out.println("Exception creating Student table: "
                                     + e.getMessage());
              // Create Users table with primary key index
            try
                   System.out.println("Creating Users table with primary key index...");
                   stmt.executeUpdate("CREATE TABLE Users ("
                                     +"userID TEXT(20) NOT NULL "
                                    +"CONSTRAINT PK_Users PRIMARY KEY, "
                                    +"FirstName TEXT(30) NOT NULL, "
                                    +"LastName TEXT(30) NOT NULL, "
                                         +"pswd LONGBINARY, "
                                    +"email TEXT(30) NOT NULL, "
                                         +"admin BIT"
                                         +")");
             catch (Exception e)
                   System.out.println("Exception creating Users table: "
                                     + e.getMessage());
              // Create UserStocks table with foreign keys to Users and Stocks tables
            try
                   System.out.println("Creating StudentUserBridge table ...");
                   stmt.executeUpdate("CREATE TABLE StudentUserBridge ("
                                     +"userID TEXT(20) "
                                       +"CONSTRAINT FK1_StudentUserBridge REFERENCES Users (userID), "
                                          +"IDNumber TEXT(8), "
                                       +"CONSTRAINT FK2_StudentUserBridge FOREIGN KEY (IDNumber) "
                                       +"REFERENCES Student (IDNumber)"
                                       +")");
             catch (Exception e)
                   System.out.println("Exception creating StudentUserBridge table: "
                                     + e.getMessage());
              // Create UserStocks table primary key index
            try
                   System.out.println("Creating StudentUserBridge table primary key index...");
                   stmt.executeUpdate("CREATE UNIQUE INDEX PK_StudentUserBridge "
                                        +"ON StudentUserBridge (userID, IDNumber) "
                                        +"WITH PRIMARY DISALLOW NULL");
             catch (Exception e)
                   System.out.println("Exception creating StudentUserBridge index: "
                                     + e.getMessage());
              // Create one administrative user with password as initial data
              String userID = "admin01";
              String FirstName = "Default";
              String LastName = "Admin";
              String initialPswd = "admin01";
              String email = "[email protected]";
              Password pswd = new Password(initialPswd);
              boolean admin = true;
            PreparedStatement pStmt =
                       con.prepareStatement("INSERT INTO Users VALUES (?,?,?,?,?,?)");
            try
                 pStmt.setString(1, userID);
                  pStmt.setString(2, FirstName);
                  pStmt.setString(3, LastName);
                pStmt.setBytes(4, serializeObj(pswd));
                pStmt.setString(5, email);
                  pStmt.setBoolean(6, admin);
                  pStmt.executeUpdate();
              catch (Exception e)
                   System.out.println("Exception inserting user: "
                                     + e.getMessage());
            pStmt.close();
              // Read and display all User data in the database.
            ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
            System.out.println("Database created.\n");
            System.out.println("Displaying data from database...\n");
            System.out.println("Users table contains:");
            Password pswdFromDB;
            byte[] buf = null;
            while(rs.next())
                   System.out.println("Logon ID         = "
                                     + rs.getString("userID"));
                 System.out.println("Last name        = "
                                   + rs.getString("FirstName"));
                 System.out.println("First name       = "+rs.getString("LastName"));
                 System.out.println("E-mail           = "+rs.getString("email"));
                 System.out.println("Administrative   = "+rs.getBoolean("admin"));
                 System.out.println("Initial password = "+initialPswd);
            // Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
            // SQL NULL data value is not handled correctly.
                buf = rs.getBytes("pswd");
                if (buf != null)
                      System.out.println("Password Object  = "
                                      + (pswdFromDB=(Password)deserializeObj(buf)));
                      System.out.println("  AutoExpires    = "+ pswdFromDB.getAutoExpires());
                      System.out.println("  Expiring now   = "+ pswdFromDB.isExpiring());
                      System.out.println("  Remaining uses = "
                                        + pswdFromDB.getRemainingUses()+"\n");
                  else
                      System.out.println("Password Object  = NULL!");
            rs = stmt.executeQuery("SELECT * FROM Student");
            if(!rs.next())
                 System.out.println("Student table contains no records.");
              else
                 System.out.println("Student table still contains records!");
            rs = stmt.executeQuery("SELECT * FROM StudentUserBridge");
            if(!rs.next())
                 System.out.println("StudentUserBridge table contains no records.");
              else
                 System.out.println("StudentUserBridge table still contains records!");
             stmt.close(); // closing Statement also closes ResultSet
        } // end of main()
         // Method to write object to byte array and then insert into prepared statement
        public static byte[] serializeObj(Object obj)
                                  throws IOException
              ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
            ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
            objOStream.writeObject(obj); // object must be Serializable
            objOStream.flush();
            objOStream.close();
            return baOStream.toByteArray(); // returns stream as byte array
         // Method to read bytes from result set into a byte array and then
         // create an input stream and read the data into an object
        public static Object deserializeObj(byte[] buf)
                                      throws IOException, ClassNotFoundException
             Object obj = null;
            if (buf != null)
              ObjectInputStream objIStream =
                new ObjectInputStream(new ByteArrayInputStream(buf));
              obj = objIStream.readObject(); // throws IOException, ClassNotFoundException
            return obj;
      } // end of class
    //STLogon.java
    import javax.swing.*;
    import javax.swing.border.TitledBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class STLogon extends JFrame implements ActionListener, Activator
        StudentDB db;
        User user = null;
        String userID;
        String password;
        JTextField userIDField;
        JPasswordField passwordField;
        JButton jbtLogon;
        public STLogon()
            super("Stock Tracker"); // call super (JFrame) constructor
              int width = 300;
              int height = 100;
            try{
                 db = new StudentDB();
            catch(ClassNotFoundException ex){
                        JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "Class not found exception creating database object",
                    JOptionPane.ERROR_MESSAGE);
                           System.exit(0);
            catch(SQLException ex){
                        JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "SQL exception creating database object",
                    JOptionPane.ERROR_MESSAGE);
                           System.exit(0);
              // define GUI components
            JLabel label1 = new JLabel("User ID: ");
            userIDField = new JTextField(20);
            JLabel label2 = new JLabel("Password:   ");
            passwordField = new JPasswordField(20);
            passwordField.setEchoChar('*');
            jbtLogon = new JButton("Log on");
              // set up GUI
            JPanel userPanel= new JPanel(new BorderLayout());
            userPanel.add(label1,BorderLayout.CENTER);
            userPanel.add(userIDField,BorderLayout.EAST);
            JPanel pswdPanel= new JPanel(new BorderLayout());
            pswdPanel.add(label2,BorderLayout.CENTER);
            pswdPanel.add(passwordField,BorderLayout.EAST);
            JPanel buttonPanel= new JPanel(new FlowLayout());
            buttonPanel.add(jbtLogon);
            JPanel contentPanel= new JPanel(new BorderLayout());
            contentPanel.add(userPanel, BorderLayout.NORTH);
            contentPanel.add(pswdPanel, BorderLayout.CENTER);
            contentPanel.add(buttonPanel, BorderLayout.SOUTH);
             contentPanel.setBorder(new TitledBorder("Log on"));
            setContentPane(contentPanel);
            // add listeners
            jbtLogon.addActionListener(this);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e)
                                       try {db.close();
                                    catch(Exception ex)
                                    System.exit(0);
              // Enable Enter key for each JButton
              InputMap map;
              map = jbtLogon.getInputMap();
              if (map != null){
                   map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
                   map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
            pack();
              if( width < getWidth())                    // prevent setting width too small
                 width = getWidth();
              if(height < getHeight())               // prevent setting height too small
                   height = getHeight();
              centerOnScreen(width, height);
           public void centerOnScreen(int width, int height)
             int top, left, x, y;
             // Get the screen dimension
             Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
             // Determine the location for the top left corner of the frame
             x = (screenSize.width - width)/2;
             y = (screenSize.height - height)/2;
             left = (x < 0) ? 0 : x;
             top = (y < 0) ? 0 : y;
             // Set the frame to the specified location & size
           this.setBounds(left, top, width, height);
         private boolean validUser(String userID,String password)
                        throws PasswordException,SQLException,IOException,ClassNotFoundException
              boolean userOK = false;
              user = db.getUser(userID); // get user object from DB for this ID
              if(user != null)
                   user.validate(password); // throws PasswordException
                   userOK = true;
                   if(user.pswdAutoExpires())     // if tracking uses
                        db.updUser(user);          // update DB for this use
             return userOK;
        private void doStockActivity()throws PasswordException,SQLException,
                                                      IOException,ClassNotFoundException
            StockTracker f = new StockTracker(user,this,db);
            f.pack();
            this.setVisible(false);
            f.setVisible(true);
        public void activate()
            this.setVisible(true);
            userIDField.setText("");
            userIDField.requestFocus();
            user = null;
        public void actionPerformed(ActionEvent e)
              try
                   userID = userIDField.getText();
                if(userID.equals(""))
                           JOptionPane.showMessageDialog(this,
                            "Please enter a valid user ID.",
                           "Missing User ID.",
                           JOptionPane.ERROR_MESSAGE);
                       userIDField.requestFocus();
                   else
                        password = new String(passwordField.getPassword());
                     if(password.equals(""))
                                JOptionPane.showMessageDialog(this,
                                 "Please enter a valid password.",
                                "Missing Password.",
                                JOptionPane.ERROR_MESSAGE);
                            passwordField.requestFocus();
                        else
                             try
                                  // See if userID exists and validate password
                                  if(validUser(userID,password))
                                   if(user.pswdIsExpiring())
                                              JOptionPane.showMessageDialog(this,
                                                             user.getUserID()+" logon successful; "
                                                +user.getPswdUses()+" use(s) remaining.");
                                    if(e.getSource() == jbtLogon)
                                               doStockActivity();
                               else
                                    JOptionPane.showMessageDialog(this, "Invalid user.");
                             catch (PasswordExpiredException ex)
                                  JPasswordField pf1 = new JPasswordField();
                                  JPasswordField pf2 = new JPasswordField();
                                  Object[] message1 = new Object[]
                                            {"Password has expired. Please enter a new password.", pf1};
                                  Object[] options = new String[] {"OK", "Cancel"};
                                  JOptionPane op1 = new JOptionPane(message1,
                                                                     JOptionPane.WARNING_MESSAGE,
                                                              JOptionPane.OK_CANCEL_OPTION, null, options);
                                  JDialog dialog1 = op1.createDialog(null, "Change Password");
                                  dialog1.show();
                                  if(op1.getValue() != null && options[0].equals(op1.getValue()))
                                       String pswd1 = new String(pf1.getPassword());
                                       if(pswd1 != null)
                                           Object[] message2 = new Object[]
                                                               {"Please verify new password.", pf2};
                                            JOptionPane op2 = new JOptionPane(message2,
                                                                               JOptionPane.WARNING_MESSAGE,
                                                                       JOptionPane.OK_CANCEL_OPTION,
                                                                       null, options);
                                            JDialog dialog2 = op2.createDialog(null, "Verify Password");
                                            dialog2.show();
                                            if(op2.getValue() != null && options[0].equals(op2.getValue()))
                                                 String pswd2 = new String(pf2.getPassword());
                                                 if(pswd2 != null)
                                                      if(pswd1.equals(pswd2))
                                                        user.changePassword(password, pswd1);
                                                           db.updUser(user);
                                                           doStockActivity();
                                                      else
                                                           JOptionPane.showMessageDialog(this,
                                                          "Both passwords are not identical.",
                                                         "Password not changed",
                                                         JOptionPane.ERROR_MESSAGE);
                 userIDField.setText("");
                passwordField.setText("");
                userIDField.requestFocus();
            }// end of try
            catch (PasswordUsedException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "Password Previously Used. Try again.",
                    JOptionPane.ERROR_MESSAGE);
            catch (PasswordSizeException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "Invalid password size. Try again.",
                    JOptionPane.ERROR_MESSAGE);
            catch (PasswordInvalidFormatException ex)
                if(ex.getCount() > 2) // allows only 3 tries, then exits program
                     System.exit(0);
                else
                     JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
                                                        "Invalid password format. Try again.",
                                                              JOptionPane.ERROR_MESSAGE);
            catch (PasswordInvalidException ex)
                if(ex.getCount() > 2) // allows only 3 tries, then exits program
                     System.exit(0);
                else
                     JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
                                                        "Invalid password. Try again.",
                                                              JOptionPane.ERROR_MESSAGE);
            catch (PasswordException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "PasswordException.",
                    JOptionPane.ERROR_MESSAGE);
            catch (IOException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "IOException.",
                    JOptionPane.ERROR_MESSAGE);
            catch (SQLException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "SQLException.",
                    JOptionPane.ERROR_MESSAGE);
            catch (ClassNotFoundException ex)
                JOptionPane.showMessageDialog(this,
                    ex.getMessage(),
                    "ClassNotFoundException.",
                    JOptionPane.ERROR_MESSAGE);
        public static void main(String[] argv)
              final STLogon f = new STLogon();
              f.setVisible(true);
    //StudentDB.java
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    public class StudentDB
         private Connection con = null;
         // Constructor; makes database connection
        public StudentDB() throws ClassNotFoundException,SQLException
              if(con == null)
                   String url = "jdbc:odbc:saad";
                 try
                      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   catch(ClassNotFoundException ex)
                        throw new ClassNotFoundException(ex.getMessage() +
                                  "\nCannot locate sun.jdbc.odbc.JdbcOdbcDriver");
                 try
                        con = DriverManager.getConnection(url);
                   catch(SQLException ex)
                        throw new SQLException(ex.getMessage()+
                                  "\nCannot open database connection for "+url);
         // Close makes database connection; null reference to connection
         public void close() throws SQLException,IOException,ClassNotFoundException
              con.close();
               con = null;
         // Method to serialize object to byte array
        private byte[] serializeObj(Object obj) throws IOException
              ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
            ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
            objOStream.writeObject(obj); // object must be Serializable
            objOStream.flush();
            objOStream.close();
            return baOStream.toByteArray(); // returns stream as byte array
         // Method to deserialize bytes from a byte array into an object
        private Object deserializeObj(byte[] buf)
                             throws IOException, ClassNotFoundException
             Object obj = null;
            if (buf != null)
                   ObjectInputStream objIStream =
                      new ObjectInputStream(new ByteArrayInputStream(buf));
                obj = objIStream.readObject(); //IOException, ClassNotFoundException
            return obj;
         // Methods for adding a record to a table
        // add to the Student Table
         public void addStudent(String IDNumber, String FirstName, String LastName)
                     throws SQLException, IOException, ClassNotFoundException
              Statement stmt = con.createStatement();
               stmt.executeUpdate("INSERT INTO Student VALUES ('"
                                 +IDNumber+"'"+",'"+FirstName+"'"+",'"+LastName+"')");
               stmt.close();
         // add to the Users table
         public boolean addUser(User user) throws SQLException,IOException,
                                                  ClassNotFoundException
           boolean result = false;
          String dbUserID;
          String dbLastName;
          String dbFirstName;
          Password dbPswd;
          String dbemail;
          boolean isAdmin;
          dbUserID = user.getUserID();
          if(getUser(dbUserID) == null)
                dbLastName = user.getFirstName();
                dbFirstName = user.getLastName();
              Password pswd = user.getPassword();
    //          dbemail = user.getEmail();
                isAdmin = user.isAdmin();
              PreparedStatement pStmt = con.prepareStatement(
                  "INSERT INTO Users VALUES (?,?,?,?,?,?)");
              pStmt.setString(1, dbUserID);
              pStmt.setString(2, dbFirstName);
              pStmt.setString(3, dbLastName);
              pStmt.setBytes(4, serializeObj(pswd));
    //          pStmt.setString(5, dbemail);
              pStmt.setBoolean(5, isAdmin);
              pStmt.executeUpdate();
              pStmt.close();
              result = true;
           else
                throw new IOException("User exists - cannot add.");
           return result;
         // add to the UserStocks table
         public void addStudentUserBridge(String userID, String IDNumber)
                     throws SQLException,IOException,ClassNotFoundException
              Statement stmt = con.createStatement();
               stmt.executeUpdate("INSERT INTO StudentUserBridge VALUES ('"
                                 +userID+"'"
                                 +",'"+IDNumber+"')");
               stmt.close();
         // Methods for updating a record in a table
        // updating the Users Table
         public boolean updUser(User user) throws SQLException,IOException,
                                                  ClassNotFoundException
           boolean result = false;
             String dbUserID;
          String dbLastName;
          String dbFirstName;
          Password dbPswd;
          String dbemail;
          boolean isAdmin;
          dbUserID = user.getUserID();
          if(getUser(dbUserID) != null)
                dbLastName = user.getFirstName();
                dbFirstName = user.getLastName();
              Password pswd = user.getPassword();
    //          dbemail = user.getEmail();
                isAdmin = user.isAdmin();
              PreparedStatement pStmt = con.prepareStatement("UPDATE Users SET FirstName = ?,"
                                           +" LastName = ?, pswd = ?, email = ?, admin = ? WHERE userID = ?");
              pStmt.setString(1, dbFirstName);
              pStmt.setString(2, dbLastName);
              pStmt.setBytes(3, serializeObj(pswd));
    //          pStmt.setString(4, dbemail);
              pStmt.setBoolean(4, isAdmin);
              pStmt.setString(5, dbUserID);
              pStmt.executeUpdate();
              pStmt.close();
              result = true;
           else
                throw new IOException("User does not exist - cannot update.");
           return result;
         // Methods for deleting a record from a table
        // delete a record from the Student Table
         private void delStudent(String IDNumber)
                      throws SQLException,IOException,ClassNotFoundException
              Statement stmt = con.createStatement();
               stmt.executeUpdate("DELETE FROM Student WHERE "
                                 +"IDNumber = '"+IDNumber+"'");
            stmt.close();
        // delete a record from the Users Table
         public void delUser(User user) throws SQLException,IOException,
                                                  ClassNotFoundException
               String dbUserID;
            String stockSymbol;
              Statement stmt = con.createStatement();
              try {
                   con.setAutoCommit(false);
                   dbUserID = user.getUserID();
                   if(getUser(dbUserID) != null)  // verify user exists in database
                         ResultSet rs1 = stmt.executeQuery("SELECT userID, IDNumber "
                                           +"FROM StudentUserBridge WHERE userID = '"+dbUserID+"'");
                         while(rs1.next())
                         try
                             stockSymbol = rs1.getString("IDNumber");
                                  delUserStocks(dbUserID, stockSymbol);
                            catch(SQLException ex)
                                  throw new SQLException("Deletion of user student failed: "
                                                        +ex.getMessage());
                          } // end of loop thru UserStocks
                    try
                    {  // holdings deleted, now delete user
                             stmt.executeUpdate("DELETE FROM Users WHERE "
                                           +"userID = '"+dbUserID+"'");
                       catch(SQLException ex)
                             throw new SQLException("User deletion failed: "+ex.getMessage());
                     else
                          throw new IOException("User not found in database - cannot delete.");
                   try
                      con.commit();
                    catch(SQLException ex)
                        throw new SQLException("Transaction commit failed: "+ex.getMessage());
              catch (SQLException ex)
                   try
                        con.rollback();
                   catch (SQLException sqx)
                        throw new SQLException("Transaction failed then rollback failed: "
                                              +sqx.getMessage());
                   // Transaction failed, was rolled back
                   throw new SQLException("Transaction failed; was rolled back: "
                                         +ex.getMessage());
            stmt.close();
        // delete a record from the StudentUserBridge Table
         public void delUserStocks(String userID, String stockSymbol)
                     throws SQLException,IOException,ClassNotFoundException
              Statement stmt = con.createStatement();
             ResultSet rs;
               stmt.executeUpdate("DELETE FROM StudentUserBridge WHERE "
                                 +"userID = '"+userID+"'"
                                 +"AND IDNumber = '"+stockSymbol+"'");
               rs = stmt.executeQuery("SELECT IDNumber FROM StudentUserBridge "
                                     +"WHERE IDNumber = '"+stockSymbol+"'");
                 if(!rs.next()) // no users have this stock
    //               delStock(stockSymbol);
               stmt.close();
         // Methods for listing record data from a table
         // Ordered by:
         //           methods that obtain individual field(s),
         //           methods that obtain a complete record, and
         //           methods that obtain multiple records
         // Methods to access one or more individual fields
        // get a stock description from the Stocks Table
         public String getStockDesc(String stockSymbol)
                       throws SQLException, IOException, ClassNotFoundException
              Statement stmt = con.createStatement();
                String stockDesc = null;
               ResultSet rs = stmt.executeQuery("SELECT IDNumber, name FROM Student "
                                               +"WHERE IDNumber = '"+stockSymbol+"'");
               if(rs.next())
                   stockDesc = rs.getString("IDNumber");
               rs.close();
               stmt.close();
                return stockDesc;
         // Methods to access a complete record
        // get User data from the Users Table
         public User getUser(String UserID) throws SQLException, IOException,
                                                   ClassNotFoundException
           Statement stmt = con.createStatement();
             String dbUserID;
          String dbLastName;
          String dbFirstName;
          Password dbPswd;
          String dbemail;
          boolean isAdmin;
          byte[] buf = null;
          User user = null;
          ResultSet rs = stmt.executeQuery("SELECT * FROM Users WHERE userID = '"
                                          +UserID+"'");
          if(rs.next())
                dbUserID = rs.getString("userID");
                 dbFirstName = rs.getString("FirstName");
                 dbLastName = rs.getString("LastName");
                 dbemail = rs.getString("email");
            // Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
            // SQL NULL data value is not handled correctly.
              buf = rs.getBytes("pswd");
                 dbPswd = (Password)deserializeObj(buf);
                 isAdmin = rs.getBoolean("admin");
                user = new User(dbUserID,dbFirstName,dbLastName,dbPswd,isAdmin);
          rs.close();
          stmt.close();
           return user; // User object created for userID
         // Methods to access a list of records
        // get list of selected fields for all records from the Users Table
         public ArrayList listUsers() throws SQLException,IOException,
                                             ClassNotFoundException
          ArrayList aList = new ArrayList();
           Statement stmt = con.createStatement();
          ResultSet rs = stmt.executeQuery("SELECT userID, FirstName, LastName, admin "
                                          +"FROM Users ORDER BY userID");
          while(rs.next())
                aList.add(rs.getString("userID"));
                  aList.add(rs.getString("FirstName"));
                  aList.add(rs.getString("LastName"));
                  aList.add(new Boolean(rs.getBoolean("admin")));
          rs.close();
          stmt.close();
          return aList;
        // get all fields in all records for a given user from the Userstocks Table
         public ArrayList listUserStocks(String userID) throws SQLException,IOException,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    saaddani wrote:
    No information popped up in the console window before, during, or after the error was given. The program compiled and ran and therefore no error information was provided in the complier window either.
    If I am missing what you are asking then please provide instructions as to how to find this error information. You are posting the error message for the exception but not printing the stack trace.
    Far as I can tell you are printing more information with each exception (for example "Exception creating Users table") but you did not post what that was, that info would localize the problem.
    As a guess the problem is when you extract the fields via the query. You are using named values rather than indexes and you use "select *" rather than specifically naming the columns. Some databases (for example Oracle), require that using names must be in exactly the same order as the query returns them. You have no idea what that order is because you use "select *"
    Finally it would be a LOT easier if you wrote classes that did nothing but the database operations. NO GUI CODE. You then test that code to make sure it works. Once that code works then you write gui code which uses those classes. Besides making it easier to understand you are also more likely to get assistance since there is less code to look at.

  • Database Access through JSP

    Hi im trying to access my ORACLE database through a jsp program. The page loads up in the browser, no errors or anything like that, but i get no output.
    I am running things on localhost with TomCat 3.2.3
    Here is the code, any help gratefully appreciated.
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE>Testing Database Access</TITLE>
    </HEAD>
    <BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
    VLINK="#551A8B" ALINK="#FF0000">
    <CENTER>
    <TABLE BORDER=5 BGCOLOR="#EF8429">
    <TR><TH CLASS="TITLE">
    Testing Database Access</TABLE>
    </CENTER>
    <P>
    <P>
    Here Is what Might be in the Database
    <P>
    <%@ page language="java" %>
    <%@ page import="java.util.*" %>
    <%@ page import="oracle.jdbc.driver.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="java.sql.*" %>
    <%
         try
    %>
    <%
         DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
         String username = "Donnchadh", password = "zcbu5mya";
         Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@kiwi.isg.computing.dcu.ie:1521:kiwi",username,password);
         java.sql.Statement stmt = conn.createStatement();
         String query = "SELECT * FROM PERSONALS";
         ResultSet rs = stmt.executeQuery(query);
         while(rs.next())
              int ccount = rs.getMetaData().getColumnCount();
              for( int i = 1; i <= ccount; i++ )
                   System.out.print(rs.getString(i)+"\t");
              System.out.println();
    %>
    <%
         rs.close();
         stmt.close();
         if(conn != null)
              try
                   conn.close();
              catch(Exception e)
                   return;
         catch(Exception e)
              return;
    %>
    <P>
    </BODY>
    </HTML>
    I have also tried to access columns directly with this code in the while loop
    while(rs.next())
                        String Title = rs.getString("title");
                        String FName = rs.getString("fname");
                        String LName = rs.getString("lname");
                        String Phone = rs.getString("phone1");
                        String Phone2 = rs.getString("phone2");
                        String Addr = rs.getString("addr");
                        String County = rs.getString("county");
                        String Country = rs.getString("country");
                        out.println("<tr><td>" + Title + "</td><td>" + FName + "</td><td>" + LName
                        + "</td><td>" + Phone + "</td><td>" + Phone2 + "</td></tr>" + "</td></tr>" + Addr
                        + "</td></tr>" + County + "</td></tr>" + Country + "</td></tr>" );

    i give a servlet access to oracle ,that have test ok!
    import java.sql.*;
    import javax.servlet.*;
    import javax.sql.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    public class TestServlet1 extends HttpServlet {
    private static final String CONTENT_TYPE = "image/jpeg; charset=GBK";
    //Initialize global variables
    String strRno =null;
    ResultSet rs=null;
    byte [] buf=null;
    InputStream in;
    int IntNo;
    public void init() throws ServletException {
    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    // PrintWriter out = response.getWriter();
    // System.out.println("TEst database prepaired ok��");
    strRno = request.getParameter( "PictNo" );
    IntNo = 0;
    if( strRno != null ) {
    try { IntNo = Integer.parseInt( strRno ); }
    catch( NumberFormatException e ) {
    strRno = null;
    System.out.println("��������������������"); }
    else
    System.out.println("��������������������");
    if( strRno == null ) {
    // response.sendError( HttpServletResponse.SC_NOT_FOUND );
    return;
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    catch (ClassNotFoundException ex2) {
    //      out.println("TEst2��");
    // System.out.println("TEst2�� ex2��");
    String url="jdbc:oracle:thin:@erdos00:1521:erdos";
    Connection con = null;
    try {
    con = DriverManager.getConnection(url, "system", "manager");
    catch (SQLException ex1) {
         //out.println("TEst�� ex1");
         System.out.println("TEst�� ex1��");
    // PreparedStatement sql=con.PrepareStatement("select photo from blob_test WHERE rno = IntNo" );
    PreparedStatement sql = null;
    try {
    sql = con.prepareStatement("select photo from blob_test WHERE rno = 14 ");
    // sql = con.prepareStatement("select photo from blob_test WHERE rno = " +"+ IntNo +" );
    catch (SQLException ex) {
         //out.println("TEst�� ex");
         System.out.println("TEst�� ex��");
    //method prepareStatement(sting) not found in interface java.sql.connection
    // sql.setInt( 1, rno );
    try {
    rs = sql.executeQuery();
    catch (SQLException ex3) {
         //out.println("TEst�� ex3");
         System.out.println("TEst�� ex3");
    System.out.println("TEst database operate ok��");
    // out.println("TEst database operate ok��");
    //��������������������
    try {
    if (rs.next()) {
    buf = rs.getBytes(1);
    in = rs.getBinaryStream("photo");
    else {
    buf = new byte[0];
    }catch (Exception e){
    //throw e;
    response.reset();
    //������image/jpeg������������������������
    response.setContentType("image/bmp");
    // ��bmp��jpeg
    byte[] b = new byte[1024*1024];
    int len;
    while((len=in.read(b)) >0)
    response.getOutputStream().write(b,0,len);
    OutputStream out1 = response.getOutputStream();
    out1.flush();
    out1.write(buf);
    in.close();
    try {
    rs.close();
    catch (SQLException ex4) {
    // out.println("<html>");
    // out.println("<img src='http://192.168.0.1/examples/servlet/TestServlet1?PictNo="+IntNo+"'>");
    // out.println("</html>");
    out.println("<html>");
    out.println("<head><title>TestServlet</title></head>");
    out.println("<body bgcolor=\"#ffffff\">");
    out.println("<p>The servlet has received a GET111111111. This is the reply.</p>");
    out.println("</body></html>");
    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>TestServlet</title></head>");
    out.println("<body bgcolor=\"#ffffff\">");
    out.println("<p>The servlet has received a POST. This is the reply.</p>");
    out.println("</body></html>");
    //Process the HTTP Put request
    public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Process the HTTP Delete request
    public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //Clean up resources
    public void destroy() {
    hope u can get some thing from that

  • PJC and database access through JDBC

    Hello,
    I'm trying to access to the database through a PJC via JDBC.
    conn = DriverManager.getConnection ("jdbc:oracle:thin:@machine:1521:XE", "user", "pwd");It works fine on a XE database, but fails on another XE one:
    Oracle JInitiator: Version 1.3.1.22
    java.lang.NullPointerException
         at oracle.jdbc.ttc7.O3log.marshal(O3log.java:606)
         at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:255)
         at oracle.jdbc.driver.OracleConnection.<init>(OracleConnection.java:377)
         at oracle.jdbc.driver.OracleDriver.getConnectionInstance(OracleDriver.java:515)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:345)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at oracle.forms.fd.AsyncJob.connect(AsyncJob.java:68)
         at oracle.forms.fd.AsyncJob.run(AsyncJob.java:121)
         at java.lang.Thread.run(Unknown Source)It also fails on a remote Unix database:
    java.security.AccessControlException: access denied (java.net.SocketPermission monadev resolve)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
    ...so I edit the java.policy file of the Jinitiator directory:
    permission java.net.SocketPermission "machine:port-", "accept,connect,listen,resolve";     and then get the same execption:
    java.lang.NullPointerException
         at oracle.jdbc.ttc7.O3log.marshal(O3log.java:606)
         at oracle.jdbc.ttc7.TTC7Protocol.logon(TTC7Protocol.java:255)
    ...Finally, it work on only one machine and only a local database.
    I'm probably missing something somewhere.
    Is anyone could give me some light on this ?
    Thanks in advance,
    Francois

    I'm just learning to work with PJC's, so I'm unsure whether I can help, but here goes. I found the following archived on Google Groups (http://groups.google.com):
    Hi. The basic applet security model is that it can only make connections
    back to the machine from which it was downloaded. If you want to do
    JDBC from an applet to a DBMS not on the applet-server machine,
    you need a type-3 JDBC driver. A type-3 JDBC driver has an all-Java
    client driver piece which an applet can download and use. This driver
    piece connects to a proxy piece which is running on the webserver
    machine. This proxy piece then connects to any DBMS anywhere on the
    net, and is the middleman between the JDBC client and DBMS.
       For security, management and performance reasons it's usually better to
    constrain JDBC to a middle tier such as in a servlet, and use HTML to and
    from the client, rather than the space and time involved in downloading a
    full general query engine (a JDBC driver) to a client which typically uses
    .1% of the capability or classes of the JDBC driver.
    Joe Weinstein at BEA HTH,
    Eric Adamson
    Lansing, Michigan

  • Database access through Beans

    My question is about high level design. I've written some JSP pages and some very simple JavaBeans that work on Tomcat.
    Now I'm trying to design a Database access layer
    I want to have a connection pool class and some other business logic classes communicating with each other.
    How can I start a bean and keep it running and how do I access its methods from other beans?
    Is this even feasible?
    if I declare the scope of the bean as the application would I have to put it in all the pages of the web site or not?
    Also, should I just forget about JavaBeans and do Servlets? Maybe EJB is better for this?
    Please provide some examples in your answer if possible.
    Thanks,
    David A

    My question is about high level design. I've written
    some JSP pages and some very simple JavaBeans that
    work on Tomcat.
    Now I'm trying to design a Database access layerThe design and implementation of a persistence layer has nothing at to do with how the data is eventually displayed. Persistence is the same whether you use a Web or a Swing interface, so the question about Tomcat is moot.
    I'd look at Martin Fowler's "Patterns of Enterprise Application Architecture" for its chapter on persistence or the Hibernate object/relational mapping tool.
    I want to have a connection pool class and some other
    business logic classes communicating with each other.Personally, I prefer to let Tomcat handle the database connection pool. I use the Commons DBCP class and configure my connections that way. Then I have my Java code do a JNDI lookup to access them, do the required database operation, and then close the connection to return it to the pool.
    How can I start a bean and keep it running and how do I access its methods from other beans?
    Is this even feasible? I'm not sure I know what you mean by "start a bean and keep it running". HTTP is a request/response, stateless protocol. You should think about operations as being initiated by a request and then going out of scope once the response is generated, much like the protocol itself. You don't keep a bean running in that case.
    if I declare the scope of the bean as the application would I have to put it in all the pages of the web
    site or not?You have to <jsp:useBean> in every page that needs it. Whether or not application scope is really appropriate or necessary is another matter.
    Also, should I just forget about JavaBeans and do Servlets? You can and should use JSP for View, a servlet as your front controller, and JavaBeans to do the work in the back. It's not an either/or question. You really should be using all three.
    Maybe EJB is better for this?You use EJBs if you have a highly transactional, distributed, clustered application. If none of those things apply to you, there's no reason why you must use EJBs.
    Have a look at the Struts and Spring frameworks.

  • Keystore access in Java Mapping Program - user J2EE_GUEST

    Dear Gurus,
    I have the following problem:
    I need to validate the digital signature of a XML document and I'm using some examples provided by SAP as follows:
              InitialContext ctx = ctx = new InitialContext();          
              Object o = (Object) ctx.lookup("keystore");          
              KeystoreManager manager = (KeystoreManager) o;          
              KeyStore ks = manager.getKeystore("Serasa");
    {/code}
    But I get the error below, saying that user J2EE_GUEST is not authorized. How do I change the user who executes java mapping, because I granted permissions in Visual Admin to another user.
         at com.sap.aii.ibrun.sbeans.mapping.MappingServiceObjectImpl0_0.processFunction(MappingServiceObjectImpl0_0.java:131)
         at sun.reflect.GeneratedMethodAccessor267.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:62)
         at java.lang.reflect.Method.invoke(Method.java:391)
         at com.sap.engine.services.ejb.session.stateless_sp5.ObjectStubProxyImpl.invoke(ObjectStubProxyImpl.java:187)
         at $Proxy218.processFunction(Unknown Source)
         at sun.reflect.GeneratedMethodAccessor266.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:62)
         at java.lang.reflect.Method.invoke(Method.java:391)
         at com.sap.engine.services.rfcengine.RFCDefaultRequestHandler.call(RFCDefaultRequestHandler.java:284)
         at com.sap.engine.services.rfcengine.RFCDefaultRequestHandler.handleRequest(RFCDefaultRequestHandler.java:219)
         at com.sap.engine.services.rfcengine.RFCJCOServer$J2EEApplicationRunnable.run(RFCJCOServer.java:254)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(AccessController.java:219)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:104)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:176)
    Caused by: com.sap.engine.services.keystore.exceptions.BaseKeystoreException: User is not authorized to execute keystore operation[{GET_VIEW Serasa }]
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkUserPermission(UserBasedSecurityConnector.java:889)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.checkUserPermission(SecurityRestrictionsChecker.java:52)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.isUserAuthorized(SecurityRestrictionsChecker.java:148)
         at com.sap.engine.services.keystore.impl.security.SecurityRestrictionsChecker.checkPermission(SecurityRestrictionsChecker.java:174)
         at com.sap.engine.services.keystore.impl.ParameterChecker.checkPermission(ParameterChecker.java:35)
         at com.sap.engine.services.keystore.impl.KeystoreManagerImpl.checkPermission(KeystoreManagerImpl.java:46)
         ... 28 more
    Caused by: java.security.KeyStoreException: (thread: SAPEngine_Application_Thread[impl:3]_56,view:Serasa, entry: , user: J2EE_GUEST) - checkPermissions  'getView': com.sap.engine.services.security.exceptions.BaseSecurityException: Caller not authorized.
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkFailed(UserBasedSecurityConnector.java:1097)
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkPermissions_getView(UserBasedSecurityConnector.java:773)
         at com.sap.engine.services.keystore.impl.security.UserBasedSecurityConnector.checkUserPermission(UserBasedSecurityConnector.java:823)
         ... 33 more
    {/code}
    Thank you very much

    Hi Fabio,
    first of all have you checked if standard functions to verify digital signature for pi adpaters would work for you?
    We have used the following code to access the Keystore in a custom adapter. It accesses the keystore with the access rights of a JEE application (it has a reference to the sample adapter "sap.com/com.sap.aii.adapter.sample.ra"). Check out if it works in your mapping, too.
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.PublicKey;
    import java.security.UnrecoverableKeyException;
    import java.util.HashMap;
    import java.util.Map;
    import javax.resource.ResourceException;
    import com.sap.aii.af.service.resource.SAPSecurityResources;
    import com.sap.aii.security.lib.KeyStoreManager;
    import com.sap.aii.security.lib.PermissionMode;
    public class XIKeystoreAccessor {
        private static final XITrace TRACE = new XITrace(XIKeystoreAccessor.class.getName());
        static XIKeystoreAccessor instance = null;
        SAPSecurityResources securityResources;
        KeyStoreManager keystoreManager;
        Map<String, KeyStore> keystores = null;
        private XIKeystoreAccessor() throws ResourceException {
         final String SIGNATURE = "XIKeystoreAccessor()";
         TRACE.entering(SIGNATURE);
         keystores = new HashMap<String, KeyStore>();
         securityResources = SAPSecurityResources.getInstance();
         try {
             keystoreManager = securityResources.getKeyStoreManager(PermissionMode.SYSTEM_LEVEL,
                  new String[] { "sap.com/com.sap.aii.adapter.sample.ra" });
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         * Get a key from AS Java keystore
         * @param view
         * @param alias
         * @param password
         * @return
         * @throws ResourceException
        public Key getPrivateKey(String view, String alias, String password) throws ResourceException {
         final String SIGNATURE = "getPrivateKey()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore = getKeystore(view);
         Key privateKey = null;
         try {
             privateKey = keystore.getKey(alias, password.toCharArray());
             if (privateKey == null) {
              throw new ResourceException("Key not found. alias=" + alias);
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         } catch (NoSuchAlgorithmException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         } catch (UnrecoverableKeyException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         return privateKey;
        public PublicKey getPublicKey(String view, String alias) throws ResourceException {
         final String SIGNATURE = "getPublicKey()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore = getKeystore(view);
         PublicKey publicKey = null;
         try {
             publicKey = keystore.getCertificate(alias).getPublicKey();
             if (publicKey == null) {
              throw new ResourceException("Key not found. alias=" + alias);
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
         TRACE.exiting(SIGNATURE);
         return publicKey;
         * Get a keystore i.e. a view from AS Java
         * @param view
         * @return
         * @throws ResourceException
        public KeyStore getKeystore(String view) throws ResourceException {
         final String SIGNATURE = "getKeystore()";
         TRACE.entering(SIGNATURE);
         KeyStore keystore;
         try {
             if (keystores.containsKey(view) == true) {
              keystore = keystores.get(view);
             } else {
              keystore = keystoreManager.getKeyStore(view);
              if (keystore == null) {
                  throw new ResourceException("Keystore not found. view=" + view);
              keystores.put(view, keystore);
             TRACE.exiting(SIGNATURE);
             return keystore;
         } catch (KeyStoreException e) {
             TRACE.catching(SIGNATURE, e);
             throw new ResourceException(e);
        static public XIKeystoreAccessor getInstance() throws ResourceException {
         if (instance == null) {
             instance = new XIKeystoreAccessor();
            return instance;

  • Help...create database(access) using java

    i had developed an java application that capture packet using Jpcap but i dont know how to keep the packet captured into database(access).i can save the packet captured in text file but not in database(access).i already had the database conectivity but i don't know how to insert the packet caputred in the table in access, is it using sql statement like INSERT INTO? or else?i realy don't know.can someone help me....?

    i can save the packet captured in to text file but not in database(access).I guess that you wish to get a databse file with your data, not a simple insert sql question.
    1. commercial solution: HXTT Access(http://www.hxtt.com/access.html), which supports create database, create table sql, and batch insert data from any JDBC driver.
    2. free solution: jdbc-odbc bridge and dsn-less jdbc url, you need to prepare a blank mdb file with blank table, then copy that blank mdb file into new mdb file, then repeat insert sql for that new mdb file.

  • Registrykey access through java program

    hi,i need help in accessing the registrykey entries made by the any software installed in the system through java program...pls send sample source code to [email protected]

    have you tried Runtime.getRuntime.exec("cmd /c start telnet");or someting like that?

  • Webservice to RFC Scenario - Through Java Mapping

    Hello All,
    In my integration scenario, I will receive a request from a webservice consumer. The webservice is my outbound interface.
    Now I have to write a Java Mapping for it because a similar interface (file to RFC) has been implemented using it and the customer wants minimum deviation from that functionality.
    One question, that I have at this point in time is:
    I must define a Java class that implements the Java interface com.sap.aii.mapping.api.StreamTransformation. This interface has two methods, one of them is:
    public void execute(java.io.InputStream in, java.io.OutputStream out). In the existing interface the InputStream object say 'input' has been initialized to FileInputStream:
    InputStream in = new FileInputStream(new File("Sample7.xml"));
    What shall I initialize it to in my case? One probable is a InputSource, but does the execute method accept an InputSource?
    Please help,
    Regards,
    Varun

    Hello Jose,
    Thanks for your reply, but what I have mentioned above is how it is being done in a similar interface. That being a file to RFC interface, it makes sense to initialize 'in' with the file name.
    But if you mean that I do not need to initialize in my case (Webservice to RFC), then I'll surely give it a try and if useful, will get back to you.
    Thanks again,
    Varun

  • SAP database updations through Java program

    Hi All,
    From Java program, I want to access SAP database batch RFC
    Please tell me which batch RFC's I have to use for read and update of a table.
    Please also tell me how to find out a batch RFC for a particular table.Is there any way to find it out like BAPI.
    What are the steps and settings ?
    Detailed steps help the requirement.
    Thanks,
    Giri

    Giri,
    Ya...Java APP sents data to XI and XI needs to insert the data into the database.
    Before the next round of data is sent by the Application, Xi should sent back info on the status of the records.
    Is this what you want?
    This will be like I have pointed earlier possible without a BPM. But, make the call from the sending application Synchronous. And then map the JDBC response to the calling aplication.
    But this updation is only possible through XI.
    If i got the requirement wrong can you let me know in more detail, what is it that you are trying?
    Reward if solved

  • XML database query through Java

    Hi all.
    I am collecting information about a little application i am trying to build:
    I have an XML database with records divided in a lot of subdirectory (with three or four .xml files);
    directories' names are defined by date in format "yyyymmdd",
    the file within are "date_something.xml":
    what is the best way to access it by a web app or a java class to search all the dirs adn print results in a readable way (aka not in cmd) ? I need first to define a period of time to search and then some attribute or node to print referred to some element.
    I was guessing to use xpath, anyway I ve tryed JSP but it is too difficult and the query i have to do are really simple to build a full servlet.
    I am learning xalan through servlet and I think in future this will be my choice but now i need to collect the data by queries without any automation, just to have results for researching and paper writing.
    The main problem I found is to search a full series of directory, with transformations i can find out stuff from a single file, but how to do it for a system of directories?
    Any suggestion or link to resource would be good also.

    lm00 wrote:
    ProjectMoon wrote:
    By XML database do you mean an actual XML native database, or just a bunch of XML files in a directory structure? If it is an actual XML native database, you should probably use the XML:DB API. If they are just flat files you will need to probably make something that is able to navigate through your directory structure to the documents you want. Once you have that, you can then use XQuery or XPath to get information from those documents.The data is a bunch of directories named by date in format "yyyymmdd", inside each of these there are three or four files .xml
    All files have data definitions and schemas but i dont think they are a 'database'. What do u mean "something to navigate through"? A class? Suppose I would like to do it as a webapp what should i have to do?
    Yes, I basically meant a class. Before querying the XML file you need something that will retrieve its location. If it's by date you could probably concoct something that takes a Date object and returns a set of File objects. Internally it would traverse the directory trees and find the proper XML file(s).
    >>
    If you have a LOT of XML documents I honestly recommend something like the eXist XML Native Database, or another XND. I have been playing with them lately and they are very useful.in this case what i have to do? Take the data and put it into a database by this tool? And then I should acces it by a JSP? There is a program using Xpath instead?Well, yes. You would put the files in the XND. Although I don't know if that's useful or not in your situation. It all depends. I also think you're a bit confused as to what JSPs and XPath are...
    JSPs are just Java Server Pages, which get dynamically compiled into servlets. If you are following the MVC pattern for servlets/JSP (which you should), JSPs represent your views while servlets are the controllers. The model would be your XML data in this case. XPath is a way to get at that data. If it was in an XND, you could just throw an XQuery/XPath expression at the database and it would give you back XML documents/fragments representing the results of your query. You don't have to make your own system to find the XML documents. Of course, you do have to learn how to use an XND.
    Perhaps you should separate what you are trying to do. You have two problems: 1) how to get the XML data you need. 2) How to present it. You should separate those two completely and learn how to do both before attempting to put it together.
    Edited by: ProjectMoon on Oct 21, 2009 12:05 PM

  • How to enable database access from Java or CSharp ?

    I set up an Oracle Express database on my local computer.
    Now I want to connect to this databsee from a CSharp (or Java) program.
    How do I have to specify the connection string?
    The following does NOT work:
    connectionstring = "Data Source=XE;User Id=karl;Password=mypassword";
    connection = new OracleConnection(connectionstring);
    connection.Open();
    I am getting an error
    "Invalid argument" ORA-12532 error
    How do I have to specify the connection string otherwise ?
    Is the sequence of the parameter Data Source, User Id and Password
    important ?
    How do I get a more detailed error message from Oracle ?
    Do I have to enable the accessibility from outside programs
    in Oracle somewhere ?

    about to the error:
    ORA-12532 TNS:invalid argument
    Cause: An internal function received an invalid parameter. This message is not normally visible to the user.
    Action: For further details, turn on tracing and re-execute the operation. If the error persists, contact Oracle Support Services.
    Regards

  • Database access with Jave Web Start

    Can a java application, that has been deployed by using Java Web Start, access information from a database that's located on the web server from where the application was deployed?

    Yes, if you use the type 4 (ie, thin) driver and include the driver's jar file as part of the app.
    Technically you can do it with a thick driver but then you have first install the driver on the client machine and I assume this isn't what you are looking for,

  • Regarding database access through jndi

    Hi All,
    Plz tell me the steps.
    I want to access data from MS Access, and i want to do it using JNDI .
    what should be added in struts-config.xml, web.xml .
    if any one have example code that will be better to understand.

    Nothing necessary added to struts-config.xml
    What server are you using? The JNDI configuration for each server is slightly different.
    The page for Tomcat is here: http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html
    I would follow that apart from instead of editing server.xml, put the JNDI configuration in a "mycontext.xml" file as defined here:
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/config/host.html#Automatic%20Application%20Deployment
    http://jakarta.apache.org/tomcat/tomcat-5.0-doc/config/context.html
    Cheers,
    evnafets

  • KM Access through java

    Hi Experts,
    I want to write a Java application, which would acess the SAP Knowledge Managemnet i want to build the functionality like
    Uploading/Downloading a documet into KM
    Creating a Folder in KM
    Does the KMApi will be useful in this application
    Please help me out in this issue
    Regards Vinod

    Hi! Vinodh,
    you can write a Webdynpro application for this purpose and use SAP KM API's.
    if you are aware of WebDynpro development then it's wonderful otherwise search SDN for this kind of Application.
    Webdynpro is nothing but an MVC architecture. you need to have NWDS as in Integrated Development Environment to develop WebDynpro appl which is freely available on SDN.
    giving you link to start with WebDynpro appl...
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/49f2ea90-0201-0010-ce8e-de18b94aee2d#backend
    Hope this will be helpful to you.
    regards,
    Noel

Maybe you are looking for

  • HT4847 can't reduce the size of my iCloud mail

    hi I got an email from I cloud saying that my 25gb free storage becomes 5gb in a few days and did I want to buy more space as I have more than 5gb used I did not think I was using any so had a look and sure enougth I have 5.3 gb of email on it I have

  • Position text box  in centre part of region

    Hi I want to position of componentes (text box, buttons, combo box) in region at center. i.e if i have region having only two text boxes and i want to put it in centre part of form/region. How it can be done, do i need to write any code or from APEX

  • Custom image from Address book not syncing to Exchange.

    I am running Mac OS X v 10.7.5. I have added custom images to contacts in address book. I have an Exchange account which will sync the data (ie name, address, email) but not the custom image. Is there away to have custom images sync to Exchange/Outlo

  • Asha 308 and MS Exchange client

    Hello all, Nokia user since birth (or almost), I desperately searched for a dual-sim product... All I could find was the Asha series. So, foolishly, I bought the Asha 308 and now I realised that there is no MS Exchange client and therefore I can't ma

  • Chinese Language Item Data Conversion

    Hi All, We get the Item data in the chinese language and we have to perform the Item data conversion. Please let me know what are the precautions, i have to take while migrating the data into oracle EBS system. Thanks, Rajesh