Best Practice: passing properties to a Singleton

Hi,
I have an object in my app that must only exist once. It is a DatabasConnectionPool. I would like to implement it as a Singleton and access it from anywhere in the app with
DatabaseConnectionPool dbcp = DatabaseConnectionPool.getInstance();
But the thing is that I would like to pass it some settings: number of connections to the database, username and password, ...
If I had a constructor for the class I would pass a Properties object with the constructor containig all the values but how do I do it with a Singleton?
Right now I have:
class Singleton {
private static Properties _appProps = null;
private static Singleton _instance = null;
static public void setProperties(Properties appProps) {
_appProps = appProps;
static public Singleton getInstance() {
if (null == _instance) {
instance = new Singleton(appProps);
private Singleton(Properties props) {
So, the Launch code for the application reads the .properties files and calls:
DatabaseConnectionPool.setProperties(props);
WebServer.setProperties(props);
LDAPServer.setProperties(props);
Thanks a lot for your time guys!
Rafa

You don't need synchronization at all if you do it the way a previous post suggested:
private static Singleton instance = new Singleton();
public Singleton getInstance(){
    return instance;
}This is lazy initialization by default because the singleton instance will only be created when the class is loaded into memory. It will be loaded into memory when you first call getInstance() so it's already using lazy initialization.
The properties question seems to have several options
1. Use your setProperties method to pass in dynamic properties. This will potentially make your singleton behave differently between uses if you change its properties while it's running.
2. Hardcode the properties inside the singleton. This doesn't allow dynamic changes.
3. Your connection pool is probably dishing out Connection objects and creating new ones when needed right? So, put the Connection creation in a different class called ConnectionFactory and pass in the factory to the singleton. This way you can customize the kind of connections to make in the factory without changing the singleton code. All the singleton cares about is saying factory.createConnection() and returning it.

Similar Messages

  • Best practice - Pass data from Custom Comp to Another Custom Comp

    Hi, id like to know what would be the best practice to pass data from a custom component to another custom component. Right now I got these options:
    1st Component Custom Event - Main App - Public Properties 2nd Component
    1st Component Custom Event - Main App - Public Setter 2nd Component
    Is there another more directly way of doing it? or a better way?
    Thanks

    Hi, id like to know what would be the best practice to pass data from a custom component to another custom component. Right now I got these options:
    1st Component Custom Event - Main App - Public Properties 2nd Component
    1st Component Custom Event - Main App - Public Setter 2nd Component
    Is there another more directly way of doing it? or a better way?
    Thanks

  • Best practice using regular properties

    What is considered best practice when it comes to using properties ? Example like hostname, port number when connecting towards an external resource.
    Should property files be used ? Is this considered a bad practice ? Should deployment descriptors be used - if so - how do one update these properties when changed ?
    Are there any utility classes that makes easy access to this kind of properties ?
    ---- Trond

    Depends on what properties. Many properties like hostname etc can be retrieved using different API calls - such as the request object or other portal specific objects.
    Properties that you applications need, that might change - can be stored in a properties file. I use a singleton to retreive them - and have a reload method on the singleton that I can call if I need to reload the properties once the server has started.
    Kunal

  • Best Practices - Update Explorer Properties of BW Objects

    What are some best practices of using the process chain type "Update Explorer Properties of BW Objects"?
    We have the option of updating Conversion Indexes, Hierarchy Indexes, Authorization Indexes, and RKF/CKF Indexes.
    When should we run each update process?
    Here are some options we're considering:
    Conversion Indexes - Run this within InfoCube load process chains that contain currency conversions within explorer objects.
    Hierarchy Indexes - When would this need to be run? Does this need to be run for PartProviders and/or Snapshots? Do ACRs handle this update? Should this be run within InfoCube load chains, or after ACRs?
    Authorization - We plan to run this a couple times a day for all explorer objects.
    RKF/CKS - Does this need to run after InfoCube loads? With PartProvider and/or Snapshot indexes? After transports have completed?
    Thanks,
    Cote

    Does anyone productively use explorer and this process type for process chains?

  • Best practice to restart weblogic and managed  servers after changing pass

    hi
    i need to know if have an installation with the following structer what is the best practice to restart the servers after we change weblogic password ?and i know that i should change boot.properties with the new password ,is there anything else to change ? please advise .
    oracle access manager &oid (dose it affected by weblogic password change ?)
    thank you
    Edited by: hsweiss on Jul 31, 2012 10:45 AM

    the order is to restart:All managed servers and followed by Admin server
    If your weblogic server is integrated with oid, you need to change the credentilas in both the places ie weblogic server(boot.properties) and idm server
    if your weblogic server is using your internal ldap for the authentication, your idm and oam wil not effect with this change
    if you change the boot.properties file that is enough, you don't need to change anywhere

  • Best practice from passing messages from servlets

    Is there a best practice for passing user messages (typically errors) back to the page from servlets?
    e.g. http://localhost:4502/content/geometrixx/en.html?message=Some user error message
    Dan

    Well I suppose that answer to that question depends somewhat on your requirements, but I would say using a query string as you have indicated would be less than ideal because the page with the message would not be cached. No depending on your requirements and what sort of message you are passing that might be OK - especially if you message is highly personalized.
    If however you have a limited number of standard messages to display a more common approach is to have each message have it's own page and then to configure the servlet to redirect to the appropriate page based on the desired message.
    If you want the user to end up on the same page they submitted to the servlet from then another common approach would be to have the post to the servlet be AJAX and then display the message client side without having to change the URL.

  • Best Practice Needed: Global Application Properties...

    Hi All,
    When developing a web-based application that reads certain configurable parameters from .properties files, I usually put the appropriate code in a static block in the appropriate Java class, storing the property in a static final constant. For example, a DBConnection class might have a static block that reads the driver, username, and password from a properties file.
    My question is, what are some "best practice" techniques for accessing and storing such parameters for use in an application? Are all global properties initialized in one class? at the same time? only when first needed?

    over all, I would say that your approach is fine. Personally, I load properties through a single class, some thing like PropertyReader, and have the different classes initialize their static fields via a get method on that class, like getProperty("db.user"). I prefer to load them via a single class because I can place all of my IO trapping in one location, it is easier to implement new security measures and, if necessary, easier to support internationalization.
    I initialize all properties once, at startup, into a Wrapper Object, typically ResourceBundle or Properties (although Hashtable or any some thing else would be suitable). I believe that it is best to initialize all properties at the same time, at startup because the costs of storing properties that may not be used is going to be less then the cost of making multiple IO calls to load properties on a need-by-need basis. In other words, you are almost always going to take a bigger performance hit by loading properties only when a request for that key is received, rather then just loading them all at once.

  • Constants or properties file - best practice question

    Hi,
    My application has a number of values that will be used in different classes throughout my project. For example, I perform a check against the max allowed length of an ID in numerous places in my code.
    Therefore, it makes sense to set this value in a central location, and refer to it as a variable where it is required in my code.
    I see in other projects that using a public static final member in a Constants class is used to set these types of values. Is this recommended or best practice?
    The only alternative I can think of would be to use a properties file, and inject the value using Spring etc.
    What is considered best practice or the neatest way for doing this?
    Thanks

    user10340197 wrote:
    Thanks. I'm using Spring anyways, so it would provide me with the PropertyPlaceHolderConfigurer for injecting these.And the name of that class provides a clue. As Kayaman said, constants are constants. Math.PI does not and will not change, EVER. Neither will Integer.MAX_VALUE.
    Configuration parameters, on the other hand, might change. If your MAX_ID_LENGTH is ever likely to change, and could do so without causing widespread chaos, then it probably should be a property (ie, a configuration) value.
    If not, it should probably be a constant (with appropriate 60-point documentation warning people what might happen if they DO change it).
    Winston
    PS: There is nothing particularly terrible about having a Properties class (except that you'll want to call it something different) that initializes its values from configuration files; except that if there are gazillions of them, you might want to:
    (a) Split them up into "themes".
    (b) Re-think your design.
    Winston

  • Best practice for passing parameters to a Timer event handler?

    The code hinting is suggesting that I use a Timer object rather than setTimeout or setInterval, however I need to pass a parameter to the timer handler.
    What is the best practice for doing this?
    + Subclass Timer?
    + Subclass TimerEvent?
    + Global variable?
    + other?
    Thanks

    Hmm.  I don’t think I would’ve chosen that option.  I would probably create a class that listens for the TimerEvent dispatches a custom event.  Unless there is information you need in TimerEvent, I don’t see a need to extend it.

  • Best Practices: Question about Passing DataSet to Crystal through C#

    I have used the tutorial provided by Business Objects and have successfully passed a dataset from C# code to Crystal Reports.
    I have a few questions about "best pratices" though.
    It appears that when passing the dataset to crystal then you no longer have the ability to put SQL Expressions in the report anymore otherwise errors will occur.
    So, I'm trying to come up with a way to have a custom field in the SELECT statement and have it show up on the report as a field. So, in the below example I created a custom SQL field called TIMES7 in the query.
    "Select CLM_ID, CLM, PAID_111X, *(PAID111X * 7) As TIMES7*_ From WIKI.MULCRICKET WHERE CLM_ID < 5"
    If I create a formula field in Crystal and set it's value to {MULCRICKET .TIMES7} then it works like a hybrid SQL Expression at run-time.
    This does work but has issues because the database field doesn't really exist in the design environment which causes error when the formula is saved. But it does work at run-time.
    I was wondering if their was a best practice for this?

    So why are you using a formula that doesn't work? If it errors in the designer it's telling you it's not supported.
    Drop the formula into a filed and hide it if you don't want it displayed, this way it gets into the record selection formula.
    "Best Practices" is don't use formulae that won't verify in the Designer. "If it doesn't work in the designer it won't work in code"
    If you need to add an "unknown" field at run time then use RAS to insert the field.

  • Best practices for pass collections and to navigate between 2 view endlessl

    Hello, I have a doubt about efficiency and optimization of memory in this case. I have a managedBean for to show a activities´s list, then I can select one activity and the application redirects another view. This view is controlled for another managedBean for to show the specificied activity.
    My idea is pass the collection and the id of specificied activity to he second managedBean, and since second managedBean pass the collection to the first managedBean.
    I had thought pass properties by request and retrieve in the second bean, but I am not sure wich scope to usea in both bean. Because, the first bean pass collection to the first again.
    I also thought to use SessionScope in both bean, but I doubt about efficiency of memory in this case.
    How to pass parameters is not yet defined:
    -Using h:link and attributes
    - Using setPropertyactionListener between both bean
    -Others who do not know
    First managedBean (show list)
    @ManagedBean(name="actividades")
    @ViewScoped I'm not sure which scope to use
    public class ActividadesController implements Serializable {
         private static final long serialVersionUID = 1L;
         private final static Logger logger=Logger.getLogger(ActividadesController.class);
         private List<Actividad> listado; All activities
         @ManagedProperty(value="#{actividadBO}")
         private ActividadBO actividadBo;
         @ManagedProperty(value="#{asociaciones}")
         private AsociacionController asociacionController;
    /** methods **/
    Second managedBean (specified activity)
    @ManagedBean(name="actV")
    @ViewScoped I'm not sure which scope to use
    public class ActividadView implements Serializable {
         private static final long serialVersionUID = 1L;
         private Actividad actividad;
         private String comentario;
    private List<Actividad> listado; All activities for to avoid having to search again
         @ManagedProperty(value="#{actividadBO}")
         private ActividadBO actividadBo;
         private Integer idActividad;
         @PostConstruct
         public void init(){
              //actividad=actividadBo.get(idActividad);
              actividad=actividadBo.get(idActividad);
              actualizarComentarios(actividad.getIdActividad());
              actualizarAdjuntos(actividad.getIdActividad());
    /** methods **/
    Any suggestions??
    Kind regards.

    Hello, I have a doubt about efficiency and optimization of memory in this case. I have a managedBean for to show a activities´s list, then I can select one activity and the application redirects another view. This view is controlled for another managedBean for to show the specificied activity.
    My idea is pass the collection and the id of specificied activity to he second managedBean, and since second managedBean pass the collection to the first managedBean.
    I had thought pass properties by request and retrieve in the second bean, but I am not sure wich scope to usea in both bean. Because, the first bean pass collection to the first again.
    I also thought to use SessionScope in both bean, but I doubt about efficiency of memory in this case.
    How to pass parameters is not yet defined:
    -Using h:link and attributes
    - Using setPropertyactionListener between both bean
    -Others who do not know
    First managedBean (show list)
    @ManagedBean(name="actividades")
    @ViewScoped I'm not sure which scope to use
    public class ActividadesController implements Serializable {
         private static final long serialVersionUID = 1L;
         private final static Logger logger=Logger.getLogger(ActividadesController.class);
         private List<Actividad> listado; All activities
         @ManagedProperty(value="#{actividadBO}")
         private ActividadBO actividadBo;
         @ManagedProperty(value="#{asociaciones}")
         private AsociacionController asociacionController;
    /** methods **/
    Second managedBean (specified activity)
    @ManagedBean(name="actV")
    @ViewScoped I'm not sure which scope to use
    public class ActividadView implements Serializable {
         private static final long serialVersionUID = 1L;
         private Actividad actividad;
         private String comentario;
    private List<Actividad> listado; All activities for to avoid having to search again
         @ManagedProperty(value="#{actividadBO}")
         private ActividadBO actividadBo;
         private Integer idActividad;
         @PostConstruct
         public void init(){
              //actividad=actividadBo.get(idActividad);
              actividad=actividadBo.get(idActividad);
              actualizarComentarios(actividad.getIdActividad());
              actualizarAdjuntos(actividad.getIdActividad());
    /** methods **/
    Any suggestions??
    Kind regards.

  • External System Authentication Credentials Best practice

    We are in the process of an 5.0 upgrade.
    We are using NTLM as our authentication source to get teh users and the groups and authenticate against the source. So currently we only have the NT userid, group info(NT domain password is not stored).
    We need to get user credentials to other systems/applications so that we can pass that on the specfic applications when we search/crawl or integrate with those apps/systems.
    We were thinking of getting the credentials(App userid and password) for other applications by developing a custom Profile Web service to gather the information specific to these users. However, don't know if external application password is secured when retrieving from the external repository via a PWS and storing into the Portal database.
    Is this the best approach to take to gather the above information? If not, please recommend the best practice to follow.
    Alternatively, can have the users enter the external system credentials by having them edit their user profile. However, this approach is not preferred.
    If we can't store the user credential to the external apps, we won't eb able to enhance the user experience when doing a search/or click-thorugh to tthe other applications.
    Any insight would be appreciated.
    Thanks.
    Vanita

    Hi Vanita,
    So your solution sounds fine - however, it might be easier to use an SSO Token or the Plumtree UserID in your external applications as a difinitive authentication token.
    For example if you have some external application that requires a username and password, then if you are in a portlet view of the application the application should be able to take the userid plumtree sends it to authenticate that it is the correct user.  You should limit this sort of password bypass to traffic being gatewayed by the portal (i.e. coming from the portal server only).
    If you want to write a Profile Web Service, the data the gets stored in the Plumtree Database is exactly what the Profile Web Service send it as the value for a particular attribute.  For example if your PWS tells Plumtree that the APP1UserName and APP1Password for user My Domain\Akash is Akash and password then that is what we save.  If your PWS encrypts the password using some 2-way encryption before hand, then that is what we will save.  These properties are simply attached to the user, and can be sent to different portlets.
    Hope this helps,
    -aki-

  • Best practice for default values in EO

    I have and entity called AUTH_USER (a user table) within it has 2 TIMESTAMP WITH TIME ZONE columns like this ...:
    EFF_DATE TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT current_timestamp,
    TERM_DATE TIMESTAMP WITH TIME ZONE
    Notice EFF_DATE has a default constraint and is not nullable.
    In the EO, EFF_DATE is represented as a TIMESTAMPTZ and is checked as MANDATORY in its attribute properties. I cannot commit a NEW RECORD based on VO derived from this EO because of the MANDATORY constraint that is set in the EFF_DATE attribute's properties unless I enter a value. My original strategy was to have the field populated by a DEFAULT DATE if the user should attempt to leave this field null.
    This is my deli ma.
    1. I could have the database populate the value based on the default constraint in the table definition. Since EFF_DATE and TERM_DATE resemble the Effective Date (Start, End) properties that the framework already provides then I could set both fields as Effective Date (Start, End) and then check Refresh After Insert. But this still won't work unless I deselect the mandatory property on EFF_DATE.
    2. The previous solution would work. However, I'm not sure that it is part of a "Best Practices" solution. In my mind if a database column is mandatory in the database then it should be mandatory in the Model as well.
    3. If the first option is a poor choice, then what I need to do is to leave the attribute defined and mandatory and have a DEFAULT VALUE set in the RowImpl create method.
    4. Finally, I could just force the user to enter a value. That would seem to be the common sense thing to do. I mean that's what calendar widgets and AJAX enabled JSF are for!
    Regardless to what the correct answer is, I'd like to see some sample code of how the date can be populated inside the RowImpl create method and it pass to setEffDate(TimestampTZ dt). Keep in mind though that in this instance I need the timezone at the database server side and not the client side. I would also ask for advice on doing this with Groovy Scripting or expressions.
    And finally, what is the best practice in this situation?
    Thanks in advance.

    How about setting the default value property of the attribute in the EO to be adf.currentDate ?
    (assuming you are using 11g).
    This way there is a default date being set when the record is created and the user can change it if he wants to.

  • Best practice for backing bean population? (also, ActionListener RANT)

    Hello,
    I am about 3/4 of the way through development of a small to medium size JSF application. Sometimes I really like JSF, but much of the time I am left puzzled or frustrated for hours trying to find workarounds to JSF's bugs/glitches and design flaws.
    For example, early on, I was impressed with how easily it was to invoke a method from a page using an actionlistener. Now that I'm actually building things with JSF, the actionlistener funtionality still seems cool, but incredibly half baked. I find myself using request parameters LIKE CRAZY to work around the fact that JSF doesnt support passing parameters directly to backing bean methods. This feels awkward and wrong considering the fact that JSF is intended to abstract the HTTP underpinnings. To add insult to injury, I often have to iterate through ALL of the request parameters looking for one that has an id with an ending matching my desired property name (since JSF appends it's own crap to the beginning). I don't like doing things in a hacky way. This seems very hacky, and I feel dirty doing it.
    So, my first question is, what is the best practice for populating backing beans??? How do others accomplish this. I can think of several other approaches, but none feel less hacky.
    Second, are there plans in the next spec (please say there are) to allow parameters to be passed to backing bean methods? If not, WHY THE HECK NOT?
    Even though JSF expert group people have been conspicuously absent from this forum of late, I'd really appreciate responses from you as well.
    Thank you for your thoughts.

    Hi BrownBear,
    I've been using JSF for about 6 months now and I'd be glade to help as much as I can.
    Concerning parameters, I'm not sure what your issue is but I use the f:param tag to pass them. If you could post an example of what you are trying to do, I could see exactly what your issue is. Maybe the f:param can't help you.
    As for best practice for populating backing beans, I personaly try to let JSF do as much as possible. For example, if I have a backing bean with five properties, I make sure that they all are on the JSP page the bean serves. If one of the property is just there as an Id like, lets say, a Person ID (DB row key), then I put it on my JSP page as a hidden input field. I do the same with the properties that only for display, if I want them to be back in my bean when request comesback.
    Hope this help some how. Please, feel free to ask specific questions related to your specific problem and I monitor this post and trnasfer to you the ;little JSF experience I have.
    I'm pretty happy with JSF as it is but it sure needs improvements. :) What the heck, it's version 1.01 after all, and the next release should be a great one with the integration of JSTL.
    Cheers

  • Set filter criteria on page 1 for page 2 OData model - "best practice"?

    Hello, I have a problem with an app - where I want to filter data on a second page, based on settings from the first page. I use an OData model.
    The collections on both pages are not related in terms of "navigation" properties, that is my problem and I can not change the data source...
    So I am looking for ideas/best practices to solve this because sometimes my filtering doesn't work... the following problem occurred: Request aborted
    I have a page with a sap.m List with items="{/tabWorkPlace}" and and a local JSON model where I store relevant data during the app lifecycle.
    handleListSelect - first page
    var context = evt.getParameter("listItem").getBindingContext();
    var dataModel = sap.ui.getCore().getModel("dataModel");
    var workplace = context.getProperty("WORKPLACE_ID");
    dataModel.setProperty("/WORKPLACE_ID", workplace);
    this.nav.to("SubMaster", context);
    The general App.controller.js handles the nav.to function:
    var app = this.getView().app;
    var page = app.getPage(pageId);
    if(pageId == "secondPage") {
         page.getController().filterData();
    And the controller of the second page:
    filterData: function() {
    var oModel = sap.ui.getCore().getModel("odata");
    var dataModel = sap.ui.getCore().getModel("dataModel");
    var workplace = dataModel.getProperty("/WORKPLACE_ID");
    var items = this.getView().byId("list");
    var oFilter=new sap.ui.model.Filter("WORKPLACE_ID",sap.ui.model.FilterOperator.EQ,workplace);
    items.getBinding("items").filter(oFilter);
    I don't write this code into the onInit() or beforeRendering() function, because they are called only once and I am navigating back and forth between the two pages, because the pages are created only once and "just" the data is changed.
    The desired page looks like this - with an other collection bound to it:
    <List
      id="list"
      select="handleListSelect"
      items="{/tabWorkstep_Status}"
    >
    But when I call it - then the request gets aborted:
    The following problem occurred: Request aborted
    But despite the fact the Request is aborted, the list on the second page is filtered!
    The filter criteria for the model works when I type it into the browser with URL. Maybe this fails because the data binding for the list didn't took place at this phase?
    I have this pattern (filter criteria on one page and result on the second page) more times - (and I think a better data model would be better with navigation properties would be better, but I cannot change it)
    But at another constellation the filtering doesn't work - same error... the following problem occurred: Request aborted
    I also don't want to change the pattern (page 1 to page 2) into popup lists or this fancy new filtering possibilities because it is not suitable for my use case.
    Is there maybe a more elegant solution - because sometimes filtering works, sometimes don't..., do I have an error in my solution (general approach)?
    Many thanks for any input!
    BR,
    Denise

    Hello, yeah you are right, but it works without the odata> stuff because of this in App.controller.js:
    var uri = "http://localhost:32006/JsonOdataService.svc";
    var oModelMS = new sap.ui.model.odata.ODataModel(uri);
    sap.ui.getCore().setModel(oModelMS, "odata");
    oView.setModel(oModelMS);
    So my question is - how to navigate from one page to another - and on the other page first bind a collection to a select and then when selecting bind certain elements (a textfield) to the selected filtered entity.
    The stuff with context and binding won't work, because the two Collections don't have a navigation/association property between them...
    So for example:
    page1
    select a list item with property color: red and year 1985. Press one of the buttons and pass this criteria to another page.
    page 2:
    show a dropdown box with all car names which fullfill this criteria, and when one car is selected, then display the data for THIS car in several text fields.
    This is not a master->detail navigation example, because on page 1 i select certain criterias, and then with buttons I navigate to several pages with those criterias.
    But since the OData model has no relationships it is really hard to do it manually... With a dummy mock.json like in DJ Adams Fiori like SAPUI5 apps it is no problem... But with OData and no things related to each other it is hard...

Maybe you are looking for

  • Hiding a tablix column conditionnaly from page to page (group member to group member)

    Hi I have the following report               Col1   Col2    Col3 Group1                  1          2      3                 2          4      3                3           6      6 (page break)             Col1   Col2    Col3 Group2                 

  • I have a bright white screen on my Gen 4 ipod nano. I can still see text if I look hard enough, and it still plays music and stuff, but it's really hard to see.

    As described above, my screen is bright white, but it still plays music. It's really hard to see, and I've tried everything. I manually restarted it like 20 times, I updated software and reset it, and I've just waited. It's happened once before, but

  • I'm a SUCKER

    Is Tiger to Leopard OS a major release like Windows Vista or XP to Windows 7? One that you would expect to pay for. I don't think it is. And, forcing customers into at least Leopard (10.5.8) for the iPhone 4 is some fine print I didn't read. And it's

  • AGPM 4.0 SP2 - AGPM Service Account Member of Backup Operators

    Hi all, I've installed AGPM without having the Service Account in the group of Backup Opperators, and I get no error or sth. like that. I have, maybe a stupid question, but why does the AGPM Service Account need the group membership of the Domain "Ba

  • Elements 10 Blending Brush

    I am new to PhotoShop Elements and have been doing my best to learn everything.  I have been using the blending brush to do skin softening and somehow my blending brush disappeared.  Has this happened to anyone and can you help me find it? I still ha