Servlet and utility problem

Can we Implement "observer" utility in a class extending "HttpServlet"???
I am giving a proposed code. Assume that all the packages has been imported. This code is giving run time error......
The Code follows Like :
class SomeServlet extends HttpServlets implements Observer
       public void Service(HttpServletRequest request, HttpServletResponse response)
                BeingWatched bw = new BeingWatched(this);
      update(Observable o, Object arg)
//Here is the code which is implementing Observable
public class BeingWatched extends Observable
     public BeingWatched(Observer o)
          addObserver(o);
          counter(10);
     void counter(int period)
          for(;period>=0;period--)
               setChanged();
               //notifyObservers();
               notifyObservers(new Integer(period));
               try
                    Thread.sleep(1000);
               catch(InterruptedException e)
                    System.out.println("sleep Interrupted");
     }

Hi sumitk,
Sorry for the delay in responding, I live down under so I'm in bed when everyone else is logged on.
You can implement Observer as you have done from a servlet, I think something in the way you have written the servlet is causing you threading problems. My knowledge is a bit vague but try this article from javaworld:
http://www.javaworld.com/javaworld/javatips/jw-javatip29.html?
Its seems pretty good.

Similar Messages

  • GS70 driver and utility problems

    after i do a clean install of the windows 8.1 on my GS70 today, there is a few problems from the software support, someone at tech support please fix it.
    1st, i found out that the GS70 Windows 8.1 EC firmware w8_1771EMS1.507.zip is an empty file over all of the download server.
    2nd, there is no Hybrid Power utility on the GS70 download page, i'm sure this one comes with the pre-loaded windows 8.
    3rd, after install the Elantench Touchpad x64 driver version 11.13.4.4 the multi touch function is no longer working, but the old one 11.13.3.3 works fine.
    btw, how do i update the EC firmware on the GS70? since i can't take out the battery without breaking the warranty seal.

    Quote
    btw, how do i update the EC firmware on the GS70? since i can't take out the battery without breaking the warranty seal.
    there should't be sticker on battery
    for other things, report it to msi here: >>How to contact MSI.<<

  • Problem exchanging values between a Servlet and Thread???

    Hi Everybody,
    I have got a problem exchanging values between a Servlet and a Thread...
    The actual thing will go like this
    I take a request from JSP which is served by a servlet..
    A thread is invoked in the servlets into which the parameter values taken from JSP page is sent...
    In between the thread needs to be suspended for a moment, relieve the control back to the servlet and then come back with the new values modified in the servlet...
    How is this achieved?
    Please give ur suggestions regarding this...
    Thanks in advance

    I really have no clue how you can use URLConnection to do that!
    Could you please explain in the following scenario how it can help me as an alternative solution to the following:
    Non-Servlet A continously running & saving to some prop regularly
    --> servlet B reads prop file regularly --> display continously on a jsp file
    I wish I could do a servlet A --> servlet B-- > display jsp scenario but I do not know how to have servlet A continously running while keep the servlet B interacting with the jsp.

  • Problem for getting the real path using one servlet and one jsp page

    I have one tomcat machine and several virtual domains. Eahc virtual domain has one realpath in the disc.
    I am using one servlet and one jsp page for using this servlet.
    my purpose is to load, using the servlet , the real path for the domains (eahc domain has its path).
    for this i make this:
    the servlet code is this:
    package utils.ticker;
    import java.io.*;
    import java.io.File;
    import java.io.IOException;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class Edicion extends HttpServlet{
    public Edicion() {
    public String cc(){
    ServletContext myContext= getServletContext();
    String abspath = myContext.getRealPath("/");
    //here i want to return the real path
    return abspath;
    public static void main(String args[]){
    and the jsp page is:
    <%@ page import="utils.ticker.*" %>
    <jsp:useBean id="tick" class="utils.ticker.Edicion" scope="session"/>
    <html><head><body>
    <%
    tick.cc();
    %>
    </body></head></html>
    But this produces one error, NullPointerException and dont shows me the real path.
    Can anyone help me?
    thanks

    i have put this into one sevlet:
    package utils.ticker;
    import javax.servlet.ServletContext;
    public class Edicion{
    private ServletContext myContext;
    public Edicion(ServletContext myContext) {
    this.myContext = myContext;
    public String getCC(){
    return myContext.getRealPath("/");
    and in the jsp page this:
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*"%>
    <%@ page import="utils.ticker.*" %>
    <jsp:useBean id="tick" class="utils.ticker.Edicion" scope="session"/>
    <html><head><body>
    <%=tick.getCC()%>
    </body></head></html>
    but appear this error in the tomcat.
    Can you, please, help me. i am trying to solve this during one week and i am desesperate.
    Thanks.
    ERROR:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: class utils.ticker.Edicion : java.lang.InstantiationException: utils.ticker.Edicion
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:248)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    root cause
    javax.servlet.ServletException: class utils.ticker.Edicion : java.lang.InstantiationException: utils.ticker.Edicion
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:533)
         at org.apache.jsp.pruebas_jsp._jspService(pruebas_jsp.java:72)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:204)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    Apache Tomcat/4.1.18

  • Problems Compiling javax.servlet and javax.servlet.http

    When I try to compile a program that imports both javax.servlet and javax.servlet.http, the compiler keeps telling me that "package javax.servlet does not exist"... I have place the javax.servlet packages in the src.zip and in the src folder but i dont understand why the compiler isnt picking them up. Maybe I did something wrong ... could someone help please

    Try to compile vith the option "-classpath /your/path/to/servlet.jar"

  • Servlets and java.util.concurrent

    Hey --
    I know one is not supposed to spawn their own threads from Servlets and EJBs, but is it also 'bad form' to use Callables from a Servlet or EJB? If not can something similar be done safely?
    I need to be able to (a) submit a file to be processed (b) give the user back a 'got it, will work on it' response, (c) let the user see the status of his 'job' and (4) open the results when complete.
    The file processing would be running outside of the normal send request/return response path which is, of course, a synchronous process. I don't see a way, other than spawning a thread in that servlet (or another servlet which manages the 'jobs') to provide for 'long running processes.'
    Thanks for any insight.
    - Z -
    Message was edited by:
    zelmak

    Hey --
    I know one is not supposed to spawn their own threads from Servlets and EJBs, but is it also 'bad form' to use Callables from a Servlet or EJB? If not can something similar be done safely?
    I need to be able to (a) submit a file to be processed (b) give the user back a 'got it, will work on it' response, (c) let the user see the status of his 'job' and (4) open the results when complete.
    The file processing would be running outside of the normal send request/return response path which is, of course, a synchronous process. I don't see a way, other than spawning a thread in that servlet (or another servlet which manages the 'jobs') to provide for 'long running processes.'
    Thanks for any insight.
    - Z -
    Message was edited by:
    zelmak

  • Using database connection in a servlet and get errors after 8 hours

    Hey,
    I'm running a poker script using applet/servlets and it works great. But for some reason about about 8 hours that database layer stops working. At first I thought it was the connections to mySQL that were timing out (because im using connection pooling) but after turning pooling off (I now create the connection each time) I'm still seeing that same error (I can create a connection but when I do an action ex. like a select statment I get an error). What i'm wondering could it be that the driver I load with Class.forName() some how unloads it's self after x amount of time not being used? Not sure if that is it but if anyone could give me some insight that would be great. The Error i recieve is below:
    INFO: Database Event:DatabaseController: Error executing database query.
    ERROR: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.net.SocketException
    MESSAGE: Software caused connection abort: recv failed
    STACKTRACE:
    java.net.SocketException: Software caused connection abort: recv failed
         at java.net.SocketInputStream.socketRead0(Native Method)
         at java.net.SocketInputStream.read(Unknown Source)
         at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:104)
         at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
         at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:172)
         at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1839)
         at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2288)
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2784)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2370)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:2297)
         at com.mysql.jdbc.Statement.executeQuery(Statement.java:1183)
         at com.softnet.database.DatabaseController.executeDatabaseQuery(DatabaseController.java:190)
         at com.softnet.games.GameServer.validateUser(GameServer.java:438)
         at com.softnet.games.GameServer.handleData(GameServer.java:113)
         at com.softnet.network.HttpConnectionThread.run(HttpServletListener.java:191)
    ** END NESTED EXCEPTION **
    I know the query is good because it works all other times just not after about 8 hours.
    --Z3r0CooL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hey,
    Thanks for the responces. For the connection pooling I would open 5 connections and keep them open. So i though maybe after 8 hours after not being used they would timeout. Thats why i turned off conection pooling and create a new connection each time. Anyways i'll post the code below incase i made a mistake somewhere.
    package com.softnet.database;
    /************************ DatabaseControler **************************/
    import java.sql.*;
    import java.util.*;
    import com.softnet.database.DatabaseConnectionPool;
    import com.softnet.database.DatabaseSettings;
    public class DatabaseController
    implements DatabaseListener
         //Used to make sure the database driver is loaded
         private boolean databaseDriverState = false;
         //Used to store a database connection
         private Connection databaseConnection = null;
         //If to user connection pooling or not
         private boolean useConnectionPooling = false;
         //Used to hold the connection pool varible
         private DatabaseConnectionPool connectionPool = null;
         //Used to store database settings
         private DatabaseSettings databaseSettings;
         //Used to hold the DatabaseController listeners
         private List databaseControllerListeners = new ArrayList();
         //min number of connections for connection pool
         private int minNumberOfConnections = 1;
         //max number of connections for connection pool -1 is unlimited
         private int maxNumberOfConnections = -1;
         //DatabaseController Constructors
         public DatabaseController(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
              databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
         public DatabaseController(DatabaseSettings databaseSettings, boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
              this.databaseSettings = databaseSettings;
              this.useConnectionPooling = useConnectionPooling;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              if(useConnectionPooling == true)
                   connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
                   connectionPool.addDatabaseListener(this);
              else
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
         public DatabaseController() {}
         //Database Settings Get/Set
         public DatabaseSettings getDatabaseSettings()
              return databaseSettings;
         public void setDatabaseSettings(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
         //Connection Pooling Get/Set
         public boolean getConnectionPooling()
              return useConnectionPooling;
         public void setConnectionPooling(boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
              this.useConnectionPooling = useConnectionPooling;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              if(useConnectionPooling == true)
                   if(connectionPool == null)
                        connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
                        connectionPool.addDatabaseListener(this);
              else
                   if(connectionPool != null)
                        connectionPool.destroyConnections();
                        connectionPool.removeDatabaseListener(this);
                        connectionPool = null;
         //Return if there connected
         public boolean isConnected()
              boolean isConnected;
              if(databaseConnection != null)
                   isConnected = true;
              else
                   isConnected = false;
              return isConnected;
         //Used to connect to database or get a connection for the connection pool
         public void connect()
              if(databaseDriverState == false)
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //If we dont have a current connection, make one
              if(databaseConnection == null && databaseDriverState == true)
                   if(useConnectionPooling == false)
                        try
                             databaseConnection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                        catch (SQLException sqle)
                             //Raise event
                             raiseDatabaseEvent("DatabaseController: Error connecting to database. \nERROR: " + sqle.getMessage());
                             databaseConnection = null;
                   else
                        databaseConnection = connectionPool.getConnection();
         //Used to disconnect from the database or give back the connection to the connection pool
         public void disconnect()
              if(databaseConnection != null)
                   if(useConnectionPooling == false)
                        try
                             //Close DB Connection
                             databaseConnection.close();
                        catch(SQLException ignore) {}
                        finally
                             databaseConnection = null;
                   else
                        connectionPool.returnConnection(databaseConnection);
                        databaseConnection = null;
         public ResultSet executeDatabaseQuery(String sSQL)
              ResultSet databaseResult = null;
              if(databaseConnection != null)
                   try
                        Statement databaseStatement = databaseConnection.createStatement();
                        databaseResult = databaseStatement.executeQuery(sSQL);
                   catch(SQLException sqle)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error executing database query.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
              return databaseResult;
         public int executeDatabaseUpdate(String sSQL)
              int rowsAffected = -1;
              if(databaseConnection != null)
                   try
                        Statement databaseStatement = databaseConnection.createStatement();
                        rowsAffected = databaseStatement.executeUpdate(sSQL);
                   catch(SQLException sqle)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error executing database update.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
              return rowsAffected;
         //Used to load the Database Driver
         private boolean loadDatabaseDriver(String databaseDriver)
              boolean driverLoaded;
              if(databaseDriver.equals("") == false)
                   try
                        //Load Database Driver
                        Class.forName(databaseDriver).newInstance();
                        driverLoaded = true;
                   catch (Exception e)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + e.getMessage());
                        driverLoaded = false;
              else
                   driverLoaded = false;
              return driverLoaded;
         //Wrap the DatabaseConnectionPool Error to the DatabaseController
         public void databaseEventOccurred(DatabaseEvent de)
              raiseDatabaseEvent(de.getErrorMessage());
         //Event Handling Code
         //Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
    public synchronized void addDatabaseListener(DatabaseListener databaseControllerListener)
    databaseControllerListeners.add(databaseControllerListener);
    //Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
    public synchronized void removeDatabaseListener(DatabaseListener databaseControllerListener)
    databaseControllerListeners.remove(databaseControllerListener);
    //Used to send the raise event to the listeners
    private synchronized void raiseDatabaseEvent(String databaseError)
    DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
    Iterator listeners = databaseControllerListeners.iterator();
    while(listeners.hasNext())
         DatabaseListener listener = (DatabaseListener) listeners.next();
    listener.databaseEventOccurred(databaseEvent);
    /********************* DatabaseConnectionPool **************/
    package com.softnet.database;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import com.softnet.database.*;
    import com.softnet.database.DatabaseSettings;
    public class DatabaseConnectionPool
         //min number of connections
         private int minNumberOfConnections = 1;
         //max number of connections -1 is unlimited
         private int maxNumberOfConnections = -1;
         //Store the connections
         protected Hashtable databaseConnections = null;
         //Database Info
         protected DatabaseSettings databaseSettings;
         //to hold Driver state
         private boolean databaseDriverState = false;
         //To hold connection checker
         private DatabaseConnectionCheck connectionChecker = null;
         //Used to hold the DatabaseConnectionPool listeners
         private List databaseConnectionPoolListeners = new ArrayList();
         public DatabaseConnectionPool(DatabaseSettings databaseSettings, int minNumberOfConnections, int maxNumberOfConnections)
              this.databaseSettings = databaseSettings;
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
              //Load Driver
              databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //Create connection
              createConnections();
         public DatabaseConnectionPool(int minNumberOfConnections, int maxNumberOfConnections)
              this.minNumberOfConnections = minNumberOfConnections;
              this.maxNumberOfConnections = maxNumberOfConnections;
         //Database Settings Get/Set
         public DatabaseSettings getDatabaseSettings()
              return databaseSettings;
         public void setDatabaseSettings(DatabaseSettings databaseSettings)
              this.databaseSettings = databaseSettings;
         //Driver State Get
         public boolean getDatabaseDriverState()
              return databaseDriverState;
         public void createConnections()
              if(databaseDriverState == false)
                   databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
              //Create all connections and load the minimum in the Hashtable
              if(databaseConnections == null)
                   if(databaseDriverState == true && minNumberOfConnections != 0)
                        databaseConnections = new Hashtable();
                        for(int i = 0; i < minNumberOfConnections; i++)
                             try
                                  databaseConnections.put(DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword()), Boolean.FALSE);
                             catch(SQLException sqle)
                                  //Problem break loop and destroy any connections
                                  destroyConnections();
                                  //Raise event
                                  raiseDatabaseEvent("DatabaseConnectionPool: Error creating database connections. \nERROR: " + sqle.getMessage());
                                  break;
              //If no connection check exists create one
              if(connectionChecker == null)
                   connectionChecker = new DatabaseConnectionCheck(this);
                   connectionChecker.start();
         public Connection getConnection()
              Connection connection = null;
              boolean errorWithConnection = false;
              Enumeration connections = databaseConnections.keys();
              synchronized (databaseConnections)
                   while(connections.hasMoreElements())
                        errorWithConnection = false;
                        connection = (Connection) connections.nextElement();
                        Boolean state = (Boolean) databaseConnections.get(connection);
                        //If connection is not used, use it.
                        if(state == Boolean.FALSE)
                             try
                                  connection.setAutoCommit(true);
                             catch(SQLException e)
                                  //Problem with connection remove connection and replace it
                                  databaseConnections.remove(connection);
                                  try
                                       connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                                  catch(SQLException sqle)
                                       errorWithConnection = true;
                             if(errorWithConnection == false)
                                  // Update the Hashtable to show this one's taken
                                  databaseConnections.put(connection, Boolean.TRUE);
                                  // Return the connection
                                  return connection;
                   //All connections being used check to max to see if we can make a new one
                   if(maxNumberOfConnections == -1 || maxNumberOfConnections > databaseConnections.size())
                        try
                             connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                        catch(SQLException sqle)
                             errorWithConnection = true;
                        if(errorWithConnection == false)
                             databaseConnections.put(connection, Boolean.TRUE);
                             return connection;
              //If not connections free and max connections reached wait for a free connection
              return getConnection();
         public void returnConnection(Connection connection)
              boolean errorWithConnection = false;
              //Make sure connection still works
              try
                   connection.setAutoCommit(true);
              catch(SQLException e)
                   //Problem with connection remove connection and replace it
                   databaseConnections.remove(connection);
                   try
                        connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
                   catch(SQLException sqle)
                        errorWithConnection = true;     
              if(errorWithConnection == false)
                   databaseConnections.put(connection, Boolean.FALSE);
         public void destroyConnections()
              Connection connection = null;
              if(databaseConnections != null)
                   //Close all connections
                   Enumeration connections = databaseConnections.keys();
                   while (connections.hasMoreElements())
                        connection = (Connection) connections.nextElement();
                        try
                             connection.close();
                        catch(SQLException ignore) {}
                   //Free up hashtable
                   databaseConnections = null;
         private boolean loadDatabaseDriver(String databaseDriver)
              boolean driverLoaded;
              if(databaseDriver.equals("") == false)
                   try
                        //Load Database Driver
                        Class.forName(databaseDriver);
                        driverLoaded = true;
                   catch (ClassNotFoundException cnfe)
                        //Raise event
                        raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + cnfe.getMessage());
                        driverLoaded = false;
              else
                   driverLoaded = false;
              return driverLoaded;
         //Event Handling Code
         //Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
    public synchronized void addDatabaseListener(DatabaseListener databaseConnectionPoolListener)
    databaseConnectionPoolListeners.add(databaseConnectionPoolListener);
    //Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
    public synchronized void removeDatabaseListener(DatabaseListener databaseConnectionPoolListener)
    databaseConnectionPoolListeners.remove(databaseConnectionPoolListener);
    //Used to send the raise event to the listeners
    private synchronized void raiseDatabaseEvent(String databaseError)
    DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
    Iterator listeners = databaseConnectionPoolListeners.iterator();
    while(listeners.hasNext())
         DatabaseListener listener = (DatabaseListener) listeners.next();
    listener.databaseEventOccurred(databaseEvent);
    class DatabaseConnectionCheck extends Thread
         private DatabaseConnectionPool connectionPool;
         DatabaseConnectionCheck(DatabaseConnectionPool connectionPool)
              this.connectionPool = connectionPool;
         public void run()
              try
                   while(true)
                        //check threads every 30 seconds
                        this.sleep(300000);
                        if(connectionPool.databaseConnections != null)
                             Connection connection = null;
                             Enumeration connections = connectionPool.databaseConnections.keys();
                             synchronized (connectionPool.databaseConnections)
                                  while(connections.hasMoreElements())
                                       connection = (Connection) connections.nextElement();
                                       Boolean state = (Boolean) connectionPool.databaseConnections.get(connection);
                                       //If connection is not used, use it.
                                       if(state == Boolean.FALSE)
                                            try
                                                 connection.setAutoCommit(true);
                                            catch(SQLException e)
                                                 //Problem with connection remove connection and replace it
                                                 connectionPool.databaseConnections.remove(connection);
                                                 try
                                                      connection = DriverManager.getConnection(connectionPool.databaseSettings.getDatabaseURL(), connectionPool.databaseSettings.getUserName(), connectionPool.databaseSettings.getUserPassword());
                                                 catch(SQLException sqle)
                                                      connection = null;
                                                 // Update the Hashtable with new connection if its not null
                                                 if(connection != null)
                                                      connectionPool.databaseConnections.put(connection, Boolean.FALSE);
              catch(InterruptedException ignored) {}     
    Basicly the why it works is the connection pool hold the database connections. When the user needs a connection they use the database controller to request a connection (By create a instance and called the connect() method) and the connection is either created or grabed from the connection pool. After the user is done with the connection they call the disconnect() method which closes the connection or returns it to the connection pool.
    --Z3r0CooL                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 

  • Simple authentication and authorization with a servlet and a filter

    Could somebody point me to code example that do simple authentication/authorization using one servlet and one filter? (without Spring, Struts, JSF or any framework)
    I&rsquo;m having a lot of problems with that, apparently, easy task.
    These are the rules:
    - A simple login page
    - Two roles (admin, registered).
    - If the user loged is an admin, redirect to his entry page (private/admin/index.jsp).
    - If the user loged is of role registered, redirect him to his entry page (private/registered/index.jsp).
    - If it&rsquo;s not a valid user, redirect again to login page.
    - Admin&rsquo;s users cannot go to private/registered/ area.
    - Registered users cannot go to private/admin/ area.
    - Non authenticated user cannot go to private/ area
    Thanks a lot in advance!
    Edited by: JLuis on 25-ago-2010 15:27

    AccessControl.java:
    package com.tlsformacion.security;
    import java.io.IOException;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.tlsformacion.utils.Log;
    public final class AccessControl extends HttpServlet {
         private static final long serialVersionUID = 5741058615983779764L;
         private static final String USERNAME_ATTR = "username";
         private static final String PWD_ATTR = "password";
         private static final String LOGIN_PAGE_ATTR = "login_page";
         private static final String ROL_ATTR = "role";     
         private boolean isAuthentic = false;
         private String role = null;
         private String loginPage = null;
         public AccessControl() {
            super();
         public void init(ServletConfig config) throws ServletException {
              loginPage = config.getInitParameter(LOGIN_PAGE_ATTR);
         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doGet");
              doAccessControl(request, response);
         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doPost");
              doAccessControl(request, response);
         private void doAccessControl (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside doAccessControl");
              doAuthentication(request, response);     
              if (isAuthentic) { //Authentic user
                   doAuthorization(request, response);                         
              } else { //User NOT authentic
                   doRejection(request, response);
         private void doAuthentication(HttpServletRequest request, HttpServletResponse response) {     
              debug("Inside doAuthentication");                         
            String requestedURI = request.getRequestURI();
            if (requestedURI.contains("/AccessControl")) { //Comes from login page           
                 debug("Comes from login page");
                  String username = request.getParameter(USERNAME_ATTR);
                String pwd = request.getParameter(PWD_ATTR);   
                 role = getRole(username, pwd);
                 if (role != null) {
                      isAuthentic = true;
                      request.getSession().setAttribute(ROL_ATTR, role);
            } else { //Doesn't comes from login page
                 debug("Doesn't comes from login page");
                 if (isInSession(request)) {
                      debug("Rol is in session");               
                      isAuthentic = true;
                 } else {
                      debug("Rol is NOT in session");
         private void doAuthorization(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
              debug("Inside doAuthorization");
              String requestedURI = request.getRequestURI();
              debug("requestedURI: " + requestedURI);
              if (requestedURI.contains("/AccessControl")) { //Comes from login page                                                                 
                   goHomePage(request, response);
              } else if (requestedURI.contains("/private/" + role)) { //Trying to access his private area
                   goRequestedPage(request, response);
              } else { //Trying to access other roles private area
                   goLoginPage(request, response);
        private void doRejection(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {          
             debug("Inside goRejection");
             role = null;
              goLoginPage(request, response);         
         private void goHomePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goHomePage");     
              String homePage = "private/" + role + "/index.jsp";
              goPage(request, response, homePage);
         private void goLoginPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goLoginPage");
              goPage(request, response, loginPage);
         private void goRequestedPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              debug("Inside goRequestedPage");
              String contextPath = request.getContextPath();          
              debug("contextPath: " + contextPath);
              String requestedPage = request.getRequestURI().replace(contextPath + "/", "");
              goPage(request, response, requestedPage);
         private void goPage(HttpServletRequest request, HttpServletResponse response, String page) throws IOException, ServletException {
              debug("Inside goPage ...trying to go to: " + page);
              //Option A
              response.sendRedirect(page);
              //Option B
              //RequestDispatcher requestDispatcher = request.getRequestDispatcher(page);
              //requestDispatcher.forward(request, response);                  
         private boolean isInSession(HttpServletRequest httpRequest) {
             boolean inSession = false;
              role = (String)httpRequest.getSession().getAttribute(ROL_ATTR);
              if (role != null && !role.equals("")) {
                   inSession = true;
             return inSession;
        //PENDIENTE: mock method!
        private String getRole(String username, String pwd) {         
             String role = null;
             if (username.equals("admin") && pwd.equals("admin")) {
                  role = "administrator";
             } else if (username.equals("regis") && pwd.equals("regis")) {
                  role = "registered";
             return role;
        private void debug(String msg) {
             Log.debug(msg);
    }Proyect Folder Structure:
    WebContent
         login.html
         private
              administrator
                   index.jsp
              registered
                   index.jspBasically, the problem is that if you try to log as admin/admin (for example) the servlet AccessControl executes infinitely
    Edited by: JLuis on 26-ago-2010 8:04

  • JSP Servlet and convert the result set of an SQL Query To XML file

    Hi all
    I have a problem to export my SQL query is resulty into an XML file I had fixed my servlet and JSP so that i can display all the records into my database and that the goal .Now I want to get the result set into JSP so that i can create an XML file from that result set from the jsp code.
    thisis my servlet which will call the jsp page and the jsp just behind it.
    //this is the servlet
    import java.io.*;
    import java.lang.reflect.Array;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.*;
    import javax.sql.*;
    public *class *Campaign *extends *HttpServlet
    *private* *final* *static* Logger +log+ = Logger.+getLogger+(Campaign.*class*.getName());
    *private* *final* *static* String +DATASOURCE_NAME+ = "jdbc/SampleDB";
    *private* DataSource _dataSource;
    *public* *void* setDataSource(DataSource dataSource)
    _dataSource = dataSource;
    *public* DataSource getDataSource()
    *return* _dataSource;
    *public* *void* init()
    *throws* ServletException
    *if* (_dataSource == *null*) {
    *try* {
    Context env = (Context) *new* InitialContext().lookup("java:comp/env");
    _dataSource = (DataSource) env.lookup(+DATASOURCE_NAME+);
    *if* (_dataSource == *null*)
    *throw* *new* ServletException("`" + +DATASOURCE_NAME+ + "' is an unknown DataSource");
    } *catch* (NamingException e) {
    *throw* *new* ServletException(e);
    protected *void *doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    Connection conn = *null*;
    *try* {
    conn = getDataSource().getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select post_id,comments,postname from app.posts");
    // out.println("Le r&eacute;sultat :<br>");
    ArrayList <String> Lescomments= *new* ArrayList<String>();
    ArrayList <String> Lesidentifiant = *new* ArrayList<String>();
    ArrayList <String> Lesnoms = *new* ArrayList <String>();
    *while* (rs.next()) {
    Lescomments.add(rs.getString("comments"));
    request.setAttribute("comments",Lescomments);
    Lesidentifiant.add(rs.getString("post_id"));
    request.setAttribute("id",Lesidentifiant);
    Lesnoms.add(rs.getString("postname"));
    request.setAttribute("nom",Lesnoms);
    rs.close();
    stmt.close();
    *catch* (SQLException e) {
    *finally* {
    *try* {
    *if* (conn != *null*)
    conn.close();
    *catch* (SQLException e) {
    // les param&egrave;tres sont corrects - on envoie la page r&eacute;ponse
    getServletContext().getRequestDispatcher("/Campaign.jsp").forward(request,response);
    }///end of servlet
    }///this is the jsp page called
    <%@ page import="java.util.ArrayList" %>
    <%
    // on r&eacute;cup&egrave;re les donn&eacute;es
    ArrayList nom=(ArrayList)request.getAttribute("nom");
    ArrayList id=(ArrayList)request.getAttribute("id");
    ArrayList comments=(ArrayList) request.getAttribute("comments");
    %>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    Liste des campagnes here i will create the xml file the problem is to display all rows
    <hr>
    <table>
    <tr>
    </tr>
    <tr>
    <td>Comment</td>
    <td>
    <%
    for( int i=0;i<comments.size();i++){
    out.print("<li>" + (String) comments.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>nom</td>
    <td>
    <%
    for( int i=0;i<nom.size();i++){
    out.print("<li>" + (String) nom.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    <tr>
    <td>id</td>
    <td>
    <%
    for( int i=0;i<id.size();i++){
    out.print("<li>" + (String) id.get(i) + "</li>\n");
    }//for
    %>
    </tr>
    </table>
    </body>
    </html>
    This is how i used to create an XML file in a JSP page only without JSP/SERVLET concept:
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%
    // Identify a carriage return character for each output line
    int iLf = 10;
    char cLf = (*char*)iLf;
    // Create a new empty binary file, which will content XML output
    File outputFile = *new* File("C:\\Users\\user\\workspace1\\demo\\WebContent\\YourFileName.xml");
    //outputFile.createNewFile();
    FileWriter outfile = *new* FileWriter(outputFile);
    // the header for XML file
    outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);
    try {
    // Define connection string and make a connection to database
    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/SAMPLE","app","app");
    Statement stat = conn.createStatement();
    // Create a recordset
    ResultSet rset = stat.executeQuery("Select * From posts");
    // Expecting at least one record
    *if*( !rset.next() ) {
    *throw* *new* IllegalArgumentException("No data found for the posts table");
    outfile.write("<Table>"+cLf);
    // Parse our recordset
    // Parse our recordset
    *while*(rset.next()) {
    outfile.write("<posts>"+cLf);
    outfile.write("<postname>" + rset.getString("postname") +"</postname>"+cLf);
    outfile.write("<comments>" + rset.getString("comments") +"</comments>"+cLf);
    outfile.write("</posts>"+cLf);
    outfile.write("</Table>"+cLf);
    // Everything must be closed
    rset.close();
    stat.close();
    conn.close();
    outfile.close();
    catch( Exception er ) {
    %>

    Please state your problem that you are having more clearly so we can help.
    I looked at your code I here are a few things you might consider:
    It looks like you are putting freely typed-in comments from end-users into an xml document.
    The problem with this is that the user may enter characters in his text that have special meaning
    to xml and will have to be escaped correctly. Some of these characters are less than character, greater than character and ampersand character.
    You may also have a similiar problem displaying them on your JSP page since there may be special characters that JSP has.
    You will have to read up on how to deal with these special characters (I dont remember what the rules are). I seem to recall
    if you use CDATA in your xml, you dont have to deal with those characters (I may be wrong).
    When you finish writing your code, test it by entering all keyboard characters to make sure they are processed, stored in the database,
    and re-displayed correctly.
    Also, it looks like you are putting business logic in your JSP page (creating an xml file).
    The JSP page is for displaying data ONLY and submitting back to a servlet. Put all your business logic in the servlet. Putting business logic in JSP is considered bad coding and will cause you many hours of headache trying to debug it. Also note: java scriptlets in a JSP page are only run when the JSP page is compiled into a servlet by java. It does not run after its compiled and therefore you cant call java functions after the JSP page is displayed to the client.

  • First day with java: and first problem

    Hi friends,
    may be i'm hurrying a bit. But i really don't have time. I'm a PHP programmer , trying to shift to java, and i have one week to learn core java, j2ee and blah blah! And here i'm with a confusion.
    When i tried implementing servlet , i didn't get any output:
    public void init(ServletConfig config) throws ServletException {
    System.out.println("init");
    but when i tried extending httpServlet , that worked.
    whats the problem?
    and will be happy to get a few tips.
    Thanks.

    Your best bet would be to get someone with years of java experience at your side and have him set up your environment and will stand by when you get stuck. There is a LOT to learn that will take far far longer than one week to learn (more like years to get any good). Its a totally unrealistic expectation.
    Here's a rundown for a quick start:
    * Download and install JDK
    * Download and install Eclipse Ganymede IDE
    * Download and install Tomcat
    * Download and install Tomcat plugin for Eclipse
    * Build a hello world JSP page and run it in tomcat
    * Build a hello world Servlet and run it in tomcat
    * Install a free database such as Oracle Lite or MySql.
    * learn how to use the database's free utility to create database tables and grant permission to read/write to them.
    * Learn JDBC and get your program to connect to the database and query it.
    * Learn MVC design

  • Refresh code servlet and session bean don't work more.

    Hi all,
    I'm not sure if it's a problem with oc4j, but maybe someone can
    help me.
    I'm working with Jdev 10.1.3.0.4(SU4) on Fedora Core 5 and XP.
    I create an application with a servlet, ran the servlet and
    all things work. Change the code in servlet, recompile and refresh
    the browser and all work fine.
    But, when I create a CMP Entity Beans from Tables with EJB 3.0 on
    a simple table and change the code in servlet, recompile and refresh
    the browser the code of servlet stay old. Just restart oc4j make the changes
    work. Changes on entity bean ou session beans or junit class take
    the same problem, just after the restart oc4j do the job.
    Is it a bug? Is thera a workaround?
    Thanks for all,
    Luciano

    Oh and before you tell me to just use XSLT on the output to get it how I want it, or use XMLType views where the XML is generated on the database server, I can assure you I know both of those options, but they both cut into the profitability of running a high-volume service.
    The XSU (XML SQL Utility for those keyword searching) is great in that I can host it on middle tier servers in any servlet container and take the burden of XML generation and parsing off the $40K/processor server. If I can further take the burden of XSLT transformations off the middle tier, so much the better... The XSU allows me to run the same throughput on probably something like half the hardware and a tenth the licensing fees.
    So here's a huge vote in favor of continued development of the XSU...I would also like it to handle XML attributes on inserts/updates rather than having to use the "canonical" element form.
    If anyone knows an even better approach, please speak up!

  • I am making code to try to make a game and my problem is that my code......

    I am making code to try to make a game and my problem is that my code
    will not let it change the hit everytime so im getting the first guy to hit 1 then next hits 8 and so on and always repeats.
    Another problem is that I would like it to attack with out me telling it how much times to attack. I am using Object oriented programming.
    Here is the code for my objects:
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class rockCrab {
         //Wounding formula
         double sL = 70;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 50;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         rockCrab() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              double done = rint(fH - fA);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("Rockcrab hit" +done);
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class self {
         //Wounding formula
         double sL = 1;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 1;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         self() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("You hit" +done);
    }Here is the main code that writes what the objects do:
    class fight {
         public static void main(String[] args) {
              self instance1 = new self();
              rockCrab instance2 = new rockCrab();
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
    }when the code is run it says something like this:
    you hit 1
    RockCrabs health is 9
    RockCrab hit 7
    your health is 38
    you hit 1
    RockCrabs health is 8
    RockCrab hit 7
    your health is 31
    you hit 1
    RockCrabs health is 7
    RockCrab hit 7
    your health is 24
    you hit 1
    RockCrabs health is 6
    RockCrab hit 7
    your health is 17
    my point is whatever some one hits it always repeats that
    my expected output would have to be something like
    you hit 1
    RockCrabs health is 9
    RockCrab hit 9
    your health is 37
    you hit 3
    RockCrabs health is 6
    RockCrab hit 4
    your health is 33
    you hit 2
    RockCrabs health is 4
    RockCrab hit 7
    your health is 26
    you hit 3
    RockCrabs health is 1
    RockCrab hit 6
    your health is 20
    Edited by: rade134 on Jun 4, 2009 10:58 AM

    [_Crosspost_|http://forums.sun.com/thread.jspa?threadID=5390217] I'm locking.

  • IPod Shuffle 2nd gen and Mac problem/troubleshooting guide

    Ok, warning this is going to be a little long...
    The problem: Brand spanking new out of the box ipod shuffle 2nd gen won't play songs after ipod assistant setup. Flashing green/orange lights. Also will not update or restore (greyed out). Shows up as formatted for Windows. Software and Serial show up as "n/a".
    System specs: Powerbook G4 17inch 1ghz, 1gb RAM, 10.4.9 running iTunes 7.1.1
    Attempted solutions that have NOT worked:
    1) mac retail store visit to genius bar. it restored on mactel machine. worked and played songs. unfortunately resyncing to my library caused ipod to return to problems above immediately.
    2) another mac retail store visit to genius bar, this time with laptop to show them the problem. they told me it was my machine not the shuffle. i explained i am a mac sys admin and that is ridiculous...my machine though a few years old is completely up to date. we then deleted all receipts out of the Library dealing with iTunes and reinstalled iTunes via software update. same problem immediately after the setup assistant. no software version and no choice to update or restore ipod. downloaded the ipod reset utility for mac for 2nd gen shuffle and error message shows "the selected ipod is not supported by this utility". also shuffle icon shows up as generic white ipod. mac genius stumped so they swap out my brand new shuffle for another brand new shuffle.
    3) 2nd shuffle in a week and same problems occur. will not update in iTunes. will not restore in iTunes. will not restore in ipod reset utility. icon shows generic white ipod. i can copy music to it but it will not play, lights flash green and orange.
    4) tried to use disk utility to reformat. erase using MS-DOS, but it says FAT16 instead of FAT32. same problems as above.
    *weird that I can't reformat to FAT32 when selecting the MS-DOS format. I only see FAT16 as a choice. Disk utility should do FAT32 but I can't seem to get it to work on shuffle and i don't have a spare hard drive to test it on. Anyone have any experience reformatting ipods via Disk Utility to windows format? Please share...
    At this point I have access to a mactel book and will attempt to fix it on the newer machine. I will be very upset if it works because there is nothing saying that you need new hardware to use the new shuffle. i also get the usb 1.1 error message but again there is nothing saying you need usb 2.0 for shuffle use.
    if anyone has tried anything different with good results please respond! from my experience this seems to be an issue specifically between older mac ppc machines and the new windows drivers installed on the shuffle. i use windows drives all the time with my mac and there are no problems. however a brand new ipod shuffle 2nd gen out of the box does not seem to like my older machine...even after two reinstalls of itunes! even the reset utility is not working as described....
    any help with this is much appreciated!!!
    Powerbook G4, 1ghz, 1gb RAM, usb 1.1, 17inch Mac OS X (10.4.9)

    Ok here it is, my final post on thoughts on this issue...
    Unfortunately, my guess was correct, there does seem to be a hardware issue related to iTunes 7.1.1 and whether it is on a mactel machine or an older ppc machine.
    I can confirm this because the ipod settings screen on my older PPC powerbook is TOTALLY different than the screen I saw on the newer mactel macbooks, even though the software version says its EXACTLY THE SAME! (iTunes 7.1.1)
    On a mactel macbook, I see the ipod shuffle settings such as "Autofill" etc with the correct icon and software version and serial number.
    On my PPC powerbook, I see a generic white ipod icon (even though the finder shows the correct icon of my 2nd gen shuffle) and the settings tab for the ipod is completely different....the update and restore continued to be grayed out, there is no software version or serial number available as well. This is probably why I am not able to register my ipod shuffle from my machine.
    I did not erase and resync the ipod shuffle to my PPC machine to see if that would allow it to continue working. So far so good. After unmounting, it still plays songs. However, I checked the "manage songs manually" option and added just one more song to the shuffle. I tried to then play that song but it would not play even though it was copied onto the shuffle...I could play it from the ipod via iTunes but not when I was just listening to the shuffle. I confirmed this with the application "PodWorks", the song I copied from my library does NOT show up in the list of songs on my ipod shuffle...however it DOES show up and play in iTunes.
    So I feel pretty stuck right now...
    I can have a working ipod shuffle but NOT from my ipod library. It seems I can only listen to songs off my friends newer machines because for whatever reason, the ipod shuffle DOES NOT WORK with a PPC Powerbook 17inch, 1ghz, 1gb RAM, 10.4.9 running the current latest version of iTunes 7.1.1.
    ***** to be me. Anyone else come to same conclusion?
    If this is real then other users with older macs should not waste their money on the 2nd generation ipod shuffle. Please respond if you have any suggestions or thoughts on this matter.
    Mac OS X (10.4.9)

  • Airport Extreme Utility problem with Vista (works with XP, MacOS)

    Hi,
    I just setup a new Airport Extreme network at my house, and most things are working fine. I have wirelessly connected at various points an Airport Express (using WDS), a MacBook Pro (OSX) and an IBM Thinkpad. I have several wired machines as well.
    My problem: The wired machine I use to configure and setup everything is a Vista Ultimate machine. Unfortunately, the Airport Utility won't connect to the Airport Extreme (or Airport Express for that matter) from Vista. The utility works fine from XP or OSX, but not from Vista. Note that I'm using this in a wired capacity. The Vista machine is directly connected to the Airport Extreme, while several other machine are connected through a GBit switch.
    Any help would be much appreciated? Is this a Vista security problem or an Airport Utility problem with Vista?

    It's most likely a security issue with Windows Vista. Vista has the ability to set "compatibility modes" for applications.
    Try:
    1. right mouse clicking the Airport Utility's .exe file.
    2. Click the Compatibility tab. Change the Compatibility mode to Windows XP (Service Pack 2).
    3. Now go down to "Privilage Level" and check the "Run this program as an administrator"
    Apple never tells you this but you must connect to the Airport Extreme wirelessly. Now run the Airport Utility. You should see it.

  • I had this imac 27" two years ago,updated to snow leopard 10.6.8 and suddenly the imac shut down and able to start again from the beggining,i had the leopard 10.5.8 and my problem is i cannot re-installed my snow leopard.Do i have to update my old leopard

    I had this imac 27" two years back(leopard 10.5.8) and no problem was encountered so far! (thanks 4that),i always made an update as far to snow leopard 10.6.8. Unfortunately when i did some application /downloading,the system was off and when i turn it On the logo of an apple only came.So what i did is to start all over again,now i am two years old back with Leo-10.5.8,My problem is i cannot install my snow leopard,it reads that i have to clean tha disc which i did and thru utility disc.Any help please and i really appreciate to every1 helping me to solve the problem.I will keep in touch.
    Many thanks! - Angel

    BTW,I purchased the SL by retail and originally installed for the first time in my IMAC 27" ,unfortunately during the upgrading of the system,suddenly it was totally gray.then off as it killed my imac.i switch it On but only the apple logo came and waiting for so long.I tried to start from the very beginning,installed the DVD installation that was originally came from imac..it works and i have now the latest version of Leopard 10.5.6...then .8 thru updates. My problem is i cannot re-install my SNOW LEOPARD that i purchased from retail store..proceeded to install in my imac but everytime it ends with 'FAILED-pls clean the disc" i did the cleaning but still the same,:installed failed!-The installer could not copy the necessary support file",i tried booting from the disc holding C down but no luck at all. Anybody can help me please. Many thanks ..

Maybe you are looking for

  • Safari and ICloud locked and frozen

    Safari has stopped working on my I-Pad mini. It just sows a grey screen and is completely non functional. If I open Settings and select Safari. Settings locks and becomes frozen also. I have to double tap the main button to close both Safari and Sett

  • Have lost original iTunes music files on my MacBook Air

    Hi, can someone help? My purchased music files are no more aviailible on my mac, probably i have deleted them. Although on iTunes they are indicated under "purchased" but unfortunately I cannot access them. The list of music albums and songs still is

  • Bought Ipod to replace stolen Ipod

    Hi, I've just bought an Ipod 60gb off Ebay to replace a 20gb Ipod I had stolen. I had my original Ipod in the manual setting.I have over 2000 songs on my computer. When I connected the new Ipod to my computer,it said something like update or restore.

  • Transaction ENTR is unknown

    I am trying to do an RRI to jump from BW report to a transaction code, each time I try to launch it it gives me an error message saying that Transaction ENTR is unknown Anybody with a clue?

  • How can I turn off automatic right side format bar?

    Using Pages 5.0 + Mavericks: When I open any Pages document (new or old), there appears a format bar on the right. It's a nuisance to have to manually close it each time. Is there some way that I can turn off that format bar so it won't appear unless