Passing initialization parameters to a singleton

So here's the classic Singleton code:
public class MySingleton {
private static MySingleton _instance;
private MySingleton() {
// construct object . . .
public static synchronized MySingleton getInstance() {
if (_instance==null) {
_instance = new MySingleton();
return _instance;
What I can't find any discussion of is: what do you do if that "// construct object . . ." bit requires parameters (e.g. the username and password for the DB connection)?
Obviously, adding those parameters to the getInstance() method would be a bad idea so some kind of init() method is probably required. I've used that approach in simple cases so the calling sequence is
MySingleton foo = MySingleton.getInstance();
foo.init(parameterObject);
That's fine so long as the initialization is simple and I can keep track of where the singleton gets used and just be careful not to use it before init() gets called. But if the initialization involves setting up a DB connection, how do I arrange the code so (a) most of my application can just call getInstance() without worrying about error situations (b) the code that does set up the connection can do so reliably and provide detailed analysis when something does go wrong and (c) the app doesn't just crash when some other idiot calls getInstance() without first calling init(), or calls init() multiple times with different parameters? Or does that last possibility mess up the singleton so badly I should reject the init() idea and take a different approach entirely?
Thanks,
Graeme

Hi Graeme! I guess I misunderstood what you wanted to do. I was under the impression that the necessary data (eg. DB connection parms) was not dependent upon user input.
Based on what you've described, are you sure you need a singleton? Here's a possible implementation. If there are items that are constant (for the most part anyway) such as database names, connection strings, etc., those can be located in a properties file which is read once, when the singleton instance is created. Now, let's say one of the variables is a user id & password, which are supplied by a given user. Then, your implementation could look somewhat like the following:
public class DBAccess
   private static DBAccess m_instance;
   private DBAccess()
      // Read properties file and store necessary data
   public static DBAccess getInstance()
      // Standard lazy initialization here
   public DBConnection getConnection( String userId, String password )
      // Get actual DB connection using the supplied arguments
   // Any other required methods
} // class DBAccessNote that the getConnection() method above is an instance method, not a class method.
The above code presents a single, well-known point of access to a database. You can add any other instance methods you deem necessary. Note that some instance methods may need to be declared with the synchronized keyword, based upon the data it handles to avoid concurrency problems.
Hope this helps!
Cheers!
-- Amol.

Similar Messages

  • Initialization Parameters for Servlet

    I am working with Tomcat Apache server 6.0
    I am not able to pass initialization parameters to my servlet program.
    Please tell me how to do it.
    Thanks.

    use <init-param> in <servlet> tags
    it is set in the web.xml which is located in the directory of "webapps/yourwebapp/web-inf/"!
    If you want to get more informations about its setting, google it with "init-param web.xml"
    Best regards!

  • Passing Runtime initialization parameters to a Servlet

    Hi all.
    Plz.let me know, how do you pass runtime initialization parameters to a Servlet. Also, when do we need this approach. Thank You.

    Global parameters that may change should be passed as parameters so that the servlet doesn't have to be recompiled to make the change.
    Here a global parameter is used to store a timeOut value. This value is written to every web page to force the page to refresh.
    <web-app>
        <servlet>
            <servlet-name>
                KioskServlet
            </servlet-name>
            <servlet-class>
                KioskServlet
            </servlet-class>
            <init-param>
                <!-- number of seconds of inactivity until timing out -->
                <!-- 300 = 5 minutes -->
                <param-name>timeoutValue</param-name>
                <param-value>300</param-value>
            </init-param>
         </servlet>
    </webapp>

  • Passing URL parameters to WD application

    Hi!
    To pass URL parameters to WD application I currenly inbound plug 'defauld' (of type 'Startup') of main window. I use following code:
    types:
        begin of param_t,
          name type string,
          value type string,
        end of param_t.
      data: params type standard table of param_t.
      data: param like line of params.
      wdevent->get_data(
        exporting
          name = '_ALL_URL_PARAMETERS'
        importing
          value = params
    It works fine but this plug is called after init methods of the component controller an of the view. So if I want to do something with parameters, I must do in this plug.
    Is there way to pass URL parameters in a WD app. so that they were available from the very beginning of the application work i.e. in init method of the component controller etc.?
    Thanks!

    I had the same requirement too. There are a couple of threads on the subject as well, I've posted in one of them but had no answer:
    Re: Read URL Parameters programmatically
    The workaround i've used is this, it's definitely not as neat as I would like to since you end up having two initialization methods per controller, WDDOINIT and the one you create (for each controller you want to run code in using the received parameters). Nevertheless, it works:
    1) Create an event in your component controller, for example INIT_COMPLETED.
    2) Define a new method in your component controller, e.g. INIT_AFTER_WINDOW. This method receives an Importing parameter TYPE tihttpnvp. It uses this received HTTP parameters for the initialization logic and finally raises the INIT_COMPLETED event (This is the method that "replaces" WDDOINIT).
    3) In the Window's Inbound plug handler, you get the HTTP parameters (with wdevent->get_data) and afterwards call the method WD_COMP_CONTROLLER->INIT_AFTER_WINDOW (maybe you need to declare the usage previously in the Window to have the reference available).
    4) Finally, if you need some of the Views to be initialized afterwards the component controller's INIT_AFTER_WINDOW runs (for example to show some initialization messages), you'll have to replace the WDDOINIT method with an INIT_AFTER_COMPCTRL method and subscribe it to the component controller's INIT_COMPLETED event.
    I hope you got the idea, and more importantly, that we get some cleaner solution from SAP for achieving this in the future.
    Regards
    Edited by: Alejandro Bindi on Nov 6, 2008 10:08 PM
    INIT_AFTER_WINDOW is the method to be called on step 3

  • Issues passing drillthrough parameters from a multi-level tablix in SSRS 2008 R2

    Hello,
    I am really struggling with trying creating a drillthrough report that starts with a matrix (tablix)  and passing those  parameters. I am using SSRS 2008 R2.
    Here's my scenario:
    I have a matrix that has mulitple levels where you can drill down. Here an example with all the levels open:  
    Active
    Term
    Leave
    Total
    128
    88
    121
    United States
    110
    80
    85
    New York
    65
    30
    57
    Manhattan
    10
    6
    9
    Buffalo
    20
    23
    4
    Albany
    35
    1
    44
    Texas
    45
    50
    28
    Dallas
    40
    30
    22
    Houston
    5
    20
    6
    France
    18
    8
    36
    Centre
    18
    8
    36
    Blois
    7
    2
    8
    Druex
    6
    1
    15
    Tours
    5
    5
    13
    I want to drillthrough to another report - Detail Report. As I understand it, I would click the 65 for New York and I would see the detail for the 65 Active people. If I click the 2 under Blois, I would see the 2 terminated people in Blois. My understanding
    for this to work, the Detail Report would need a a parameter for each of the level possibilities in the matrix that I could click: Country, State, City as well as the Status (Active, Term, Leave).
    While I understand about passing parameters, what I don't understand is how to pass the parameters if they are blank. Let's say I clicked 65 for New York, I would need to pass State = New York  Status = Active. But the remaining parameters (Country
    and City  would be null). I know Country doesn't need to be Null in this case.
    My Detail Report has the parameters defaulted to Null, but whether I put the parameters in a Filter for the dataset or in the query itself, I cannot get it to ignore the Nulls.
    As a crazy work-around (I think) I can put in the Where of the query  something along the lines of: this:
            and (a.Country in (@paramCountryCode) or NULL  in (@paramCountryCode) )
    and I would need to do that for each parameter. Usually I have to use 'ALL' instead of NULL, I'm note sure why.
    Additionally, in the Report Action of the Main Report, I need to pass those parameters for each level and their Status. I am also not clear whether or not I need to put in all the parameters on each of the levels (Country, State, City) of the matrix. And if
    I do, do I need to make the expressions an IIF statement stating whether or not they are In Scope?
    All the examples I was able to find, only showed one or maybe two parameters being passed. Doing the way I am trying, seems convoluted, error-prone and tedious. I really hope that I am wrong.
    Is there a better way to approach drilltrough reports from a matrix when there are multiple levels?
    Thank you for the help.
    ~J

    Hi Jenna_Fire,
    According to your description, you have a matrix contains total for each group on each level. Now your requirement is, when you click on any number (data field or total), it will go to the detail report which returns all the detail information of the people
    within the group scope. For example, if you click on the total of Active users in United States, it will return the detail information of Active users in New York and Texas. Right?
    In this scenario, we should set the parameter (@Country, @State, @City) allow multiple values in both main and detail report. And in Default Value (@Country, @State, @City), query out all distinct values. In the textbox which contains
    those total values, when set use these parameters to run the report, we only need to pass the parameters of parent groups. For example, if we click on the total of Active users in New York, we only need to pass Country, State, Status to detail report, and
    in the detail report, the City parameter will use all distinct values (Default Values) because we don't pass the City parameter. We have tested this case with sample data in our local environment. Here are steps and screenshots for your reference:
    1. Create parameter Country, State, City and Status in both main report and detail report. Set both Available Value and Default Value get values from query (Create a dataset for each parameter, use "select distinct [column] from [table]" as query). Set allow
    multiple values for parameter Country, State and City in both reports.
    2. In corresponding textbox, pass appropriate parameters in go to report Action.
    4. Filter data in detail report (in where clause or using filters).
    5. Save and preview. It looks like below:
    Reference:
    Using Parameters to Connect to Other Reports
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou

  • Problem with passing date parameters in cursor

    Is there any problem in passing date parameters and like clause as below
    CURSOR eftcursor(start_date DATE, end_date DATE, where_clause varchar2) IS
    select * from r_records
    where created_date between start_date and end_date and description like where_clause;
    and in the open statement
    select to_date('01/06/2010 00:00:00', 'dd/mm/yyyy hh24:mi:ss') into startDate from dual;
    select to_date('01/07/2010 00:00:00', 'dd/mm/yyyy hh24:mi:ss') into endDate from dual;
    str := '%something%aaaaa%';
    open eftcursor(startDate ,endDate , str);
    Do i need to do any kind of conversion in the cursor where clause or when i am passing the parameter in open statement.

    Almora wrote:
    Do i need to do any kind of conversion in the cursor where clause or when i am passing the parameter in open statement.No, your code looks correct -- ou're passing a date to the cursor.
    You might consider whether you really need an explicit cursor though. An implicit cursor is easier to code and performs better.

  • What is the better way to pass input parameters between components?

    Hi all,
    I had a dispute with a colleague about passing data between different WDP Development Components. The situation is like this:
    Colleague has a SearchWDP (parent) und I have a BrowseWDP (child). After searching for some objects and clicking a hit in the SearchWDP, the corresponding details should be shown in BrowseWDP, via passing a bunch of parameters such as selected item's id, etc.
    Now which of the following is the better practice:
    - Defining a node in BrowseWDP (child) with isInputParameter set to TRUE, creating a similar node from the same type (simply via ModelBinding, both WDPs are using the same model) in SearchWDP, and defining a mapping between them so that SearchWDP fills the input nodes. From BrowserWDPs perspective, I'd call this Pull method.
    or...
    - Defining a node in BrowseWDP (child) with isInputParameter set to FALSE, creating a setter method in BrowseWDP Interface Controller for the collection (to be passed as parameters) and calling a wdContext.nodeBlaBla().bind(pInputParameterFromModelType). From BrowserWDPs perspective, I'd call this Push method.
    The colleague's argumentation in favor of Push has not convinced me at all and I'd like to ask your opinions. Is there a best practice or recommendation for this scenario? TIA
    ps: Any answer will be rewarded.

    Hi Cuneyt,
    Refer the links below, they are very informative!
    http://help.sap.com/saphelp_nw04s/helpdata/en/22/15a441cd47a209e10000000a155106/content.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/67/cc744176cb127de10000000a155106/content.htm
    These links are a part of the WebDynpro ABAP documentation, but the concepts are same for WDA and WDJ.
    Considering your scenario, I would recommend the first alternative you have mentioned (if you refer the second link its called External Context Mapping), where component controller context node of component A (SearchWDP) is the source for Interface controller context (same name) of component B (BrowseWDP).
    Thanks.
    Chitrali

  • Passing URL parameters to PL/SQL Pages

    Hi,
    I want to pass parameters from url to the PL/SQL page . How is this possible?
    http://myserver/pls/portal/url/PAGE/page_group/page/testplsqlpage?course_ref=##COURSE_ID##&staff_ref=##STAFF_ID##
    I will to received course_ref and staff_ref in the PL/SQL page and pass the values to SQL query so that its filtered.
    Can pls anyone guide me? If there is any alternate way or there is sample code pls let me know
    Many Thanks
    Ganesh

    Hi Mick,
    Thanks for your reply. However my problem is still not resolved.
    I have created a Omniportlet with lists the staff details. When I click on the staff link I am passing to parameters as follows
    http://servername/pls/portal/url/PAGE/CCM_MIS_PORTAL/TUTOR_HOME/Course_Info?Param1=10017031/M2523&Param2=001434
    on the receving page I have a omni portlet which must receive these 2 parameters and pass it on to the query and filter the results.
    On the received page I have created 2 page parameters (Param1 and Param2)
    I have assigned these 2 paramaters to the portlet paramers through page parameters' section
    on the omni portlet in the query I have created 2 bind variables (p1, p2) and the default value of the bind variable is set using ##Param1## and ##Param2## so the received values from page is passed to to bind variable and hence to the query.
    However the omni portlet is not received the parameters and I can not figure out whats wrong?
    Is there any problem with my URL (guide says I should use relative URL)
    Please help

  • How does one pass import parameters to a report within a method?

    Hello all,
    Well how does one  pass import parameters to a report which is within a method ...end method.
    for example :
    method 123
    SUBMIT reportname using selection '1000'
    endmethod .
    Here we need to pass values into the selection screen and run the report for those values.
    The values are say 'ABC'   (  tablename "DEF" and field name "HIJ" ).
    I hope the question is clear, awaiting your response 
    Thanks and Regards,
    Sandeep.

    Go to SE24
    Parameters: Give the Parameter name, Typing method is "Type" is the domain type that u are selecting, say for e.g :  Parameter is "P_CONT" , its associated type "CHAR32" etc
    For Select Options:  Parameter name say "S_CUST", Type"importing". For this you need to give an associated type which must be created as "TABLE TYPE " in SE11. That table type needs to have a "LINE TYPE" .
    LINE TYPE is a Structure created with components "SIGN, OPTION, LOW & HIGH" for select-Options.
    NOTE: for a Table type related to Customer data fields "say KUNNR", the line type created must have the Component Type and data Type corresponding to the Data Element associated with "KUNNR" ;i.e: "CHAR" etc.
    See if this is clear to you or revert back in case of any Confusion.

  • Question about the Initialization Parameters Information in the Alert.log

    Hi, All -
    What is the correct answer for the following question.
    Specifically, what information does Oracle provide you with in the alert.log regarding initialization parameters?
    a. Values of all initialization parameters at startup
    b. Values of initialization parameters modified since last startup
    c. Values of initialization parameters with non-default values
    d. Only values of initialization parameters that cannot be modified dynamically.
    I think the answer should be B, but I would like to confirm.

    The answer is C
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14220/process.htm#sthref1633
    The alert log is a special trace file. The alert log of a database is a chronological log of messages and errors, and includes the following items:
    All internal errors (ORA-600), block corruption errors (ORA-1578), and deadlock errors (ORA-60) that occur
    Administrative operations, such as CREATE, ALTER, and DROP statements and STARTUP, SHUTDOWN, and ARCHIVELOG statements
    Messages and errors relating to the functions of shared server and dispatcher processes
    Errors occurring during the automatic refresh of a materialized view
    The values of all initialization parameters that had nondefault values at the time the database and instance start
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com

  • Any Easy Way to pass initial parameters to a VI created with New VI?

    In LabVIEW 2010 I can use OpenG's New VI function to create and launch a VI that is built from a template.
    Is there any easy way to pass initial parameters from the VI that creates the New VI to the New VI that will be available as soon as the New VI starts?

    Check out the Control Value Set invoke node. I personally don't like this node, and tst has got a great suggestion to promote cleaner, less fragile syntax for launching VI's dynamically that require input parameters.
    a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"] {color: black;} a.lia-user-name-link[href="/t5/user/viewprofilepage/user-id/88938"]:after {content: '';} .jrd-sig {height: 80px; overflow: visible;} .jrd-sig-deploy {float:left; opacity:0.2;} .jrd-sig-img {float:right; opacity:0.2;} .jrd-sig-img:hover {opacity:0.8;} .jrd-sig-deploy:hover {opacity:0.8;}

  • How To Pass Multiple Parameters In URL with Report Builder

    Hi,
    I use apex 4.2 with database xe 11g and i use report builder to build my report i use this link to call report
    function runrep(){
    var vurl = 'http://192.168.0.57:8889/reports/rwservlet?userid=retail/1@xe&destype=cache&desformat=PDF&paramform=no&report=item_cost&P_BATCH_NO='+$v('P138_BATCH_NO');
    popupURL(vurl);
    now i want to pass Multiple Parameters like P138_ITEM_CODE , P138_UOM_CODE
    how can i add this Parameters in URL ?
    Regards
    Ahmed

    Ramani_vadakadu wrote:
    window.open("http://hq-orapp-03.kuf.com:9704/xmlpserver/~weblogic/kufpec/BTA/KUF_CONF_ITINUD.xdo?_xpf=&_xpt=1&_xdo=%2F~weblogic%2Fkuf%2FBTA%2FKUF_CONF_ITINUD.xdo&_xmode=&_paramsP_BTM_ID="+parseInt(document.getElementById('P3_BTA_ID').value)+"&_xt=KUF_CONF_ITINUD&_xf=pdf&_xautorun=true&id=weblogic&passwd=kuf2011","_blank");
    the above code we are using apex JS to BI publisher calling for report as PDF
    i don't know exactly where your parameters , did you customize my link to multiple parameters
    'http://192.168.0.57:8889/reports/rwservlet?userid=retail/1@xe&destype=cache&desformat=PDF&paramform=no&report=item_cost&P_BATCH_NO='+$v('P138_BATCH_NO'); 

  • Use hyperlink to open another page , and pass some parameters to that page

    Hi
    Thank you for reading my post.
    How i can use hyperlink to open another jsp file in a new window meanwhile pass some parameters to it.
    for example i need something like this :
    http://127.0.0.1:8080/myProj/faces/Viewmessage.jsp?messageID=10
    i can not use session bean because i must open that in a new window and use hyperlink not Action
    Thank you

    I tried the following in the equivalent of your Viewmessage (page bean):
            ExternalContext eContext = FacesContext.getCurrentInstance().getExternalContext();
            String text = "Parameters: ";
            Iterator it = eContext.getRequestParameterNames();
            Map requestParams = eContext.getRequestParameterMap();
            while (it.hasNext()) {
                String key = (String)it.next();
                String value = (String)requestParams.get(key);
                text += "; " + key + " = " + value;
            staticText1.setText(text);That works as expected when you reach that new page via a hyper link.
    The session object is also the same as in your `old' window. So be careful about synchronization!
    I hope this helps.
    -- Marco

  • Passing User Parameters through Run_Report_Object

    hi,
    How to pass multiple user parameters through run_report_object.example i have to pass 20 parameters, have i write 20 statements? is there any way to come in single statement.i am using Forms 6i.
    thks in advance,

    A parameter list can be the second parameter of RUN_REPORT_OBJECT,
    rjob := RUN_REPORT_OBJECT(rep_id,paramlist_id);
    Gerald Krieger

  • Passing multiple parameters between two report portlets on the same page

    Hi,
    I want to pass multiple parameters between two report portlets on the same page.
    I have been succussful passing a single parameter between two portlets. The
    following are the steps :
    (1) Created first report based on the query
    SELECT htf.anchor('http://192.168.0.84:7778/servlet/page?&_pageid=97&_dad=portal30&_schema=portal30&_mode=3&dept_code='||DEPTNO,DEPTNO) Department, ename FROM EMP;
    (2) Created 2nd report
    select * from EMP where DEPTNO = :dept_code
    (3) Added pl/sql code before display page on the 2nd report
    portal30.wwv_name_value.replace_value(
    l_arg_names, l_arg_values,
    p_reference_path||'.dept_code',portal30.wwv_standard_util.string_to_table2(nvl(g
    et_value('dept_code'),10)));
    (4) Created a page and added these reports as portlets.
    Sofar it works fine for one parameter (deptno) . Now I want to add one more
    parameter say empno to my first report query and would like to pass both the
    parameters deptno and empno to the 2nd report. Please tell me how to pass multiple parameters ?
    Thanks
    Asim

    Hi,
    You will have to do the same thing
    The select will be like this
    SELECT htf.anchor('http://toolsweb.us.oracle.com:2000/servlet/page?_pageid=97&_dad=mb&_schema=mybugs&_mode=3&dept_code='||DEPTNO||'&empno='||empno,DEPTNO) Department,ename
    FROM EMP
    In the additional plsql code do the same for empno like this
    mybugs.wwv_name_value.replace_value(l_arg_names,l_arg_values, p_reference_path||'.dept_code',mybugs.wwv_standard_util.string_to_table2(nvl(get_value('dept_code'),10)));
    mybugs.wwv_name_value.replace_value(l_arg_names,l_arg_values, p_reference_path||'.empno',mybugs.wwv_standard_util.string_to_table2(get_value('empno')));
    Thanks,
    Sharmila

Maybe you are looking for