Concurrent accessing of a static method

Hi,
We have an online application, which has some methods in the middle tier that have been declared as "static".
Application is running fine with less number of users but when the load is increasing the application is crashing with a core dump.
The application is running on Solaris.
Can somebody give some inputs on what can be wrong in this scenario.
Thanks in advance..
Niranjan

Application is running fine with less number of
users but when the load is increasing the application
is crashing with a core dump.
The application is running on Solaris.Crashes with a core dump and no stack trace? Then your application does something very bad to the JVM, or the JVM is buggy. Maybe it's enougth to upgrade to the latest stable Java version.

Similar Messages

  • Concurrent access to a static variable

    I think that I need a static lock to protect a static variable. However, the code below seems to be running fine on a 24-CPU machine.
    public class test {
    public static void main(String[] args)
      new Thread(new myclass()).start();
      new Thread(new myclass()).start();
    class myclass implements Runnable {
    private static int msgid;
    private Object lock = new Object();
    public void run()
       synchronized(lock) {
       int i=200000;
       while(i-- >0) {
       msgid = msgid+1;
       System.out.println("Thread " + Thread.currentThread().getName() + "value => "
    + msgid);
    }This testcode is roughly based on my actual program. I have a code (written by someone else) which protects the static msgid with an instance-level lock. IMHO , this shouldn't stop the multithreaded access to the msgId because two threads will have two different instances of the lock. However, I can't reproduce this on a 24-CPU machine. I know the MT-related bugs are hard to reproduce. So I just thought of confirming it with the experts. In my opinion, lock object should be :
    private static Object lock = new Object();
    Anyone against this thought?

    Yes I see the code and I can see the "msgid" can be updated by both threads randomly behaved as per CPU time slicing for each thread.
    like ThreadOne msgId-->10
    ThreadTwo msgId-->11
    ThreadTwo msgId--->12
    ThreadOne msgId -->13
    etc..
    What do you want to achieve if you use a common resource to lock in order to prevent the msgId to be incremented by two thread at the same time but rather by one thread at a time?
    Regards,
    Alan Mehio

  • Problem in concurrent access of a single method

    Hi,
    I have one servlet named "Controllerservlet.java" and a jsp page "Inward jsp".
    Now from this jsp user enters data which are being passed to controller servlet 's "insertData" method which is a synchronized method then it stores the query result in a variable "query_result" whatever it is ( if it throws exception "duplicate value insertion.... this will be assigned to query_result).
    now when only one user is using then it is working fine.But when two user tried to enter the same data simultaneously then in one sceen it showed error message "Can't insert Duplicate value " and in others's it didn't show anything but inserted data.
    I know that when i think data is being entered simultaneously then it is actually not simultaneously for computer.but according to me it shud have shown in one screen "successfully entered" and in other error message "Duplicate value....".
    this is my servlets code
    private synchronized void insertData(HttpServletRequest req, HttpServletResponse res)
                 String date = req.getParameter("date");
                 String department[] = req.getParameterValues("Department");
                 String main_Building[] = req.getParameterValues("Main_Building");
                 String Other = req.getParameter("Other");
                 String Roll_No = req.getParameter("Roll_No");
                 String Receiver = req.getParameter("Receiver");
                 String subject = req.getParameter("subject");
                  String buttontype = req.getParameter("buttontype");
                 String entrytype = req.getParameter("type");
                 String query="";
                 String query_result="";
                 String source="";
                 String Department="",Main_Building="";
                 if(department!=null && !department[0].equals("Select"))Department=department[0];
                 if(department!=null)
                for (int i=1;i<department.length;i++)
                        Department+=","+department;
    if(!Department.equals("")) source= Department;
    if(main_Building!=null && !main_Building[0].equals("Select"))
    Main_Building=main_Building[0];
    if(main_Building!=null)
    for (int i=1;i<main_Building.length;i++)
    Main_Building+=","+main_Building[i];
    if(!Main_Building.equals(""))
    if(source.length()!=0)
    source+="/"+Main_Building;
    else source = Main_Building;
    if(Other!=null&&Other.length()!=0)
    if(source.length()!=0)
    source+="/"+Other;
    else source = Other;
    Date now = new Date();
    SimpleDateFormat formatter = new SimpleDateFormat(" hh:mm:ss a zzz");
    String user = (String)session.getAttribute("user");
    int srno=1;
    try {
    conn.setAutoCommit(false);
    ResultSet rs = stmt.executeQuery("select max(srno) from incommingletters where deleted = 'F'");
    if (rs.next())srno=rs.getInt(1);
    srno++;
    query= "insert into incommingletters values ("+srno+",'"+date+"','"+source+"','"+Roll_No+"','"+Receiver+"','"+subject+"','"+entrytype+"','F')";
    stmt.executeUpdate(query);
    query="insert into traceuser values ('"+user+"','Insertion','"+now+"','"+formatter.format(now)+"',"+srno+")";
    stmt.executeUpdate(query);
    conn.commit();
    query_result="Entry No. "+srno+" Successfully Saved";
    catch (SQLException e)
    query_result= e.toString();
    try
    conn.rollback();
    catch (SQLException e1)
    out.println(e.toString());
    out.println(e.toString());
         session.setAttribute("query_result",query_result);
         //gotojspPage("/resources/Inward.jsp", req, res);
              try
                   res.sendRedirect(res.encodeRedirectURL("../resources/Inward.jsp"));
              catch (Exception e)
                   out.println(e.toString());
    manish

    hi declangallagher,
    now i am doing the connection in bean it looks like this
    servlet code :
    public class ControllerServlet extends HttpServlet
        PrintWriter out;
        HttpSession session;
        String  name=null;
        String buttontype=null;
        ManipulationOfData md= new ManipulationOfData();
         * Method which intialises the servlet
         * @throws ServletException
        public void init() throws ServletException
             * Method in servlet
             * @param req HttpServletRequest req
             * @param res HttpServletResponse res
             * @throws java.io.IOException
             * @throws ServletException
            public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
                doGet(req, res);
         * Method used in servlet
         * @param req HttpServletRequest req
         * @param res HttpServletResponse res
         * @throws IOException
         * @throws ServletException
        public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
            res.setContentType("text/html");
            out = res.getWriter();
            session = req.getSession(true);
            initialization();
         try
                  trafficController(req, res);
            catch (Exception e)
                out.println(e.toString() + " In traffic controller");
             * Method that controls the traffic in Controllerservlet
             * @param req HttpServletRquest req
             * @param res HttpServletResponse res
             * @throws Exception
            private void trafficController(HttpServletRequest req, HttpServletResponse res) throws Exception
             String submit=null;
            submit= req.getParameter("submit");
            if (submit != null)
                submit = submit.trim();
            if (submit!=null)
                    if (submit.equalsIgnoreCase("submit"))
                             buttontype =  req.getParameter("buttontype");
                               if(buttontype!=null)session.setAttribute("buttontype",buttontype);
                               insertData(req,res);
                   else if (submit.equalsIgnoreCase("Sign in"))
                         removeValiditySession();
                           checkUser(req,res);
                   else if (submit.equalsIgnoreCase("inward"))
                          removeInwardSession();
                       res.sendRedirect(res.encodeRedirectURL("../resources/Inward.jsp"));
                        //gotojspPage("/resources/Inward.jsp", req, res);
                   else if (submit.equalsIgnoreCase("edit"))
                        removeOkSession();
                       session.setAttribute("updation","edit");
                       res.sendRedirect(res.encodeRedirectURL("../resources/serialno.jsp"));
                   else if (submit.equalsIgnoreCase("remove"))
                        removeOkSession();
                       session.setAttribute("updation","delete");
                       res.sendRedirect(res.encodeRedirectURL("../resources/serialno.jsp"));
                    else if (submit.equalsIgnoreCase("Ok"))
                        editDelete(req,res);
                    else if (submit.equalsIgnoreCase("view"))
                           removeShowSession();
                        res.sendRedirect(res.encodeRedirectURL("../resources/viewresult.jsp"));
                             //gotojspPage("/resources/viewresult.jsp", req, res);
                    else if (submit.equalsIgnoreCase("Update"))
                        updateRecord(req,res);
                    else if (submit.equalsIgnoreCase("Delete"))
                        //out.println("manish");
                          deleteRecord(req,res);
                            //gotojspPage("/resources/delete.jsp", req, res);
                    else if (submit.equalsIgnoreCase("Show Data"))
                        removeShowSession();
                           showData(req,res);
                    else if (submit.equalsIgnoreCase("signout"))
                        SignOut();
                      res.sendRedirect(res.encodeRedirectURL("../resources/signout.jsp"));
                    else if (submit.equalsIgnoreCase("home"))
                        res.sendRedirect(res.encodeRedirectURL("../resources/authentication.jsp"));
                    else if (submit.equalsIgnoreCase("back"))
                        removeShowSession();
                        res.sendRedirect(res.encodeRedirectURL("../resources/viewresult.jsp"));
                    else if (submit.equalsIgnoreCase("deleteback"))
                        removeInwardSession();
                        res.sendRedirect(res.encodeRedirectURL("../resources/Inward.jsp"));
                      else
                           out.println("No Target");
        private void checkUser(HttpServletRequest req, HttpServletResponse res)
            try
                Authentication auth = new Authentication();
                String user = req.getParameter("userid");
                user = user.trim();
                String password = req.getParameter("password");
                password = password.trim();
                session.setAttribute("password", password);
                String validity = auth.isValid(user, password);
                session.setAttribute("validity", validity);
                session.setAttribute("user",user);
                if(validity.equals("true"))
                      removeInwardSession();
                    res.sendRedirect(res.encodeRedirectURL("../resources/Inward.jsp"));
                   //gotojspPage("/resources/Inward.jsp", req, res);
                else
                    removeInwardSession();
                    res.sendRedirect(res.encodeRedirectURL("../resources/authentication.jsp"));
            catch (Exception ex)
                out.println(ex.toString());
            private   void insertData(HttpServletRequest req, HttpServletResponse res)
                 String date = req.getParameter("date");
                 String department[] = req.getParameterValues("Department");
                 String main_Building[] = req.getParameterValues("Main_Building");
                 String Other = req.getParameter("Other");
                 String Roll_No = req.getParameter("Roll_No");
                 String Receiver = req.getParameter("Receiver");
                 String subject = req.getParameter("subject");
                  String buttontype = req.getParameter("buttontype");
                 String entrytype = req.getParameter("type");
                 String query="";
                 String query_result="";
                 String source="";
                 String Department="",Main_Building="";
                 if(department!=null && !department[0].equals("Select"))Department=department[0];
                 if(department!=null)
                for (int i=1;i<department.length;i++)
                        Department+=","+department;
    if(!Department.equals("")) source= Department;
    if(main_Building!=null && !main_Building[0].equals("Select"))
    Main_Building=main_Building[0];
    if(main_Building!=null)
    for (int i=1;i<main_Building.length;i++)
    Main_Building+=","+main_Building[i];
    if(!Main_Building.equals(""))
    if(source.length()!=0)
    source+="/"+Main_Building;
    else source = Main_Building;
    if(Other!=null&&Other.length()!=0)
    if(source.length()!=0)
    source+="/"+Other;
    else source = Other;
    String user = (String)session.getAttribute("user");
    query_result=md.InsertData(date,source,Roll_No,Receiver,subject,entrytype,user);
         session.setAttribute("query_result",query_result);
         //gotojspPage("/resources/Inward.jsp", req, res);
              try
                   res.sendRedirect(res.encodeRedirectURL("../resources/Inward.jsp"));
              catch (Exception e)
                   out.println(e.toString());
    private void showData(HttpServletRequest req, HttpServletResponse res)
    String exactdate = req.getParameter("date");
    String srnostr = req.getParameter("srno");
    String fromdate = req.getParameter("from");
    String todate = req.getParameter("to");
    String Roll_No = req.getParameter("Roll_No");
    String Receiver = req.getParameter("Receiver");
    String subject = req.getParameter("subject");
    String Department = req.getParameter("Department");
    String Main_Building = req.getParameter("Main_Building");
    String Other = req.getParameter("Other");
    String entrytype = req.getParameter("type");
    String condition="";
    String buttontxt ="",source="";
    String date;
    // out.println(fromdate);out.println(todate);
    subject = subject.trim();
    if(!Department.equalsIgnoreCase("Select")) source= Department;
    if(!Main_Building.equalsIgnoreCase("Select"))
    if(source.length()!=0)
    source+="/"+Main_Building;
    else source = Main_Building;
    if(Other!=null&&Other.length()!=0)
    if(source.length()!=0)
    source+="/"+Other;
    else source = Other;
    if (exactdate!=null && exactdate.length()!=0) condition = " date = '"+exactdate+"'";
    else if(fromdate!=null &&todate!=null &&fromdate.length()!=0 && todate.length()!=0)
    condition = " date between '"+ fromdate+"' and '"+ todate+"'";
    if(source!=null&&source.length()!=0)
    if(!condition.equals(""))
    condition+=" AND source like '%"+source+"%'";
    else
    condition+=" source like '%"+source+"%'";
    if(Roll_No!=null&&Roll_No.length()!=0)
    if(!condition.equals(""))
    condition+=" AND rollno like '%"+Roll_No+"%'";
    else
    condition+=" rollno like '%"+Roll_No+"%'";
    if(Receiver!=null&&!Receiver.equalsIgnoreCase("Select"))
    if(!condition.equals(""))
    condition+=" AND reciever like '%"+Receiver+"%'";
    else
    condition+=" reciever like '%"+Receiver+"%'";
    if(subject!=null&&subject.length()!=0)
    if(!condition.equals(""))
    condition+=" AND subject like '%"+subject+"%'";
    else
    condition+=" subject like '%"+subject+"%'";
    if(entrytype!=null&&entrytype.length()!=0)
    if(!condition.equals(""))
    condition+=" AND type = '"+entrytype+"'";
    else
    condition+=" type = '"+entrytype+"'";
    if(srnostr!=null&&srnostr.length()!=0)
    int srno = Integer.parseInt(srnostr);
    if(!condition.equals(""))
    condition+=" AND srno = "+srno;
    else
    condition+=" srno = "+srno;
    buttontxt = req.getParameter("buttontxt");
    Vector show_data_vec = md.showData(condition);
    String queryexception= show_data_vec.elementAt(0).toString();
    Vector cols_name_vec = (Vector)show_data_vec.elementAt(1);
    Vector resultset_ob_vec = (Vector)show_data_vec.elementAt(2);
    if(queryexception.equals("Successful"))
    try {
    res.sendRedirect(res.encodeRedirectURL("../resources/result.jsp"));
    catch (IOException e)
    out.println(e.toString());
    else
    try
    res.sendRedirect(res.encodeRedirectURL("../resources/viewresult.jsp"));
              catch (Exception e)
                   out.println(e.toString());
    session.setAttribute("queryexception",queryexception);
    session.setAttribute("buttontxt",buttontxt);
    session.setAttribute("resultset_ob_vec",resultset_ob_vec);
    session.setAttribute("cols_name_vec",cols_name_vec);
    private void updateRecord(HttpServletRequest req, HttpServletResponse res)
    String date = req.getParameter("date");
    String department[] = req.getParameterValues("Department");
    String main_Building[] = req.getParameterValues("Main_Building");
    String Other = req.getParameter("Other");
    String Roll_No = req.getParameter("Roll_No");
    String Receiver = req.getParameter("Receiver");
    String subject = req.getParameter("subject");
         String buttonedit = req.getParameter("buttonedit");
    String entrytype = req.getParameter("type");
    String query="";
    String source="";
    String serialnostr=(String)session.getAttribute("serialno");
    int serialno=Integer.parseInt(serialnostr);
    String Department="",Main_Building="";
    if(department!=null && !department[0].equals("Select"))Department=department[0];
    if(department!=null)
    for (int i=1;i<department.length;i++)
    Department+=","+department[i];
    if(!Department.equals("")) source= Department;
    if(main_Building!=null && !main_Building[0].equals("Select"))
    Main_Building=main_Building[0];
    if(main_Building!=null)
    for (int i=1;i<main_Building.length;i++)
    Main_Building+=","+main_Building[i];
    if(!Main_Building.equals(""))
    if(source.length()!=0)
    source+="/"+Main_Building;
    else source = Main_Building;
    if(Other!=null&&Other.length()!=0)
    if(source.length()!=0)
    source+="/"+Other;
    else source = Other;
    String user = (String)session.getAttribute("user");
    String editqrexception=null;
    ResultsetData rsdata = new ResultsetData();
    editqrexception=md.UpdateData(rsdata,date,source,Roll_No,Receiver,subject,serialno,entrytype,user);
    session.setAttribute("rsdata",rsdata);
    session.setAttribute("buttonedit",buttonedit);
    session.setAttribute("editqrexception",editqrexception);
    try
    res.sendRedirect(res.encodeRedirectURL("../resources/edit.jsp"));
    catch (Exception e)
    out.println(e.toString());
    private void deleteRecord(HttpServletRequest req, HttpServletResponse res)
              String serialnostr = (String) session.getAttribute("serialno");
    int serialno = Integer.parseInt(serialnostr);
              out.println(serialno);
              String deleteqrexception=null,buttondelete=null;
    ResultsetData rsdata = new ResultsetData();
    String user = (String)session.getAttribute("user");
    deleteqrexception=md.DeleteData(rsdata,serialno,user);
              if(!deleteqrexception.equals("Successful"))
    session.setAttribute("rsdata",rsdata);
    session.setAttribute("buttondelete",buttondelete);
    session.setAttribute("deleteqrexception",deleteqrexception);
    try
    res.sendRedirect("../resources/delete.jsp");
    catch (Exception e)
    out.println(e.toString());
    else
    try
    res.sendRedirect(res.encodeRedirectURL("../resources/deletemessage.html"));
    catch (Exception e)
    out.println(e.toString());
    private void editDelete(HttpServletRequest req, HttpServletResponse res)
    String buttonok=null;
    String updation=(String)session.getAttribute("updation");
    String serialnostr = req.getParameter("serialno");
    buttonok = req.getParameter("buttonok");
    session.setAttribute("buttonok",buttonok);
    int rowcount = 0;
    ResultsetData rsdata = new ResultsetData();
    String query_result =null;
    int serialno = Integer.parseInt(serialnostr);
    query_result = md.editDelete(serialno,rsdata);
    session.setAttribute("serialno",serialnostr);
    session.setAttribute("rsdata",rsdata);
    if(query_result.equals("Successful"))
    if (updation!=null)
    if(updation.equals("edit"))
    try
    removeEditSession();
    res.sendRedirect(res.encodeRedirectURL("../resources/edit.jsp"));
    catch (IOException e)
    out.println(e.toString());
    else if (updation.equals("delete"))
    try {
    removeDeleteSession();
    res.sendRedirect(res.encodeRedirectURL("../resources/delete.jsp"));
    catch (IOException e)
    out.println(e.toString());
    else
    try
    res.sendRedirect(res.encodeRedirectURL("../resources/serialno.jsp"));
              catch (Exception e)
                   out.println(e.toString());
    private void initialization()
    Vector initial_vec = new Vector();
    Vector departments_vec = new Vector();
    Vector mainbuild_vec = new Vector();
    Vector receiver_vec = new Vector();
    initial_vec = md.Initialization();
    departments_vec = (Vector)initial_vec.elementAt(0);
    mainbuild_vec = (Vector)initial_vec.elementAt(1);
    receiver_vec = (Vector)initial_vec.elementAt(2);
    session.setAttribute("departments_vec",departments_vec);
    session.setAttribute("mainbuild_vec",mainbuild_vec);
    session.setAttribute("receiver_vec",receiver_vec);
    private void removeInwardSession()
              String serialno ="";
              String buttontype = (String)session.getAttribute("buttontype");
    serialno = (String) session.getAttribute("serialno");
              if(serialno!=null)
                        serialno=null;
                        session.setAttribute("serialno",serialno);
              if(buttontype!=null)
                        buttontype=null;
                        session.setAttribute("buttontype",buttontype);
    private void removeShowSession()
              String buttontxt ="";String queryexception ="";
              buttontxt = (String) session.getAttribute("buttontxt");
              if(buttontxt!=null)
                        buttontxt=null;
                        session.setAttribute("buttontxt",buttontxt);
    queryexception = (String) session.getAttribute("buttontxt");
              if(queryexception!=null)
                        queryexception=null;
                        session.setAttribute("queryexception",queryexception);
    private void removeEditSession()
              String buttonedit ="";
              buttonedit = (String) session.getAttribute("buttonedit");
              if(buttonedit!=null)
                        buttonedit=null;
                        session.setAttribute("buttonedit",buttonedit);
    private void removeDeleteSession()
              String buttondelete ="";
              buttondelete = (String) session.getAttribute("buttondelete");
              if(buttondelete!=null)
                        buttondelete=null;
                        session.setAttribute("buttondelete",buttondelete);
    private void removeOkSession()
              String buttonok ="";
              buttonok = (String) session.getAttribute("buttonok");
              if(buttonok!=null)
                        buttonok=null;
                        session.setAttribute("buttonok",buttonok);
    private void removeValiditySession()
              String validity ="";
              validity = (String) session.getAttribute("validity");
              if(validity!=null)
                        validity=null;
                        session.setAttribute("validity",validity);
    private void SignOut()
    removeValiditySession();
    public void destroy()
    try
    ConnectionPool.freeCon(conn);
    removeValiditySession();
    catch (Exception exp)
    out.println(exp.toString());
    i know its very lengthy so concentrate on insertData method and doget only
    and here is the bean
    public class ManipulationOfData
            String url="jdbc:postgresql://10.99.13.203/dispatch";
            String driver="org.postgresql.Driver";
            String username="manish";
            String password="manish";
            Connection conn=null;
            Statement stmt =null;
           String valid="false";
        public void getConnection()
          try
               Class.forName(driver);
               conn = DriverManager.getConnection(url,username,password);
               stmt= conn.createStatement();
            catch(Exception e)
                valid=e.toString();
        public void closeConnection()
          try
               stmt.close();
               conn.close();
            catch(Exception e)
                valid=e.toString();
        public synchronized String InsertData(String date,String source,String Roll_No,String Receiver,String subject,String entrytype,String user)
            getConnection();
            int srno=1;
            String query_result="";
            Date now = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat(" hh:mm:ss a zzz");
                try {
                        conn.setAutoCommit(false);
                        ResultSet rs = stmt.executeQuery("select max(srno) from incommingletters where deleted = 'F'");
                        if (rs.next())srno=rs.getInt(1);
                        srno++;
                        String query= "insert into incommingletters values ("+srno+",'"+date+"','"+source+"','"+Roll_No+"','"+Receiver+"','"+subject+"','"+entrytype+"','F')";
                            stmt.executeUpdate(query);
                            query="insert into traceuser values ('"+user+"','Insertion','"+now+"','"+formatter.format(now)+"',"+srno+")";
                            stmt.executeUpdate(query);
                            conn.commit();
                         query_result="Entry No. "+srno+" Successfully Saved";
                catch (SQLException e)
                        query_result= e.toString();
                        try
                            conn.rollback();
                        catch (SQLException e1)
                            query_result=e.toString();
                      query_result=e.toString();
            closeConnection();
        return query_result;
        public synchronized String UpdateData(ResultsetData rsdata,String date,String source,String Roll_No,String Receiver,String subject,int serialno,String entrytype,String user)
            getConnection();
            String query_result="";
            Date now = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat(" hh:mm:ss a zzz");
            try {
                    conn.setAutoCommit(false);
                    String query= "update incommingletters set date = '"+date+"',type = '"+entrytype+"',source = '"+source+"',rollno = '"+Roll_No+"',"+
                            "reciever = '"+Receiver+"',subject = '"+subject+"' where srno ="+serialno +" and deleted = 'F'";
                    stmt.executeUpdate(query);
                    query="insert into traceuser values ('"+user+"','Updation','"+now+"','"+formatter.format(now)+"',"+serialno+")";
                    stmt.executeUpdate(query);
                   conn.commit();
                   ResultSet rs = stmt.executeQuery("select * from incommingletters where srno ="+serialno+
                           " and deleted = 'F'");
                   rsdata =  putResClass(rs,rsdata);
                    //conn.close();
                    //ConnectionPool.freeCon(conn);
                    query_result="Successfully Updated";
                catch (SQLException e)
                    try
                        conn.rollback();
                        //conn.close();
                        //  ConnectionPool.freeCon(conn);
                    } catch (SQLException e1) {
                        query_result=e.toString();
                    query_result=e.toString();
            closeConnection();
         return query_result;
        public synchronized String DeleteData(ResultsetData rsdata,int serialno,String user)
            getConnection();
            Date now = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat(" hh:mm:ss a zzz");
            String query_result="";
            try {
                    conn.setAutoCommit(false);
                    stmt.executeUpdate("update incommingletters set deleted ='T' where srno ="+serialno);
                    String query="insert into traceuser values ('"+user+"','Deletion','"+now+"','"+formatter.format(now)+"',"+serialno+")";
                    stmt.executeUpdate(query);
                    conn.commit();
                    query_result = "Successful";
            catch (SQLException e)
                query_result=e.toString();
                try {
                        conn.rollback();
                        ResultSet rs = stmt.executeQuery("select * from incommingletters where srno ="+serialno+" and deleted='F'");
                        rsdata =  putResClass(rs,rsdata);
                        // conn.close();
                        //ConnectionPool.freeCon(conn);
                catch (SQLException e1)
                        query_result=e1.toString();
             closeConnection();
           return query_result;
       public Vector showData(String condition)
           getConnection();
           String query="",query_result="";
           int rowcount=0;
           Vector show_data = new Vector();
           Vector cols_name_vec = new Vector();
           Vector resultset_ob_vec = new Vector();
           ResultSet rs=null;
           try {
                    if(!condition.equals(""))
                    query = "select COUNT(*) as rowcount from incommingletters where "+condition+" and deleted='F'";
                     else
                    query = "select COUNT(*) as rowcount from incommingletters where deleted ='F' ";
                     rs = stmt.executeQuery(query);
                    if(rs.next()) rowcount= rs.getInt("rowcount") ;
           catch (SQLException e)
                    query_result=e.toString();
           if(rowcount!=0)
                     try
                         if(!condition.equals(""))
                          query = "select * from incommingletters where "+condition+" and deleted='F' order by srno";
                        else
                            query = "select * from incommingletters where deleted = 'F' order by srno";
                            rs = stmt.executeQuery(query);
                         query_result ="Successful";
                         ResultSetMetaData rsmd = rs.getMetaData();
                         int totcols=rsmd.getColumnCount();
                         String col;
                         for(int i=0;i<totcols;i++)
                             if(!rsmd.getColumnName(i+1).equals("type")&&!rsmd.getColumnName(i+1).equals("deleted"))
                             cols_name_vec.addElement(rsmd.getColumnName(i+1));
                            try {
                                    while (rs.next())
                                              ResultsetData rsdata = new ResultsetData();
                                              rsdata = new ResultsetData();
                                              rsdata.setSrno(rs.getInt("srno"));
                                              rsdata.setDate(rs.getDate("date"));
                                              rsdata.setRollno(rs.getString("rollno"));
                                              rsdata.setSource(rs.getString("source"));
                                              rsdata.setReciever(rs.getString("reciever"));
                                              rsdata.setSubject(rs.getString("subject"));
                                              resultset_ob_vec.addElement(rsdata);
                            catch (SQLException e)
                         Results                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

  • Dynamic programming accessing static method on classes

    Hi
    I need access to a static method on a class.
    The class name is first decided at runtime.
    How do I do that?
    Regards,
    Morten

    Hello Morten
    Here is a sample program for you:
    *& Report  ZUS_SDN_DYNAMIC_METHOD_CALL
    REPORT  zus_sdn_dynamic_method_call.
    DATA: go_msglist    TYPE REF TO if_reca_message_list.
    DATA: gd_method     TYPE tmdir-methodname,
          gd_class      TYPE seoclsname.
    START-OF-SELECTION.
      IF ( 1 = 2 ).
        CALL METHOD cf_reca_message_list=>create
    *      EXPORTING
    *        id_object    = 'RECA'
    *        id_subobject = 'MISC'
    *        id_extnumber =
          RECEIVING
            ro_instance  = go_msglist.
        go_msglist = cf_reca_message_list=>create( ).
      ENDIF.
      gd_class  = 'CF_RECA_MESSAGE_LIST'.
      gd_method = 'CREATE'.
      CALL METHOD (gd_class)=>(gd_method)
        RECEIVING
          ro_instance = go_msglist.
      IF ( go_msglist IS BOUND ).
        WRITE: / 'Class is bound'.
      ELSE.
        WRITE: / 'Class is NOT bound'.
      ENDIF.
    END-OF-SELECTION.
    Obviously, that is only half of the task. You need to make the method signature dynamically as well.
    Regards
      Uwe

  • Accesing database from static method on java collaboration

    Hi *,
    I want cache data from a oracle database in a java collaboratioon when java collaboration is enabled by emanager.
    My java collaboration has a oracleOTD
    I did an static method on java collaboration, but I can't access database from static method.
    Thanks
    Hector

    hi hector,
    this wont work!
    regards chris

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Static methods in multi-threaded environment

    Hi,
    I am wondering what happens when several threads try to access the same static method ?
    The static method is not synchronized.
    Will this create any performance issues ?
    The actual scenario is of a J2EE server, where several Session Bean instances try to access a static method in a utility class. Will some session beans have to wait till others are being serviced ?
    thnx n regards
    s giri

    thanx for replying.
    yes. the operations are thread-safe. we do not change the state of any object.
    but we make an rmi call to another application thru this static method.
    is it ok?
    Currently, my session bean has too many private methods - each calling the other application. Due to some quality metrics (a class must be restricted to 700 lines) we have to consider moving these private methods into some Helper class in the form of "public static methods". We have made many utility methods as static, but have some reservations abt doing a similar thing for these methods that call other application.
    regards
    Shivraman

  • Static methods in startup class

    I have declared few static methods in startup class. What will happen
              once startup class is executed in cluster environment, will the access
              to those static methods be clustered and replicated across the
              clusters. How exactly the startup class behaves in clustered
              environment.
              I will appreciate an urgent response.
              Thanks,
              SidShar .
              

    SidShar,
              > I have declared few static methods in startup class. What will
              > happen once startup class is executed in cluster environment,
              > will the access to those static methods be clustered and
              > replicated across the clusters.
              No.
              > How exactly the startup class behaves in clustered environment.
              It is run on each server that it is configured to run on. The method calls
              to the startup class will all be local unless you do some special work to
              force it to be otherwise.
              If you want to have something done once and only once in the cluster, or
              coordinate stuff like that, then either use a shared resource (such as the
              database) to coordinate it all, or use Coherence, which lets you share and
              coordinate access to data among all the servers in the app tier.
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com/coherence.jsp
              Tangosol Coherence: Clustered Replicated Cache for Weblogic
              "sidshar" <[email protected]> wrote in message
              news:[email protected]..
              >
              

  • Help on calling static method in a multithreaded environment

    Hi,
    I have a basic question.. pls help and it is urgent.. plss
    I have a class with a static method which does nothing other than just writing the message passed to a file. Now i have to call this static method from many threads..
    What actually happens ???
    Does all the thread start to execute the static method or one method executes while the other threads wait for the current thread to complete execution?. I am not talking about synchronizing the threads...my question is what happens when multiple threads call a static method??
    Pls reply.. I need to design my project accordingly..
    Thanks
    Rajeev

    HI Omar,
    My doubt is just this..
    I wanted to know what might happen if two threads try to access a static method.. Logically only one thread can use the method since it is only only copy... but i was wondering what might happens if f threads try to access the same static method.. My Situation is this.. I have a cache which is just a hash table which will be only one copy for the whole application.. No when i get a request I have to check if the id is avaible in the cache. if it is available i call method 1 if not i call method2. Now Ideally the cache should be a static object and the method to check the id in the cache will be a normal instance method..
    I was just wondering what might happen if i make the method static.. If i can make it static i can can save a lot of space by not creating the object each time.. u know what i mean.. That y i wanted to know what happens..
    Rajeev

  • Acessing non static methods

    Anyone any ideas if it's possible to access a non-static method from another class?
    I'm trying to access a method used in my GUI class that deals with GUI components, but access it from another class.
    I know I could do it by making the method static, but this would meen that I would have to make all the GUI components static as well (as far as I'm aware)
    Cheers for any ideas,
    Al

    Of course it is possible. Presumably you have an application with a static main method, and you are creating your GUI in that method. Well, don't. Do something like this instead:
    public class GUI {
      public static void main(String[] args) {
        GUI l = new GUI();
        l.run();
      private void run() {
      // all your code goes here
      // this method is not static so you don't have that problem

  • When a static method is accessed concurrently

    When a static method is accessed by many objects symultaneously(concurrently),
    What is happened in the static method.
    Are the stacks for that method maded seperately and
    each stack doesn't influence other stacks?
    thank you in advance.

    The static objects or methods concept is clear, one
    instance for all objects.No. One instance for the class.
    , and every
    one know that, static methods is slower than
    nonstatic, Since when? I've certainly never heard that before... Do you have a reference I can look at?
    and this is as i thought because static
    methods are syncronized by default.Absoloutely not!
    All synchronization locks on an object. When you synchronize an instance method, it locks on the implicit "this"; When you synchronize a static method, it locks on the class's associated Class object.
    So two synchronized static methods in the same class can not be called at the same time, but synchronized instance methods that access static variables can all access those variables at the same time and potentially cause threading problems. In this situation you can declare the static fields volatile or wrap synchronized blocks around all code that accesses them, and synchronize on the same object (perhaps the Class object associated with the current class would be appropriate, but that reallt depends on the rest of your design).

  • How to synchronize concurrent access to static data in ABAP Objects

    Hi,
    1) First of all I mwould like to know the scope of static (class-data) data of an ABAP Objects Class: If changing a static data variable is that change visible to all concurrent processes in the same Application Server?
    2) If that is the case. How can concurrent access to such data (that can be shared between many processes) be controlled. In C one could use semaphores and in Java Synchronized methods and the monitor concept. But what controls are available in ABAP for controlling concurrent access to in-memory data?
    Many thanks for your help!
    Regards,
    Christian

    Hello Christian
    Here is an example that shows that the static attributes of a class are not shared between two reports that are linked via SUBMIT statement.
    *& Report  ZUS_SDN_OO_STATIC_ATTRIBUTES
    REPORT  zus_sdn_oo_static_attributes.
    DATA:
      gt_list        TYPE STANDARD TABLE OF abaplist,
      go_static      TYPE REF TO zcl_sdn_static_attributes.
    <i>* CONSTRUCTOR method of class ZCL_SDN_STATIC_ATTRIBUTES:
    **METHOD constructor.
    *** define local data
    **  DATA:
    **    ld_msg    TYPE bapi_msg.
    **  ADD id_count TO md_count.
    **ENDMETHOD.
    * Static public attribute MD_COUNT (type i), initial value = 1</i>
    PARAMETERS:
      p_called(1)  TYPE c  DEFAULT ' ' NO-DISPLAY.
    START-OF-SELECTION.
    <b>* Initial state of static attribute:
    *    zcl_sdn_static_attributes=>md_count = 0</b>
      syst-index = 0.
      WRITE: / syst-index, '. object: static counter=',
               zcl_sdn_static_attributes=>md_count.
      DO 5 TIMES.
    <b>*   Every time sy-index is added to md_count</b>
        CREATE OBJECT go_static
          EXPORTING
            id_count = syst-index.
        WRITE: / syst-index, '. object: static counter=',
                 zcl_sdn_static_attributes=>md_count.
    <b>*   After the 3rd round we start the report again (via SUBMIT)
    *   and return the result via list memory.
    *   If the value of the static attribute is not reset we would
    *   start with initial value of md_count = 7 (1+1+2+3).</b>
        IF ( p_called = ' '  AND
             syst-index = 3 ).
          SUBMIT zus_sdn_oo_static_attributes EXPORTING LIST TO MEMORY
            WITH p_called = 'X'
          AND RETURN.
          CALL FUNCTION 'LIST_FROM_MEMORY'
            TABLES
              listobject = gt_list
            EXCEPTIONS
              not_found  = 1
              OTHERS     = 2.
          IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
          CALL FUNCTION 'DISPLAY_LIST'
    *       EXPORTING
    *         FULLSCREEN                  =
    *         CALLER_HANDLES_EVENTS       =
    *         STARTING_X                  = 10
    *         STARTING_Y                  = 10
    *         ENDING_X                    = 60
    *         ENDING_Y                    = 20
    *       IMPORTING
    *         USER_COMMAND                =
            TABLES
              listobject                  = gt_list
            EXCEPTIONS
              empty_list                  = 1
              OTHERS                      = 2.
          IF sy-subrc <> 0.
    * MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    *         WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
          ENDIF.
        ENDIF.
      ENDDO.
    <b>* Result: in the 2nd run of the report (via SUBMIT) we get
    *         the same values for the static counter.</b>
    END-OF-SELECTION.
    Regards
      Uwe

  • Synchronized method not preventing concurrent access

    Hi
    I have 3 classes, T (a Runnable), TRunner (instantiates and starts a thread using T), and Sync (with one synchronized method, foo).
    The problem is that foo is entered concurrently by different threads at the same time. How so?
    T.java:
    import java.util.Calendar;
    class T implements Runnable
       private String name;
       public T(String name)
         this.name = name;
       public void run()
          Thread.currentThread().setName(name);
          Sync s = new Sync();
          System.out.println(Calendar.getInstance().getTime() + ".....Running " + Thread.currentThread().getName());
          s.foo(name);
    }TRunner.java:
    class TRunner
       public static void main(String args[])
           T tx = new T("x");
           T ty = new T("y");
           T tz = new T("z");
           Thread t1 = new Thread(tx);
           Thread t2 = new Thread(ty);
           Thread t3 = new Thread(tz);
           t1.start();
           t2.start();
           t3.start();
    }Sync.java:
    import java.util.Calendar;
    class Sync
       public synchronized void foo(String threadname)
              System.out.println(Calendar.getInstance().getTime() + ":" + threadname + "....entering FOO");
              try
                   Thread.sleep(5000);
              catch (InterruptedException e)
                   System.out.println("interrupted");
              System.out.println(Calendar.getInstance().getTime() + ":" + threadname + "....leaving FOO");
    }Console output:
    C:\javatemp>java TRunner
    Mon Apr 09 15:35:46 CEST 2007.....Running x
    Mon Apr 09 15:35:46 CEST 2007:x....entering FOO
    Mon Apr 09 15:35:46 CEST 2007.....Running y
    Mon Apr 09 15:35:46 CEST 2007:y....entering FOO
    Mon Apr 09 15:35:46 CEST 2007.....Running z
    Mon Apr 09 15:35:46 CEST 2007:z....entering FOO
    Mon Apr 09 15:35:51 CEST 2007:x....leaving FOO
    Mon Apr 09 15:35:51 CEST 2007:y....leaving FOO
    Mon Apr 09 15:35:51 CEST 2007:z....leaving FOO
    C:\javatemp>Thanks in advance.

    Only for static methods. For instance methods, the lock >is the object.You are absolutely right.
    The Class object is no different from any other object. >"Entire" Class object makes no sense.What I wanted to say is that it's better to synchronize on the object we want to protect from concurrent access rather than on the entire class or instance object.
    "Efficiency" is not altered by locking on a Class object vs. >any other object.I studied that it's better to synchronize on the objects we want to protect instead of the entire instance or class object. If one declares a method as synchronized, it means that other threads won't be able to access other synchronized methods for the same object, even if the two weren't in conflict. That was explained as a performance penalty.
    >
    Or when one or more threads may modify it and one or
    more may read it.
    Yep, sure.
    >
    No, they're not.
    You are absolutely right. What I wanted to say is that local variables are unique per thread.
    >
    Local variables are unique per thread, but that's NOT
    atomicity.Sorry for any confusion
    Message was edited by:
    mtedone

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Static methods in concurrency

    I have a static method which takes a few String and double parameters and contains only local variables. When it is called by multiple threads there seems to be an exception thrown intermittenly. I got a little paranoid and so I've changed it to an instance method, and now the problem seems to disappear.
    Is this just a coincidence? Is my static method intrinsically thread-safe? Or are there any concurrency issues with static methods that I'm not aware of?
    Any reply is much appreciated!

    public static net.opengis.sos.v_1_0_0.InsertObservationResponse insertObservation(String serverURL, String AssignedSensorId, String dataType, String timeFrom, String timeTo, String srsName, double x, double y, long numElement, String dataString) throws MalformedURLException, IOException, JAXBException, ParserConfigurationException {
            OutputStream out = null;
            InputStream in = null;
            try {
                URL url = new URL(serverURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-type", "text/xml, application/xml");
                out = connection.getOutputStream();
                JAXBContext jaxbContext = JAXBContext.newInstance("net.opengis.sos.v_1_0_0:net.opengis.ows.v_1_1_0:net.opengis.sos.v_1_0_0.filter.v_1_1_0:net.opengis.sensorml.v_1_0_1:net.opengis.swe.v_1_0_1:net.opengis.om.v_1_0_0:net.opengis.gml.v_3_1_1:net.opengis.sampling.v_1_0_0");
                /////////////////////////////////request
                Marshaller marshaller = jaxbContext.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                //////////////////////////////////////object factories
                net.opengis.gml.v_3_1_1.ObjectFactory gmlOF = new net.opengis.gml.v_3_1_1.ObjectFactory();
                net.opengis.swe.v_1_0_1.ObjectFactory sweOF = new net.opengis.swe.v_1_0_1.ObjectFactory();
                net.opengis.sampling.v_1_0_0.ObjectFactory saOF = new net.opengis.sampling.v_1_0_0.ObjectFactory();
                ////////////////////////////////////////////////////////////////////////////////////////////////getObservation request
                net.opengis.sos.v_1_0_0.InsertObservation insertObservation = new net.opengis.sos.v_1_0_0.InsertObservation();
                insertObservation.setAssignedSensorId(AssignedSensorId);
                net.opengis.om.v_1_0_0.ObservationType observation = new net.opengis.om.v_1_0_0.ObservationType();
                ///////////////////////////////om:samplingTime
                //begin position
                net.opengis.gml.v_3_1_1.TimePositionType beginTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                beginTimePosition.getValue().add(timeFrom);
                //end position
                net.opengis.gml.v_3_1_1.TimePositionType endTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                endTimePosition.getValue().add(timeTo);
                //time period
                net.opengis.gml.v_3_1_1.TimePeriodType timePeriod = new net.opengis.gml.v_3_1_1.TimePeriodType();
                timePeriod.setBeginPosition(beginTimePosition);
                timePeriod.setEndPosition(endTimePosition);
                net.opengis.swe.v_1_0_1.TimeObjectPropertyType timeObjectPropertyType = new net.opengis.swe.v_1_0_1.TimeObjectPropertyType();
                timeObjectPropertyType.setTimeObject(gmlOF.createTimePeriod(timePeriod));
    //            timeObjectPropertyType.setTimeObject(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.TimePeriodType.class, timePeriod));
                observation.setSamplingTime(timeObjectPropertyType);
                /////////////////////////////////om:procedure
                net.opengis.om.v_1_0_0.ProcessPropertyType processPropertyType = new net.opengis.om.v_1_0_0.ProcessPropertyType();
                processPropertyType.setHref(AssignedSensorId);
                observation.setProcedure(processPropertyType);
                /////////////////////////////////om:observedProperty
                net.opengis.swe.v_1_0_1.CompositePhenomenonType compositePhenomenonType = new net.opengis.swe.v_1_0_1.CompositePhenomenonType();
                compositePhenomenonType.setId("cpid0");
                compositePhenomenonType.setDimension(BigInteger.ONE);
                net.opengis.gml.v_3_1_1.CodeType codeType = new net.opengis.gml.v_3_1_1.CodeType();
                codeType.setValue("resultComponents");
                compositePhenomenonType.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, codeType));
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType1 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType1.setHref("urn:ogc:data:time:iso8601");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType1);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType2 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType2.setHref("Abfluss");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType2);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType observedProperty = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                observedProperty.setPhenomenon(sweOF.createCompositePhenomenon(compositePhenomenonType));
                observation.setObservedProperty(observedProperty);
                ////////////////////////////////om:featureOfInterest
                net.opengis.sampling.v_1_0_0.SamplingPointType samplingPoint = new net.opengis.sampling.v_1_0_0.SamplingPointType();
                samplingPoint.setId(AssignedSensorId);
                net.opengis.gml.v_3_1_1.CodeType saName = new net.opengis.gml.v_3_1_1.CodeType();
                saName.setValue(AssignedSensorId);
                samplingPoint.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, saName));
                //samplingPoint.getSampledFeature().add(gmlOF.createFeaturePropertyType());
                net.opengis.gml.v_3_1_1.DirectPositionType pos = new net.opengis.gml.v_3_1_1.DirectPositionType();
                pos.setSrsName(srsName/*"urn:ogc:def:crs:EPSG:4326"*/);
                pos.getValue().add(x);
                pos.getValue().add(y);
                net.opengis.gml.v_3_1_1.PointType point = new net.opengis.gml.v_3_1_1.PointType();
                point.setPos(pos);
                net.opengis.gml.v_3_1_1.PointPropertyType pointProperty = new net.opengis.gml.v_3_1_1.PointPropertyType();
                pointProperty.setPoint(point);
                samplingPoint.setPosition(pointProperty);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureMember = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureMember.setFeature(saOF.createSamplingPoint(samplingPoint));
                net.opengis.gml.v_3_1_1.FeatureCollectionType featureCollectionType = new net.opengis.gml.v_3_1_1.FeatureCollectionType();
                featureCollectionType.getFeatureMember().add(featureMember);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureOfInterest = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureOfInterest.setFeature(gmlOF.createFeatureCollection(featureCollectionType));
    //            featureOfInterest.setFeature(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.FeatureCollectionType.class, featureCollectionType));
                observation.setFeatureOfInterest(featureOfInterest);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.newDocument();
                final String sweNS = "http://www.opengis.net/swe/1.0.1";
                Element dataArray = doc.createElementNS(sweNS, "swe:DataArray");
                Element elementCount = doc.createElementNS(sweNS, "swe:elementCount");
                Element count = doc.createElementNS(sweNS, "swe:Count");
                Element value = doc.createElementNS(sweNS, "swe:value");
                dataArray.appendChild(elementCount).appendChild(count).appendChild(value).appendChild(doc.createTextNode(String.valueOf(numElement)));
                Element elementType = doc.createElementNS(sweNS, "swe:elementType");
                elementType.setAttribute("name", "Components");
                Element simpleDataRecord = doc.createElementNS(sweNS, "swe:SimpleDataRecord");
                Element timeField = doc.createElementNS(sweNS, "swe:field");
                timeField.setAttribute("name", "Time");
                Element time = doc.createElementNS(sweNS, "swe:Time");
                time.setAttribute("definition", "urn:ogc:data:time:iso8601");
                Element featureField = doc.createElementNS(sweNS, "swe:field");
                featureField.setAttribute("name", "feature");
                Element text = doc.createElementNS(sweNS, "swe:Text");
                text.setAttribute("definition", "urn:ogc:data:feature");
                Element dataField = doc.createElementNS(sweNS, "swe:field");
                dataField.setAttribute("name", dataType);
                Element quantity = doc.createElementNS(sweNS, "swe:Quantity");
                quantity.setAttribute("definition", dataType);
                Element uom = doc.createElementNS(sweNS, "swe:uom");
                uom.setAttribute("code", "m3 per s");
                simpleDataRecord.appendChild(timeField).appendChild(time);
                simpleDataRecord.appendChild(featureField).appendChild(text);
                simpleDataRecord.appendChild(dataField).appendChild(quantity).appendChild(uom);
                dataArray.appendChild(elementType).appendChild(simpleDataRecord);
                Element encoding = doc.createElementNS(sweNS, "swe:encoding");
                Element textBlock = doc.createElementNS(sweNS, "swe:TextBlock");
                textBlock.setAttribute("decimalSeparator", ".");
                textBlock.setAttribute("tokenSeparator", ",");
                textBlock.setAttribute("blockSeparator", ";");
                dataArray.appendChild(encoding).appendChild(textBlock);
                Element sweValues = doc.createElementNS(sweNS, "swe:values");
                dataArray.appendChild(sweValues).appendChild((doc.createTextNode(dataString)));
                Element result = doc.createElementNS("http://www.opengis.net/om/1.0", "om:result");
                result.appendChild(dataArray);
                observation.setResult(result);
                insertObservation.setObservation(observation);
                //handle "ogc" namespace bug
                NamespacePrefixMapper mapper = new PreferredMapper();
                marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
                marshaller.marshal(insertObservation, System.out);
                marshaller.marshal(insertObservation, out);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                in = connection.getInputStream();
                Object response = unmarshaller.unmarshal(new StreamSource(in));
                if (response instanceof net.opengis.sos.v_1_0_0.InsertObservationResponse) {
                    return (net.opengis.sos.v_1_0_0.InsertObservationResponse) response;
                } else if (response instanceof net.opengis.ows.v_1_1_0.ExceptionReport) {
                    net.opengis.ows.v_1_1_0.ExceptionReport exceptionReport = (net.opengis.ows.v_1_1_0.ExceptionReport) response;
                    StringBuilder strBuilder = new StringBuilder();
                    for (net.opengis.ows.v_1_1_0.ExceptionType ex : exceptionReport.getException()) {
                        StringBuilder tempBuilder = new StringBuilder(ex.getExceptionCode() + ": ");
                        for (String temp : exceptionReport.getException().get(0).getExceptionText()) {
                            tempBuilder.append(temp + "\n");
                        strBuilder.append(tempBuilder.toString() + "\n");
                    throw new IllegalArgumentException(strBuilder.toString());
                } else {
                    throw new IllegalStateException("Unrecognizeable response type!");
            } finally {
                if (out != null) {
                    out.close();
                if (in != null) {
                    in.close();
        }Edited by: 808239 on 10-Feb-2011 02:44

Maybe you are looking for