Singleton Logger

Good day
I am trying to write some code that opens a file and waits for input to write to a file. Basicly i Need a singleton that writes to a file.
I have created a class and used 'Shared Memory Encabled' on the class. I then created a shared area called ZCL_FILEWRITTER.
The constructor of my File writter takes in a file name and opens the file:
method CONSTRUCTOR.
  GV_FILENAME = IV_FILENAME.
  OPEN DATASET IV_FILENAME FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
endmethod.
My Write method is just as simple
method P_WRITE_FILE.
  TRANSFER IV_VALUE TO GV_FILENAME.
endmethod.
I create the instance as
move gv_filename to lv_inst_name.
    lc_handle = zcl_filewritter=>attach_for_write( INST_NAME = lv_inst_name ).
  CREATE OBJECT lv_instance AREA HANDLE lc_handle
      EXPORTING
        IV_FILENAME = gv_filename
  lc_handle->set_root( lv_instance ).
  lc_handle->detach_commit( ).
now for the trick, i call a function module in New Task Mode
CALL FUNCTION 'Z_BULKFILE_TEMP_TEST'
  starting new task sy-index
    destination in group gv_grpnme
    EXPORTING
      IV_INDEX          = sy-index
      IV_FILENAME       = GV_FILENAME
Inside this function module I
move iv_filename to lv_inst_name.
lc_handle = zcl_filewritter=>attach_for_read( INST_NAME = lv_inst_name ).
lc_handle->root->p_write_file( IV_VALUE = LV_S ).
lc_handle->detach( ).
However I am getting the following 2 errors:
DATASET_NOT_OPEN - File "/tmp/TESTBULK.txt" is not open.
UNCAUGHT_EXCEPTION - CX_SHM_INCONSISTENT - Different Definitions Between Program and Area.
Can anyone please assist?
Marc
I will give lots and lots of points.

in general singleton is a bad idea. not going to detail the issues here, there are plenty of resource online explaining the issues.
that said, your code is not thread-safe (if that is a concern). also, i'm not sure what you hope to gain. you obviously can't mix singleton/non-singleton usage of this code, so you just have to hope that all the code which uses this class chose the same usage scenario.

Similar Messages

  • To ragnic and other about Singleton class

    Hi ragnic. Thanks for your reply. I posted the code wrong. Heres' my correct one.
    I have a GUI first loaded information and the information is stored in a databse, I have some EJB classes..and my singleton class ABC has some method to access to the EJB..
    so my first GUI will gather info using singleton class and later if I click on
    a button in my first GUI class, will pop up another frame of another class , this class also need to class setPassword in my Singleton..
    are my followign codes correctly??
    iS my Class ABC a SINgleton class? thanks
    Is my class ABC use as single correctly. And It is called from other classes is also correct?
    I'm new to java and like to learn about Singleton class.
    But I really dont' understand it clearly after reading many examples of it.
    I have a project to convert my class abc to a singleton.
    But I dont know how to do it.
    In my class(soon will become a singleton) will have few methods that later I need to use it from another class A and class B.
    I have a GUI application that first load my class A..and my class will call
    class abc(singleton) to get some information from it.
    and then in class A has a button, if I click on that button I will call SIngleton class again to update my password, in the singleton class has method calls updatePassword. But I dont know how to call a singleton from other class.
    I have my code for them below:
    1)public class ABC //attempt using a singleton
    private static ABC theABC = null;
    private ABC(){}
    public synchronized static ABC getABC()
    if(theABC == null)
    theABC= new ABC();
    return the ABC;
    public void updateUserInfo(SimpleUser user)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.updateUserInfo(user, userHome);
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    public SimpleUser getID(String id)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    SimpleUser su = uc.getID(id, userHome);
    return su;
    } catch(HomeFactoryException hfe) {
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    throw new DelegateException(re);
    } catch(CreateException ce) {
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    throw new UserNotFoundException();
    public void setPassword(String lname,String pw)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.setPassword(lname,pw, userHome);//assume that all lname are differents.
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    }//Do I have my class as a Singleton correctly???
    2)//Here is my First Frame that will call a Singleton to gather user information
    public A(Frame owner)
    super(owner, "User Personal Information",true);
    initScreen();
    loadPersonalInfo();
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen()
    txtFname = new JTextField(20);
    txtLname=new JTextField(20);
    btnsave =new JButton("Save");
    btnChange= new JButton("Click here to change PW");//when you click this button there will be a frame pop up for you to enter informaton..this iwll call class B
    JPanel pnlMain=new JPanel();
    JPanel pnlFname= new JPanel();
    pnlFname.setLayout(new BoxLayout(pnlFname, BoxLayout.X_AXIS));
    pnlFname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlFname.add(new JLabel("First Name:"));
    pnlFname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlFname.add(txtFname);
    JPanel pnlLname= new JPanel();
    pnlLname.setLayout(new BoxLayout(pnlLname, BoxLayout.X_AXIS));
    pnlLname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlLname.add(new JLabel("Last Name:"));
    pnlLname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlLname.add(txtLname);
    pnlMain.add(pnlFname);
    pnlMain.add(pnlLname);
    pnlMain.add(btnsave);
    pnlMain.add(btnChange");
    btnSave = new JButton("Save");
    btnSave.setActionCommand("SAVE");
    btnSave.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,0,0));
    pnlBottom.add(btnSave);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(500,500);
    GraphicUtilities.center(this);
    theABC=ABC.getABC();
    //Do I call my ABC singleton class correctly??
    private void loadPersonalInfo()
    String ID= System.getProperty("user.name");
    SimpleUser user = null;
    try {
    user = ABC.getID(ID);
    //I tried to use method in ABC singleton class. IS this correctly call?
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered.",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    System.exit(0);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    currentUser = user;
    txtFname.setText(currentUser.getFirstName());
    txtLname.setText(currentUser.getLastName());
    //This information will be display in my textfields Fname and Lname
    //I can change my first and last name and hit button SAVE to save
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("SAVE")) submitChanges();
    if(e.getActionCommand().equals("CHANGE_PASSWORD")) {
    changepassword=new ChangePassword(new Frame(),name,badgeid);
    public void submitChanges(){
    String currentNTUsername = System.getProperty("user.name");
    SimpleUser user =null;
    try {
    user = theABC.getID(ID);
    user.setFirstName(txtFname.getText().trim());
    user.setLastName(txtLname.getText().trim());
    currentUser = user;
    theABC.updateUserInfo(currentUser);
    //IS this correctly if I want to use this method in singleton class ABC??
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    this.setVisible(false);
    3) click on ChangePassword in my above GUI class A..will call this class B..and in this class B
    I need to access method in a Singleton class- ABC class,,DO i need to inititates it agian, if not what should I do? thanks
    package com.lockheed.vista.userinfo;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import java.beans.*;
    import java.applet.*;
    import java.net.*;
    import org.apache.log4j.*;
    import com.lockheed.common.gui.GraphicUtilities;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import vista.user.UserServicesDelegate;
    import vista.user.SimpleUser;
    import vista.user.UserNotFoundException;
    import vista.user.*;
    import com.lockheed.common.ejb.*;
    import com.lockheed.common.gui.*;
    import com.lockheed.vista.publish.*;
    * This program allow users to change their Vista Web Center's password
    public class ChangePassword extends JDialog
    implements ActionListener{
    protected final Logger log = Logger.getLogger(getClass().getName());
    private UserServicesDelegate userServicesDelegate;
    private User currentUser = null;
    private JPasswordField txtPasswd, txtVerifyPW;
    private JButton btnSubmit,btnCancel;
    private JLabel lblName,lblBadgeID;
    private String strBadgeID="";
    * This is the constructor. It creates an instance of the ChangePassword
    * and calls the method to create and build the GUI.
    public ChangePassword(Frame owner,String name,String badgeid)
    super(owner, "Change Password",true);
    initScreen(name,badgeid);//build the GUI
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen(String strname,String strBadgeid)
    txtPasswd = new JPasswordField(20);
    txtVerifyPW=new JPasswordField(20);
    txtPasswd.setEchoChar('*');
    txtVerifyPW.setEchoChar('*');
    JPanel pnlMain=new JPanel();
    pnlMain.setLayout(new BoxLayout(pnlMain, BoxLayout.Y_AXIS));
    pnlMain.setBorder(BorderFactory.createEmptyBorder(20,0,20,0));
    JPanel pnlPW=new JPanel();
    pnlPW.setLayout(new BoxLayout(pnlPW, BoxLayout.X_AXIS));
    pnlPW.setBorder(BorderFactory.createEmptyBorder(0,96,0,30));
    pnlPW.add(new JLabel("Password:"));
    pnlPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlPW.add(txtPasswd);
    JPanel pnlVerifyPW=new JPanel();
    pnlVerifyPW.setLayout(new BoxLayout(pnlVerifyPW, BoxLayout.X_AXIS));
    pnlVerifyPW.setBorder(BorderFactory.createEmptyBorder(0,63,0,30));
    pnlVerifyPW.add(new JLabel("Verify Password:"));
    pnlVerifyPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlVerifyPW.add(txtVerifyPW);
    JPanel pnlTop= new JPanel();
    pnlTop.add(pnlPW);
    pnlTop.add(Box.createRigidArea(new Dimension(0,10)));
    pnlTop.add(pnlVerifyPW);
    pnlMain.add(pnlTop);
    btnSubmit = new JButton("Submit");
    btnSubmit.setActionCommand("SUBMIT");
    btnSubmit.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,20,30));
    pnlBottom.add(btnSubmit);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(350,230);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("CANCEL")) this.setVisible(false);
    if(e.getActionCommand().equals("SUBMIT")) submitPW();
    * This method is called when the submit button is clicked. It allows user to change
    * their password.
    public void submitPW(){
    myABC= ABC.getABC();//Is this correct?
    char[] pw =txtPasswd.getPassword();
    String strPasswd="";
    for(int i=0;i<pw.length;i++){
    strPasswd=strPasswd+pw;
    char[] vpw =txtVerifyPW.getPassword();
    String strVerifyPW="";
    for(int i=0;i<vpw.length;i++){
    strVerifyPW=strVerifyPW+pw;
    if((strPasswd==null)||(strPasswd.length()==0)) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not enter a password. Please try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    if((!strPasswd.equals(strVerifyPW)))
    //password and verify password do not match.
    JOptionPane.showMessageDialog(new JDialog(),"Your passwords do not match. Reenter and try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    try
    myABC.setUserPassword(strPasswd);//try to use a method in Singleton class
    txtPasswd.setText("");
    txtVerifyPW.setText("");
    this.setVisible(false);
    } catch(DelegateException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    } catch(UserNotFoundException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    And ofcourse I have other EJB classes to work with these classes.
    ***It compiles okey but when I ran, it say "NullPointerException"
    I think I call my Singleton wrong.
    Please help me.thanks

    1. When replying, use <reply>, don't post a new topic.
    2. Implementing a singleton is a frequently asked question. Search before you post.
    3. This is not a question about Swing. A more appropriate forum would be "New To Java Technology" or perhaps "Java Programming", but see point 1.
    4. When posting code, keep it short. It increases the chance of readers looking at it. And in composing your shorter version for the forum, you just may solve your problem.

  • Singletons

    I have an application that implemented its own Logging class which is a singleton.
    I realize that OOD expects you to always use set and get methods but in this case - since there is only one - should I REALLY call the getInstance() function in every method I need it in or should I just declare a global Logger and reference that all the time? What would the good design practice be?
    null

    The logger actually instantiates a and configures a JUL. And it's not a very pretty implementation.
    The first time it is called it must be called as
    MyLogger logger = MyLogger.getInstance(properties).
    But after that the usages is:
    Logger logger = MyLogger.getInstance().getLogger().
    Kinda messy and gross but I didn't write it.
    I just find it a pain to have to "get" it in nearly EVERY method.
    Thanks for the advice...I guess I'll stick to calling the getInstance method.

  • Things to consider while making a class singleton?

    sometimes i need to share the state of object across application.I get confused should i declare it singleton or declare state vaiables as static.
    As per mythoughts, if intention is just to share the state of object across application i should go for static variables. Is this right?
    My understanding about when we should go about singleton is below
    We should declare the class as singleton when we need only one instance across jvm. But i am not unable to find any practical scenario
    when we where we may need singleton . Any help here will be appreciated. Everywhere on different sites i get to see the example of logger
    class where the reason is generally given as so that single log file is created not multiple log files.
    But again this could have been achieved with declaring the file variable as static in logger file?
    So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
    which wont be possible if we make the separate instance of logger for each write..
    Is the above reasoning correct so that i can proceed in right direction?

    How will declaring its state as static accomplish that objective?With declaring variables as class variable instead of instance variables, there will be a single copy of each variable. In each instance (in this case logger if we dont declare it singleton) we can check if file is already created or not. I mean it will be visible across all instances.
    No, because the file name isn't the only state. There is also the output stream/writer, its current position, its charset, the log level, the logger name, its filters, its formatters, ...Agreed. I just wanted to convey the point. As you said there will be other parameters,in that case we can declare all of them as static.
    A configuration file holder is a good example: there is only one configuration file so there should only be one holder instance.Thanks for pointing it out. Configuration file is used mainly to read the properties. we usually dont update the values there.So even if we dont make it singleton it may be correct. The advantage i can think of making it singleton is that if configuration file is used frequently then we dont have create the object again and again.
    So actual reason is for declaring the logger as singleton is becuase we need the single log file with issues avoiding concurrent writing
    No it isn't, and that doesn't follow from anything you said previously so the 'so' part is meaningless.I want to say here is that t to have single log file should not be the only reason behind making the logger file as singleton, other reasons can be handling of concurrent writing too.
    Have a look at the Wikipedia article on the Singleton pattern, or buy the booki have gone through the singleton pattern in headfirst book and some of the articles on net. But they mainly describe how the make the class as singleton and the reason that We should declare the class as singleton when we need only one instance. But looking for actual scenarios where we need singleton. So i took the examplle of logger file which is used in many project and trying to understand it is constructed as singleton so that i can use in my project if required.
    Edited by: JavaFunda on Aug 28, 2011 3:51 AM
    Edited by: JavaFunda on Aug 28, 2011 3:56 AM

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • Singleton serialization and weblogic - help!

    hi everyone,
    I'm trying to serialize a singleton cache object we're using for our (intranet)
    website running on weblogic 6.1. I've made sure the singleton class
    implements serializable, and i've also put the following method in the
    singleton class (ChartCache.java):
    private Object readResolve()
    return theInstance; //which is of type ChartCache
    By the way I'm using jdk 1.3. I've trawled the web and can't find anything to help me yet...
    Basically I've written a jsp to get the current instance of the cache
    and serialize it to a file. When I invoke another jsp i want it to
    reinflate the object and place it back into the weblogic jvm so it can
    once again be accessed as a singleton by all classes in the webapp. At
    the moment its just not working - the cache object will eventually
    take over half an hour to create (huge database processing going on)
    so I want the option, if weblogic falls over, to reinstantiate the
    cache without having to rebuild it from scratch. The cache will only
    be refreshed once a day.
    I'll c&p my jsp code below...
    ======================= restoreCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = null;
    try
    String filename = "chartCache.dat";
    FileInputStream fis = new FileInputStream(filename);
    ObjectInputStream in = new ObjectInputStream(fis);
    theCache = (ChartCache)in.readObject();
    in.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Resurrected chart cache from file.
    ======================= saveCache.jsp
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.io.*" %>
    <%@ page import = "com.drkw.agencylending.website.chartcache.*" %>
    <%@ page import = "com.drkw.agencylending.log.Logger" %>
    <%
    ChartCache theCache = ChartCache.getInstance();
    String fileName = "chartCache.dat";
    try
    FileOutputStream fos = new FileOutputStream(fileName);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(theCache);
    oos.flush();
    oos.close();
    catch(Exception e)
    Logger.log(e);
    %>
    Wrote cache object to file.
    ============================
    At the moment, a file is getting written but it seems suspiciously
    small (73 bytes!) for what is a very large object. When I try to load
    it up again, I get no errors but when I call ChartCache.getInstance()
    (my singleton) it recreates the cache rather than using the one I've
    reinflated. BTW I don't need to worry about server clustering/JNDI to
    ensure I have a truly singleton instance - there will only ever be one
    JVM to worry about.
    Any help greatly appreciated!

    solved the problem using another technique. Rather
    than serialize the entire singleton object, I just
    serialized the hashmap (the only bit I really care
    about). Then in the private constructor, the class
    checks a database flag to see whether the singleton
    was created today - if not, I refresh the cache,
    otherwise load in the serialized hashmap and set that
    as my class member. No complicated jndi/ejb registry
    needed to get around it..!singleton serialization is not recommended in ejb enviroment, it will cause problems. in what you are doing, it is far better to persist the data values in a database.
    just for the sake of writing a serializable sington: in addition to what you do in a regular object, you would first check to see if this obj has been serialized, if it is, deserialize it and return this one. you would have to write your own method to do serialization, making sure you have only one place to serialize it, and let the object know where the file is.

  • ExceptionInInitializerError with logger

    Hello,
    when I run my application I'm always getting the following error:
    Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
         at helios.visual.PreferencesGUI.<init>(PreferencesGUI.java:48)
         at helios.visual.MainGUI.actionPerformed(MainGUI.java:672)
    Caused by: java.lang.NullPointerException
         at helios.properties.LogProperties.init(LogProperties.java:63)
         at helios.properties.LogProperties.<init>(LogProperties.java:33)
         at helios.properties.LogProperties.<clinit>(LogProperties.java:15)
         ... 28 more
    This is a piece of the code:
    public class LogProperties
         private final static LogProperties instance = new LogProperties();
         //Logger
         static Logger logger = Logger.getLogger("helios.properties.LogProperties");
         //Objects
         private DirectoriesAndFiles df = DirectoriesAndFiles.getInstance();
         private Message m = Message.getInstance();
         //Other
         private File inputfile;
         private FileInputStream inputstream;
         private FileOutputStream outputstream;
         private Properties properties = new Properties();
         //Constructor
         private LogProperties()
              init();
         //Get instance of LogProperties
         public static LogProperties getInstance()
              return instance;
         //Load the properties from the appropriate properties file
         private void init()
                   try
                   logger.info("Loading LogProperties.");
                   inputfile = new File(df.getPropertiesPath() + df.getLogPropertiesName());
                   inputstream = new FileInputStream(inputfile);
                   properties.load(inputstream);
              catch (IOException e)
                   m.showErrorMessage(e.getMessage());
              finally
                   try
                        inputstream.close();
                   catch(IOException e)
                        e.printStackTrace()
              }So as soon as my application instantiates this LogProperties class I get this error.
    I don't know if the fact that this is written according to the Singleton pattern has something
    to do with it.
    When I set the line "logger.info("Loading LogProperties.");" in comment, then the error is not thrown.
    So as soon as my logger wants to log something I'm gettting into trouble.
    Does anyone know what could be the problem here. It's giving me a headache.
    Thx.
    Message was edited by:
    Mynca

    Yes, it's because of static, as malcolmmc suggested. What he is also saying is:
    Switch the order of the following two lines:
    private final static LogProperties instance = new LogProperties();
    //Logger
    static Logger logger = Logger.getLogger("helios.properties.LogProperties");Then logger will be initialized first, and LogProperties will be able to be constructed.
    Is logger used by other classes in the package? If not, it could be private and non-static, and then you could leave the order that you had.

  • How to Plot number and string in one row (data logger counter) ?

    hi all i made data log quantity using Digital Counter via modbus to monitoring quantity and reject that has and Name Operator, Machine and Part Number.
    i have problem about plot the number & string in one row, as shown on the picture below :
    how to move that string on one row ? i attach my vi.
    Thanks~
    Attachments:
    MODBUS LIB Counter.vi ‏39 KB

    Duplicate and answered - http://forums.ni.com/t5/LabVIEW/How-to-Plot-number-and-string-in-one-row-data-logger-counter-via/m-p...

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • I purchased a Holux M-1200E Bluetooth GPS Data Logger.  The device paired with my laptop just fine so I know it is working right.  The device will not even show up on my iphone or ipad to pair via bluetooth.  Is there a way to pair without jailbreaking???

    I purchased a Holux M-1200E Bluetooth GPS Data Logger.  The device paired with my laptop just fine so I know it is working right.  The device will not even show up on my iphone or ipad to pair via bluetooth.  Is there a way to pair without jailbreaking???  I haven't had any trouble to date pairing any devic with my iphone or ipad, this is ridiculous!!!!  Is there a way to update my bluetooth settings on my iphone 4s to be able to have this device be recognized???  I love my apple devices, but this is very frustrating.  I bought this Data Logger for a specific purpuse to help out with my Search and Rescue volunteer activities, and I really need help with this!!!  I am hoping apple will help me!!!
    Thanks,
    Melissa

    melissafromlenexa wrote:
    That is not the right device, it is the
    Holux
    M-1200E Bluetooth GPS Logger
    I looked at the same sight for that and it does not say that.  This is the first time I have posted a question, you don't have to be mean about it.  I am trying to get this to work for a good cause. 
    It may be the best source of assistance is the manufacturer of the device. I suspect you will need a specific app for the iPhone to get it to work, but the site is rather ambiguous about that.

  • HT1420 Hi I am trying to sync my pone but wont allow me to transfer music purchased on the phone. States I have 5 authorised computers on my account but when i  logg into my account it only identifies 1 so i carn't deactive?  trying to backup data to put

    Hi I am trying to sync my ip3 but wont allow me to transfer music purchased on the phone to itunes on the laptop. States I have 5 authorised computers on my account but when i  logg into my itunes account it only identifies 1 so i carn't deactive all to start again? I am trying to backup data fom myip3 to put on ip4 so carnt even complete sync atm Any ideas on what to do??

    To change the iCloud ID you have to go to Settings>iCloud, tap Delete Account, provide the password for the old ID when prompted to turn off Find My iDevice, then sign back in with the ID you wish to use. 
    If your sister doesn't know the password for her old ID, and if her old ID is an earlier version of her current ID, she needs to temporarily recreate the old ID so you can delete if from your phone using her current password.  To do this, have her go to https://appleid.apple.com, click Manage my Apple ID and sign in with her current iCloud ID.  Click edit next to the primary email account, change it back to her old email address and save the change.  Then edit the name of the account to change it back to her old email address.  You can now use the password for her current ID to turn off Find My iDevice on your device, even though it prompts you for the password for her old account ID.  After you do this, Next, have your sister recreate her current ID again by going back to https://appleid.apple.com and changing her primary email address and iCloud ID name back to the way it was.
    Then your can save any photo stream photos that you wish to keep to the camera roll on your device, then go to Settings>iCloud, tap Delete Account and choose Delete from My iDevice when prompted.  You will be prompted to either keep or delete the iCloud data from your device.  If the data is already in another account you can choose Delete.  If you need to migrate it to another account, choose Keep, then choose Merge when signing into the new account.

  • Hello my name is consuela mayfield and I hope you have read my emails I sent to you off of lately and If u dint I'm askin I'm trying to logg into my iTunes for my apple ID and when I logg into it it says either I can't conne.

    I need help with my iPod touch and I deleted my iTunes account and trying to make a new one but won't let me it keeps telling me cannot connect to iTunes or server not found and I cannot connect to my computer because It freezes and turns off and I'm try a see if I logg on iTunes on here will it let me download iTunes on here instead of the other one could someone help out please!!???
    <Email Edited by Host>

    You really should not post your email address on a public forum such as this unless you just love spam. I have requested that Host edit for you protection.
    Allan

  • How to implement logger in this ftp server

    I have written a FTP Server that is used by the clients to upload xml over to the server.
    Currently it is using a console and it is printing stuff out on a console.
    I have tried a lot to implement a logger class so that all console messages get written to a file.
    But it has not been working out at all.
    I would deeply appreciate if all you java gurus out there could modify the code given below to correctly log messages to a log file.
    Please do Explain if possible ...I will try to rectify this issue in several other applications i developed as well.
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    import java.text.DateFormat;
    import java.text.Format;
    import java.lang.Object;
    import java.lang.*;
    import javax.crypto.*;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.PBEParameterSpec;
    import java.security.spec.AlgorithmParameterSpec;
    import java.security.spec.KeySpec;
    public class FTPServer
    {     public static void main(String args[]) throws Exception
         {     ServerSocket soc=new ServerSocket(5217);
              System.out.println("FTP Server Started on Port Number 5217");
              while(true)
                   System.out.println("Waiting for Connection ...");
                   transferfile t=new transferfile(soc.accept());               
    class transferfile extends Thread
         Socket ClientSoc;
         DataInputStream din;
         DataOutputStream dout;     
         transferfile(Socket soc)
         {     try
              {     ClientSoc=soc;                              
                   din=new DataInputStream(ClientSoc.getInputStream());
                   dout=new DataOutputStream(ClientSoc.getOutputStream());
                   System.out.println("FTP Client Connected ...");
                   System.out.println("External IP of Client ..." + ClientSoc.getInetAddress());
                   //System.out.println("FTP Client Connected ..." + ClientSoc.getRemoteSocketAddress());
                   start();               
              catch(Exception ex)
    //encrypto routine starts
    class DesEncrypter {
            Cipher ecipher;
            Cipher dcipher;   
            // 8-byte Salt
            byte[] salt = {
                (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
                (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03 };   
            // Iteration count
            int iterationCount = 19;   
           DesEncrypter(String passPhrase) {
                try {
                    // Create the key
                    KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
                    SecretKey key = SecretKeyFactory.getInstance(
                        "PBEWithMD5AndDES").generateSecret(keySpec);
                    ecipher = Cipher.getInstance(key.getAlgorithm());
                    dcipher = Cipher.getInstance(key.getAlgorithm());   
                    // Prepare the parameter to the ciphers
                    AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);   
                    // Create the ciphers
                    ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                    dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
                } catch (java.security.InvalidAlgorithmParameterException e) {
                } catch (java.security.spec.InvalidKeySpecException e) {
                } catch (javax.crypto.NoSuchPaddingException e) {
                } catch (java.security.NoSuchAlgorithmException e) {
                } catch (java.security.InvalidKeyException e) {
            // Buffer used to transport the bytes from one stream to another
            byte[] buf = new byte[1024];   
            public void encrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes written to out will be encrypted
                    out = new CipherOutputStream(out, ecipher);   
                    // Read in the cleartext bytes and write to out to encrypt
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                    out.close();
                } catch (java.io.IOException e) {
            public void decrypt(InputStream in, OutputStream out) {
                try {
                    // Bytes read from in will be decrypted
                    in = new CipherInputStream(in, dcipher);   
                    // Read in the decrypted bytes and write the cleartext to out
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0) {
                        out.write(buf, 0, numRead);
                        //added later on
                        in.close();                    
                    out.close();
                } catch (java.io.IOException e) {
    }     //encryptor routine ends
    //not implemented right now as we arent using the ftp server to download stuff...can be activated later on if we want
         void SendFile() throws Exception
              String filename=din.readUTF();
              File f=new File(filename);
              if(!f.exists())
                   dout.writeUTF("File Not Found");
                   return;
              else
              {     dout.writeUTF("READY");
                   FileInputStream fin=new FileInputStream(f);
                   int ch;
                   do
                        ch=fin.read();
                        dout.writeUTF(String.valueOf(ch));
                   while(ch!=-1);     
                   fin.close();     
                   dout.writeUTF("File Received Successfully");                                   
         String Compare(String filename) throws Exception
                        ///dout.writeUTF("entering compare");
                        String dateTempString=new String();
                        Date dateValue=new Date();
                        SimpleDateFormat formatter = new SimpleDateFormat ("hhmmss");
                        dateTempString = formatter.format(dateValue);
                        File dir1 = new File("C:\\FTPnew");
                        boolean success2 = dir1.mkdir();
                        if (!success2) {
                             // Directory creation failed /Already Exists
                        File dir = new File("C:\\FTPnew\\server");
                        boolean success = dir.mkdir();
                        if (!success) {
                             // Directory creation failed /Already Exists
                        File ftemp=new File(dir,dateTempString + filename);
                        File fnewtemp=new File(dir,"new-enc-"+filename);
                        // Create encrypter/decrypter class
                        DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
                        FileOutputStream fout=new FileOutputStream(fnewtemp);     
                        int ch;
                        String temp;
                        do
                        {     temp=din.readUTF();
                             ch=Integer.parseInt(temp);
                             if(ch!=-1)
                                  fout.write(ch);                         
                        }while(ch!=-1);
                        fout.close();
                        //dout.writeUTF("written temp en file");
                        // Decrypt
                    encrypter.decrypt(new FileInputStream(fnewtemp),
                    new FileOutputStream(ftemp));
                        //String Option;
                        dout.writeUTF("Delete");                    
                        System.out.println("File Upload Successfull--Duplicate file with timestamp Created");          
                        boolean success1 = fnewtemp.delete();                    
                        return "hello" ;
         void ReceiveFile() throws Exception
              String ip=din.readUTF();
              System.out.println("\tRequest Coming from Internal IP Address : "+ ip);
              String filename=din.readUTF();
              if(filename.compareTo("File not found")==0)
                   return;
              // Destination directory
       File dir11 = new File("C:\\FTPnew");
                        boolean success22 = dir11.mkdir();
                        if (!success22) {
                             // Directory creation failed /Already Exists
                        File dir = new File("C:\\FTPnew\\server");
                        boolean success21 = dir.mkdir();
                        if (!success21) {
                             // Directory creation failed /Already Exists
              File f=new File(dir ,"enc-"+filename);
              File fe=new File(dir,filename);
              String option;
              if(fe.exists())
                   //dout.writeUTF("File Already Exists");
                   String compvalue = Compare(filename);
                   //dout.writeUTF(compvalue);
                   if(compvalue.compareTo("hello")==0)
                        //dout.writeUTF("Transfer Completed");
                        return;
                   option=din.readUTF();
              else
                   //dout.writeUTF("SendFile");
                    option="Y";
                   if(option.compareTo("Y")==0)
                        // Generate a temporary key.       
            // Create encrypter/decrypter class
             DesEncrypter encrypter = new DesEncrypter("My Pass Phrase!");
                 FileOutputStream fout=new FileOutputStream(f);                    
                        int ch;
                        String temp;
                        do
                        {     temp=din.readUTF();
                             ch=Integer.parseInt(temp);
                             if(ch!=-1)
                                  fout.write(ch);                         
                        }while(ch!=-1);
                        fout.close();                    
                        // Decrypt
                    encrypter.decrypt(new FileInputStream(f),
                    new FileOutputStream(fe));          
                        boolean success2 = f.delete();
                        dout.writeUTF("Delete");
                        System.out.println("File Upload Successfull");                    
                   else
                        return;
         public void run()
              while(true)
                   try
                   String Command=din.readUTF();
                   if(Command.compareTo("SEND")==0)
                        System.out.println("\tSEND Command Received ...");     
                        ReceiveFile();
                        continue;
                   catch(Exception ex)
                        //System.out.println("\tClient Terminated Abnormally ...........");
                        continue;
    }

    Stick a
    Logger log = Logger.getLogger( "me ftp server" );at the top.
    Checn Sys.out.println to log.info( ... )
    Add a logging prefs file.
    http://java.sun.com/j2se/1.4.2/docs/guide/util/logging/overview.html

  • Error when running VI logger 2.01 with MX driver

    Hi,
    When I run a VI task , the following message from Task Validation shows up:
    Database does not exist in the specified path.
    I have reinstalled the software, but it want fix the problem.
    How do I solve this problem?
    Do I need the full vers. of VI logger, to run and log data?
    Do I need the Citadel database installed ? Where do I finde the Citadel database? What CD? I have the full NI Academic software.
    Please help me!!!
    I'm LOST.
    S.
    Tævje
    [email protected]

    Look here for solving problem.
    RegardsMessage Edited by Indiana on 04-21-2005 08:33 AM
    Message Edited by Indiana on 04-21-2005 08:34 AM
    Message Edited by Indiana on 04-21-2005 08:34 AM
    Message Edited by Indiana on 04-21-2005 08:36 AM

  • "file not found" error in VI Logger when running an imported VI Logger task

    I'm having trouble getting all of my imported tasks to run in VI Logger.
    I'm using VI Logger 2.0, with an SCXI-1100.  The data acquisition tasks I import run fine.  One of the VI Logger tasks I've imported runs OK, but the other one gives an error:
    "Engine Error!
    Error Code = 7
    LabView: File not found.  The file may have been moved or deleted, or the file path might be incorrectly formatted for the OS."
    If I create a new VI Logger task, the new task works OK.  And my 1st VI Logger task to be imported works OK.  So I know my setup mostly works.  But our company has never been able to figure out importing tasks very well, so I'm looking for help.
    Question 1: What file is LabView looking for?  I've checked my Export path and database path, and they are identical in both the working task and the non-working task.
    Question 2: Where else might I look for the difference between the 2 VI Logger tasks?  Neither task uses any weird characters in the name, both have analog input channels and calculated channels.  And I've mixed and matched the data acquisition tasks with no change (the good VI Logger task will run with either data task, the bad VI Logger task won't run with either data task), so I'm pretty sure the problem is in the VI Logger task, and not the data task.  I've also tried importing the 2nd task on its own, as a separate import function, but that gave the same error.
    Thanks for the help in advance,
    Jake

    Hi Spex,
    I can import the VI Logger task OK (from another PC running VI Logger 2.0), but I can't run the task.  I've attached the file.  The "1 channel" task runs OK.  The "x-probe" task starts, takes 1 or 2 data points, then hangs for a few seconds, then pops up the "file not found" error. The data acquisition taks run OK, so I don't think they're the problem.
    This file I've attached includes 2 good data tasks ("1 channel" and xprobe"), 1 good VI Logger task ("1 channel"), and my non-working VI Logger task ("x-probe", which works fine on the PC it was exported from).
    I have also tried exporting the non-working VI Logger task on its own, and it still imports OK, but still doesn't run, and gives the same error.
    Thanks,
    Jake
    Attachments:
    configData1.zip ‏353 KB

Maybe you are looking for

  • Getting Event of Popup after duplicate of a document

    Hello, thank you very much for your effort and valuable time in advance. I have a question concerning duplicate of documents: When you duplicate a document and give an a different Business Partner, the system asks you by a popup wether you want to up

  • New mail indicator won't go away

    My mail icon continuously says I have 1 new mail even though I don't -- once I access my inbox it says I have no new messages, but the icon won't go away. Also, I have BCC turned off, but my gmail is still BCCing me all of my sent messages. How can I

  • If I delete one message from my inbox they all disappear -why & how do I retrieve them?

    Twice this week I have deleted a message from my inbox, using the edit button & then highlighting the message to delete, then pressing the delete button at the bottom of the page & ALL my emails in my inbox disappear!  Where are they & how can I retr

  • Transaction data from one cost center to another cost center

    Hi All Can any one tel me how to move the Transaction data from one cost center to another cost center . My scenario is basically : Users posted for  company code 1003 for Cost center S00570 for the period 01.04.2007  to 30.11.2007 but it has to go t

  • Homesharing library shows up on one computer but not the other

    So tonight I just connected my two computers, a Windows Vista and a Windows 7, with homesharing.  Although it worked at first, I turned off the computers, then returned to them, wanting to homeshare again.  I noticed the Vista connected but the 7 did