What's the best way to use an enum to validate statuses

I am trying to write and use an enum to represent a status code and validate status code values. Ultimately the input data from another system and the database will be 1 or 2 i.e.the indexes and the java code will use the LIVE and CANCELLED when referring to the status. The code I have written
public class TestEntityStatus {
     private static EntityStatusImpl es;
     public static void main(final String args[]){
                es =  new EntityStatusImpl();  
                es.setStatusCode("1"); // valid test
                es.setStatusCode("3"); // invalid test
}The EntityStatusImpl class:
public class EntityStatusImpl {
    private String statusCode;
    public EntityStatusImpl() {
    public final String getStatusCode() {
        return statusCode;
    public final void setStatusCode(final String statusCode) {
         String allStsIndexesAsRegExpr = "[";                                                                                 //
            EntityStatus allStatuses [] = EntityStatus.values();                                                     // would like to 
            for(EntityStatus e : allStatuses)                                                                                // put this code
                allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + e.getStatusCode();   // in the enum
            allStsIndexesAsRegExpr = allStsIndexesAsRegExpr + "]";                                        // EntityStatus
            System.out.println(" allStsIndexesAsRegExpr = " + allStsIndexesAsRegExpr);           //
             if (statusCode.matches(allStsIndexesAsRegExpr)) {
                 this.statusCode = statusCode;          
             else {
                  throw new IllegalArgumentException("Entity status " + statusCode + " is invalid");     
}The EntityStatus enum has a method "getAllIndexesAsRegex" which I would like to call. However, my understanding of enums is preventing me from doing so.
If I declared an EntityStatus, I expected that I would be able to get all of the indexes back as follows in
EntityStatus x;
x.getAllIndexesAsRegex();
Instead I have to copied the code from the enum into the setStatusCode method above, where it works but does not seem to be in the right place.
public enum EntityStatus {
                 LIVE(1), CANCELLED(2);
                 private int index;
             private EntityStatus(int index) {
                 this.index = index;
              public int getStatusCode(){
                       return index; 
              public String getAllIndexesAsRegex(){
                   String output = "[";
                   PromiseStatus allStatuses [] = PromiseStatus.values();
                   for(PromiseStatus p : allStatuses)
                        output = output + p.getStatusCode();
                   output = output + "]";
                   return output;
     }The java tutorial doesn't seem to throw much light on this type of application of enums for me, neither does Herbert Schilt's excellent book on Java 5.
Can anyone spot any flaws in my logic or suggest better ways of achieving this?

If you want to ensure type safety and retrict the user to a range of values it seems to me you are over complicating
the implementation. Simply change your Impl class accessor and mutator methods to accept and return the enum
type respectively. For example:
private EntityStatus entityStatus;
public EntityStatus getEntityStatus()
   return entityStatus;
public void setEntityStatus(EntityStatus entityStatus)
  if (entityStatus == null)
    throw new IllegalArgumentException("Invalid entity status!");
  this.entityStatus = entityStatus;
}The one downside is that you are retrieving the actual underlying enum values from external source systems which you need to map back to your
enum types. Unfortunately the Enum class does not have a method that will return what you need (the valueOf method returns the enum type
based on the enum name). However you can provide a method in your enum class that will map the external source values to the enum. Below is
one such implemetation.
import java.util.HashMap;
import java.util.Map;
public enum EntityStatus
  LIVE("1"),
  CANCELLED("2");
  private String statusCode;
  private static Map<String,EntityStatus> enumMap = new HashMap<String,EntityStatus>(EntityStatus.values().length);
  static
    enumMap.put(LIVE.getStatusCode(),LIVE);
    enumMap.put(CANCELLED.getStatusCode(),CANCELLED);
  private EntityStatus(String statusCode)
    this.statusCode = statusCode;
  public String getStatusCode()
    return statusCode;
  public static synchronized EntityStatus deriveObject(String statusCode)
    return enumMap.get(statusCode);
}Below is a usage example:
  public static void main(String args[])
    EntityStatus status1 = EntityStatus.deriveObject("1");
    EntityStatus status2 = EntityStatus.deriveObject("2");
    EntityStatus status3 = EntityStatus.deriveObject("3");
    System.out.println(status1);
    System.out.println(status2);
    System.out.println(status3);
  }

Similar Messages

  • What is the best way to use a cellular enabled iPad in France?

    What is the best way to use a cellular enabled iPad in France?

    Frankly, I expect a bit more courtesy and details from someone wanting help from fellow users.
    Don't use your AT&T SIM/plan out of the country for the iPad.
    Just purchase a SIM in France for about 15 euros and use that.
    -> http://www.tripadvisor.com/ShowTopic-g187070-i12-k4781004-o30-Prepaid_French_3G_ micro_SIM_for_iPad_it_s_not_a_problem-France.html

  • What's the best way to use your iPad instead of textbooks?

    What's the best way to use your iPad instead of textbooks? I'm about to start a BSN program and have heard of using your iPad for textbooks instead of buying and carrying around 8 different books. Is there an app for that? Or do you buy or rent the books? What's the best solution?

    Or, if you're like me and you want to do a lot of heavy reading, use the iPad because the low contrast on a Kindle is extremely fatiguing.  
    Seriously, though "screen glare will cause eye strain" is often taken as an article of faith, there's not a lot of good scientific evidence for it. "Eye strain" can be caused by concentrating on any close work for long periods of time. Looking up and focusing on something distant periodically is very helpful. Older CRT screens that flicker also can be aggravting. I'm not denying that some people find reading backlit screens uncomfortable. However, it's not dangerous. And, then, there are other people who find the higher contrast a backlit screen affords to be much less wearying over long periods of time.

  • What is the best  way for using a  C++ in the EJB?

    What is the best way for using C++ in the EJB ie
    either 1. Socket programming
    2. JNI

    To what purpose?
    To use C++ in the client you could generate IDL from your remote interfaces and run that through your vendor's IDL-to-C++ processor.

  • What is the best way to use Berkeley DB, C or C++ interface ?

    Hello,
    I'm using C++ interface but much samples, solutions and utils are in C.
    What is the best way to use Berkeley DB, C or C++ interface ?
    Lets talk a little about this...which is the interface you prefer and why ?
    Thanks
    DelNeto

    Hi DelNeto,
    There is a complete documentation set for C, C++ and Java. There are also examples in all 3 languages in the examples directories in your kit.
    http://www.oracle.com/technology/documentation/berkeley-db/db/index.html
    Ron

  • What is the best way to use recovery files

    I am working in FM 11 and have crashed FM a few times. What is the best way to use the recovery files and save them as the normal file? Then should I filter an explorer window for "recovery" so FM won't keep asking me if I want to use older recovery files? Thanks for your help.

    > What is the best way to use the recovery files ...
    Use a .recover file to extract only the new/changed content that would otherwise be lost if you were instead to open the .auto (if any), or .backup files.
    > ... and save them as the normal file?
    Don't. If the document crashed because of an internal data structure problem, the .recover file (although actually a MIF) is apt to contain that problem.
    Before doing anything, preserve the debris. Copy the .backup and .auto files in particular, because as soon as you open the main .fm file, it's going to overwrite that .backup, and then the .auto at the next auto-save interval. You can dispose of any zero-length files or files with temporary names (which result from the crash itself crashing).
    I typically:
    preserve a snapshot of the debris
    open the original file, and if it won't, the .backup
    open the .recover, .auto or .backup (whichever seems the most useful candidate as a sourcing file)
    copy in the changes from the .recover, .auto or .backup to the working copy
    save the working copy as the original.fm, close the sourcing file
    do a MIF wash on the new original.fm
    clean up the debris in preparation for the next crash

  • What is the best way to use Airport Express?

    What is the best way to use Airport Express?

    It would really depend on your networking goals.
    The AirPort Express can be used for a number of things:
    Internet router
    Wireless Access Point
    Ethernet switch
    Wireless Ethernet bridge
    Network print server
    AirPlay speaker
    Portable travel router
    ... or some combination of the above.

  • What is the best way to use wi-fi to transfer pdf files from an ipad to a mac mini, not using an internet, just wi-fi.

    What is the best way to use wi-fi to transfer pdf files from an ipad to a mac mini, not using an internet, just wi-fi?

    If the Mac use Lion (10.7) you can use Airdrop for that.
    With Mac's not using Lion you may set up a computer to computer (ad hoc) connection.
    How to --> http://docs.info.apple.com/article.html?path=Mac/10.6/en/8339.html
    Lupunus

  • What is the best way to use a SSD for Photoshop/photo editing?

    Computer hardware newbie here: I do a significant amount of photo editing work and for a very long time I've experienced Photoshop, Bridge and Photomatix crashing constantly (usually due to insufficient RAM) or just generally taking forever (Bridge took forever to load the thumbnail/preview extractions in a folder full of images, Photoshop took forever to save images and Photomatix took ages to load/merge a set of bracketed photos).  Here are the typical error messages I'd get: http://pastebin.com/J9byczse
    As a professional photographer, constantly running into that sort of thing is quite aggravating, so to hopefully avoid ever having to deal with that again I invested in a new custom built computer.  It's Windows 7 Professional 64 bit with 32GB of RAM and a 240GB SSD; I'm using the 240GB SSD as my boot drive/OS, all of my programs are installed there, and the page file.  My photos and data are stored on several HDDs.  I have yet to install any of my photo editing software (Photoshop CS6 Extended, Lightroom, Photomatix etc) to the new computer yet since I'd like some advice first.
    My basic question is this: what is the best way to take advantage of the SSD (and the computer in general) when it comes to my photo editing software?
    Specifically...
    1. If I have a folder of photos I'm working on, should I move it to the SSD and then work on them from there in order to take advantage of the speed of the SSD?  Would this make any difference in terms of speed if the photos are located on the SSD vs. an internal/external HDD?
    2. Most of what I've read online seems to recommend two separate SSDs, one for installing/booting the apps and one for cache/scratch.  Does it matter if I use my 240GB SSD for both?
    3. This is a fairly new computer and the SSD is already almost half full (102GB used, 120GB free) *WITHOUT* any of my photo editing software installed yet.  I'm concerned about how fast that remaining 120 GB may fill up.  As it fills up will I lose the speed advantage of the SSD vs. a regular HDD?
    4. Sort of similar to #3, but should I bother moving any of my other non-photo editing programs/caches off of the SSD to a HDD and would there be any major difference in the speed/lifespan of the SSD if I did so?  It's mostly Firefox and Chrome and their caches that I'm concerned may be a problem if they remain on the SSD.
    Thanks for any help!

    If you have an SSD you can run the cache and programs on the same drive.  However, many recommend a scratch disk size of 100-200 gigs so that will not work here unless you opt for a larger SSD.  Otherwise an internal spinner is recommended that does not contain the program files, or idealy any other files that may want to get acessed at same time (only one read/write head per drive).
    With 32 gig of RAM you may not need the constant use of the scratch drive unless working on large images with lots of layers.  So see no advantage to moving folder to SSD for temp work environment.
    From what I read the new crop of SSD do not have the wear problems of the older versions.

  • What is the best way to use single shot drum sounds?

    I have a huge collection of wav. format single sound drum sounds that I use in FL Studio. What is the best way to program drums in GB using them besides buying iDrum? I like the flexibility of using drums from different kits when I make my music so I kind of get board using a preset drum kit from GB even layering 3-4 kits isn't as nice as choosing each individual drum sound.

    Would be great to have more info but on a 24fps timeline with 24fps footage, you can simply right click and change the speed/duration to whatever. It'll be more jittery than smooth 60fps slow-mo. If your footage is shot at 60fps and you are editing on a 24fps timeline, just select the clip and right-click and choose MODIFY>Interpret footage and change the fps to 23.976 and you're done. Now when you drop that clip on the timeline it's in smooth slow-mo. Or, you can just toss the original clip on the timeline and change the speed/duration setting to 40%. Pretty much the same thing although the former is better if you need to add any warp stabilization to the clip. Anything you want to speed back up you can either duplicate the clip in the project panel and change it back to the original frame rate OR you can simply adjust it on the timeline to 250% speed which is back to normal. Good luck!

  • What is the best way to use EJB modules with JAX-WS?

    Hi.
    I am doing a project that returns EAN13 encoded data to external java clients.
    I think I need to use a webservice that send response, a webservice client that send the request, and other project that transforms a data to an EAN encoded data, returns it and store it in MySql database.
    It is possible that I need to authenticate users for every request made.
    -I have created a EJB module contained into Glassfish for the webservice
    -I have created a Common Java project with 3 layers: Entities, bussines and data access layer for mysql database
    -I have a project for the webservice client with JAX-WS ( is the best choice? or Would be better JAX-RPC? )
    **How would you suggest me create the structure of the project with all the java power?*
    **Could you help me with goods tutorial of design patterns about webservices using EJB and the best way for use databases for this kind of projects ( I have heard about JNDI, Hibernate, Session EJB, ... )?*
    **Would be better use other EJB module instead of a Common java project that has classes?*
    h3. {color:#333399}I shall be pleased with your help{color}

    Kappy is dead on correct about Bridge Mode as a requirement for the Time Capsule.
    Do you know how to check to see if the Time Capsule is configured this way?
    Next question.....you really should not try to have two wireless networks....one Arris and another Time Capsule.....unless it is absolutely necessary. Two wireless routers in close proximity can create wireless interference effects that can cause problems with either...or both...networks.
    Best to turn off the wireless on one router to keep the chances of wireless interference between routers minimized.
    Are both the Arris and Time Capsule providing wireless signals?

  • 1163R... What is the best way to use the 1163R.

    I need to record voltage on the SCXI 1121 as soon as the 1163R is switched. What is the best way to do this.

    Hi,
    You may want to take a look at following:
    Link 1
    Link 2
    I know my answer is very general. You may want to elaborate on your question and I will try my best.
    Sincerely,
    Sastry

  • What is the best way to use Swing GUIs in an MVC design?

    I have a question on how to build an application using swing frames for the UI, but using an MVC architecture. I've checked the rest of the forum, but not found an answer to my question that meets my needs.
    My application at this stage presents a login screen to get the userid and password, or to allow the user to choose a new locale. If an Enter action is performed, the userid and password are checked against the DB. If not accepted, the screen is repainted with a "try-again" message. If the Cancel action is performed, the process stops. If a locale action is performed, the screen is repainted with different langauge labels. Once the login process is passed, a front screen (another swing frame) is presented.
    Implementation: I am using a session object (Session, represents the user logging in) that calls the Login screen (LoginGUI, a Swing JFrame object with various components). Session uses setters in LoginGUI to set the labels, initial field entries etc, before enabling the screen. From this point, the user will do something with the LoginGUI screen - could be closing the window, entering a mix of userid and password, or maybe specifying a locale. Once the user has taken the action, if required, the session object can use getters to retrieve the userid and password values entered in the fields.
    The crux of the problem is 1) how will Session know that an action has been taken on the LoginGUI, and 2) how to tell what action has been taken.
    This could be solved by getting LoginGUI to call back to Session, however, I am trying to buid the application with a good separation of business, logic and presentation (i.e MVC, but not using any specific model). Therefore, I do not want LoginGUI to contain any program flow logic - that should all be contained in Session.
    I am aware of two possible ways to do this:
    1. Make LoginGUI synchronised, so that Session waits for LoginGUI to send a NotifyAll(). LoginGUI could hold a variable indicating what has happened which Session could interrogate.
    2. Implement Window Listener on Session so that it gets informed of the Window Close action. For the other two actions I could use a PropertyChangeListener in Session, that is notified when some variable in LoginGUI is changed. This variable could contain the action performed.
    Has anyone got any comments on the merits of these methods, or perhaps a better method? This technique seems fundamental to any application that interfaces with end-users, so I would like to find the best way.
    Thanks in advance.

    Hi,
    I tried to avoid putting in specific code as my question was more on design, and I wanted to save people having to trawl through specific code. And if I had any school assignments outstanding they would be about 20 years too late :-). I'm not sure computers more sophisticated than an abacus were around then...
    Rather than putting the actual code (which is long and refers to other objects not relevant to the discussion), I have put together two demo classes to illustrate my query. Comments in the code indicate where I have left out non-relevant code.
    Sessiondemo has the main class. When run, it creates an instance of LoginGUIdemo, containing a userid field, password field, a ComboBox (which would normally have a list of available locales), an Enter and a Cancel box.
    When the Locale combo box is clicked, the LoginGUIdemo.userAction button is changed (using an ActionListener) and a property change is fired to Session (which could then perform some work). The same technique is used to detect Enter events (pressing return in password and userid, or clicking on Enter), and to detect Cancel events (clicking on the cancel button). Instead of putting in business code I have just put in System.out.printlns to print the userAction value.
    With this structure, LoginGUIdemo has no business logic, but just alerts Sessiondemo (the class with the business logic).
    Do you know any more elegant way to achieve this function? In my original post, I mentioned that I have also achieved this using thread synchronisation (Sessiondemo waits on LoginGUI to issue a NotifyAll() before it can retrieve the LoginGUI values). I can put together demo code if you would like. Can you post any other demo code to demonstrate a better technique?
    Cheers,
    Alan
    Here's Sessiondemo.class
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.beans.*;
    public class Sessiondemo implements PropertyChangeListener {
        private LoginGUIdemo lgui;   // Login screen
        private int localeIndex; // index referring to an array of available Locales
        public Sessiondemo () {
            lgui = new LoginGUIdemo();
            lgui.addPropertyChangeListener(this);
            lgui.show();
        public static void main(String[] args) {
            Sessiondemo sess = new Sessiondemo();
        public void propertyChange(java.beans.PropertyChangeEvent pce) {
            // Get the userAction value from LoginGUI
            String userAction = pce.getNewValue().toString();
            if (userAction == "Cancelled") {
                System.out.println(userAction);
                // close the screen down
                lgui.dispose();
                System.exit(0);
            } else if (userAction == "LocaleChange") {
                System.out.println(userAction);
                // Get the new locale setting from the LoginGUI
                // ...modify LoginGUI labels with new labels from ResourceBundle
    lgui.show();
    } else if (userAction == "Submitted") {
    System.out.println(userAction);
    // ...Get the userid and password values from LoginGUIdemo
                // run some business logic to decide whether to show the login screen again
                // or accept the login and present the application frontscreen
    }And here's LoginGUIdemo.class
    * LoginGUIdemox.java
    * Created on 29 November 2002, 18:59
    * @author  administrator
    import java.beans.*;
    public class LoginGUIdemo extends javax.swing.JFrame {
        private String userAction;
        private PropertyChangeSupport pcs;
        /** Creates new form LoginGUIdemox */
        // Note that in the full code there are setters and getters to allow access to the
        // components in the screen. For clarity they are not included here
        public LoginGUIdemo() {
            pcs = new PropertyChangeSupport(this);
            userAction = "";
            initComponents();
        public void setUserAction(String s) {
            userAction = s;
            pcs.firePropertyChange("userAction",null,userAction);
        public void addPropertyChangeListener(PropertyChangeListener l) {
            pcs.addPropertyChangeListener(l);
        public void removePropertyChangeListener(PropertyChangeListener l) {
            pcs.removePropertyChangeListener(l);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.FlowLayout());
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTextField1.setText("userid");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField1);
            jTextField2.setText("password");
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField2);
            jComboBox1.setToolTipText("Select Locale");
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    LocaleActionPerformed(evt);
            getContentPane().add(jComboBox1);
            jButton1.setText("Enter");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton2.setText("Cancel");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    CancelActionPerformed(evt);
            getContentPane().add(jButton2);
            pack();
        private void LocaleActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("LocaleChange");
        private void CancelActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Cancelled");
        private void EnterActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Submitted");
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new LoginGUIdemo().show();
        // Variables declaration - do not modify
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton1;
        // End of variables declaration

  • What is the best way to use Sharepoint to manage rotations of responsibilities?

    What would be the best way to manage rotations of responsibilities in SharePoint (2013, cloud)?   We have several such cases where we rotate people taking turns (sometimes overlapping and more than one at a time and other times not)
    - just a simple document or simple list or other good ideas? 

    Thank you - I'll give an analogy that may help to see if you still think the type of list you descried may be best.
    If you think of a school system where there is a rotation of teachers required to cover sports events:
    There exists a list of teachers in the order that they would normally be assigned
    Certain events have special rules (night football game requires 3 teachers to be assigned)
    Holiday events are "burdensome duty" and so past holiday coverage is noted and try to avoid repeat person on holidays.
    Each year the admin would look at those factors and assign out coverage for the semester and then update the list with what occurred.  The next semester, the admin would fill out the next assignment on the calendar factoring in what occurred last time
    and new teachers, etc.
    I think a given semester's calendar is easy to visualize what to do in SharePoint - the list used to build that each semester is harder for me to picture how to maintain/display (for transparency sake).
    Thanks!

  • What is the best way to use STACKS?

    I want to be able to use this function but I have yet to read anything that will teach me the best way to go about using this function.
    I hear people's suggestions for how to make it better, I hear complaints about not liking it at all, but I have yet to hear how to make use of what is there.
    Does anyone have any useful suggestions of how I might use STACKS to aid in my everyday organization of information/files/applications?
    Thanks in advance for your assistance.

    Honestly? It's very difficult (for me) to think of a way to use Stacks productively. If you have relatively few items in the folders that you keep in the Dock, and know with a high degree of accuracy which items are in those folders, AND you tend not to nest folders within other folders, you'll probably find Stacks to be fairly useful (or at least not much of a detriment).
    The real value of Stacks (in my opinion) lies in a feature that has been left out of the current release of Leopard. As I understand it, previous versions allowed you to create Stacks of your own, by bringing files and folders from different locations together into a Stack, which you could then place on your Desktop or in the Dock or somewhere else entirely. That kind of cross-location organization would be very powerful.
    But (at the moment) Stacks are simply a different and less-powerful way to browse folders, and they only exist in the Dock; so there's not very much to take advantage of, unless you're already working in such away that Stacks' limitations aren't confining to you.

Maybe you are looking for