Tuesday, June 3, 2014

JPA Annotations and Migrating from SQLServer to Derby in unit tests: A debugging case study

Problem: 

Our service layer has a series of integration tests that rely heavily on the data in the SQL Server development database. This was fraught with issues.

  • If the status of a targeted record changed, the tests would fail
  • If the test had an error, it would fail to cleanup and there would be "unitTestUsers" left in the db. 
  • If you were debugging, and didn't finish test execution, it wouldn't clean up the record
  • It was slow and required VPN access 

Solution: 

Move to Derby, which is an in-memory Java database.

Obviously we knew that we'd have to create all of the lookup tables, like the us_states table, and the roles table.

But we ran into numerous bugs which warrant a blog post.  I'm going to list them in order and how I solved them, but like an onion, resolving one layer lead to another and another.

Background: 

We are using JPA Annotations in a JAXB framework to manage the persistence. Derby (should) read these annotations and auto-generate the tables.

Roadblock: 

Missing tables:

We were getting a dozen missing tables and the tests would have the following errors:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.4.2.v20130514-5956486): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: Table/View 'RC_ACTIVITY_LOG' does not exist.
Error Code: 20000

After exploring typos, case sensitivity, persistence.xml settings and configurations, there were two solutions that came out.  The short version is that there were 2 errors that were happening during the create table phase.

Discoveries: 

Turning on logging to "Fine" in the persistence.xml will output all of the SQL that is being run.
<property name="eclipselink.logging.level" value="FINE" />

Then, the log is very, very long (obviously), and was being cleared from the console.
So then I saved the output to a file.

This is easily done within IntelliJ in the Run/Debug Configurations window. There is a 3rd tab called "Logs" and a checkbox to indicate "Save console output to file:"

The following errors were discovered:
Internal Exception: java.sql.SQLSyntaxErrorException: Column name 'IDX' appears more than once in the CREATE TABLE statement.  
Error Code: 30000

With the corresponding SQL Statement:
CREATE TABLE job_category (occupation_id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL, major_group_id VARCHAR(255), profile_nbr INTEGER, idx INTEGER, idx INTEGER, PRIMARY KEY (occupation_id))

Notice the double "idx INTEGER?"

After much research, finally found that it was coming from our Annotations:
@OneToMany(cascade = CascadeType.ALL, mappedBy="profile", orphanRemoval = true)
@OrderColumn(name="idx") 

Couldn't figure out why it was doubling, but changing the name="idx" was reflected in the error (still doubled), and leaving it out resulted in the default name doubled. If you have an answer or link to why it doubles, and a better solution, I'd love to hear about it.

Ultimately, ended up copying the SQL statement from the logs, removed one of the idx references and recreated the table at the beginning of our tests.

Here is the code for that:
    private static void createTable(String sql)  throws Exception
    {
        Connection connection = getConnection();
        Statement stmt = connection.createStatement();
        stmt.executeUpdate(sql);
    }

    private static Connection getConnection() throws ClassNotFoundException, SQLException {
        String strConnectionURL = "jdbc:derby:memory:TestDB;create=true";
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        return DriverManager.getConnection(strConnectionURL);
    }

But then we ran into another problem error creating tables:

Internal Exception: java.sql.SQLSyntaxErrorException: Constraints 'SQL140602131233001' and 'SQL140602131233000' have the same set of columns, which is not allowed. 
Error Code: 30000

With its corresponding SQL
CREATE TABLE rc_activity_log (rc_activity_log_id INTEGER GENERATED BY DEFAULT AS IDENTITY NOT NULL UNIQUE, created_on_dt TIMESTAMP NOT NULL, NOTE VARCHAR(255), user_id INTEGER NOT NULL, profile_nbr INTEGER, PRIMARY KEY (rc_activity_log_id))

And the Annotations: 
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="rc_activity_log_id", unique=true, nullable=false)

Which means that because there is an @ID and unique=true, that it creates two identical constraints on the table, which causes it to fail. (Thanks https://java.net/jira/browse/GLASSFISH-3252)

Given that the code was working before the derby migration, and we didn't want to change any of that, We just manually created these tables as well.

Extra: 

One thing that was particularly helpful was being able to determine the actual tables that existed in memory. So from http://stackoverflow.com/questions/7411020/calling-derby-java-db-show-tables-from-jdbc we have:

public static void printDerbyTables() {
        //http://stackoverflow.com/questions/7411020/calling-derby-java-db-show-tables-from-jdbc
        try {
            Connection connection = getConnection();
            DatabaseMetaData dbmd = connection.getMetaData();
            ResultSet resultSet = dbmd.getTables(null, null, null, null);
            System.out.println("DERBY TABLES >>>>>>>>> ");
            while (resultSet.next()) {
                String strTableName = resultSet.getString("TABLE_NAME");
                System.out.println("TABLE_NAME is " + strTableName);
            }
            System.out.println("<<<<<<<<<<<<< END DERBY TABLES  ");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }









Wednesday, April 16, 2014

Flex debugging timing out in Firefox

Recently I was debugging a project in Firefox and couldn't step through the code for more than a minute before I would get disconnected. 

Discovered this link

https://coderwall.com/p/fhhdla

Which suggests: 



  1. In your url bar type in "about:config" without the quotes.
  2. Locate the search field at the top of the document and enter: "dom.ipc.plugins.timeoutSecs" without the quotes.
  3. Double click on that item and set its value to what ever you'd like to increase the amount of time before it considers a plugin hung. 4 NOTE: if you change that value to -1 it should never time out.
And it seems to work for me, your mileage may vary. 


Monday, March 10, 2014

Udacity Online Training Review

Udacity Hadoop and MapReduce
I recently took the Udacity Hadoop and MapReduce online course, with the extra classroom / coaching option. The other interesting aspect was that a number of my coworkers at Twin Technologies  took the class at the same time.

I come at this course from a unique context. Not only am I a senior developer, but I'm also a university professor, a professional technical trainer, and my wife will have a a PhD in educational psychology in May. (This is relevant in our shared discussions about learning and trends).

I thought that this course was excellent. I liked that the videos explained the big picture, but there there was hands on, real world exercises to practice with. The multiple choice / multiple answer questions throughout the video were a little annoying, but I recognize the need for assessment if you are going to  be offering a certificate at the end.

I appreciated that the data sets were "messy", some being incomplete or in different formats, and that you had to add error checking to your code.  It was great to actually have to get in a do some real examples. I'm happy that the exercises weren't step-by-step, as I have found that most students I've had were pretty good at following directions, but after the exercise is over, they really didn't get anything from the "happy path".

One of the things that struck me as interesting, was since this class is mostly automated, that there is a "right" answer. This was useful, as it allowed for safe failures and fast feedback, both of which promote leaning. It was also frustrating, when in some of the exercises the answer that I got was not what the computer wanted, mainly because of an anomaly in the data.

For example, one of the exercises was to determine the most frequently accessed file, and how often had it been accessed. I found the file easily enough, but I was 4 off the total. The course software only told me I was wrong. I had to read through the discussion to determine that I was 4 off, and what the reasons behind it. Apparently, 99.98% of the files were relative paths in the log files that we were processing. But there was that .01% that had absolute paths. This meant that the file in question didn't match the specific string criteria that the others did, and thus ended up outside the total.

Overall this was a good lesson to learn, that the data might come in forms that are unexpected. However, I feel in the real world, missing that .01% would have been an acceptable oversight. Mostly I was frustrated at the extra time that the exercise required to determine this.

The coaches were readily available, and certainly had a good handle on coaching.... asking leading questions, listening, providing appropriate feedback without giving away the answers. That was nice to see, and I always enjoyed talking to them.

The exit interview was a novel idea. Obviously part of the interview is for you to prove you are who you said you are, which I'm assuming is for whatever accreditation Udacity is seeking. But the other interesting part is the feedback. Being an agileist, feedback is hugely important and good feedback is really difficult to come by. So I ended up talking to the interviewer for longer than he probably expected, but I offered up lots of ideas for improvement as well as my thoughts on the course (some of which are reflected here). One thing to note is that scheduling the exit interview is about 1 week away from the time of request. If you are seeking certification and no the subscription plan, you will want to account for that extra time.

It was fantastic to take this course with some of my co-workers. Of course we all worked at a different pace, but in a remote environment to be able to have a shared experience outside of our annual meetings and project work, is really valuable for team building. It was nice to be able to share our successes and pitfalls. I especially liked having other people checking in with each other to make sure we were all still moving along. I enjoyed feeling like I was helping when I could clarify a question or tell people to read the discussion or notes before starting on an exercise. It certainly was more personal and satisfying than posting to the forum.

My take away from taking this class, is that while not new information, I certainly prefer to be higher up on Bloom's taxonomy of learning with fast feedback, safe failures, and "messy" real world data / problems in my learning opportunities.

Next time, I would push myself to complete it a little faster so that I didn't incur a 2nd month charge of the subscription fee though.


Monday, January 27, 2014

Using Twitter for classroom queue management

Problem: 

I teach a hands-on multimedia class of 25-30 students. During lab times, the students often need help. I was finding that as I was helping one student, their neighbor would grab me as soon as I was done, and I could never get to the other side of the room.

I wanted a way to create a queue that made it fair to all students.

Constraints:


  • Students didn't need an account or access for it
  • Would always be available, so that if they were having a problem before class, they could be first in line
  • There was a mobile option, so I could check the queue while walking around the room. I didn't want to have to go back to the computer to determine who was next
  • I could get a notification if I didn't have the queue running on my machine
  • Students saw their location in the queue. 
  • It was easy, without many moving parts. This was something that I needed to stand up in a couple of hours and work reasonably well.  

Solution: Twitter as the backend


Twitter offered everything that I needed. 
  • Already managed and ordered timestamps
  • Already had access and notifications on my phone
  • Some students already had accounts, but a dev twitter account and simple custom interface would allow for anybody to access it
  • Search for the special hashtag, and the queue comes up. 
And as an added bonus, I got a chance to play with Node.js, socket.io, JQuery, jade templating, Heroku hosting and a bunch of other technologies which were new to me. 

The end result is that the students LOVE it. They recognize that it is fair, and that it is really easy for them to use at any time. 

Inspired by Google, my UI was super simple :


The tweet looks like "Drew Shefman needs help #uhmultimediaHelp @UHMultimedia 1390595370659"

  • Drew Shefman is obviously the first and last name. 
  • #uhmultimediaHelp is the hashtag that I've choosen. (University of Houston multimedia). This is ultimately my search term. 
  • @UHMultimedia is a DIFFERENT twitter account than the dev account. It is the twitter account I use for my class for announcements. I include this in the message, so that I will receive email notifications. 
  • The number at the end is the timestamp in milliseconds. I found that if a student asked for help twice, that it was not showing up a 2nd time, because twitter prevents a duplicate tweet in a short time period. 

So here is the flow: 

  1. On page load and before page display, twitter.search() for #uhmultimediaHelp
  2. Filter out  any tweets older than 5 hours (my class is only 3 hours long)
  3. Display results on page, showing name and formatted time (HH:MM)
  4. Student enters name and hits "I need help" 
  5. Socket broadcasts new entry and it gets prepended to the list element
    (this is primarily so that there is immediate feedback, and the impatient students know not to submit multiple times)
  6. twitter.updateStatus()
  7. On twitter submit success, repeat twitter.search()
  8. On search success, socket broadcasts a refresh with the resultant search list.
    (I perform this seemingly duplicate step of refresh so that if any students are using their personal twitter account, with the hashtag, they will get pulled into the queue. I decided to not use twitter.stream() api as it added a significant layer of complexity. The majority of my students opt for my interface versus using their accounts, so this is a reasonable solution for now. This decision will fail if the number of personal accounts outweighs this queue, as there is only a twitter refresh when a student submits through the queue. 
  9.  Then, starting from the bottom of the list, I can help the students in order. Woot!

Technical challenges: 


 This was my first foray into a decently complex HTML5  / Node app. So starting out *everything* seemed to be a technical challenge.  So outside of googling nearly every single line of code I was typing, here are the specific things that I ran into. 
  • I choose ntwitter as the node package to leverage for the twitter api. Unfortunately it had not been updated to Twitter's new 1.1 API. So I had to fork it, and modify it for that. You can get that version on https://github.com/dshefman/ntwitter. The change to the 1.1 was simple and you can see it at this commit
  • I tried using the twitter.stream API, but it requires a single instance. But each connection (webpage) was trying to create a new stream. After much researching, there was an idea to create two Heroku instances, one for the stream and one for the app. This was going to be too much work, so I took a different path.
  • On Heroku, I pushed up my repository without following the instructions, basically leaving out the init(). Boy it didn't like that. Basically had to delete my whole Heroku account and start over. 
  • My timezone is -5 from GMT, which is what twitter uses. Not a problem, until 7pm (my class is from 5:30 - 8:30pm). At 7pm CDT, that is 12am GMT (00:00:00), in which all of my displayed times switched to -5. It was a simple solution, but something I didn't account for when I was testing it during the day. 
  • Initially I didn't provide fast enough feedback, and the students would submit a half a dozen times before it would show up on their screen. Then they were embarrassed for submitting so much. 

Technologies Leveraged (Each was decently new to me):

  • CSS 
  • Jade templating 
  • JS
  • Jasmine BDD
  • Karma test runner (continuous mode is SUPER cool)
  • Node.js / Express
  • Socket.io
  • Twitter API via ntwitter
  • Heroku node hosting
  • JQuery

Usage example





Code:

You can find the project at:
https://github.com/dshefman/TwitterHelpQueue

There is one file missing: twitterAPICredentials.js
You will need to add your own API keys if you want to use the code.

Since I'm fairly new to all of these technologies, I gladly welcome feedback / best practices for improvement.  Thanks! 



Thursday, January 2, 2014

SCNA 2013 review



I attended Software Craftmanship North America (SCNA), this past November (2013) and wanted to share some of the major things that I got from this conference.

Software Craftmanship is a philosophy about developing software and raising the bar of the entire profession. The craftmanship manifesto augments the agile manifesto and adds that the craftsman also values well-crafted software, steadily adding value, community of professionals, and productive partnerships.

SCNA is the conference for raising the bar. It is a language / technology agnostic conference. It is a community of people who share the above values. The opening remarks of the conference are "Your annual attitude adjustment," which is absolutely true. I find the conference humbling and inspiring and everyone there cares about my growth as a developer. Thank you Twin Technologies for sending me.


The conference started with a reprimand from renown author and personal inspiration Robert Martin. His admonition was regarding the heathcare.gov debacle and how it's fallout has and will negatively effect our profession.

The take away from his presentation was regarding the "responsibility of knowing". Somewhere, some developer knew that heathcare.gov, wasn't tested and ready for production. Relating this to the Challenger explosion, Robert Martin asserts that we, professional software developers, MUST be able to stand firm when we "know" that something isn't ready.   A technology problem has now become a policy problem, where technology is preventing a legally created policy from happening. He cited some great references to the  Developer Bill of Rights and Client Bill of Rights.


Sara Gray, then presented a fantastic analogy regarding writing new worlds. Her statement is that you create the [programming] world that you live in, and are you thinking about the others (including your future self) that will have to live in that world. The analogy that she used was Harold and the Purple Crayon. You get to create your world and everything that you need, but sometimes you accidentally create monsters.

Sara asserts that like parts of a sentence, that there are parts of code. There are named things, like variable, parameters, and methods. There are pieces of knowledge, which should be extracted and then named. There are changes of state, which could be represented as "who changes state", and might be a good place for helper classes. Finally, there is the "speaking voice", which I believe is the overall flow.


Ken Auer says that you can't live on stackoverflow or github alone. The goal is to raise the bar, not win an arguments. When addressing poor code, the goal should be to raise the bar, to transfer knowledge in a constructive way, and not win the argument by proving your superior knowledge. He gave his mantra, which was "make it run, make it right, make it fast", but recognize that "make it right" is limited by the most skilled participant. Based on the Dreyfus learning models, the novice has to be "in sight" of the expert, in order for them to grow. One of the nuggets that I always look for at conferences is potential interview questions. Ken provided a good one. "What software have you shipped?"



One of the most thought provoking, and immediately applicable sessions was given by Corina Zona, entitled "Schemas for the Real World". Her assertion is that giving a form field a name or restricted answers limits its scope, and that you could declare a person invalid. People are never edge cases. Some examples would be a gender field of male/female; a sexuality field of hetero/bi/gay; drop down boxes for religion, race, or relationship status. The user often has to choose to be inauthentic to fill in these fields, saying "this isn't really me, but it is the only option". Why can't all of these fields be text inputs? What questions are we really trying to answer? Maybe the question that you are trying to answer, instead of asking for gender, ask "what pronoun do you prefer?" Based on her research, when given a free text option for gender, only 40% responded with "m, f, male, or female".


Here is another example of potential invalidation: Facebook's relationship status. Does it alienate people not in or not looking for a relationship? When does a "widowed" status change to "single"? How is the "Married, Separated, and Looking" status represented?

The cool thing about this session, was that that evening I had dinner with some college friends who work in admissions in higher education. We discussed that this was the exact thing that they *battle* with their IT group all of the time. It is very unusual to have a long lasting conversation about the things that I've learned in a conference with non-developers.

The other neat aspect of this, was that I was able to put it to use in the next form that I created. I'm organizing a parent / child dance for my daughter's school, and on the form, instead of having check boxes for mother and father, I have the following field: "Relationship of the attending adults to the child(ren)." This will hopefully give me the answers that I'm looking for... answers like "mother and father, step-father, mom1 and mom2, grandmother, etc". It provides a very rich data set.



The panel on software quality had some interesting insights. Does quality even exist? Given that it, quality, is an individual definition, it might not even be describable until you can see it or see its absence. Interestingly enough, is that quality has no value today. It has value tomorrow; it is something that you pay forward. Simplicity, which is often the sign of good quality, takes experience because it is hard. Testing is a good *tool* that might be an indicator of quality, but it is not a rule that tests mean high quality.





Dave Thomas, one of the Pragmatic Programmers,
talked about the unknown knowns and that we should teach people what we were taught, but infuse them with what we have learned. Given the matrix of what you know that you know, what you know that you don't know, what you don't know you don't know, and the what you don't know that you know; it is this last one, the unknown knowns that might be the most valuable. It is the cumulative integration of your experiences, and the critical piece which we have to try to share. A simple example to references is how do you recognize a face, or describe how you walk. Thinking about them actually breaks your ability to use the knowledge. The parts that we need to transfer, is why did you structure the code this way instead of that, or why does this code make you feel dirty?


Sandro Mancusio provided some insight into some of the criticism and rebuttal that the craftmanship movement has encountered. 

The first criticism is the "craftmanship is just XP rebranded". Craftmanship is an ideology not a methodology like XP. It is about principles not practices. Practices are chosen based on the value that they bring. 

"Craftmanship is an elitist movement." Actually, we (the crafts-people) are fully inclusive, trying to raise the bar across the industry. We recognize and support the need of novices. We NEED them for everyone to grow. 

"First crafted code, then whatever the client wants." We practice writing quality code, so that time is not a factor to deliver quality. Quality becomes inherit in our work. 

"Pragmatism over religion." The message is professionalism, it is not TDD or practices. "What does it mean to be a craftsman", is not universally definable, but a personal definition. How it is done is as important as having it done. 

One thing that struck me as particularly powerful, was his mentor's description of his first attempt at code as "disrespectful". Out of all of the adjectives available to him.... "bad, inefficient, ugly, unmaintainable", he choose disrespectful. That is quite an interesting context. 




On the nature of software development, by Ron Jefferies and Chet Hendrickson, they assert that most agile teams have it wrong. Coding is a team sport, and that everyone on the team should be somewhat capable of "scoring" even if that isn't their primary duty. Backlog refinement shouldn't be the sole job of the product owner, but a team problem-solving effort. The whole team needs the vision of the product, the "what are we building". The team is actually the product owner, and the product owner is technically the "product champion" 



Finally outside of what I've already written about, there were some notable quotes that I wanted to share. 
  • Trust-driven development. How transparent can you be to build trust? 
  • "Does my commit increase or decrease the entropy of the system?"

Oh and one last thing. I was able to participate in a code retreat at 8th Light. I'm very envious of their bookshelf.

Monday, December 30, 2013

Sequence Based FlexUnit integration testing

Did you know that sequence based testing is built into FlexUnit? I was relieved to find this link in the documentation (http://tutorials.digitalprimates.net/flexunit/Unit-13.html). If you go to that page, please scroll to the bottom section about "Using Sequences".

One of Twin's clients needed a real time update for currency exchange. Basically in our system, instead of a continuous feed, the business requirement was that every week the admin would enter the new exchange rates (there were only 5 that were relevant). Once saved, there was supposed to be a real time push notification to all open clients so that they could update their forecast data. 

Here is what my integration test needed to prove: 
  • Get the current exchange rates from the service
  • Save a new exchange rate
  • Receive the push notification
  • Validate that the new rates has been recorded into model under the correct date.
var rtmpManager:ExchangeRateRTMPManager = new ExchangeRateRTMPManager();
var sequence:SequenceRunner = new SequenceRunner(this);
    sequence.addStep(new SequenceCaller(eventDispatcher, getInitialExchanges, [weeks] ))
    sequence.addStep(new SequenceWaiter(eventDispatcher, INITIAL_RATES_EVENT,TIMEOUT, handleTimeout));
         
    sequence.addStep(new SequenceCaller(eventDispatcher, saveCurrency ,[er]))
    sequence.addStep(new SequenceWaiter(eventDispatcher, SAVE_CURRENCY_EVENT,TIMEOUT, handleTimeout));
  
    sequence.addStep(new SequenceDelay(15*1000)) //Delay 15 s to see if we can get a notification in that time
    sequence.addAssertHandler( validateRTMPManagerReceivedPushNotifcation, null);

    sequence.run();

Tests passed, and it worked beautifully!

Permissions Modelling in Flex

Permissions is something that most of my projects have needed. I've been iterating on a design for many projects, and I've finally come up with something (leveraging some work that my Twin teammates have produced)  that is scalable, testable, and easy for my team to implement. I've written this up in the context of Flex / Actionscript, but there is no reason why it couldn't apply to other languages.

Just to clarify my requirements, here are the user stories that I'm working with. 
  • Should be testable.
    As the developer, I want to be able to declare which permissions are present during testing and development independent of my actual permissions on the system. (In other words - decoupled)  
  • Should be scalable
    As a client, I want to be able to add/remove permissions at any time without major work/rework in the application
  • Easy to understand
    As a new or jr. developer, I want to be able to understand and implement permissions in a best practices way

What I came up with, was a hierarchical string based system. It looks like the following:
public class PermissionTaskConstants
    {
        public static const DEVELOPER:String = "developer"
        public static const ADMIN:String = "admin";
        public static const ADMIN_USER:String = "admin.user";
 public static const ADMIN_CURRENCY:String = "admin.currency"
        public static const LOGIN:String = "login"
        public static const PROJECT:String = "project"
        public static const PROJECT_EDIT:String = "project.edit"
        public static const STAFFING:String = "staffing";
        public static const STAFFING_EDIT:String = "staffing.edit";
        public static const STAFFING_ALLOCATE:String = "staffing.edit.allocate"

    }

In this way, if you were assigned a permission of "staffing.edit.allocate", you would inherit all of the rights of "staffing" and "staffing.edit". This satisfy's the scalable requirement. It is trivial to add or remove permissions, as it would only mean adding / removing strings from the permission path.

These permissions would live in a "permission registry", which would contain an array of strings. This registry could be populated from a service call to a database, or it could be filled at run time. Filling it at run-time would satisfy the "should be testable" requirement. The code is availabe at the bottom, but I've set it up so that it dispatches events when permissions are changed.  A developer can listen for those events and update the UI. Although the typical workflow is that after login, we retrieve the permissions from the database, and the registry is populated before any of the UI is displayed.

IMPORTANT: Decouple the registry from the view!

So this is super important. In order to make this testable and decoupled, never, ever, ever reference the registry in the view. Said differently MXML files should have NO KNOWLEDGE of the PermissionsRegistry.

Here is the recommended workflow. You have a MXML file that represents the view. Just for clarification, this view is in charge of the layout and interactions with the user. There should be no business logic in the view.

Then you have an presentation model (PM) that is in charge of all business logic. This is likely a pure actionscript file. Business logic means conditionals, domain level events, and in this case permissions. The PM receives a copy of the permission registry through dependency injection. The PM then exposes the specific permissions that the view needs through methods.

The view creates its own Bindable public properties that represent the various permission states, and then reads them from the PM. (Please forgive the incorrect capitalization in the MXML objects, the css "brush" for this formatting strips that out)



    <![CDATA[
        import mx.controls.Alert;
        import mx.events.FlexEvent;

        public var pm:PermissionsPM;
        [Bindable] public var canReadProjects:Boolean;
        [Bindable] public var canEditProjects:Boolean;
        [Bindable] public var canReadStaffing:Boolean;
        [Bindable] public var canEditStaffing:Boolean;

        private function creationCompleteHandler(event:FlexEvent):void
        {
            pm = new PermissionsPM();
            canReadProjects = pm.canSeeProjects();
            canEditProjects = pm.canEditProjects();
            canReadStaffing = pm.canSeeStaffing();
            canEditStaffing = pm.canEditStaffing();

        }
        ]]>
    
    
    

package
{
 import com.squaredi.permissions.PermissionTaskConstants;
 import com.squaredi.permissions.PermissionsRegistry;

 import mx.collections.ArrayCollection;

 public class PermissionsPM
 {
  [Inject]  public var permissionsRegistry: PermissionsRegistry;

  public function PermissionsPM()
  {
   permissionsRegistry = new PermissionsRegistry();
   var permissions:Array = [PermissionTaskConstants.PROJECT_EDIT, PermissionTaskConstants.STAFFING]
   permissionsRegistry.permissionsList = new ArrayCollection(permissions);
  }

  public function canSeeProjects():Boolean
  {
   return permissionsRegistry.hasPermission(PermissionTaskConstants.PROJECT);
  }

  public function canEditProjects():Boolean
  {
   return permissionsRegistry.hasPermission(PermissionTaskConstants.PROJECT_EDIT);
  }

  public function canSeeStaffing():Boolean
  {
   return permissionsRegistry.hasPermission(PermissionTaskConstants.STAFFING);
  }

  public function canEditStaffing():Boolean
  {
   return permissionsRegistry.hasPermission(PermissionTaskConstants.STAFFING_EDIT);
  }
 }
}


A couple of other special features about the code. As a developer I can manually add and remove permissions from the list. When I do this, it sets a "developerUpdated" flag, which will ignore setting the whole array. Here is the use case for that. I login to the system but the service call to get permissions is delayed (for some reason). Then I want to verify how the system looks for other users, and add specific permissions, then the service call comes back and could potentially overwrite the values that I've modified. So there is code in place to prevent that.
public function set permissionSource(v:Array):void
        {
          if (developerUpdated) { return} //Don't allow it to be overwritten if the developer has already set individual permissions for testing
          permissionsList.source = v;
          permObj = createPermObj(_permissionsList)
          notifyUpdate();
        }

        public function addPermission(permission:String):void
        {
            var idx:int = permissionsList.getItemIndex(permission);
            if (idx <0)
            {
                permissionsList.addItem(permission);
                permObj = createPermObj(permissionsList)
                developerUpdated = true;
                notifyUpdate();
            }
        }

The other feature that is in the code, is an interface for extracting the data. This could be used in the case of a value object (VO) that returns from the database that has a list of permissions for a given user. This VO is an object, and doesn't have the necessary string representation for permissions. The permission registry accepts an PermissionExtractor helper, that can convert the VO into permissions strings.
package com.squaredi.permissions
{
    public interface IPermissionExtrator
    {
        function getPermissionString(perm:Object):String; // returns a.b.c
    }
}


All of the code and an example can be found at: https://github.com/dshefman/FlexPermissions