Design Questions: To sql or java?

Howdy,
I've got a quick question on sort of the "best" way to do something with java or sql. I know best is relative to app and case but just bare with me.
Basically I have a table set up in such a way that is making pulling reports awkward.
I have a user column which is also non unique, and an order column which is also not unique. There is a date column, which isn't important to make the entries unique.
so basically it looks like this:
user                    order                         time_spent
foo                     1                                       12
foo                      1                                       21
bar                     1                                       3
tfecw                  4                                       3
foo                      4                                       6
foo                      23a                                   6Basically I want to add up all the time spent based on a user, or based on an owner.
So if I wanted to pull the reports from an X date range, I need to get a list of orders numbers, then each order number is going to have a list of different users. Then each user is going to have a list of time_spent.
So finally the question. What would be a good way to do this? I could do pull the orders from the db, put them in an array then using that array pull the users of x order number, and then store that info into an array. Then finish it up with one last call to get all the times spent passed on my array of users and array of orders.
This seems cumbersome and I'd have to do a lot of queries to the db. One to get all the orders, one to get all the users for that order. Then one for each user to get the time_spent.
Is there way to sql statement that would work better? I've looked at what a procedure is and using cursors to loop data on the db server. I saw it's pretty resource intensive. Also I have basic sql knowledge. Simple selects and inserts..ect.
Finally the third way. Would it be a good idea to pull a result set of the entire table then manipulate the resultset the way I mentioned in the first option? I'm sort of leaning to the third option. It's still slow but I�ll be cutting out the reads from the db.
Thanks and sorry about the length

You aren't making senseYeah Thats probably right :)
just to clear up the date ranges. The orderNumbers can be traced to another table. So i'll search the date range, group, region ect from that table then based on the order numbers that query returns I'll use those ordernumbers in the table that i mentioned.
So I'll use a join to pull that data and get the desired orderNumbers. I was saying it wasn't going to help that much because of the confusion with how to access the desired data from the table i described.
basically i was trying to figure out a query that would return a result set similar to this (I'm basing this off the example i provided in the OP)
lets say the order numbers that are valid based on the users filters are 1 & 4
i want this to be returned.
1   foo   33
1   bar     3
4   tfecw  3
4   foo      6  thats searching by order number.
I know how to pull the users when i have the order number.
select * from time_table where orderNum = '1'
I also now how to add up the time_spent when i have the orderNum and the user
select sum(time_spent) from time_table where orderNum='1' and user="foo"
the confusion comes from doing that multiple times (with out accessing the db multiple times)
so
select sum(time_spent) from time_table where orderNum=validOrderList and user=validUserList
where valid* are lists of users and orderNums. so it would the first iteration it would return the time for order 1 user foo,
the second time it would return the time for order 1 user bar
3rd order 4 user tfecw ....ect
I was looking for a query to do that. But if I just order the data correctly I should be able to manipulate all of the entries returned by a
select * from time_table where oderNum = (the valid ordernums) order by orderNum, user
then i can add all the time_spents myself and print the disiered data.
sorry if this is still confusing, or even more confusing! I think this is all i can do right now. I'll post the final solution when i come up with it.
Thanks again guys.

Similar Messages

  • Database Connection design question

    Hello, I have a design question. Awhile back I needed to create a database connection to SQL Server, so I created a class to do it
    import java.sql.*;
    import java.io.*;
    import java.net.MalformedURLException;
    import org.w3c.dom.Document;
    import org.w3c.dom.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    public class SQLServerConnection
         private static Connection connection = null;
         public SQLServerConnection(String user, String password, String dbName) throws java.sql.SQLException
              getDBConnection(user, password, dbName);
         public SQLServerConnection(String configFileName) throws java.sql.SQLException
              getDBConnection(configFileName);
         private void getDBConnection(String user, String password, String dbName) throws java.sql.SQLException
             DriverManager.registerDriver(new com.microsoft.jdbc.sqlserver.SQLServerDriver());
             connection = DriverManager.getConnection(
                  "jdbc:microsoft:sqlserver:" + dbName, user, password);              
         private void getDBConnection(String configFileName) throws java.sql.SQLException
              String user;
              String password;
              String dbName;
              try
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   DocumentBuilder db = factory.newDocumentBuilder();
                   Document doc = db.parse(configFileName);
                   doc.getDocumentElement().normalize();
                   // get the configuration information
                   password = getConfigParameter("password", doc);
                   user = getConfigParameter("username", doc);
                   dbName = getConfigParameter("databasename", doc);
                   getDBConnection(user, password, dbName);
              catch (MalformedURLException murle)
                   System.out.println("Unable to connect to: " + configFileName + " -- " + murle);
                   System.exit(1);
              catch (FileNotFoundException fnfe)
                   System.out.println("Configuration file " + configFileName + " not found.");
                   System.exit(1);
              catch (IOException ioe)
                   System.out.println("IOException: " + ioe);
                   System.exit(1);
              catch (javax.xml.parsers.ParserConfigurationException pce)
                   System.out.println ("Parser Configuration Error: " + pce);
              catch (SAXException saxe)
                   System.out.println ("SAXException: " + saxe);
         private String getConfigParameter(String paramName, org.w3c.dom.Document doc)
              NodeList nl = doc.getElementsByTagName(paramName);
              if(nl != null)
                   Node n = null;
                   for (int i = 0; i < nl.getLength(); i++)
                        n = nl.item(i);          
                        if(n.hasChildNodes())
                             NodeList children = n.getChildNodes();
                             return ((Node)children.item(0)).getNodeValue();
              else
                   System.out.println ("nl is null");
              return "";          
         public void setCatalog(String catalogName) throws java.sql.SQLException
              connection.setCatalog(catalogName);
         public Connection getConnection()
              return connection;
         public void closeConnection()
              try
                   connection.close();
              catch(java.sql.SQLException sqle)
                   System.err.println ("SQL Server Connection failed to close: " + sqle);
    }Later on, I needed to do the same thing for MySQL, so I created a class for that, MySQLServerConnection which is exactly the same as above, except for:
    private void getDBConnection(String user, String password, String dbName) throws java.sql.SQLException
              try
                   Class.forName("com.mysql.jdbc.Driver").newInstance();
                   connection = DriverManager.getConnection(dbName, user, password);     
              catch(java.lang.ClassNotFoundException cnfe)
                   System.out.println (cnfe);
              catch(java.lang.InstantiationException ie)
                   System.out.println (ie);
              catch(java.lang.IllegalAccessException iae)
                   System.out.println (iae);
         }Later, on, I did the same thing with OracleServerConnection. My question is, I know this is probably not optimal code. For example, I didn't originally have a close connection method, so I had to go in and code one for all 3. I'm assuming that an interface would be a good idea so that if I have to code another database connection class I make sure and include all of the appropriate methods. I'm also assuming that it would have been smart to have a master class, maybe something like DatabaseConnection and extended these classes from that. Am I on the right track? Totally offbase?

    @nclow - I will work on trying the Factory Pattern for this over the weekend and post when I finish to see what you think.
    @abillconsl - just to make sure I understand, you're saying that I just try to connect and it will cycle through the different database connection possibilities and connect when it finds the right one? If it fails all 3, log an appropriate message. One question I have about this is, I thought I was being object oriented by separating the different types of db connections (Oracle, SQL Server, MySql) into different classes. Am I missing the point of OOP by what I was/am trying to accomplish? Going overboard? Also, does your way try and connect to all 3 even if I connected to one already?
    Thx, Grantarchy
    Edited by: grantarchy on May 9, 2008 9:50 PM

  • What is the diffrence between package javax.sql and java.sql

    Is javax designed for J2EE?
    And when to use package javax?

    Hi,
    What is the diffrence between package javax.sql and java.sql?The JDBC 2.0 & above API is comprised of two packages:
    1.The java.sql package and
    2.The javax.sql package.
    java.sql provides features mostly related to client
    side database functionalities where as the javax.sql
    package, which adds server-side capabilities.
    You automatically get both packages when you download the JavaTM 2 Platform, Standard Edition, Version 1.4 (J2SETM) or the JavaTM 2, Platform Enterprise Edition, Version 1.3 (J2EETM).
    For further information on this please visit our website at http://java.sun.com/j2se/1.3/docs/guide/jdbc/index.html
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Micro Systems
    http://www.sun.com/developers/support/

  • How to generate XML from relational data : PL/SQL or Java

    I'm new to Oracle XML and would appreciate some advice. I've been asked to generate XML documents from data stored in relational tables. The XML documents must be validated against a DTD. We will probably want to store the XML in the database.
    I've seen a PL/SQL based approach as follows :
    1.Mimic the structure of the DTD using SQL object types 2.Assign the relational data to the object type using PL/SQL as required
    3.Use the SYS_XMLGEN package to render the required XML documents from the SQL objects
    However, creating the object types seems to be quite time consuming (step 1 above) for anything other than the simplest of XML documents.
    I've also seen that there is the Java based approach, namely :
    1. Use the XML generator to build Java classes based on a DTD.
    2. Use these classes to build the required XML
    On the face of it, the Java based approach seems simpler. However, I'm not that familiar with Java.
    Which is the best way to proceed ? Is the PL/SQL based approach worth pursuing or should I bite the bullet and brush up my Java ?
    Is it possible to use a combination of PL/SQL and Java to populate the dtd generated java classes (step 2 of the Java approach) to reduce my learning curve ?
    Thanks in advance

    To help answer your questions:
    1) Now, in 9iR2, you can use SQL/XML as another choice.
    2) You can also use XSU to generate the XML and use XSLT to transform it to a desired format instead of using object views if possible.
    3) XDK provide Class generator support to populate XML data to Java classes.

  • Design question: Scheduling a Variable-timeslot Resource

    I originally posted this in general java programming, because this seemed like a more high-level design descussion. But now I see some class design questions. Please excuse me if this thread does not belong here (this is my first time using the forum, save answering a couple questions).
    Forum,
    I am having trouble determining a data structure and applicable algorithm (actually, even more general than the data structure -- the general design to use) for holding a modifiable (but more heavily read/queried than updated), variable-timeslot schedule for a given resource. Here's the situation:
    Let's, for explanation purposes, say we're scheduling a school. The school has many resources. A resource is anything that can be reserved for a given event: classroom, gym, basketball, teacher, janitor, etc.
    Ok, so maybe the school deal isn't the best example. Let's assume, for the sake of explanation, that classes can be any amount of time in length: 50 minutes, 127 minutes, 4 hours, 3 seconds, etc.
    Now, the school has a base operation schedule, e.g. they're open from 8am to 5pm MTWRF and 10am to 2pm on saturday and sunday. Events in the school can only occur during these times, obviously.
    Then, each resource has its own base operation schedule, e.g. the gym is open from noon to 5pm MTWRF and noon to 2pm on sat. and sun. The default base operation schedule for any resource is the school which "owns" the resource.
    But then there are exceptions to the base operation schedule. The school (and therefore all its resources) are closed on holidays. The gym is closed on the third friday of every month for maintenance, or something like that. There are also exceptions to the available schedule due to reservations. I've implemented reservations as exceptions with a different status code to simplify things a little bit: because the basic idea is that an exception is either an addition to or removal from the scheduleable times of that resource. Each exception (reservation, closed for maintenance, etc) can be an (effectively) unrestricted amount of time.
    Ok, enough set up. Somehow I need to be able to "flatten" all this information into a schedule that I can display to the user, query against, and update.
    The issue is complicated more by recurring events, but I think I have that handled already and can make a recurring event be transparent from the application point of view. I just need to figure out how to represent this.
    This is my current idea, and I don't like it at all:
    A TimeSlot object, holding a beginning date and ending date. A data structure that holds list of TimeSlot objects in order by date. I'd probably also hold an index of some sort that maps some constant span of time to a general area in the data structure where times around there can be found, so I avoid O(n) time searching for a given time to find whether or not it is open.
    I don't like this idea, because it requires me to call getBeginningDate() and getEndDate() for every single time slot I search.
    Anyone have any ideas?

    If I am correct, your requirement is to display a schedule, showing the occupancy of a resource (open/closed/used/free and other kind of information) on a time line.
    I do not say that your design is incorrect. What I state below is strictly my views and should be treated that way.
    I would not go by time-slot, instead, I would go by resource, for instance the gym, the class rooms (identified accordingly), the swimming pool etc. are all resources. Therefore (for the requirements you have specified), I would create a class, lets say "Resource" to represent all the resources. I would recommend two attributes at this stage ("name" & "identifier").
    The primary attribute of interest in this case would be a date (starting at 00:00hrs and ending at 24:00hrs.), a span of 24hrs broken to the smallest unit of a minute (seconds really are not very practical here).
    I would next encapsulate the availability factor, which represents the concept of availability in a class, for instance "AvailabilityStatus". The recommended attributes would be "date" and "status".
    You have mentioned different status, for instance, available, booked, closed, under-maintainance etc. Each of these is a category. Let us say, numbered from 0 to n (where n<128).
    The "date" attribute could be a java.util.Date object, representing a date. The "status", is byte array of 1440 elements (one element for each minute of the day). Each element of the byte array is populated by the number designation of the status (i.e, 0,1,2...n etc.), where the numbers represent the status of the minute.
    The "Resource" class would carry an attribute of "resourceStatus", an ordered vector of "ResourceStatus" objects.
    The object (all the objects) could be populated manually at any time, or the entire process could be automated (that is a separate area).
    The problem of representation is over. You could add any number of resources as well as any number of status categories.
    This is a simple solution, I do not address the issues of querying this information and rendering the actual schedule, which I believe is straight forward enough.
    It is recognized that there are scope for optimizations/design rationalization here, however, this is a simple and effective enough solution.
    regards
    [email protected]

  • LDAP design question for multiple sites

    LDAP design question for multiple sites
    I'm planning to implement the Sun Java System Directory Server 5.2 2005Q1 for replacing the NIS.
    Currently we have 3 sites with different NIS domains.
    Since the NFS over the WAN connection is very unreliable, I would like to implement as follows:
    1. 3 LDAP servers + replica for each sites.
    2. Single username and password for every end user cross those 3 sites.
    3. Different auto_master, auto_home and auto_local maps for three sites. So when user login to different site, the password is the same but the home directory is different (local).
    So the questions are
    1. Should I need to have 3 domains for LDAP?
    2. If yes for question 1, then how can I keep the username password sync for three domains? If no for question 1, then what is the DIT (Directory Infrastructure Tree) or directory structure I should use?
    3. How to make auto map work on LDAP as well as mount local home directory?
    I really appreciate that some LDAP experta can light me up on this project.

    Thanks for your information.
    My current environment has 3 sites with 3 different NIS domainname: SiteA: A.com, SiteB:B.A.com, SiteC:C.A.com (A.com is our company domainname).
    So everytime I add a new user account and I need to create on three NIS domains separately. Also, the password is out of sync if user change the password on one site.
    I would like to migrate NIS to LDAP.
    I want to have single username and password for each user on 3 sites. However, the home directory is on local NFS filer.
    Say for userA, his home directory is /user/userA in passwd file/map. On location X, his home directory will mount FilerX:/vol/user/userA,
    On location Y, userA's home directory will mount FilerY:/vol/user/userA.
    So the mount drive is determined by auto_user map in NIS.
    In other words, there will be 3 different auto_user maps in 3 different LDAP servers.
    So userA login hostX in location X will mount home directory on local FilerX, and login hostY in location Y will mount home directory on local FilerY.
    But the username and password will be the same on three sites.
    That'd my goal.
    Some LDAP expert suggest me the MMR (Multiple-Master-Replication). But I still no quite sure how to do MMR.
    It would be appreciated if some LDAP guru can give me some guideline at start point.
    Best wishes

  • Execution/ better performace on sql  or  java)

    hi experts,
    i would like to began a topic on better performance or best pratice adf using sql or java codes.
    basically am from Oracle forms - pl/sql background. well i knew about java and i have some awareness on Exception(my code maynt be consistent somtimes(run time) or or in other words sometimes ran into run time exceptions based on the user entries).
    say as example: consider this scenario.
    i had input lov named as employee, if the entered data is not avaiable i would throw an entered employee is not found.
    basically i would like to follow this method.
    method 1:
    vo query :
    Select * From sometable
    Where Btx = :px1 And
    :px2 Between Btbx And Btbxo And Btb_x=:pxamimpl.code
    public void Validatex(String px ,String px1, oracle.jbo.domain.Date px2 ) {
           someVOImpl vo1 = (someVOImpl)this.getsomeRequest1();
            Row r = vo1.getCurrentRow();
            String Schx = (String)r.getAttribute("Btrxxx");
              if(Schxx.equals("somevalue"))
                xffVOImpl vo2 = (xffVOImpl)this.getxkEff1();
                vo2.setNamedWhereClauseParam("px", px.toString());
                vo2.setNamedWhereClauseParam("px1", px1.toString());
                vo2.setNamedWhereClauseParam("px2", px2);
                vo2.executeQuery();
                 if(vo2.getEstimatedRowCount() == 0)
                   throw new JboException("xxx Not Found");
           if(Scheme.equalsIgnoreCase("somevalue"))
            xxffVOImpl vo = (xxxffVOImpl)this.getxxkEff1();
            vo.setNamedWhereClauseParam("px", px);
            vo.setNamedWhereClauseParam("px1", px1);
            vo.setNamedWhereClauseParam("px2", px2);
            vo.executeQuery();
             if(vo.getEstimatedRowCount() == 0)
                throw new JboException("xxx Not Found");
           }this will exposed as method called in when valuechange listeners. it's work fine.
    my question is :
    if i wrote same thing in java like this. i think it take some more time than above methods sometimes exceptions comes out.
    public void Validatex(String px ,String px1, oracle.jbo.domain.Date px2 ) {
    some vos... as like same of which i mentioned above
    using iterator iterate each and every row.
    try{
    for (.......)
    if(...)
    else
    } } catch()
    }which would be best practice.? i hope that iterating each and every row taking little bit amount of time.
    but i feel that method1 without any exception and smarter time produce result.
    so people suggest me ? where am which would be better approach.
    thanks&&REgards
    adf7.

    Hi,
    before went into testing. could please tel me. how to get/display both of the method time taken to execute and some memory consumption.See if this helps..
        public HashMap doSomethingInProc(Long serialNo, Long custNo) {
            HashMap map = new HashMap();
            CallableStatement cs = null;
            String stmt = "sy_pkg_xx.p_doSomethingInProc(?,?,?,?)";
            logger.info("execute " + stmt);
            try {
                cs = getCurrentConnection().prepareCall("begin " + stmt + "; end;");
                cs.registerOutParameter("O_2", OracleTypes.VARCHAR);
                cs.registerOutParameter("O_1", OracleTypes.NUMBER);
                cs.setLong("I_SerialNo", serialNo);
                cs.setLong("I_CustNo", custNo);
                Long start = System.currentTimeMillis();
                cs.execute();
                Long end = System.currentTimeMillis();
                logger.info("time taken to execute " + stmt + " : " + (end - start) + " ms.");
                map.put("1", cs.getString("O_1"));
                map.put("2", cs.getLong("O_2"));
                logger.info("map : " + map.toString());
            } catch (SQLException e) {
                throw new JboException(e);
                }finally{
                if(cs!=null){
                    try{
                        cs.close();
                    }catch(SQLException ex){
            return map;
        private Connection getCurrentConnection() {
            Statement st = null;
            try {
                st = getDBTransaction().createStatement(0);
                return st.getConnection();
            } catch (SQLException s) {
                s.printStackTrace();
                return null;
            } finally {
                if (st != null)
                    try {
                        st.close();
                    } catch (SQLException s2) {
        }The main code is
                Long start = System.currentTimeMillis();
                cs.execute();
                Long end = System.currentTimeMillis();
                logger.info("time taken to execute " + stmt + " : " + (end - start) + " ms.");In fact i say that every body should use this approach while executing any procedure or function as it helps us to track which part of application is running slow..
    Hope this helps !!!
    Regards,
    Edited by: Santosh Vaza on Jul 16, 2012 3:50 PM

  • Designer10g R2 Design Capture of SQL Server DDL file Failed

    I have been using Designer 10g R2 to design capture Oracle Database Schema into the Server Model Diagram with no problems at all.
    I have a SQL Server 2005 exported DDL file into an ASCII text file. I then import the DDL script into the Server Model Diagram but ERRORs.
    I use SQL Server 2005 to import the DDL script and then create an ODBC to connect to the SQL Server. I can then design capture the SQL Server schema into Designer.
    What has gone wrong? Does Designer 10g R2 support design capture from SQL Server DDL file directly to Designer?
    By the way, if I want to generate MySQL DDL script or design capture MySQL DDL script into Designer, how could this be done as there is no ODBC driver for MySQL?

    Hello,
    Please see the following links:
    http://social.msdn.microsoft.com/Forums/en-US/sqlsetupandupgrade/thread/df35f9f5-9c52-4ec4-8f5a-03a8dbef4352/
    http://social.msdn.microsoft.com/forums/en-US/sqlsetupandupgrade/thread/e8e27857-7bb7-46a2-af9b-25e397b37374/
    http://ask.sqlservercentral.com/questions/3582/sqlbol-cab-is-corrupt-and-cannot-be-used-in-sql-server-2005
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Design questions on using JMX

    I have been reading about JMX and trying to understand it
    I have some specific design realted questions and wanted some opinions to validate my understanding
    Assume a simple j2ee application that exposes 2 webservices .
    I would like to find out how many times each service is called and the total number of success/faults/errors
    encountered for each service along with params like starttime etc
    From what I have understood , I will have to first create a Bean , say "StatsCollector"
    and then creae a StatsCollectorMBean interface.
    The StatsCollector will provide the methods to set/update the above values and those will also be exposed by the StatsCollectorMBean interface
    1) I have trouble understanding how to create and maintain the MBean Resource...
    Shouldnt there be always 1 instance of this resource ? ie shouldnt there be only one StatsCollector ?
    Most of the examples create a simple class "Hello implements HelloMBean" and that makes it a MBean
    but they create Hello hello = new Hello() and then register it with the MBean server
    What if we create multiple objects of Hello? Wouldnt that defeat the porpose of the MBean ?
    I think that we need to make sure that this resource is always created once only.
    Is that correct ?
    2) Is it the right practice to separate your MBean and your "managed" resource ?
    ie in the above case , should there be a Singleton StatsCollector POJO that stores the Appliction
    statistics and another StatsMBean that will be the MBean that will access the POJO ? This makes sure that your Resource does not have
    dependency management classes.
    3) How does the application update the values in the MBean ?
    In the above example , how do you update the success and failure counts in the MBean from the application ?
    Can I update the singleton StatsCollector directly or do I have to go through the MBean Server to update
    any value in the MBean ?
    If I update them directly , will they be "visible" thru the MBean server ?
    4) Assuming that the above app gets deployed in a appserver like WebSphere and in a Clustered environment ,
    how to ensure that statisitcs are collected for all the services on all servers cummulativly ?
    Is this something that the appserver should provide ? Do we register the MBean with the Appserver
    MBean server ?
    Any ideas/suggestions will be helpful !
    thanks
    Pat

    Hello pat,
    very interesting questions. You are covering the main JMX design questions there.
    You should have a look (if you not already did) to the JMX best practices : http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/best-practices.jsp
    This document summarize common JMX design patterns.
    Answers to your questions:
    1) The resources you want to manage/monitor are Web Services. The life cycle of these services is handled by the J2EE container itself. As you say, the tricky part is to link the WebService resource life cycle to the MBean resource
    The MBean leaves inside its own container, the MBeanServer.
    You should identify an initialization phase in which you create your MBeans and register them inside the MBeanServer once.
    In your case, you can go for a single collector that monitors the 2 Web Services or a collector per Web Service. It seems that you want to track each service independently. Having 2 MBeans should offer a more flexible solution.
    If you go for 1 MBean, you should name it "<your management domain>:type=StatsCollector". This name identify an MBean for which you have a single instance. Once the collector registered with this name, the MBeanServer will guarantee that no MBean with the same name can be registered.
    If you go for 2 MBeans, you should add the Web Service name to each MBean ObjectName. For example:
    MBean 1 : "<your management domain>:type=StatsCollector,name=MyWebService1"
    MBean 2 : "<your management domain>:type=StatsCollector,name=MyWebService2"
    Example of MBean creation and registration code :
    StatsCollector collector1 = new StatsCollector();
    ManagementFactory.getPlatformMBeanServer().registerMBean(collector1,
    new ObjectName("com.foo.bar:type=StatsCollector,name=WebService1");
    At this point you have an MBean registered inside the platform MBeanServer.
    2) A Standard MBean is formed of a java interface and a class. Generally the interface and the class are not separated. They could be but I don't see a strong reason in your case to have the POJO and interface not being the same object.
    3) You shouldn't expose the methods to set the values in your MBean interface. Only getters should be visible. It means that you will have to keep a direct reference to the collectors to update the statistics. During your initialization phase, you could use JNDI to register the collector instances. The WebServices will then use JNDI to retrieve the collectors.
    An example of a simplified StatsCollector class and StatsCollectorMBean interface
    public interface StatsCollectorMBean {
    public int getNumRequests();
    public class StatsCollector implements StatsCollectorMBean {
    private int numRequests.
    public int getNumRequests() {
    return average;
    public serviceCalled() {
    numRequests++;
    In the above example, serviceCalled is not part of the management interface and is called by the Web Service.
    4) Difficult question for which I can't provide you with a reply. JMX doesn't offer such cumulative service in a standard way. In some appserver (glassfish for instance), MBeans are cascaded inside the domain server. There is no cumulative representation offered, but you could implement your own by defining new MBeans linked to the StatsCollector ones.
    To conclude, Appservers are offering some "out of the box" management and monitoring features . For example glassfish relies on the AMX framework (that is JMX based) . AMX (https://glassfish.dev.java.net/javaee5/amx/) allows you to monitor and manage your services. A possible solution would be to rely on this infrastructure to build your own management and monitoring.
    Hope this help.
    Regards.
    Jean-Francois Denise

  • Design Question: Parent/Child Distribution

    Hi,
    I have what I think is a straightforward design question. I tried
    searching this forum for the answer, but struggled with what keywords
    to use in the searches. (I also struggled with what to put on the
    subject line for this post!)
    Anyhow, here is my question: Given:
    public class Pet {...}
    public class Dog extends Pet {...}
    public class Cat extends Pet {...}
    public class Pig extends Pet {...}
    Which is the better design?
    DESIGN A:
    public abstract class PetOwner {
    private Pet pet;
    PetOwner(Pet pet) {
    this.pet = pet;
    public Pet getPet() { return this.pet; }
    public class DogOwner extends PetOwner {
    public DogOwner(Dog dog) {
    super(dog);
    public class CatOwner extends PetOwner {
    public CatOwner(Cat cat) {
    super(cat);
    public class PigOwner extends PetOwner {
    public PigOwner(Pig pig) {
    super(pig);
    ===============================================
    or DESIGN B:
    public abstract class PetOwner {
    PetOwner() {
    public class DogOwner extends PetOwner {
    private Dog dog;
    public DogOwner(Dog dog) {
    super();
    this.dog = dog;
    public class CatOwner extends PetOwner {
    private Cat cat;
    public CatOwner(Cat cat) {
    super();
    this.cat = cat;
    public class PigOwner extends PetOwner {
    private Pig pig;
    public PigOwner(Pig pig) {
    super();
    this.pig = pig;
    This is a somewhat contrived example, so don't take it too literally.
    My question is where should I put the field that holds a Pet object?
    All pet owners own a pet, so should I put it in the parent class
    (Design A)? Note the constructors for the child classes (e.g.
    DogOwner) are designed so that the correct type of pet is checked
    for. Or should each child class hold its own type of pet (Design B)?
    If the answer is "it depends" (as I suspect it is), then what are
    the questions I should be asking myself in order to decide?
    Thanks very much, in advance!!
    Chris

    eg,
    import java.util.*;
    class Pet {
        private String name = null;
        public Pet( String n ) {
         this.name = n;
        public String toString() {
         return name;
    class Dog extends Pet {
        public Dog( String n ) {
         super( n );
    class Pig extends Pet {
        public Pig( String n ) {
         super( n );
    class Cat extends Pet {
        public Cat( String n ) {
         super( n );
    class PetOwner {
        private Vector pets = new Vector();
        private int dogs = 0;
        private int cats = 0;
        private int pigs = 0;
        public void add( Dog d ) {
         pets.add( d );
         dogs++;
        public void add( Cat c ) {
         pets.add( c );
         cats++;
        public void add( Pig p ) {
         pets.add( p );
         pigs++;
        public boolean isCatOwner() {
         return cats > 0;
        public boolean isDogOwner() {
         return dogs > 0;
        public boolean isPigOwner() {
         return pigs > 0;
        public int numberOfPets() {
         return pets.size();
        public String toString() {
         String s = "";
         Enumeration en = pets.elements();
         while( en.hasMoreElements() ) {
             Pet pp = (Pet) en.nextElement();
             s += pp.toString() + "\n";
         return s;
    public class Pets {
        private PetOwner po = new PetOwner();
        public Pets() {
         po.add( new Dog( "doggy" ) );
         po.add( new Cat( "catty" ) );
        public String toString() {
         String s = "";
         s += po.toString();
         s += po.isDogOwner() + "\n";
         s += po.isPigOwner() + "\n";
         s += po.isCatOwner() + "\n";
         s += po.numberOfPets();
         return s;
        public static void main( String[] args ) {
         Pets p = new Pets();
         System.out.println( p );
    }

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

  • Design question - add another table or another column?

    Hi there,
    quick design question:
    I have the following tables:
    Traveler
    CreditCard
    Group
    A traveler is going with group X and pay (creditCard) with Y. he can go on multiple groups and can pay with Y or Z...
    my question is this:
    should I make another table CrditCard_Group which will have the following columns:
    user_id
    group_id
    creditCard_id
    or simply to have in the creditCard table another column: Group_id
    thanks for any advise

    This is not JDBC nor Java, it's database modeling.
    Said this, the answer is: it depends; if you have to record the fact that a traveler belonging to a group pays with credit card X you need the table with three ids. If you just need to record the traveler using a credit card and the traveler belonging to a group you need two tables each with the two ids.

  • Partner Application written in other language than PL/SQL and Java

    I have an application written in another language than PL/SQL or Java. I want to integrate this application as an Partner apps where I use the same user repository as Portal.
    Can I integrate the application by calling a stored PL/SQL-procedure based on the PLSQL SSO APIs examples that authenticates the user based on the username/password in portal and redirects the user to the application ?
    Are there any examples / references where this has been done ?
    Jens

    Check out the PDK referance for URL-Services, which allow you to integrate with any web based service/content.
    http://portalstudio.oracle.com/servlet/page?_pageid=350&_dad=ops&_schema=OPSTUDIO

  • PL/SQL w/ Java to run OS batch file crashes Oracle

    I followed instructions from "Ask Tom" on using PL/SQL with Java to execute an OS batch file. For testing purposes, my batch file does nothing more than display the date and time from the OS.
    However, when I run the PL/SQL that executes this simple batch file repeatedly - anywhere from two to four times, the Oracle instance crashes abruptly. Nothing is written to the alert log. No trace files are created.
    Here is a sample session:
    SQL*Plus: Release 9.0.1.3.0 - Production on Wed Mar 24 10:04:26 2004
    (c) Copyright 2001 Oracle Corporation. All rights reserved.
    Connected to:
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    SQL> set serveroutput on size 1000000
    SQL> exec dbms_java.set_output(1000000) ;
    PL/SQL procedure successfully completed.
    SQL> begin
    2 rc('c:\dba_tools\jobs\test.cmd') ;
    3 end ;
    4 /
    C:\Ora9ir2\DATABASE>date /t
    Wed 03/24/2004
    C:\Ora9ir2\DATABASE>time /t
    10:05 AM
    PL/SQL procedure successfully completed.
    SQL> begin
    2 rc('c:\dba_tools\jobs\test.cmd') ;
    3 end ;
    4 /
    C:\Ora9ir2\DATABASE>date /t
    Wed 03/24/2004
    C:\Ora9ir2\DATABASE>time /t
    10:06 AM
    PL/SQL procedure successfully completed.
    SQL>
    Shortly after the second "run", Oracle crashed. All I received was the following error message:
    Unhandled exception in oracle.exe (ORAJOX9.DLL): 0xC0000005: Access Violation
    Here is the Java procedure at the heart of my PL/SQL:
    create or replace and compile
    java source named "Util"
    as
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    public static int RunThis(String args)
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    try
    Process p = rt.exec(args);
    int bufSize = 4096;
    BufferedInputStream bis =
    new BufferedInputStream(p.getInputStream(), bufSize);
    int len;
    byte buffer[] = new byte[bufSize];
    // Echo back what the program spit out
    while ((len = bis.read(buffer, 0, bufSize)) != -1)
    System.out.write(buffer, 0, len);
    rc = p.waitFor();
    catch (Exception e)
    e.printStackTrace();
    rc = -1;
    finally
    return rc;
    I am running Oracle 9i rel. 2 installed on my PC under Windows XP Professional (Service Pack 2). My knowledge of Java is next to nothing.
    Can anyone give me an idea(s) as to what might be causing Oracle to crash?
    Thanks.

    Using 9.2.0.4 I made the following adjustments and it seems to run as often as I care to do it:
    Java changes:
    create or replace and compile
    java source named "Util"
    as
    import java.io.*;
    import java.lang.*;
    public class Util extends Object
    public static void RunThis(java.lang.String args)
    Runtime rt = Runtime.getRuntime();
    int rc = -1;
    try
    Process p = rt.exec(args);
    int bufSize = 4096;
    BufferedInputStream bis =
    new BufferedInputStream(p.getInputStream(), bufSize)
    int len;
    byte buffer[] = new byte[bufSize];
    // Echo back what the program spit out
    while ((len = bis.read(buffer, 0, bufSize)) != -1)
    System.out.write(buffer, 0, len);
    rc = p.waitFor();
    catch (Exception e)
    e.printStackTrace();
    finally
    PL/SQL Wrapper :
    create or replace procedure rc (cmd VARCHAR2) as
    language java name 'Util.RunThis(java.lang.String)';
    Execution:
    begin
    rc('c:\dba_tools\jobs\test.cmd');
    end ;
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:48 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:48 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:49 AM
    PL/SQL procedure successfully completed.
    SQL> /
    D:\oracle\ora92\DATABASE>date /t
    Fri 03/26/2004
    D:\oracle\ora92\DATABASE>time /t
    10:50 AM
    PL/SQL procedure successfully completed.
    SQL>
    The only thing I really changed was the reurn value from the java procedure. If it has a return value then it should be declared as a function, not a procedure. Since you probably (apparently) weren't using the return value I dropped it and made it a procedure.

  • PL/SQL to Java Interface - Overwhelming Overhead?

    My company is running Oracle 10g R2. I am currently exploring the use of java classes from PL/SQL. This is because we have multiple code bases, including Java, PowerBuilder (which can interface with Java), and PL/SQL (which can interface with Java).
    Doing some performance testing, I found some rather alarming results. Running a simple java function 1 million times, I tested performance of PL./SQL to java and PowerBuilder to Java.
    In PL/SQL, the 1 mil calls executed in ~120 s.
    In PowerBuilder, the 1 mil calls executed in ~54 s.
    Is it possible that our database is incorrectly configured for best java performance? Not only does it appear that PowerBuilder, a much less pervasive language than PL/SQL, is over twice as fast, but the PB test was run on my laptop, which is no where near as powerful as the database server that the PL/SQL procedure ran against, leading me to believe that the performance gap is actually much wider.
    Anyone have any tips to improve the performance? Or is this simply the nature of the beast? I can't seem to find any posts on the net about people experiencing huge PL/SQL to Java overhead, so I'm hoping it is just something I am doing wrong.
    Thanks for your help!
    -Brett Birschbach

    Below is my test code. Any suggestions are appreciated.
    Thanks!
    -Brett
    ==================================================
    Java Class:
    public class TestConvert {
        // For running straight from Java
        public static void main(String[] args){
            System.out.println(callAndTime());
        // For running 1 mil calls with only one call from PowerBuilder or PL/SQL
        public static long callAndTime(){
            TestConvert.convertEsnDecToHex("13005454488");
            long start = System.currentTimeMillis();
            for (int i = 0; i < 1000000; i++){
                TestConvert.convertEsnDecToHex("13005454488");
            long end = System.currentTimeMillis();
            return end-start;
        // For performing the actual work
        public static String convertEsnDecToHex(String esn) {
            String result = null;
            result = Integer.toHexString(new Integer(esn.substring(0, 3)).intValue());
            result += Integer.toHexString(new Integer(esn.substring(3)).intValue());
            return result.toUpperCase();
        // Non-static wrapper necessary for PowerBuilder
        public String callAndTimeNS(){
            return String.valueOf(callAndTime());
        // Non-static wrapper necessary for PowerBuilder 
        public String convertEsnDecToHexNS(String esn){
            return convertEsnDecToHex(esn);
    }PL/SQL Script for 1 Million Java Calls:
    DECLARE
      var       VARCHAR2( 20 );
      t_begin   NUMBER;
      t_end     NUMBER;
    BEGIN
      var := testconvert.convertesndectohex( '13005454488' );
      t_begin := DBMS_UTILITY.get_time;
      FOR i IN 1 .. 1000000
      LOOP
        var := testconvert.convertesndectohex( '13005454488' );
      END LOOP;
      t_end := DBMS_UTILITY.get_time;
      DBMS_OUTPUT.put_line( var );
      DBMS_OUTPUT.put_line(  ( t_end - t_begin ) / 100 || ' seconds' );
    END;
    /PowerBuilder for 1 Million Java Calls:
    EJBConnection lEJBConn
    TestConvert lnv_test
    String ls_ret
    Long i
    Time t_begin, t_end
    lEJBConn = CREATE EJBConnection
    lEJBConn.CreateJavaInstance( lnv_test, "TestConvert")
    ls_ret = lnv_test.convertesndectohexns("13005454488")
    t_begin = now()
    FOR i = 1 TO 1000000          
         ls_ret = lnv_test.convertesndectohexns("13005454488")
    NEXT
    t_end = now()
    MessageBox("Hex Version",ls_ret + " - " + String(SecondsAfter(t_begin, t_end)) + " seconds")
    DESTROY lEJBConn

Maybe you are looking for

  • Vendor tax deductions

    Hi all, Same vendor with different tax deductions. How to capture?

  • Convert Spool Request in chinese Language to PDF

    kindly help me to solve the issues. is there any way to convert the spool request which is in chinese langauge, Requirement is to download SAP Script to PDF, where the PDF file should be in Chinese format. i used the following FM 1)CONVERT_OTFSPOOLJO

  • Communication between separate ADF Web Applications

    Using 11.1.1.5 of JDeveloper I have two Fusion Web Applications that each have a single "view" task flow. Those task flows will be dropped into regions within a WebCenter Portal application so they behave like portlets. I'd like to have a value from

  • How to display html tags content in flex

    hi all, It would be great if any one can lead me to a tutorial of integrating html tags content in flex. Actulay i have to insert and series to table in flex thanks

  • Remove applets in Safari iOS7

    I just upgraded my iPad to OS7 and every time I open a new tab in Safari, I get three stupid applets to link me to either Yahoo!, Disney or Apple. I never asked for them, so does anyone know how to get rid of them?