Using a static wrapper method to access session

Hello,
I'm attempting to develop a utility class comprised of static convenience methods that will access the different scopes. Given the fact that the methods are static, will this pose any risk in a multi-threaded environment? See example below. Thanks.
public static void setSessionObject(HttpServletRequest req, String attrName,
               Object object) {
          HttpSession session = req.getSession(false);
          if (session != null) {
               session.setAttribute(attrName, object);
     }

What happens if two instances call this method simultaneously? Would it be possible to set the wrong attribute in the wrong session?

Similar Messages

  • Static Classes/Methods vs Objects/Instance Classes/Methods?

    Hi,
    I am reading "Official ABAP Programming Guidelines" book. And I saw the rule:
    Rule 5.3: Do Not Use Static Classes
    Preferably use objects instead of static classes. If you don't want to have a multiple instantiation, you can use singletons.
    I needed to create a global class and some methods under that. And there is no any object-oriented design idea exists. Instead of creating a function group/modules, I have decided to create a global class (even is a abstract class) and some static methods.So I directly use these static methods by using zcl_class=>method().
    But the rule above says "Don't use static classes/methods, always use instance methods if even there is no object-oriented design".
    The book listed several reasons, one for example
    1-) Static classes are implicitly loaded first time they are used, and the corresponding static constructor -of available- is executed. They remain in the memory as long as the current internal session exists. Therefore, if you use static classes, you cannot actually control the time of initialization and have no option to release the memory.
    So if I use a static class/method in a subroutine, it will be loaded into memory and it will stay in the memory till I close the program.
    But if I use instance class/method, I can CREATE OBJECT lo_object TYPE REF TO zcl_class then use method lo_object->method(), then I can FREE  lo_object to delete from the memory. Is my understanding correct?
    Any idea? What do you prefer Static Class OR Object/Instance Class?
    Thanks in advance.
    Tuncay

    @Naimesh Patel
    So you recommend to use instance class/methods even though method logic is just self-executable. Right?
    <h3>Example:</h3>
    <h4>Instance option</h4>
    CLASS zcl_class DEFINITION.
      METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    <h4>Static option</h4>
    CLASS zcl_class DEFINITION.
      CLASS-METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      CLASS-METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
    zcl_class=>add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
    zcl_class=>subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    So which option is best? Pros and Cons?

  • Static factory methods, instead of constructor

    Hi All,
    why we use static factory methods, instead of constructor.
    Apart from Singleton class , what is use of static factory methods ?
    Thanks in Advance,
    Rishi

    One reason for using factories is that they simplify creating instances of immutable classes that might otherwise have messy constructors with lots of arguments.

  • Use of synchronized in constructor for accessing static SimpleDateFormat

    Just a little confused. I have
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    in my class. I made dateFormat static final, because its a costly operation that I dont want to do more than once. I access dateFormat in the constructor of my class to format a date. Since SimpleDateFormat is not threadsafe, my understanding is the access has to happen in synchronized block to ensure thread-safety, as follows
    public MyClass (date) {
    synchronized(dateFormat) {
    dateFormat.format(new Date());
    Is that right? I know that constructors dont need to be synchronized because they are object creations, hence cant have multiple threads stepping on one another. But since dateFormat is a static field, doesnt it need to be protected, inspite of the above argument? Would appreciate responses/comments. Thanks

    this constructor constructs a log record and uses the dateformatter to add timestamp to the log. It is executed very frequently. My tests indicate that using a static dateformatter is better performing than using a new formatter per thread. I am including the results below. 'u method' stands for unsynchronized (new formatter for each thread) and 's method' for synchronized (with static formatter)
    run completed, took [ 10] milliseconds to format date, using 'u method' for [ 1] threads
    run completed, took [ 0] milliseconds to format date, using 's' method for [ 1] threads
    run completed, took [ 10] milliseconds to format date, using 'u method' for [ 10] threads
    run completed, took [ 0] milliseconds to format date, using 's' method for [ 10] threads
    run completed, took [ 40] milliseconds to format date, using 'u method' for [ 50] threads
    run completed, took [ 30] milliseconds to format date, using 's' method for [ 50] threads
    run completed, took [ 70] milliseconds to format date, using 'u method' for [ 100] threads
    run completed, took [ 40] milliseconds to format date, using 's' method for [ 100] threads
    run completed, took [ 260] milliseconds to format date, using 'u method' for [ 500] threads
    run completed, took [ 170] milliseconds to format date, using 's' method for [ 500] threads
    run completed, took [ 491] milliseconds to format date, using 'u method' for [ 1000] threads
    run completed, took [ 310] milliseconds to format date, using 's' method for [ 1000] threads
    run completed, took [ 1793] milliseconds to format date, using 'u method' for [ 5000] threads
    run completed, took [ 1472] milliseconds to format date, using 's' method for [ 5000] threads
    run completed, took [ 3164] milliseconds to format date, using 'u method' for [ 10000] threads
    run completed, took [ 2524] milliseconds to format date, using 's' method for [ 10000] threads
    run completed, took [ 14571] milliseconds to format date, using 'u method' for [ 50000] threads
    run completed, took [ 12819] milliseconds to format date, using 's' method for [ 50000] threads
    run completed, took [ 28050] milliseconds to format date, using 'u method' for [ 100000] threads
    run completed, took [ 25107] milliseconds to format date, using 's' method for [ 100000] threads

  • Should I use a static method or an instance method?

    Just a simple function to look at a HashMap and tell how many non-null entries.
    This will be common code that will run on a multi-threaded weblogic app server and potentially serve many apps running at once.
    Does this have to be an instance method? Or is it perfectly fine to use a static method?
    public static int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    OR
    public int countNonNullEntries(HashMap hm){
    if(hm==null)return 0;
    int count=0;
    for(int i=0; i<hm.size(); i++) {
    if(hm.get(i)!=null)
    { count++;}
    return count;
    }

    TPD Opitz-Consulting com wrote:
    The question is the other way around: Is there a good reason to make the method static?
    Ususally the answer is: no.The question is: does this method need state? Yes -> method of a class with that state. No -> static.
    The good thing of having this method statig is that it meight decrese memory foot pring but unless you're facing memory related problem you should not think about that.I doubt there is any difference between the memory foot print of a static or not method.
    I'm not shure if this method beeing static maks problems in multithreaded environments like the one you're aiming at. But I do know that an immutable object is always thread save.Does the method use shared state (data)? No -> no multi threaded problems.
    Can the parameters be modified by different threads? Yes, if multiple threads modified the parameter map, but nothing you can do about it here (no way to force the calling thread to lock on whatever you lock on).
    So my answer to your question is: yes, it should be non static.The method should be static since it uses no state.
    It is thread-safe when only the calling thread can modify the passed map (using a synchronized or ConcurrentHashMap is not enough, since you don't call a single atomic method on the map).
    // Better use Map instead of HashMap
    // We don't care about the generic type, but that does not mean we should use a raw type
    public static int countNonNullEntries(Map<?, ?> map) {
      // whether to accept null map or not, no need for explicit exception
      // since next statement throw NPE anyway
      Collection<?> values = map.values();
      // note your method is called countNonNull, not countNull!
      // (original code it would need to by if(null != mapValue) notNullsCounter++;
      return values.size() - java.util.Collections.frequency(values, null);
    }

  • Use of 'static' keyword in synchronized methods. Does it ease concurrency?

    Friends,
    I have a query regarding the use of 'synchronized' keyword in a programme. This is mainly to check if there's any difference in the use of 'static' keyword for synchronized methods. By default we cannot call two synchronized methods from a programme at the same time. For example, in 'Program1', I am calling two methods, 'display()' and 'update()' both of them are synchronized and the flow is first, 'display()' is called and only when display method exits, it calls the 'update()' method.
    But, things seem different, when I added 'static' keyword for 'update()' method as can be seen from 'Program2'. Here, instead of waiting for 'display()' method to finish, 'update()' method is called during the execution of 'display()' method. You can check the output to see the difference.
    Does it mean, 'static' keyword has anything to do with synchronizaton?
    Appreciate your valuable comments.
    1. Program1
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    end display:
    start update:
    end update:
    2. Program2
    package camel.java.thread;
    public class SynchTest {
         public synchronized void display() {
              try {
                   System.out.println("start display:");
                   Thread.sleep(7000);
                   System.out.println("end display:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static synchronized void update() {
              try {
                   System.out.println("start update:");
                   Thread.sleep(2000);
                   System.out.println("end update:");
              } catch (InterruptedException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              System.out.println("Synchronized methods test:");
              final SynchTest synchtest = new SynchTest();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.display();
              }).start();
              new Thread(new Runnable() {
                   public void run() {
                        synchtest.update();
              }).start();
    Output:
    Synchronized methods test:
    start display:
    start update:end update:
    end display:

    the synchronized method obtain the lock from the current instance while static synchronized method obtain the lock from the class
    Below is some code for u to have better understanding
    package facado.collab;
    public class TestSync {
         public synchronized void add() {
              System.out.println("TestSync.add()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.add() - end");          
         public synchronized void update() {
              System.out.println("TestSync.update()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.update() - end");          
         public static synchronized void staticAdd() {
              System.out.println("TestSync.staticAdd()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticAdd() - end");
         public static synchronized void staticUpdate() {
              System.out.println("TestSync.staticUpdate()");
              try {
                   Thread.sleep(2000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              System.out.println("TestSync.staticUpdate() - end");
         public static void main(String[] args) {
              final TestSync sync1 = new TestSync();
              final TestSync sync2 = new TestSync();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.add();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.update();
              }).start();
              try {
                   Thread.sleep(3000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              new Thread(new Runnable(){
                   public void run() {
                        sync1.staticAdd();
              }).start();
              new Thread(new Runnable(){
                   public void run() {
                        sync2.staticUpdate();
              }).start();
    }

  • When a static method is accessed concurrently

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

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

  • ISE 1.2 Guest Access session expired

    We have set up the ISEs to allow wired guest users to logon with CWA but every time we get
    "Your session has expired. Sign on again".
    We successfully get to the portal and can logon, change password, accept conditions but then we just get the session expired page.
    From the switch (some data redacted fro privacy):
    sw01#sh auth ses int f0/1
                Interface:  FastEthernet0/1
              MAC Address:  0021.xxda.xx28
               IP Address:  xxx.xx.40.45
                User-Name:  00-21-xx-DA-xx-28
                   Status:  Authz Success
                   Domain:  DATA
           Oper host mode:  multi-domain
         Oper control dir:  both
            Authorized By:  Authentication Server
              Vlan Policy:  901
                  ACS ACL:  xACSACLx-IP_GuestWired_ISE_Portal_Access-53182da8
         URL Redirect ACL:  dot1x_WEBAUTH-REDIRECT
             URL Redirect:  https://guest.ourdomain.com:8443/guestportal/gateway?sessionId=AC1262FB000000FA0FCEFDB8&portal=TT_GuestPortal&action=cwa
          Session timeout:  N/A
             Idle timeout:  N/A
        Common Session ID:  AC1262FB000000FA0FCEFDB8
          Acct Session ID:  0x000001CF
                   Handle:  0x370000FB
    Runnable methods list:
           Method   State
           dot1x    Failed over
           mab      Authc Success
    The ISE reports a failed login
    Event
    5418 Guest Authentication Failed
    Failure Reason
    86017
    Now the reason appears to be that the guest portal being accesed is on an ISE in our DMZ but the RADIUS/MAB authentication is done by our internal ISEs (all ISEs are part of the same cluster however).  This is because the NAD is a switch and its management interface is on the inside of the network while  the guest VLAN is in a DMZ.  If we authenticate the RADIUS and guest on the same ISE (by breaking routing/security) then the access is granted and it all works corrcetly.
    We are summarising that the session ID sent by the RADIUS ISE server is not avaialble to the Guest Portal ISE server so the session ID does not exist in the session cache.
    So does the  guest portal ISE server have to be the same ISE server that does the RADIUS/MAB session generation?  There is no obvious way to tie a FQDN (e.g. guest.ourdomain.com) to the ISE used by the NAD.
    Should the session ID not be shared across all enforcement nodes?
    Any other ideas or thoughts?
    Chris Davis

    Thanks Jan, do you know if this is by design, even across nodes in node groups?  I'm guessing that Bug CSCul10677 is the same issue.
    Thing is, it rather makes the CWA static IP/Hostname option redundant/useless in a resilient configuration.  It also means that the NAD must use the guest network for dot1x traffic or that the guest nework must be able to route over/into the internal network neither of which appear to be ideal from a security perspective...

  • Should we try to access session scope in ADF BC ?

    hi
    In the blog post "How to Access Session Scope in ADF BC "
    at http://andrejusb.blogspot.com/2012/01/how-to-access-session-scope-in-adf-bc.html
    Andrejus Baranovskis suggests it is no problem to access session scope in ADF BC using
    Map sessionScope = ADFContext.getCurrent().getSessionScope();But I wonder if this is really a good practice, as it looks very much like breaking the MVC pattern.
    At the same time I wonder where the Oracle documentation says this would be a good or bad idea.
    One starting point could be the ADFContext.getCurrent() method
    at http://docs.oracle.com/cd/E24382_01/apirefs.1112/e17486/oracle/adf/share/ADFContext.html#getCurrent%28%29
    that starts with saying "Gets the ADF context for the current thread. ..." which in a typical deployment scenario of ADF BC might not cause a problem.
    But, I wonder how defensive your programming should be when using the getSessionScope() method in your ADF Business Component code (that implements the Model).
    Ideas and feedback welcome.
    many thanks
    Jan Vervecken

    Hi Shay,
    Reviewing ADFContex methods it seems that this object shouldn't be accessible from BC. Example:
    public static ADFContext initADFContext(java.lang.Object context,
                                            java.lang.Object session,
                                            java.lang.Object request,
                                            java.lang.Object response)
        Initializes the ADFContext for the environment of the specified context.
        Parameters:
            context - the ServletContext or PortletContext of the current execution environment.
            session - the HttpSession or PortletSession of the current execution environment. OPTIONAL.
            request - the HttpServletRequest or PortletRequest of the current execution environment. OPTIONAL.
            response - the HttpServletResponse or PortletResponse of the current execution environment. OPTIONAL.
        Returns:
            the ADFContext that was current when init was invoked. Should be passed back to resetADFContext after the block requiring the ADFContext has completed.Kuba

  • Calling Enity Bean's business methods from a session bean in EJB 3.0 specif

    Hello everybody,
    Happy to be a member with you in this forum.
    This is my first participation in this forum.
    I have some problem to start with EJB 3.0 specification, I have created an entity bean with some business methods that access a mysql datbase, then i want to create a stateful session bean to provide the client an interface to consume business methods in Enity be
    Please can someone you help me with an example

    @Vladimir Pavlov
    I did not understand what you are trying to convey...
    Whenever an attribute of this bean is modified we want to access that latest value.... Is there any way to know, when the attribute is modified? Just with get/set we can not know, when it is modified... am i right?
    We want to achieve this without modifying the existing source code of the EJB....
    @ Ivo Simeonov
    As of my knowledge, to use interceptors we need to modify the EJB source code, but we do not want to touch the source code....
    All this has to be achieved dynamically when the application is deployed in the production.... is it possible???

  • How do I access session data through an EJB?

    Hi
    How do I access session data through an EJB?
    I am currantly developing a Web service (using ejb's, JBoss.net and Apache Axis). A client making a call to this Web service, is expecting a bussiness-object in return. My problem is that this bussiness-object i stored in a users session data. How do I retrieve this bussiness-object from the users session.
    I have read that this does not work with httpsessions, is this true? If this is true, is it possible to store the bussiness object in a JavaBean e.g:
    <jsp:useBean id="userContextWebImpl" scope="session" class="com.ac.march.client.UserContextWebImpl">
    <%
    String key = "test";
    String value = "This is the value";
    userContextWebImpl.setValue( key, value1 );
    %>
    </jsp:useBean>
    and then retrieve this information through the EJB? Or is it possible to do this by using Statfull JavaBeans? Or can this be done through a nother solution?
    Please help!

    I have created a JavaBean with scope="application" to store some data. The data is stored when a user prefomes a spesific task.
    A different person then makes a call to a Web-Service on the server. The Web-Service then asks an EJB to retrieve the data stored in the JavaBean (servlet cotext). In other words: How do I retrieve this data from the EJB?
    I have tried with this code, but with no luck.
    (ApplicationContextWebImpl is the JavaBean)
    public static String getBookingResult( String key )
         String myResult = null;
         String myKey = key;
         ApplicationContextWebImpl applicationContextWebImpl = null;
         try
              applicationContextWebImpl = new ApplicationContextWebImpl();
              myResult = (String)applicationContextWebImpl.getValue( key );
         catch ( java.rmi.RemoteException e )
         return myResult;
    }

  • Static abstract methods - how can I avoid them?

    Hi everybody,
    just found out that java doesn't allow static abstract methods nor static methods in interfaces. Although I understand the reasons, I can't think of how to change my design to gain the required behavior without the need of static abstract methods.
    Here's what I want to do and how my thoughts lead to static abstract methods:
    ClassA provides access to native code (c-dll, using jna). The path to the dll can be set programmatically. Here's a draft of the class:
    public ClassA {
       private static String path;
       public static void setRealtivePath(String path) {
          //check if path exists and is not null -> get absolute path
          setPath(path);
       public static void setPath(String absolutePath) {
          this.path = path;
      //code to provide access to native lib
    }There is some more classes which provide access to different dlls (therefore the code for accessing the dlls differs from ClassA). Although this works, the setRelativePath method has to be implemented in each class. I thought it would be nice to put this method into a abstract super class that looks like this:
    public abstract class superClass {
       public static void setRelativePath(String path) {
          //check if path exists and is not null -> get absolute path
          setPath(path);
       //force inherting class to implement a static method
       public static abstract void setPath(String absolutePath);
    }thus simplifying ClassA and it's look-a-likes:
    public ClassA {
       private static String path;
       @Override
       public static void setPath(String absolutePath) {
          this.path = path;
      //code to provide access to native lib
    }Since static abstract methods (and overriding static methods) is not allowed, this doesn't work.
    I hope someone can catch my idea ;). Any suggestions how to do this in a nice clean way?
    Thanks in advance,
    Martin
    Edited by: morty2 on Jul 22, 2009 2:57 AM

    First of all, thanks a lot for your answer.
    YoungWinston wrote:
    Actually, you can "override" static methods (in that you can write the same method for both a subclass and a superclass, providing the superclass method isn't final); it's just that it doesn't work polymorphically. The "overriding" method masks the overridden one and the determination of what gets called is entirely down to the declared type.Yes, I know that. There's one problem: Your suggestion means that I simply have to drop the abstract modifier in the super classes setPath method. However, since the super class calls the setPath method (and not the inherting classes!) it will always be the super classes' method being called.
    YoungWinston wrote:
    Why are you so concerned with making everything static? Seems to me that the simplest solution would be to make all the contents instance-based.I want ClassA and it's look-a-likes to be set up properly at application start up, be accessible quite anytime and easily, they don't do anything themselves except for setting the path and calling into the native library which does the math. (Compareable to how you call e.g. Math.cos()). Therefore I don't think that an instance-based solution would be a better approach.
    YoungWinston wrote:
    Furthermore, you could make the class immutable; which might be a good thing - I'm not sure I'd want someone being able to change the pathname after I've >set up a class like this.Thanks for that!
    PS: As mentioned in my first post, I do have a working solution. However, I'm really corious about finding a nicer and cleaner way to do it!
    Martin

  • Using mutator and accessor methods in main.

    Would somebody explain to me exactly how mutator and accessor methods make a class and it's driver program work together. I understand the principle of encapsulation, but I'm obviously missing something. I get the syntax, but what actually happens? I'm hoping a fresh perspective on it will help me understand better.
    I guess another way to ask the question could be: how do you use accessor and mutator methods in the main program that calls them?

    >
    the assignment says to have a
    "reasonable set of accessor and mutator methods
    whether or not you use them". So in my case I have
    them written in the class but do not call them inthe
    driver program. And like I said, the program does
    what it's supposed to do.This class you're in worries me. I'm sure what
    polytropos said is true: they're trying to make you
    think about reuse. But adding to an API without cause
    is widely considered to be a mistake, and there are
    those who are strongly opposed to accessors/mutators
    (or worse, direct field access) on OOP design grounds.The class is based on the book Java: Introduction to Computer Science and Progamming, by Walter Savitch. Until now I've been pretty happy with it. Another problem, to me anyway, is that so far we've done a few, cumulative programming projects per chapter. This time, there was one assignment for the whole chapter that is suppsoed to incorporate everything. But that's just me complaining.
    Here is the code I have and that it looks like I'll be turning in... criticisms welcome.
    Here is the class:
    public class GradeProgram//open class
         private double quiz1;
         private double quiz2;
         private double mid;
         private double fin;
         private double finalGrade;
         private char letterGrade;
         public void readInput()//open readInput object
              do
                   System.out.println("Enter the total points for quiz one.");
                   quiz1 = SavitchIn.readLineInt();
                   System.out.println("Enter the total points for quiz two.");
                   quiz2 = SavitchIn.readLineInt();
                   System.out.println("Enter the mid term score.");
                   mid = SavitchIn.readLineInt();
                   System.out.println("Enter final exam score.");
                   fin = SavitchIn.readLineInt();
                   if ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0))
                   System.out.println("Quiz scores are between one and ten.  Re-enter scores");
                   if ((mid>100)||(fin>100)||(mid<0)||(fin<0))
                   System.out.println("Exam scores are between zero and one hundred.  Re-enter scores.");
              while ((quiz1>10)||(quiz2>10)||(quiz1<0)||(quiz2<0)||(mid>100)||(fin>100)||(mid<0)||(fin<0));
         }//end readInput object
         public void output()//open output object
              System.out.println();
              System.out.println("You entered:");
              System.out.println("Quiz 1: " + (int)quiz1);
              System.out.println("Quiz 2: " + (int)quiz2);
              System.out.println("Mid term: " + (int)mid);
              System.out.println("Final exam: " + (int)fin);
              System.out.println();
              System.out.println("Final grade: " + (int)percent() + "%");
              System.out.println("Letter grade: " + letterGrade());
         }//end output object
         public void set(double newQuiz1, double newQuiz2, double newMid, double newFin, double newFinalGrade, char newLetterGrade)
              if ((newQuiz1 >= 0)&&(newQuiz1 <= 10))
              quiz1 = newQuiz1;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newQuiz2 >= 0)&&(newQuiz2 <= 10))
              quiz2 = newQuiz2;
              else
                   System.out.println("Error: quiz scores are between zero and ten.");
                   System.exit(0);
              if ((newMid >= 0)&&(newMid <= 100))
              mid = newMid;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              if ((newFin >= 0)&&(newFin <= 100))
              fin = newFin;
              else
                   System.out.println("Error: exam scores are between zero and one hundred.");
                   System.exit(0);
              letterGrade = newLetterGrade;
         public double getQuiz1()
              return quiz1;
         public double getQuiz2()
              return quiz2;
         public double getMid()
              return mid;
         public double getFin()
              return fin;
         public char getLetterGrade()
              return letterGrade;
         private double finalPercent()//open finalPercent object
              double quizPercent = (((quiz1 + quiz2) /2) * 10) / 4;
              if (((((quiz1 + quiz2) /2) * 10) % 4) >= 5)
                   quizPercent++;
              double midPercent = mid / 4;
              if ((mid % 4) >= 5)
                   midPercent++;
              double finPercent = fin / 2;
              if ((fin % 2) >= 5)
                   finPercent++;
              finalGrade = (quizPercent + midPercent + finPercent);
              return (finalGrade);
         }//end final percent object
         private double percent()//open percent object - helping object
              double percentGrade = finalPercent();
              return (percentGrade);
         }//end percent object
         private char letterGrade()//open letterGrade object
              double letter = percent();
              if (letter >= 90)
                   return ('A');
              else if (letter >= 80)
                   return ('B');
              else if (letter >= 70)
                   return ('C');
              else if (letter >= 60)
                   return ('D');
              else
                   return ('F');
         }//end letterGrade object
         private double quizScore()//open quizScore object
              double quizes = ((quiz1 + quiz2) /2) * 10;
              return (quizes);
         }// close quizScore object
    }//end classAnd here is the driver program:
    public class GradeProgramDemo
         public static void main(String[] args)
              String cont;
              do
                   GradeProgram firstStudent = new GradeProgram();
                   firstStudent.readInput();
                   firstStudent.output();
                   System.out.println();
                   System.out.println("Enter more student grades?  Enter Y to continue");
                   System.out.println("or press enter to quit.");
                   cont = SavitchIn.readLine();
                   System.out.println();
              while (cont.equalsIgnoreCase("y"));

  • Accessing session variable in Flex.

    Hi All,
       I'm using RemoteObjects for accessing data and using Spring BlazeDS. How to retrieve 'session' variable values in Flex?
       Main application which is calling different .mxml files. It first invokes login(login.mxml) page with successful user credentials it will display home(home.mxml) page and I have search(search.mxml) pages.
        In case user session timeouts then I'd like to send user request to login page for login.(say user is in search page and where he left for 30 minutes, after then when user clicks anything on search page, it should redisplay login page because session timeout is set to (25 minutes).  How to do this Felx??
       Thanks in advance.
    Regards,
    Sharath.

    More detail solution will be found in the help.
    Look for the following string in your local help (in flex builder): Communicating with the Wrapper.
    You will probably find that you have to do something like the following:
    a) call from flex to the wrapper page javascript function.  (this would be a polling operation, run on a timer event (say) once every minute.
    b) the javascript function you call conducts an Ajax call to determine the current session state.
    Note that the above will likely keep your session state alive.
    Another possibility is to pass in the value of your session timeout via a FlashVars variable.
    Again, in a timer function run every minute, invcrement a local counter.
    When local counter equals session passed in, then you might assume that the session has timed out.
    IHTH.
    Cheers

  • [svn:osmf:] 10996: Changing MediaElementLayoutTarget to be constructed via a static ' getInstance' method, instead of by its constructor.

    Revision: 10996
    Author:   [email protected]
    Date:     2009-10-19 07:45:26 -0700 (Mon, 19 Oct 2009)
    Log Message:
    Changing MediaElementLayoutTarget to be constructed via a static 'getInstance' method, instead of by its constructor. This prevents the construction of multiple instances that reference one single media-element. Updating client code accordingly.
    Extending layout unit tests. Adding a custom renderer, checking calculation and layout passes invokation counts.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/composition/CompositeViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/ParallelViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/composition/SerialViewableTrait.as
        osmf/trunk/framework/MediaFramework/org/osmf/gateways/RegionSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/DefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutContextSprite.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/LayoutRendererBase.as
        osmf/trunk/framework/MediaFramework/org/osmf/layout/MediaElementLayoutTarget.as
        osmf/trunk/framework/MediaFramework/org/osmf/utils/MediaFrameworkStrings.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/TestParallelViewableTrai t.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/gateways/TestRegionSprite.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestDefaultLayoutRenderer.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestLayoutUtils.as
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/layout/TestMediaElementLayoutTarget. as
    Added Paths:
        osmf/trunk/framework/MediaFrameworkFlexTest/org/osmf/composition/CustomRenderer.as

    AlexCox, can you clarify that once you get the default model out and save it in the temp var, that your ONLY access to the data is then through temp and never through the JList methods?
    Quick question for everyone: Are any of you using JList.setListData to set you initial dataset? I think that is where the bug lies. When I do not use it and start with an empty list, I am able to add to that list, and then remove from that list using the following line:
    ((DefaultListModel)myList.getModel).remove(###);
    And this cast works everytime.
    But when I start that list out with some data such as:
    myList.setListData(myStringArray);
    and then try to execute the above line, boom! I get the ClassCast exception.
    I think setListData creates a whole new model which is an inner class to JList (which seems stupid when DefaultListModel seems made for this).
    Just my thoughts on where the problem lies. I'll add my data directly to the list and see if that works better.
    PK

Maybe you are looking for

  • TCP connection error when sending MODBUS commands to WAGO 750-881 controller after 113655 bytes of data have been sent

    Hi all, I am new to the world of labview and am attempting to build a VI which sends commands to a 750-881 WAGO controller at periodic intervals of 10ms.  To set each of the DO's of the WAGO at once I therefore attempt to send the Modbus fc15 command

  • Do_handle_event

    hi Experts,               i have writen a select query on the  event of button click in do_handle_event.but ,it gets activated,but while executing it gives me an exception error on select query line..... so where should i write the select query.... I

  • Restting the number ranges

    Client Copy: Each time a client copy is made, material movement postings cannot be processed until several number ranges are reset and the user gets the message Express document “update was terminated”. These number ranges can be reset thru SNRO. But

  • Query Network interface with C#

    Hello, I'm developing a C# winforms application under Windows server 2008 (64bit) Is there a way to query all network interfaces installed in the PC and check their IP address and if there is an ethernet connection (connected \ not connected) ? I wan

  • Can labview call a test stand module

    Having problems with a test dll that runs in test stand, but I get errors when trying to use the wizard in labview, however I can use the call library function node to protypye it.  Problem - the function openComserialPort(char* comPort, ErrStruct &