text:
Developer Fusion: "SlickGrid takes a different approach. In the simplest scenario, it accesses data through an array interface (i.e. using "dataitem" to get to an item at a given position and "data.length" to determine the number of items), but the API is structured in such a way that it is very easy to make the grid react to any possible changes to the underlying data. "
var columns = [
{id:"playerID", name:"Player ID", field:"playerId", width:116, focusable:false, selectable:true, sortable:true ,formatter: playerDesclink},
{id:"description", name:"Description", field:"shortDescription", width:439, focusable:false, selectable:true, sortable:false}
Column definition options:
|Column definition option
|Column ID.
|Column name to put in the header.
|Property of the data context to bind to.
|Function responsible for rendering the contents of a cell.
|An Editor class responsible for editing the value of a cell.
|An extra validation function to be passed to the editor.
|If true, the cell cannot be selected (and therefore edited).
|If true, a new row cannot be created from just the value of this cell.
|A custom function to be called to set field value instead of setting contextfield
|Width of the column in pixels.
|If false, the column cannot be resized.
|Minimum allowed column width for resizing.
|Maximum allowed column width for resizing.
|A CSS class to add to the cell.
|Rerender the column when it is resized (useful for columns relying on cell width or adaptive formatters).
var options = {
editable: false,
enableAddRow: false,
enableCellNavigation: false,
asyncEditorLoading: false,
forceFitColumns: true,
fullWidthRows: true
|If true, a blank row will be displayed at the bottom – typing values in that row will add a new one.
|Disable automatic rerender on scroll. Client will take care of calling SlickGrid.scroll().
|If false, no cells will be switched into edit mode.
|Cells will be switched into edit mode on double-click instead of a single click. Single click will select a cell.
|If false, no cells will be selectable. This also disables editing.
|Default column width in pixels.
|Allows the user to reorder columns.
|Makes cell editors load asynchronously after a small delay. This greatly increases keyboard navigation speed.
- DataView (i.e. model or dataprovider) provides useful features that the grid doesnt have
# var dataView = new Slick.Data.DataView({ inlineFilters: true });
- Grid
# var grid = new Slick.Grid("#myGrid", dataView, columns, gridOptions);
- Grid: https://github.com/mleibman/SlickGrid/wiki/Grid-Option
- Column: https://github.com/mleibman/SlickGrid/wiki/Column-Options
- Events: https://github.com/mleibman/SlickGrid/wiki/Grid-Events
- Custom Cell Editors: https://github.com/mleibman/SlickGrid/wiki/Writing-custom-cell-editors
- https://groups.google.com/forum/#!forum/slickgrid
- endertech "Before continuing, I'd recommend you review the examples to get a feel for the true power and capabilities of this grid. No other grid can compare to what SlickGrid has to offer."
- jquery-slick-grid-java-integration
Jayson JSON
Marshalling : takes your custom objects and converts them to XML, JSON or other serialization formats.
Unmarshalling : creation of custom objects from XML
Gunner Hillert : "The easiest way to marshal JSON in Spring MVC is via the Jackson Java JSON-processor"
Create JSON response from Spring MVC 3 : "Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath"
@ResponseBody annotation is similar to
@RequestBody : " This annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name)."
Spring MVC wth @ResponseBody : "Spring will automatically marshall the return value of an annotated method to XML, JSON, etc. "
From SpringSource : "Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath."
escaping characters
I find that if you are using HTTP GET you will run into a lot of troubles with your url string with characters such as quotes, colons, and others. The way to get around that is to use HTTP POST. But, if you still want to use GET, the best way is to escape the characters.
"URL encoding is the practice of translating unprintable characters or characters with special meaning within URLs to a representation that is unambiguous and universally accepted by web browsers and servers"
Here are a few javascript solutions on how to encode url:
Javascriptwriter: You can convert any string to a URL-encoded string (suitable for transmission as a query string or, generally speaking, as part of a URL) using the JavaScript functions
encodeURI and
From an ASP dot net blog : Understand that in asp.net, virtual path in the URL with colon (:) is not allowed. To solve this problem, i replace the colon (:) with ASCII value for colon : (please check http://www.asciitable.com/)
If you are working with javascript, it provides a number of functions that encode and decode special characters
MSDN JScript Reference – escape(), encodeURI(), encodeURIComponent()
Mozilla Developer Core Javascript Guide – escape(), encodeURI(), encodeURIComponent()
ASCII Table – http://www.asciitable.com/
W3C's URIs, URLs, and URNs: Clarifications and Recommendations 1.0 – http://www.w3.org/TR/uri-clarification/
Iframe JQuery http://stackoverflow.com/questions/5044210/jquerys-attr-escaping-ampersands, if you are using jQuery 1.6 and up, you want to use .prop() rather than
One thing to consider:
//import org.apache.commons.lang.StringEscapeUtils;
StringEscapeUtils.escapeJavaScript(out, str)
Documented at :
Beginning iOS
This project i used a storyboard and I added a label and a button to it. I then took the button on the storyboard clicked the control button and held it down into the controller (h file).
This generated code:
@property (weak, nonatomic) IBOutlet UILabel *display;
I then on the storyboard located the button and clicked control button held it down and dragged the link into the controller. This created a method in the controller. I added a print to the method:
#import "RookieViewController.h"
@implementation RookieViewController
@synthesize display;
– (IBAction)buttonDo:(id)sender {
NSLog (@"test");
I then modified the above method to change the label on a button click:
– (IBAction)buttonDo:(id)sender {
NSLog (@"test");
UILabel *label1 = self.display;
NSString *label1text =label1.text;
NSLog(@"the label was %@" ,label1text);
[label1 setText:@"Luke"];
RookieAppDelegate.h: define your class as a UI Reponder
@interface RookieAppDelegate : UIResponder
@property (strong, nonatomic) UIWindow *window;
MVC can you see
link : "With your first glance at Spring MVC 2.5 you have probably noticed that controller methods don't have to return a ModelAndView anymore."
link: Some basics in Spring MVC 3 with how to construct a project, additional concepts, form processing, and more in a tutorial series.
link : an overview of Spring MVC which ends with a link to a video on Spring MVC
Moving past scriplets
In the early days, while working in JSP files, the approach was to use scriplets to present server side data. Such as
Scriptlet <% code %>
– Code is inserted in service method.
JSP Expression <%= expression %>
– Expression is evaluated and placed in output.
Insert a help message into jsp file
String s3 = new String();
s3 = s3 + "XYZ" ;
out.print("<!– " + s3 + " –>");
Moreover, to generate javascript inside a JSP, you might do something like:
out.print("");
JSTL technology followed JSP (or even the Struts tag libraries) .
These objects allow for access to any variables that are held in the particular JSP scopes. Objects include:
- pageScope
- requestScope
- sessionScope
- applicationScope
${sessionScope.loginId} will return the session-scoped attribute named LoginId, or null if the attribute is not found.
<c:if test="${someTest}"> Content</c:if>
<c:set var="string1″value="${item.value}" />
< c:out value="${'dmb: '} ${string1}" escapeXml="false"/ >
Now, for javascript jstl integration:
var totRec = '<fmt:formatNumber type="number" value="${myCount}" />';
ioS beginnings part 2
Delegate file (h) example:
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
Controller File (h) example:
@interface ViewController : UIViewController
Change the view controller example in your delegate:
@property (strong, nonatomic) UINavigationController*viewController;
Other choices:
First Steps into ioS
I had never done any programming in native mobile development with the ioS operating system prior to now. The way i found the Xcode on the iMac was searching the files on computer until i found out about cmd-space and entered xcode in the search box. There was a pdf on the computer named about Xcode 4.2
"Xcode is the complete developer toolset for creating applications for Mac, iPhone, and iPad"
In Xcode, you would start by doing File -> new project and then single view application and click next where you enter a product name, a company identifier, device such as iphone or ipad (dont click storyboarding, but click automatic reference counting), and then indicate where project goes and then you will click create.
After XCode loads the new project, you can click run to launch the simulator (or cmd-r).
You will see files AppDelegate.h AppDelegate.m ViewController.h ViewController.m ViewController.xib
Click on the sidebar the AppDelegate.h then on right at top click the tuxedu icon which will display now the AppDelegate.m beside the other file.
@interface AppDelegate : UIResponder <UIApplicationDelegate>
In the editor, if you click the command button the identifiers become URLs
On right side,
[ standard ] [ assistant] [ version ] [Navigator] [Debug] [Utilities] [open]
editor view organizer
Utilities: toggle panel on right side, Debug : toggle panel on bottom, Navigator: toggle panel on left
bottom utilities:
- file template library
- code snippet library
- Objects
- Media library
iOS programming Field Of Dreams
I guess you could say 2012 has been my Field Of Dreams . In this year, I expanded my playing field of technical knowledge learning several new computer programming languages and tool sets.
I started year off learning Base SAS Programming with SAS 9.3. I also got exposed to SAS Enterprise Guide tool. My training in data continued with Data Flux by SAS. I thought about continuing my growth in the data with possibly getting certified.But, at the end of the day, what really interested me was creating GUIs.
In my next project, I was fortunate enough to enhance my front end development knowledge base by working with Sencha EXTJS4 javascript library. I really got to learn the in and outs of this library.
Next, I was part of another front end technology project with JQuery and KnockoutJS technologies. Knockout uses the MVVC pattern which I had used before so it really fit well with me.
I have played around with BootstrapJS and even have used all different web service tools like Apache CXF and Spring-WS
This entry begins my exploration into ioS programming.
Spring WS template
So what is JAXWS: "Java API For XML Web Services can be thought of as a
Java Programming API to create Web Services. JAXWS was introduced in JAVA SE 5 and
uses Annotations in the creation of end points and service clients. JAXWS 2.0 replaced or
encompassed the JAX-RPC API. For more details on the same look at this developer works article.
JAXWS uses JAXB 2.0 for data binding"
Generating proxy classes
JAX-WS provides a tool called wsimport which takes the WSDL of a web service and generates proxy classes for the WSDL's service and port definitions. These can then be used to access the web service endpoint.
With the help of the JAX-WS Maven plugin the wsimport tool can easily be used in Maven based projects.
he WSDL to be processed can either be fetched directly from the actual web service endpoint or from a local directory (by specifying the wsdlDirectory property as shown in the example). I recommend to stick with the latter approach. That way your project can be built even if the service to be accessed is not available from your development environment.
During the "generate-sources" build lifecycle phase the plugin will generate
- proxy classes for all service and port type declarations contained within the WSDL files in the specified directory
- JAXB binding classes for all schema types used in the operations of that services
- What is Spring Web Services (WS) [Source: Spring WS Reference 2.0]
- What is WebServiceTemplate [Source: Spring WS Reference Chapter 6]
- What is wsimport? [Source: Java™ API for XML Web Services (JAX-WS) 2.0 ]
- JAXB Marshalling XML using O/X Mappers [Source :Spring WS Chapter 8 ]
- create project with maven archtype and define ws template
- maven plugin wsimport
- spring ws with jaxb plugin
- http://jax-ws-commons.java.net/jaxws-maven-plugin/
- http://j2eeroad.wordpress.com/2011/06/15/developing-web-services-using-jax-ws-spring-and-maven-3/
- http://feima2011.wordpress.com/2011/11/27/web-service-programming-with-spring-ws-jaxb2-and-jax-ws/
- http://ankeetmaini.wordpress.com/2011/10/24/spring-web-services-2-made-easy
- http://rphgoossens.wordpress.com/2011/02/20/developing-a-contract-first-jax-ws-webservice/
- http://www.java-tutorial.ch/web-services/web-services-java-tutorial
Soap Client Homemade implementation
The Soap request:
<?xml version="1.0″ encoding="utf-8″?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<GetInfoByZIP xmlns="http://www.webserviceX.NET">
The java program:
try {
// Set up the Web Service URL and SOAP Message file name
// http://www.webservicex.net/uszip.asmx
// src/exercise1/test.xml
String WebServiceUrl = args[0];
String SOAPFile = args[1];
//Create the connection where we're going to send the file.
URL url = new URL(WebServiceUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
//Get the SOAP document ready to send
File f1 = new File(SOAPFile);
String path = f1.getAbsolutePath();
FileInputStream FileIn = new FileInputStream(path);
ByteArrayOutputStream ByteOut = new ByteArrayOutputStream();
byte[] buffer = new byte[256];
while (true) {
int bytesRead = FileIn.read(buffer);
if (bytesRead == -1)
ByteOut.write(buffer, 0, bytesRead);
byte[] b = ByteOut.toByteArray();
//Set the HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
"application/soap+xml, application/dime, multipart/related, text/*");
httpConn.setRequestProperty("User-Agent", "WSAD");
httpConn.setRequestProperty("Host", "localhost");
httpConn.setRequestProperty("Cache-Control", "no-chache");
httpConn.setRequestProperty("Pragma", "no-chache");
httpConn.setRequestProperty("SOAPAction", "http://www.webserviceX.NET/GetInfoByZIP");
//Send XML File
OutputStream out = httpConn.getOutputStream();
//Get the response
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
} catch (Exception e) {
System.out.println("FaultString: " + e.toString());
} //end exception
<?xml version="1.0″ encoding="utf-8″?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetInfoByZIPResponse xmlns="http://www.webserviceX.NET"><GetInfoByZIPResult><NewDataSet xmlns="">
<CITY>Raleigh</CITY><STATE>NC</STATE><ZIP>27615</ZIP><AREA_CODE>919</AREA_CODE><TIME_ZONE>E</TIME_ZONE>
</NewDataSet></GetInfoByZIPResult></GetInfoByZIPResponse></soap:Body></soap:Envelope>
Soap Web Services Begin To End Part 3
Using the WSDL in Part 2, right click on it in the sidebar:
WebService -> Generate Java Bean Skeleton
Again move the notch up to Test Service and click Next until it completes
Then, you will see in src folder all the generated files.
This completes the Producer side of the web service.
Now, to generate a client side, you generate a new dynamic project (i.e. Call it MyClientProject). After the dynamic project is complete, you can go into the Producer project, and get the wsdl and place it in the new Client project. Right click on the WSDL, click WebService -> Generate Client.
Soap Web Services Begin To End Part 2
Create a Dynamic Web project in eclipse. In my case I called it NumbersService.
Create a new class :
learn.webservices.numbers.ElectricCompanyService :
public class ElectricCompanyService {
public int multiply(int number1, int number2)
return number1 * number2;
public int add(int number1, int number2)
return number1 – number2;
Right click in the siderbar on ElectricCompanyService
WebService-> Create Web Service
On the screen that comes up, move the selector up one notch where it shows Test Service
In Web Content you can find a folder named WSDL with the WSDL file
<?xml version="1.0″ encoding="UTF-8″?>
<wsdl:definitions targetNamespace="http://numbers.webservices.learn" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://numbers.webservices.learn" xmlns:intf="http://numbers.webservices.learn" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!–WSDL created by Apache Axis version: 1.4
Built on Apr 22, 2006 (06:55:48 PDT)–>
<schema elementFormDefault="qualified" targetNamespace="http://numbers.webservices.learn" xmlns="http://www.w3.org/2001/XMLSchema">
<element name="add">
<element name="number1″ type="xsd:int"/>
<element name="number2″ type="xsd:int"/>
<element name="addResponse">
<element name="addReturn" type="xsd:int"/>
<element name="multiply">
<element name="number1″ type="xsd:int"/>
<element name="number2″ type="xsd:int"/>
<element name="multiplyResponse">
<element name="multiplyReturn" type="xsd:int"/>
<wsdl:message name="multiplyResponse">
<wsdl:part element="impl:multiplyResponse" name="parameters">
<wsdl:message name="multiplyRequest">
<wsdl:part element="impl:multiply" name="parameters">
<wsdl:message name="addResponse">
<wsdl:part element="impl:addResponse" name="parameters">
<wsdl:message name="addRequest">
<wsdl:part element="impl:add" name="parameters">
<wsdl:portType name="ElectricCompanyService">
<wsdl:operation name="add">
<wsdl:input message="impl:addRequest" name="addRequest">
<wsdl:output message="impl:addResponse" name="addResponse">
<wsdl:operation name="multiply">
<wsdl:input message="impl:multiplyRequest" name="multiplyRequest">
<wsdl:output message="impl:multiplyResponse" name="multiplyResponse">
<wsdl:binding name="ElectricCompanyServiceSoapBinding" type="impl:ElectricCompanyService">
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="add">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="addRequest">
<wsdlsoap:body use="literal"/>
<wsdl:output name="addResponse">
<wsdlsoap:body use="literal"/>
<wsdl:operation name="multiply">
<wsdlsoap:operation soapAction=""/>
<wsdl:input name="multiplyRequest">
<wsdlsoap:body use="literal"/>
<wsdl:output name="multiplyResponse">
<wsdlsoap:body use="literal"/>
<wsdl:service name="ElectricCompanyServiceService">
<wsdl:port binding="impl:ElectricCompanyServiceSoapBinding" name="ElectricCompanyService">
<wsdlsoap:address location="http://localhost:8080/NumbersService/services/ElectricCompanyService"/>
Soap Web Services Begin To End Part I
Step 1 : Open Web Perspective -> Web Services Explorer
Launch Web services explorer:
Select WSDL page (next to star on right):
Enter the SDL URL : http://www.webservicex.net/stockquote.asmx?WSDL
Choose Soap enter stock quote and Go!
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://www.webserviceX.NET/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
– <soapenv:Body>
– <q0:GetQuote>
– <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
– <soap:Body>
– <GetQuoteResponse xmlns="http://www.webserviceX.NET/">
<GetQuoteResult><StockQuotes><Stock><Symbol>IBM</Symbol><Last>193.36</Last><Date>10/19/2012</Date><Time>4:03pm</Time><Change>-1.60</Change><Open>195.12</Open><High>196.08</High><Low>193.18</Low><Volume>6621563</Volume><MktCap>219.9B</MktCap><PreviousClose>194.96</PreviousClose><PercentageChange>-0.82%</PercentageChange><AnnRange>177.06 – 211.79</AnnRange><Earns>13.913</Earns>
14.01
<Name>International Bus</Name></Stock></StockQuotes></GetQuoteResult>
Here is a WSDL for Mortgage payments calculation:
Spring Documento
In web.xml with Spring MVC (Convenient ApplicationContext instantiation for web applications):
- org.springframework.web.context.ContextLoaderListener
ContextLoader called by
[ref] : "ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC) "
- org.springframework.web.servlet.DispatcherServlet
[ref] : "DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this contextContextLoader"
"When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context."
[ref] Spring's DelegatingFilterProxy provides the link between web.xml and the application context. .. "it finds a bean ("target bean" or "delegate") in your Spring application context, an invoke it. How is it possible? Because this bean implements javax.servlet.Filter, its doFilter method is called."
- org.springframework.context.support.ReloadableResourceBundleMessageSource
[link ] : The feature I'm talking about is the ability to reload (and detect changes in) i18n property files on-the-fly.
This interface that maps handlers based on HTTP paths expressed through the
RequestMapping annotation at the type or method level.
Now Learning Soap Web Services
Soap is a lightweight protocol for exchanging structured information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts:
- an envelope that defines a framework for describing what is in a message and how to process it
- a set of encoding rules for expressing instances of application-defined datatypes
- a convention for representing remote procedure calls and responses
Soap Request, Soap Response
RPC Style, Document Style Soap
<soapenv:Envelope> <soapenv:Body>
Apache Axis is an implementation of the SOAP by Apache
WSDL document describes the interface of a web service in a language and protocol independent way:
- service : Defines service
- binding : possible ways to invoke service
- port: defined endpoint
- porttype: particular interface
- operation: defines method
- message :
- types: datatypes with schema
Closing out Knockoutjs Adventure
I have been involved with a knockout project the past few months. I learned alot over the course of the coding journey. The Knockout simplifies your code and works well in tandem with Jquery. Along the way, I got to use JQuery Tabs, KnockoutJS templates, Knockout observable arrays, and much more
Here are some of the great sites and links I found along the way.
- http://techomaha.com/2012/09/knockoutjs-barcamp-omaha/
- http://www.syncfusion.com/Content/downloads/ebook/Knockoutjs_Succinctly.pdf
- knockout example of item select from a pulldown
- knockout group forum
- knockout dirty model example
- knockout subscribe vs event example
- Knockout principles to know
- knockout details for observable arrays
- Knockout clear selection dropdown
- knockout selection items in json
- knockout editable grid
- knockoutjs event binding documentation
- savings goal full blown knockout example
- knockout options for radio input
- knockout search/list example
- knockout clearing observable array
- Knocout passing parameters with bind
- knockout checkbox example with json
- Knockout writeup on memory and javscript techniques
- Javscript shootout podcast knockout
- Javscript libraries compared
- knockout tabs
- knockout tabs 2
- knockout tabs 3
- knockout tabs
- knockout impressive example components
- knockout plain tabs
- knockout removeable tabs
- knockout templates
- knockout template article
- ToDo Knockout example
- knockoutjs custom buttons
- knockout questionire example
- knockout performance gotchas
CSS Style
The format of a selector is as follows
Selector {property : value}
Type selector – targets selector by element name, can have comma and wild card *
Contextual Selectors – apply style to properties based on context or relation to another element
- Descendant selector: descendants of another element, list separated by space starting with the higher level element, can have commas separating multiple entries, and can be specified several levels deep
- Child selector: like a descendant but specified by a specific parent of an element, indicated as child with greater than sign between elements >
- Adjacent selector: elements that comes directly after a certain element with same parent, indicated with plus sign +
Class and Id selectors: specified in regard to specific elements which are a class or a specific ids specified by user.
- For class you define it in terms of class in regards to a specific type selector with a dot separator .
- To specify class selector to all elements within a class you can leave out the type selector
- id selector target a single element and work like class selector except indicated with a #
Attribute selectors – targets specific attribute names or values
- Simple attribute: specified for an attribute for an element, indicated as element[attribute]
- Exact attribute value : specified as element[attribute="myvalue"]
- Partial attribute value: doesnt match whole word but search value within attribute value , specified as element[attribute~="myvalue"]
- hyphen separated value : used for case where you look for value of 'myvalue' or starting with 'myvalue-' , indictaed with |=
Pseudeoclass selector : targets a group of elements such as an anchor. has a colon : after the anchor followed with the attribute kind (i.e. link, or name)
- there are others supported other than the anchor tag . i.e. :first-chld, :first-line, :first-letter,:before, :after
How you reference style sheets:
<link rel=style sheet href=file.css type=text/CSS />
@import url();
Document structure and inheritance
– parent child relationships
– sibling relationships
– descendants
Inheritance – styles passed down to desndants
Overriding styles by nodes higher in hierarchy
Can get presentation rules from several sources and conflicts
Passed down until overridden by command with more weight
Resolve rules from competing style sheets
When user agent (ie browser) encounters element looks for all style rules that may apply
Sorts out this out based on
Style sheet origin
Least weight to greatest
1 User agent style sheet 2 reader style sheet 3 authorsyle sheets 4 !Important marked
External file sheets further down document greater precedence
Imported styles sheets override linked ones
Embedded styles sheets override external ones
Inline styles override other references
More specific the selector the more priority it gets
Least to most priority for selectors follow
Individual element to pseudo element selector
Contextual selectors
Class selectors
Id selectors
rule order
Last one wins
Display roles
Block level elements – line breaks before and after it and fills in width of the parent that contains it
Inline – no line breaks
Emphasized text
None – Wont display
Box model : Element box around it
Inner edge
Outer edge
Unit measures
Color value
% values
Spring Web Services
Contract First Web Services tutorial: When using contract-first, you start with the WSDL contract, and use Java to implement said contract. Spring-WS only supports the contract-first development style.
<?xml version="1.0″ encoding="UTF-8″?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
a) add this line to above file <context:component-scan base-package="com.mycompany.hr"/>
b) Create java package com.mycompany.hr.ws
<?xml version="1.0″ encoding="UTF-8″?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
<display-name>Archetype Created Web Application</display-name>
Spring-WS, you will implement Endpoints to handle incoming XML messages. An endpoint is typically created by annotating a class with the
@Endpoint annotation.
you will create one or more methods that handle incoming request.
3.6.1. Handling the XML Message
use JDom to handle the XML message. We are also using XPath, because it allows us to select particular parts of the XML JDOM tree,
New class HolidayEndpoint
package com.mycompany.hr.ws;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import com.mycompany.hr.service.HumanResourceService;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;
public class HolidayEndpoint {
private static final String NAMESPACE_URI = "http://mycompany.com/hr/schemas";
HolidayEndpoint requires the
HumanResourceService business service to operate, so we inject the dependency via the constructor and annotate it with
public HolidayEndpoint(HumanResourceService humanResourceService)
throws JDOMException {
this.humanResourceService = humanResourceService;
Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
startDateExpression = XPath.newInstance("//hr:StartDate");
endDateExpression = XPath.newInstance("//hr:EndDate");
nameExpression = XPath.newInstance("concat(//hr:FirstName,' ',//hr:LastName)");
@PayloadRoot annotation tells Spring-WS that the
handleHolidayRequest method is suitable for handling XML messages.
//In this case, it can handle XML elements that have the
HolidayRequest local part and the
http://mycompany.com/hr/schemas namespace
//gets passed with the
<HolidayRequest/> element from the incoming XML message.
// The
@RequestPayload annotation indicates that the
holidayRequest parameter should be mapped to the payload of the request message
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "HolidayRequest")
public void handleHolidayRequest(@RequestPayload Element holidayRequest)
throws Exception {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = dateFormat.parse(startDateExpression.valueOf(holidayRequest));
Date endDate = dateFormat.parse(endDateExpression.valueOf(holidayRequest));
String name = nameExpression.valueOf(holidayRequest);
humanResourceService.bookHoliday(startDate, endDate, name);
We skipped the Schema and WSDL, but they follow here (Note that Spring WS will create the WSDL, but here it is for getting to know it):
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
<xs:element name="HolidayRequest">
<xs:element name="Holiday" type="hr:HolidayType"/>
<xs:element name="Employee" type="hr:EmployeeType"/>
<xs:complexType name="HolidayType">
<xs:element name="StartDate" type="xs:date"/>
<xs:element name="EndDate" type="xs:date"/>
<xs:complexType name="EmployeeType">
<xs:element name="Number" type="xs:integer"/>
<xs:element name="FirstName" type="xs:string"/>
<xs:element name="LastName" type="xs:string"/>
Note: Save this schema as hr.xsd in WEB-INF
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:import namespace="http://mycompany.com/hr/schemas"
<!–MESSAGE HolidayRequest–>
<wsdl:message name="HolidayRequest">
<wsdl:part element="schema:HolidayRequest" name="HolidayRequest"/>
<!–MESSAGE Holiday Request to port type Human Resource as operation–>
<wsdl:portType name="HumanResource">
<wsdl:operation name="Holiday">
<wsdl:input message="tns:HolidayRequest" name="HolidayRequest"/>
<!-Binding which tells the client how to invoke the operations just defined and service which tells where to invoke it->
<wsdl:binding name="HumanResourceBinding" type="tns:HumanResource">
<soap:binding style="document"
<wsdl:operation name="Holiday">
<soap:operation soapAction="http://mycompany.com/RequestHoliday"/>
<wsdl:input name="HolidayRequest">
<soap:body use="literal"/>
<wsdl:service name="HumanResourceService">
<wsdl:port binding="tns:HumanResourceBinding" name="HumanResourcePort">
<soap:address location="http://localhost:8080/holidayService/"/>
To generate the WSDL by spring ws add the following to spring-ws-servlet.html:
<sws:dynamic-wsdl id="holiday"
<sws:xsd location="/WEB-INF/hr.xsd"/>
The web.xml file is modified as follows:
Twitter bs (Bootstrap)
what-is-bootstrap "is an open-source Javascript framework developed by the team at Twitter. It is a combination of HTML, CSS, and Javascript code designed to help build user interface components. Bootstrap was also programmed to support both HTML5 and CSS3."

Style code:
< link href="css/bootstrap.css" rel="stylesheet" >
< link href="css/bootstrap-responsive.css" rel="stylesheet" >
bootstrap and less css "At its core, Bootstrap is just CSS, but it's built with Less, a flexible pre-processor that offers much more power and flexibility than regular CSS. With Less, we gain a range of features like nested declarations, variables, mixins, operations, and color functions."
http://tuts.wtfdiary.com/2012/07/bootstrap-tutorial-to-design-blog.html : "top navigation bar, DropDown Menu in the navigation bar, Search Box too in the navigation bar
http://www.mrgeek.me/technology/tutorials/web-design/getting-started-with-bootstrap-part-1-of-series/ : " the grid system allows you to quickly create a design by calling the required classes, which are pre-written for you in the stylesheet provided with Bootstrap. This doesn't mean you don't have to write a line of CSS ever again, but it certainly means you won't have to write much of the CSS as far as design the skeleton of the web page is concerned"
LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions.
More references:
Spring MVC Refresher II
browsers currently only support GET and POST, a common technique – is to use a normal POST with an additional hidden form field (_method) to pass the "real" HTTP method.
< filter >
< filter-name >httpMethodFilter </ filter-name >
< filter-class >org.springframework.web.filter.HiddenHttpMethodFilter < / filter-class >
< / filter >
< context:component-scan base-package="accounts.web" />
< mvc:annotation-driven/ >
An interceptor which keeps a hibernate session open to allow lazy loading of backing object
< mvc:interceptors >
< bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor" >
< property name="sessionFactory" ref="sessionFactory"/ >
< /bean >
< /mvc:interceptors >
< bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name="prefix" value="/WEB-INF/views/"/ >
< property name="suffix" value=".jsp"/ >
< /bean >
When you use a ContentNegotiatingViewResolver your web controllers return ModelAndViews or view names and the ContentNegotiatingViewResolver will, based on various criteria, choose the right data representation strategy, Here for JSON Use Jackson Java JSON-processor
< bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" >
< property name="mediaTypes" >
< map >
< entry key="json" value="application/json"/ >
< /map >
< /property >
< property name="defaultViews" >
< bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/ >
< /property >
< /bean >
Note: if had not have used component scanning would have had to wire up the controller
A Spring MVC @Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
package accounts.web;
public class AccountController {
private AccountManager accountManager;
@ Autowired
public AccountController(AccountManager accountManager) {
this.accountManager = accountManager;
The method does not explicitly select a view name because the default
view name selected by Spring MVC matches to the incoming URL accountDetails.jsp
@ param id the id of the account
@ param model the "implicit" model created by Spring MVC
@ RequestMapping(value="/accounts/{accountId}", method=RequestMethod.GET)
public void accountDetails(@PathVariable("accountId") int id, Model model) {
model.addAttribute("account", accountManager.getAccount(id)); return "accountDetails";
The method does not explicitly select a view name because the default
view name selected by Spring MVC matches to the incoming URL accountSummary.jsp
@ param model the "implicit" model created by Spring MVC
@ RequestMapping(value="/accounts", method=RequestMethod.GET)
public void accountSummary(Model model) {
model.addAttribute("accounts", accountManager.getAllAccounts());return "accountSummary";
View Account Summary
Then on the listing page you click on one of the entries to get details
This uses the Path Variable
@ RequestMapping(value="/accounts/{accountId}", method=RequestMethod.GET)
public void accountDetails(@PathVariable("accountId") int id, Model model) {
Spring MVC refresher
application context Beans makeup the configuration of the root web application context
< context-param >
< param-name >contextConfigLocation< /param-name >
< param-value >/WEB-INF/accounts-application-config.xml< /param-value >
< /context-param >
Bootstraps the root web application context before servlet initialization
< listener >
< listener-class >org.springframework.web.context.ContextLoaderListener< /listener-class >
< /listener >
Deploys the dispatcher servlet along with its configuration
< servlet >
< servlet-name >accounts< /servlet-name >
< servlet-class >org.springframework.web.servlet.DispatcherServlet< /servlet-class >
< init-param >
< param-name >contextConfigLocation< /param-name >
< param-value >/WEB-INF/accounts-servlet-config.xml< /param-value >
< /init-param >
< /servlet >
< context:component-scan base-package="accounts.web" />
< mvc:annotation-driven/ >
An interceptor which keeps a hibernate session open to allow lazy loading of backing object
< mvc:interceptors >
< bean class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor" >
< property name="sessionFactory" ref="sessionFactory"/ >
< /bean >
< /mvc:interceptors >
< bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name="prefix" value="/WEB-INF/views/"/ >
< property name="suffix" value=".jsp"/ >
< /bean >
Note: if had not have used component scanning would have had to wire up the controller
A Spring MVC @Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
package accounts.web;
public class AccountController {
private AccountManager accountManager;
@ Autowired
public AccountController(AccountManager accountManager) {
this.accountManager = accountManager;
The method does not explicitly select a view name because the default
view name selected by Spring MVC matches to the incoming URL accountDetails.jsp
@ param id the id of the account
@ param model the "implicit" model created by Spring MVC
@ RequestMapping("/accountDetails")
public void accountDetails(@RequestParam("entityId") int id, Model model) {
model.addAttribute("account", accountManager.getAccount(id));
The method does not explicitly select a view name because the default
view name selected by Spring MVC matches to the incoming URL accountSummary.jsp
@ param model the "implicit" model created by Spring MVC
@ RequestMapping("/accountSummary")
public void accountSummary(Model model) {
model.addAttribute("accounts", accountManager.getAllAccounts());
View Account Summary
Click on one of the listing entries
Again, this uses RequestParamin the nethod signature
public void accountDetails(@RequestParam("entityId") int id, Model model)
iPhone5 w iOS6 launch
Wow factor? 4 " screen, 4G LTE, new chargers needed, sleeker, no wireless charging, no NFC Wallet, A6. Sold 20x faster
Meanwhile, that new dock connector was so thoroughly leaked that it's unlikely to put the wind up the burgeoning "appcessories" industry (yes, a word used seriously by real companies).
The Dev Center – https://developer.apple.com/technologies/ios6/
Very lightweight, more usable real estate, can operate with one hand, panoramic effect on side vertical view, fits in pocket
sweet spot on market with one device, upgraded components , a6, re-engineering camera, smaller camera, LTE,
Apple chose no NFC for now or step fwd on mobile payment system – punted for now. New passbook
iOS6 – developer pure performance, console quality graphics, google kicked out of platform, Map stuff is apple and google data is gone when upgraded, apple video instead of youtube.
Apple is not and will not change things just for the sake of change. And while some may now be clamoring for this change, the paradox is that if Apple did make some big changes, many of the same people would bitch and moan about them
FOUC! (Flash of Unstyled Content)
It occurs when applying styles with JavaScript on page load.
The problem is most evident when there is some content that needs to be hidden initially and when the document is large or complex.

In the On Ready function , you would apply :
$ ('#flash').hide();
A whole lot of document that has to be ready before anything inside the ready() function can be executed.
Putting the tags just inside the closing body tag doesn't help either
Fluff 2012 August Notes on Next Gen Framework
Framework worth a look Spring Social
@Habuma : "Need to fix it if you don't know JS "
spinejs , spine mobile : based on coffee script http://www.coffeescriptlove.com/2011/11/why-is-spine-in-coffeescript.html
– tool to generate a project spine.app
– spine mobile GFX library under covers
web hosting – cloudfoundry , red hat open shift
oauth2 – mention of harsh comments by http://hueniverse.com/2012/07/oauth-2-0-and-the-road-to-hell/
zepto a jquery like library for mobile, jquery good beacuse it handles all browser types
Next-Gen "Stack":
Database : Neo4j with Spring Data
REST API : Spring MVC
OAuth 2 : Spring Security for OAuth
Client : Spine.js and Spine Mobile
Mobile : PhoneGap/Apache Cordova
Asked him about knockoutjs and said it was great for data binding but you need to pair it with a routing js framework.
Fluff 2012 August Notes on Advanced Javascript
I just attended the NFJS Raleigh tour stop. This was my third time at this great event and my focus of the sessions was javascript and mobile.
Here begins my notes:
Suggested Book: Seven Languages in Seven weeks by Bruce Tate
Prototypes – IO, LUA, SELF : access to class , define on the fly, manipulate class after you define it.
Functional JS vs OO JS
http://joda-time.sourceforge.net/ – spring data
Everything in javascript is an object but primitives. Objects consist of key value pairs + prototype
javascript function is pass by reference not by copy.
Dynamic typed language
hoisting – Only functions create a new scope.
propertyIsEnumerable : higher within prototype
passing functions to a function desirable for reuse
associative array {name: 'fred'}
two scopes: global and function level scope
this – scope you are in
null == undefined
parasitic inheritance is like composition
CommonJS – use of require
Testing- Jasmine
Knockout Custom Bindings
I am continuing to work with KnockoutJs and I noticed a few examples that use custom bindings. This post does a great overview:
Knockout bindings consist of two methods:
update. Creating a binding is as simple as creating an object with these two methods..ko.bindingHandlers.yourBindingName = { init: function(element, valueAccessor, allBindingsAccessor, viewModel) { }, update: function(element, valueAccessor, allBindingsAccessor, viewModel) { } };
initfunction – This is usually used to run one-time initialization code or to wire up event handlers …
updatefunction – provides a way to respond when associated observables are modified….
don't actually have to provide both
updatecallbacks ….
The element parameter – the DOM element that contains the binding…
The valueAccessor parameter – function that gives you access to what was passed to the binding. If you passed an observable, then the result of this function will be that observable (not the value of it). If you used an expression in the binding, then the result of the
valueAccessorwill be the result of the expression.
The allBindingsAccessor parameter – just a way to pass additional options to the binding, unless you choose to pass an object with multiple properties into your main binding.
The viewModel parameter – provides access to your overall view model for bindings outside of templates. Most of the time the
valueAccessorwill give you the data that you want, but the
viewModelparameter is particularly useful if you need an object to be your target when you call/apply functions.
ko.bindingHandlers.jqTabs = {
init: function(element, valueAccessor) {
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
update: function(element, valueAccessor, allBindingsAccessor) {
var dependency = ko.utils.unwrapObservable(valueAccessor()), //just to create a dependency
options = allBindingsAccessor().jqTabOptions || {}, //any additional options
selected = $(element).tabs("option", "selected"); //restore selected index
//do in a setTimeout, as the DOM elements are not built yet when we are using bindings to create them
setTimeout(function() {
$(element).tabs("destroy").tabs(options).tabs("option", "selected", selected);
}, 0);
JQueryUI Tab – The Uncola
Lets say you are using knockoutjs , so your tabs might look something like this in your form data.

{{each tabs}}

${title}

Handling the screen interaction is what I am interested in.
Such as the Tab events. Getting what was selected .
The JQueryUI tabs documentation lists Methods , Events, Options
For example, under methods,
tabsselect,tabsload, tabsadd selected: Get or set the
selectedoption, after init.-
var selected = $( ".selector" ).tabs( "option", "selected" ); $('#tabs').tabs("option", "selected") $('#tabs').data()$('#tabs').tabs({ selected: selection.parent().index(), });
As well the live demos under contents feature information :
A series of events fire when interacting with a tabs interface:
- tabsselect, tabsload, tabsshow (in that order)
- tabsadd, tabsremove
- tabsenable, tabsdisable
Event binding example:
$('#example').bind('tabsselect', function(event, ui) { // Objects available in the function context: ui.tab // anchor element of the selected (clicked) tab ui.panel // element, that contains the selected/clicked tab contents ui.index // zero-based index of the selected (clicked) tab });
Knockout Templating
I am in middle of the use of conditional rendering with knockout. There are some good articles out there on the use of templates.
Knockout Nuggets
1) Send an event on some screen action
< input type="button" id="Button1″ value="Create My Event" data-bind="event: { click:createGreatEvent } " />
this.createGreatEvent = handleReset;
function handleReset() { alert event('Yay');}
2) Display Label from model

this.myLabel = ko.observable("");
3) Bind to typical form objects

< textarea size=70 id='myTextVal' rows=5 cols=100 data-bind="value:$data.text" />

< input type='checkbox' id='displayByDefault' data-bind="checked: $data.awesome == 'Y' " />

< select id='questionTypeVal' data-bind="options:typeItems, optionsText: 'text', value: selectedType, event: {change: changedTypeEvent} "
< /select>

this.myObj = ko.observable("");
this.myObj = new Obj(", ", ", ", ", 'N', ", ", ", 'Y');
this.typeItems = ko.observableArray();
// choice list selected
this.selectedType = ko.observable();
this.typeItems.push(new OptionObj("Text", "Text Box"));
this.typeItems.push(new OptionObj("TextArea", "Text Area"));
this.typeItems.push(new OptionObj("Date", "Date"));
this.changedTypeEvent = handleTypeChoice;
function handleTypeChoice() {
if (this.selectedType() != null) {
var type = this.selectedType().id;
4) Conditional Rendering with Templates
this.SetupQuestions = ko.observableArray();
this.templateToUse = function (item) {
var templateName;
if (item.type == "Text") {
templateName = "temp1";
else if (item.type == "TextArea") {
templateName = "temp2";
return templateName;
var myViewModel = new myProject();
"myId": "50001",
"type": "Text"
"myId": "50002",
"type": "TextArea"
< script type="text/html" id="temp1″>

< /script>
< script type="text/html" id="temp2″>

< /script>
< script type="text/html" id="QuestionAnswerChildTemplate">
< input data-bind="value : AnswerVal" />
< /script>
< script type="text/html" id="QuestionAnswerChildTemplate2″>
< textarea size=70 id='questionTextVal' rows=5 cols=100 data-bind="value : AnswerVal" />
< /script>

Knockout webosphere
1) Decoupling with Knockoutjs [pluralsight]
2) Knockout js shootout vs other js libraries [ screencast.]
3) data-*
7) ESPN api with Knockout [arrays]
8) Knockout built in binding types
9) Conditional rendering [1] [2] [3]
10) wiki
I first heard of GitHub (what is GitHub anyway? ) several years ago at the NoFluffJustStuff conference. After the conference I set up an account (technobuzz is a member since Sep 03, 2010) , allthough I have not made much use of it.
Also, in PhoneGap they show you how to get started with Git bash .
I am using Aptana Studio which shows you a little about Git use and it comes with the tool/plugin.
– Some git hub resources
– git man pages
C:\Program Files (x86)\Git\bin\ssh>ssh-keygen -t rsa -C "firstname.lastname@example.com
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/xyz/.ssh/id_rsa):
Created directory '/c/Users/xyz/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/xyz/.ssh/id_rsa.
Your public key has been saved in /c/Users/xyz/.ssh/id_rsa.pub.
The key fingerprint is:
b2:f8:32:17:e1:ea:41:61:7b:79:39:b1:a0:55:88:4a email@example.com
go to .ssh dir and get text of pub key
C:\Users\xyz\.ssh>type id_rsa.pub
paste it into github ssh (https://github.com/settings/ssh)
Test out key:
C:\Users\xyz\.ssh>ssh -T firstname.lastname@example.com
C:\Users\xyz\.ssh>git config –global user.name "Dave-o"
C:\Users\xyz\.ssh>git config –global user.email "firstname.lastname@example.com"
GitHub for Windows includes this helper, and provides a git shell so you don't need to install and configure git manually
cd c:\wamp\www\jquery
git init
git status
git add file1.txt
git commit – m "add test file "
git remote add orgin email@example.com:technobuzz/jquery.git
git pull orgin master
git push orgin master
Knockout jQuery Binding and Visibility
Reading more on Knockout js
Here is the panel we will enable or disable:

The following is an example div

Here we have a button that sends an event when it is clicked
< input type="button" id="Button1″ value="My Button" data-bind="event: { click:buttonEvent } " />
Here is what the associated binding (javascript) looks like:
function viewModel() {
var self = this;
myValues = ko.observableArray([]);
this.isEnabled = ko.computed(function () { return myValues().length > 0; } );
// Here when er receive event we enable div tag by making size of myValues greater than zero
buttonEvent = function (selectedSection, userAction) { myValues.push("some value"); };
//Must apply a model to bindings
ko.applyBindings(new viewModel());
The documentation for this example (also an example with booleans).
Likewise, here is an example of using anonymous function in html to reference the javscript bindings.
More binding techniques
special comments for "if" binding
select list example (i.e. picklist) , alternate select list example
Knockout jQuery
In the GWT ecosystem , the Model View Presenter (MVP) pattern is the architecture of choice. However, the model requires some special capabilities when dealing with the state (i.e. what the user did should force some special visibility rules).
In MVP the model typically refers to just the domain objects that will be displayed, things like a Customer, Contact or Account. From a Presentation Model perspective the term model encompasses the domain data plus all additional state that can change during the normal operation of the UI.
Likewise, pure javascript libraries have to deal with these type of issues too. They have a name for the MVP + (Editors/Pectin) pattern. Its called MVVM.
Model–View-ViewModel talks of creating a new model (in addition to your domain model). This model normally adds additonal properties from the prespective of View (as we understand that View has controls in addition to data which it's displaying).
Knockout handles data binding : "Any time you have sections of UI that update dynamically (e.g., changing depending on the user's actions or when an external data source changes)".
A simple example always explains it best.
The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.
For example, let us imagine that we have a model containing a date attribute in unix format (e.g 1333832407). Rather than our models being aware of a user's view of the date (e.g 04/07/2012 @ 5:00pm), where it would be necessary to convert the address to it's display format, our model simply holds the raw format of the data. Our View contains the formatted date and our ViewModel acts as a middle-man between the two.
KnockoutJS interprets the ViewModel as the represtation of data and operations that can be performed on a UI.
Another simple example with code.
The intent of Knockout and other MVVM framework offerings is to move those conditional logic statements into the ViewModel and let the ViewModel be the sole source of the business logic
MVC in Javascript
- add an item
- delete an item
- update
- wired to listen for add button click, invokes controller
- wired to listen for delete button click, invokes controller
- Event (model) handler for itemAdded, itemRemoved
- sender object
- attach method to add handler to the event
- notify method to invoke a handlers
- list of current items
- selected index
- define Event (model) for item added, removed, selectedindex changed
- model getters/setter methods for items
From Sencha to jQuery
After learning alot about EXTJS, it makes sense to get familiar with jQuery. If you have 15 minutes, this is a good overview. Similarly, try this slide share too as it provides good explanations. As well, there is a jQuery fundamentals, an online book or jQuery in Action. As the first chapter says :
If you've spent any time at all trying to add dynamic functionality to your pages, you've found that you're constantly following a pattern of selecting an element or group of elements and operating upon those elements in some fashion. You could be hiding or revealing the elements, adding a CSS class to them, animating them, or modifying their attributes.
This javascript library make it easier to accomplish these routine blocks of code in your client code.
To collect a group of elements, we use the simple syntax:
The $ () function (an alias for the jQuery() function) returns a special javascript object containing an array of DOM elements (known as the wrapped set or wrapper) that match the selector.
Then, jQuery provides methods (or sometimes known as commands or actions) that can act on the group of elements. Some of these actions when completed return the same set of elements that can then again be acted on (known as chaining).
jQuery. or $. is the notation for utility functions.
Mobile advancements by Qualcomm
But in the future your mobile device, whether it be something you hold in your hand like a smart phone, or wear on your face, like Google Glasses, will know a hell of a lot about you.
Well, Qualcomm just shipped the developer SDK, called Gimbal.
Apple does NOT give developers access to the Bluetooth and Wifi radios. This is going to really hinder developers in this new contextual world.
This is the location based services we have been hearing about for years. It is the auto check in functionality. Let's say you are driving n your car, it knows you have visited Starbucks on many occasions. It knows that you are approaching a StarBucks, it offers you a coupon code.
Mobile Apps explosion
Clutter phone with apps instead of web pages
What we will do with phone in future going to explode.
Search for apps on our phone since there are so many
Periodically delete apps since cluttering phones
Web much better
One answer is phone gap
With different platforms have to know different OS and API and languages. a lot to learn, and code API changing all time.
The web provides a common software to bring different platforms together.
Build on standards (i.e. html5) , deploy app everywhere.
Native development – slow since have to develop for every platform, have to do separate implementation for every device, no portability, high cost, good performance on devices, native functionality
web development – portability, low cost , no native functionality, device specific browser
Phone Gap – hybrid, web app and native app . Build it on standards and can run on anywhere. consistent api
gwt tool for building web apps
mobile slow cpu drain battery slow network connections
can use phonegap and gwt together
web app – device, browser, mgwt great looking gui
apache 2.o license
native and javascript (web) in phone gap
adobe buys phonegap
donate code to Cordova
phone gap is one distribution of phone gap
adobe will build tools on it
web – native web control html,css – browser
phone gap plugins (native) – camera plugins, android plugins, ioS
HBase : open source, distributed, sparse (no strict schema), column oriented (control how stored on disk) sorted map data store, modeled after Big Table.
Usage scenario: alot of data, very high write throughput (i.e. sequential writes), easy to scale (distribute across machines), data layout efficient(key look up disk seeks efficient and cost transparent some rows filled in some not still efficient)
column oriented – every row with same column, transaction on single row basis, not full acid, hbase no sql except with hive, but not realtime,
get : single row get columns
put : put row these columns
scan row x in sorted order until row y, some filtering
indexing – primary key only
clustered indexes – primary key is clustered key index
Hbase built on top of Hadoop, requires HDFS, work with map reduce but built on top of it.
HDFS sequential writes , cant update in middle of file, provides streaming I/O
HDFS lacks random read/write capabilities
HBase random read and write in middle of file
converts random writes to writes into log, merge log back into table
log structure merge trees 89
Failover handled with Zookeeper
Sorted Map Datastore:
Not a relational database
Tables consists of rows and primary key
Each row any number of cols
rows stored in sorted order
Have primary key and columns have attributes (column families) that can store many different things
logical view (row key : data) :
– info and roles are column families
– Can have versions of the data
cutting (row key): info {height: '9ft', state : 'CA'}, roles {ASF : 'director', Hadoop : 'Founder'}
tlipcon (row key): info {height: '5ft7', state : 'CA'}, roles {Hadoop : 'Committer'@ts=2010,Hadoop :'PMC'@ts=2011, Hive: 'Contributor'}
physical view (for each column family, row key (primary key), col key (what data), time stamp, value) :
– column families stored separately on disk
info column family:
cutting (row key) , info.height (col key) , 12345678910 (timestamp), 9ft (value)
cutting (row key) , info.state (col key) , 12345678911 (timestamp), CA (value)
tlipcon(row key) , info.height (col key) , 12345678912 (timestamp), 5ft7 (value)
tlipcon (row key) , info.state (col key) , 12345678912 (timestamp), CA (value)
– roles column family:
cutting (row key) , roles.ASF (col key) , 12345678910 (timestamp), Director (value)
cutting (row key) , roles.Hadoop (col key) , 12345678911 (timestamp), Founder (value)
tlipcon(row key) , roles.Hadoop(col key) , 12345678912 (timestamp), PMC (value)
tlipcon (row key) ,roles.Hadoop(col key) , 12345678912 (timestamp), Committer (value)
tlipcon (row key) ,roles.Hive(col key) , 12345678912 (timestamp), Contributer (value)
– Sorted in ascending order by row key and column key, and descending order by timestamp
– column families:
each column may have different access patterns or properties
can configure compression, cache priority, #versions properties
– Java API, Rest Calls, Apache Thrift, Hive (sql)/Pig (hybrid) integrate
put (row,Map)
scan (key-range, filter)
" HBase handles basically two kinds of file types. One is used for the write-ahead log and the other for the actual data storage. The files are primarily handled by the
You may also notice that the actual files are in fact divided up into smaller blocks when stored within the Hadoop Distributed Filesystem (HDFS).
The general flow is that
a new client contacts the Zookeeper quorum (a separate cluster of Zookeeper nodes) first to find a particular row key. It does so by retrieving the server name (i.e. host name) that hosts the -ROOT- region from Zookeeper.
With that information it can query that server to get the server that hosts the .META. table. Both of these two details are cached and only looked up once.
Lastly it can query the .META. server and retrieve the server that has the row the client is looking for.
A distributed HBase depends on a running ZooKeeper cluster. All participating nodes and clients need to be able to access the running ZooKeeper ensemble. HBase by default manages a ZooKeeper "cluster" for you.
http://ria101.wordpress.com/2010/02/24/hbase-vs-cassandra-why-we-moved/ :
" I will write about why I think we will see a seismic shift from SQL to NOSQL over the coming years, which will be just as important as the move to cloud computing. "
"HBase and its required supporting systems are derived from what is known of the original Google BigTable and Google File System designs (as known from the Google File System paper Google published in 2003, and the BigTable paper published in 2006″
" Cassandra on the other hand is a recent open source fork of a standalone database system initially coded by Facebook, which while implementing the BigTable data model, uses a system inspired by Amazon's Dynamo for storing data (in fact much of the initial development work on Cassandra was performed by two Dynamo engineers recruited to Facebook from Amazon)."
HBase being more suitable for data warehousing, and large scale data processing and analysis (for example, such as that involved when indexing the Web)
Cassandra being more suitable for real time transaction processing and the serving of interactive data.
where platforms are perceived as similar, people tend to aggregate around the platform that is going to offer the best supporting ecosystem in the long term
When starting with HBase, my impression then was that it had the greatest community momentum behind it, but I now believe that Cassandra is coming through much stronger.
HBase vs Cassandra: NoSQL Battle!" link more , or HBASE vs Big Table
ccelerating momentum behind Cassandra. You might also take note of the big names coming on board, such as Twitter, where they plan broad usage (see here).
"CAP Theorem, and was developed by Professor Eric Brewer, Co-founder and Chief Scientist of Inktomi.
The theorem states, that a distributed (or "shared data") system design, can offer at most two out of three desirable properties –Consistency, Availability and tolerance to network Partitions.
Very basically, "consistency" means that if someone writes a value to a database, thereafter other users will immediately be able to read the same value back,
"availability" means that if some number of nodes fail in your cluster the distributed system can remain operational, and
"tolerance to partitions" means that if the nodes in your cluster are divided into two groups that can no longer communicate by a network failure, again the system remains operational.
a complete HBase solution is really comprised of several parts: you have the database process itself, which may run in several modes, a properly configured and operational hadoop HDFS distributed file system setup, and a Zookeeper system to coordinate the different HBase processes
HBase in pseudo distributed mode on a single server is difficult – so difficult in fact that I did my best to write a guide that takes you past all the various gotchas in the minimum time (see http://ria101.wordpress.com/2010/01/28/setup-hbase-in-pseudo-distributed-mode-and-connect-java-client/ if you wish to try it). As you will see from that guide, getting HBase up and running in this mode actually involves setting up two different system systems manually: first hadoop HDFS, then HBase itself."
Data on the Tube Blasts
Interview with Dr. Jim Goodnight CEO SAS Institute On Data Analytics
Hadoop you do
Hadoop is a computing environment built on top of a distributed clustered file system that was built specifically for large scale data. The approach of Hadoop is distributing the data into a collection of commonly available servers where each server is an in inexpenseive disk drive. Moreover, as it says here : "we introduce the idea of "big data" that the string is too huge to one master machine, so "master method" failed. Now we distribute the task to thousands of low cost machines." With Hadoop, redundancy is built into the environment where data is stored in multiple places across the cluster. Not only is the data stored in multiple places in the cluster, but the programming model is such that failures are expected and resolvedby running portions of the program on different servers in the cluster.
Hadoop has two main parts :
- HDFS, the Hadoop Distributed File System, is a distributed file system designed to hold very large amounts of data (terabytes or even petabytes), and provide high-throughput access to this information. The design of HDFS is based on GFS (Google File System). Files are stored in a redundant fashion across multiple machines to ensure their durability to failure and high availability to very parallel applications. There is one NameNode, and multiple DataNodes. Moreover, via Facebok Under the Hood says : "HDFS clients perform filesystem metadata operations through a single server known as the Namenode, and send and retrieve filesystem data by communicating with a pool of Datanodes. Data is replicated on multiple datanodes, so the loss of a single Datanode should never be fatal to the cluster or cause data loss." Also see IBM Big Data Analytics HDFS, Facebook's Realtime Hadoop
- MapReduce , the programming model. it is a programming paradigm that allows for massive scalability across the many servers in a hadoop cluster. map reduce performs two seperate tasks. first is the map job which takes a set of data and converts it into another set of data where elements are broken down into key/value pairs. The reduce job takes the output from a map as input and combines the key/value pairs into a smaller set of key/value pairs.
Note: The IBM Infosphere BigInsights platform (current version is 1.4) is built on top of Hadoop .
Learning Big Data
From the whatsthebigdata.com post on Crowdsourcing :
"The Wikipedia article on Big Data says it requires exceptional technologies to efficiently process large quantities of data within tolerable elapsed times."
Big data is making us think of ways to harness the excessive amount of unstructured data that is generated on a daily basis. Moreover, it is no surprise we have seen the introduction of many new Big Data technologies .
It was Carlo Strozzi who coined the term NoSQL ("Not only SQL") in 1998, referring to a lightweight database that did not expose a SQL interface. The NoSQL databases provide Infinite scalability, fault tolerance, high availibilty, design-friendly lack of schema. For example, Oracle has a NoSQL offering, and Globals is an Open Source NoSQL that supports a Java API.
My first experience with an unstructured like database was with the Google App Engine in which uses the BigTable like concepts (App Engine datastore and BigTable are not the same thing – datastore is built on top of the lower level BigTable, and adds extra capabilities. Bigtable is a sparse, distributed, persistent multidimensional sorted map. The map is indexed by a row key, column key, and a timestamp; each value in the map is an uninterpreted array of bytes.
Likewise, "The guts of Google are where concepts such as key-value pairs and MapReduce have been brought to the everyday user, albeit transparently.To finish the thought, NoSQL is a database-like storage engine for key-value pairs and Hadoop is an open-source implementation of MapReduce, among other things. Together, they enable mountains and mountains of data to be used purposefully"
The Primer on Big data defines the four "V's" of data: volume, velocity, variety and veracity :
Volume: The sheer amount of data being digitized, maintained, secured, and then used. Knowing the organization's current needs and having a plan for its growth is fundamental.
Velocity: The speed at which data must be moved, stored, transformed, managed, analyzed or reported on in order to maintain competitiveness. This will vary by organization and application or usage.
Variety: The different types of data, from source (origin) to storage and usage, must be well understood because competitiveness requires access to the right types of data more than ever. From aged flat files to spatial and unstructured data, a plan must be in place.
Veracity: The truthfulness or quality of data can either lead to poor understanding and decisions that belie progress or deliver a powerful jolt of reality that fuels new insight and ideas. Ultimately, data quality may be the most important frontier.
I first heard the hadoop and cassandra buzz words bounced around when they talked of the technology behind google/facebook.
More on Hadoop :
"Traditional databases have columns and structures — name, rank, serial number, data of entry, date of departure," Kay said. "In a Hadoop cluster, it's unstructured. You don't know what the structure is."
"Hadoop was created by computer scientist Doug Cutting, who developed the platform based on data-indexing research from Google Inc. Cutting, now Cloudera's chief architect, named the technology after his son's yellow stuffed-elephant toy, which went on to become the platform's logo."
Now, VMWare is bringing in Hadoop to its SpringSource Umbrella.
SAS Proc Summary and Means joined at hip
I have been working with SAS PROC Summary , and now know the PROC Means provides almost the exact same functionality (as the legend goes that two different people were designing procs that did the same thing) . If you go to documentation for either, it shows the same syntax. The core
difference is that by default PROC MEANS sends the results to an Output Window and that PROC SUMMARY, by default, creates a SAS data set.
Class statement: class variable(s) </ option(s)>;
– Specifies the variables whose values define the subgroup combinations for the analysis
Id statement: Id variable(s);
includes additional variables in the output data set.
Output statement: OUT=SAS-data-set
- statistics : The statistical analyses PROC MEANS will generate
- _FREQ_ is the count of the number of observations available for use
- _TYPE_ is a numeric flag which indicates the subgroup of the CLASS variables summarized by that observation in the output data set.
SAS BI Tasks
I am using the SAS Enterprise Guide and trying out a few things.
My samples directory is C:\Program Files\SASHome\x86\SASEnterpriseGuide\4.3\Sample\Data
- Tools-> SAS Enterprise Guide Explorer
- Tools -> Update Library Metadata
- File -> Open ->
- Right click on SAS program and click create stored process
More BI Learnings
Pre-assign Library in SAS Management Console (SMC)
We created a new SAS library (which is just a name that points to a directory in the system), but the SAS BI Dashboard was not recognizing it. Turns out you have to pre-assign the library.
We had to reset the tool for SAS BI Dashboard to take notice. Simply checking the library was not good enough.
Stored Processes
A SAS stored process is a SAS program that is hosted on a server and described by metadata.
Because a stored process is basically a SAS program, it can access any SAS data source or external file as input
and can create multiple types of output, such as new data sets, files, and report output in a variety of formats.
code is not embedded in client applications it is stored on a server
SAS stored processes can be hosted by either the SAS Stored Process Server or the SAS Workspace Server
Any SAS program can be a stored process
More on Stored Processes… http://www.bi-notes.com/2012/05/stored-process-edit-modify-change/
SAS data manipulations
SAS Transpose : "So many times we need to take our data and turn it around. One of the reasons that this is done is that it
is more efficient to store your data in a vertical format and processing the data is easier in a horizontal
- Changes the variables (columns) into observations (rows)
- eliminates the need to write a complex data step
- Horizontal data has many variables with few rows. There will be empty cells in the data if there are any missing values
SAS Summary/SAS Means : In SAS, you can use the
MEANS, or
SUMMARY procedure to obtain summary statistics such as the median, skewness, and kurtosis
By definition, a median is a statistical term identifying a piece of data (number) that divides numerically ordered data into two equal halves. In easier terms, the median is the middle piece of data when those data are placed in numerical order.
Play the InfoMap Game
an information map bridges the gap between the:
- the physical data warehouse
- business user who views or builds reports from the data
An Example:
- information architects sees physical data source that might be an array of interconnected tables and columns
- business users sees a simple list of business terms
an information map:
- enables business users access to the most current data that is needed for business reporting
- hides from business users the details of the physical data view
Information maps are :
user-friendly metadata definitions of physical data sources.
information map contains two basic elements:
A data item (a table column, an OLAP hierarchy, or an OLAP measure) –
- are used for building queries and can be an item that represents either physical data or a calculation.
- are usually customized in order to present the physical data in a form that is relevant and meaningful to a business user.
A filter is criteria that subset the data (i.e. where clause).
SAS Information Maps contain metadata to describe the following elements:
Metadata about the data sources: An information map can be based on SAS data sets, SAS OLAP cubes, or a third-party database such as Oracle, Teradata, DB2, or Microsoft Excel
Metadata about relationships : Multiple relational data tables can be combined or joined to enable optimized queries, regardless of the data source.
Metadata about the appearance and usage of data items : control the display of data items through labels and formats. It can also control the usage of the data items. For example, you can decide that a certain data item should not be used in a sort or to compute statistics.
Metadata about business rules : Standard calculations and filters can be predefined so that business users do not need to re-create them every time that they are needed.
Metadata Repository pane on left: display of the information maps
Presentation tab: physical data sources, data items, and filters
Physical data on left : shows physical data sources
Information Map: details panel displays the Information Map data items and filters
Relationship Tab: Tables and their relationships to others
You cannot use both a table and a cube in the same information map
By inserting a data source for your information map, you have made the data available to the information map.
Now, you must create data items in order to include them in the information map.
A business user sees data from the data source only if you create a data item to represent it.
- A data item can be a logical view of a field in the physical data.
- A data item can be calculated from an expression.
To create data items, you use the Presentation tab of the main SAS Information Map Studio window.
To create a data item that is a logical view of the physical data field, you select an item in the Physical Data pane, and you use the Insert button to create a corresponding data item in the Information Map pane.
Data items are listed in the Information Map pane with an icon indicating their classification. There are two classes of data items
category: distinct value that is used to group or summarize measure data items
measured: a value that is measured and can be used in expression
Each data item has metadata to describe its properties
You can view and edit a data item's properties in the Data Item Properties window
you right-click the data item in the Information Map pane of the Presentation tab and select Properties
Filters : A filter can also be based on a physical data column or on an expression. The expression that you use in a filter can reference data items, physical data columns, or both.
category data item:
- query code uses a WHERE clause
- the clause is evaluated for individual records prior to any aggregations
measure data item:
- query code uses a HAVING clause
- the clause is evaluated on summarized information after aggregating the data
To open the New Filter window, you click the New Filter tool
In the Data item box, you specify the data item, physical column, or expression to which this filter applies.
In the Condition box, you specify the condition that is used to filter the data. For relational filters, the list of available conditions is based on the data item that is selected in the Data item box.
In the Value(s) box, you specify the unformatted values that the condition uses to filter the data items
You click Combinations to display or hide the elements that enable you to create compound expressions for the filter. Or/And expressions
he Edit button on the Definition tab enables you to open the Expression Editor window, where you can specify an expression for the new data item.
OLAP Sandwich
I am learning about OLAP cubes… [concepts] [more]
Cubes are logical, multidimensional models that consist of the following elements:
- One or more dimensions
- One or more levels
- One or more hierarchies
- Members
Dimension – collection of closely related hierarchies that group data into natural categories (i.e. variables)
Level – level of detail within dimension
Dimensions have top level
Hierarchy – order of levels in a dimension based on parent child relationships
Member – individual value within level
Star Schema – The set of tables includes a single fact table and one or more dimension tables. " It is called a star schema because the diagram resembles a star, with points radiating from a center. The center of the star consists of fact table and the points of the star are the dimension tables."
Fact Table – " The fact tables contain fields for the individual facts as well as foreign key fields relating the facts to the dimension tables."
Aggregate Tables – "are special fact tables in a data warehouse that contain new metrics derived from one or more aggregate functions (AVERAGE, COUNT, MIN, MAX, etc..) or from other specialized functions that output totals derived from a grouping of the base data."
EXTJS Linkage
Over the course of doing some EXTJS4 development, I have come across some good sites that will be good reference for knowledge.
Missing CSS for Breadcrumbs [more]
EXTJS4 Tree
I am designing a Tree for use in the EXTJS4. In my tree I will be adding new nodes to the Tree. The basic Sencha Tree example is quite the simple case.
The tree I am defining makes use of the Tree Panel as follows:
Ext.define('my.view.FolderList', {
extend : 'Ext.tree.Panel'
Just like the example, I define my first column as a 'tree column':
xtype: 'treecolumn', //this is so we know which column will show the tree
Some methods of the Tree Panel which will be usefull:
- http://docs.sencha.com/ext-js/4-0/#!/api/Ext.tree.Panel-method-getRootNode – returns Ext.data.NodeInterface
- http://docs.sencha.com/ext-js/4-0/#!/api/Ext.tree.Panel-method-getSelectionModel
Via the getSelectionModel() which returns Ext.selection.Model , you can get:
- http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
- http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-hasSelection
MVC and more with extjs
Every framework/toolkit has their example app. GWT has its Stockwatcher. The Sencha EXTJS toolkit has the Pandora.
After downloading the code for this, it doesn't work out of the box until you add the following line of code to app.js:
The app.js file defines yout stores, controllers, and
Ext.application({name: 'Pandora',
autoCreateViewport: true,
models: ['Station', 'Song'],
stores: ['Stations', 'RecentSongs', 'SearchResults'],
controllers: ['Station', 'Song']
Lets start by looking at ViewPort file in view package:
Ext.define('Pandora.view.Viewport', {
extend: 'Ext.container.Viewport',
layout: 'fit',
It uses the dock item – Any components may be docked to any side of a panel via the new dockedItems config property, and docked items must be configured with a
dock property to specify which border to dock to. This allows for amazingly flexible Panel layouts now :
initComponent: function() {
this.items = {
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
height: 80,
items: [{
xtype: 'newstation',
width: 150
}, {
xtype: 'songcontrols',
flex: 1
}, {
xtype: 'component',
html: 'Pandora
Internet Radio'
From left to right,
layout: {
type: 'hbox',
align: 'stretch'
The station list and ad is in west region,
items: [{
width: 250,
xtype: 'panel',
id: 'west-region',
layout: {
type: 'vbox',
align: 'stretch'
items: [{
xtype: 'stationslist',
flex: 1
}, {
html: 'Ad',
height: 250,
xtype: 'panel'
followed by the container in middle:
xtype: 'container',
flex: 1,
layout: {
type: 'vbox',
align: 'stretch'
items: [{
xtype: 'recentlyplayedscroller',
height: 250
}, {
xtype: 'songinfo',
flex: 1
Select a station, Station.js has:
stationslist': {
selectionchange: this.onStationSelect
onStationSelect: function(selModel, selection) {
// Fire an application wide event
this.application.fireEvent('stationstart', selection[0]);
In Song.js, wired up for the event as follows:
// Listen for an application wide eventthis.application.on({stationstart: this.onStationStart,scope: this});
Thus calls onStationStart which uses store to do a proxy call, but has call back to OnRecentSongsLoad:
onStationStart: function(station) {var store = this.getRecentSongsStore();store.load({callback: this.onRecentSongsLoad,params: {station: station.get('id')},scope: this});},
Next, we go into call back after proxy call:
onRecentSongsLoad: function(songs, request) {var store = this.getRecentSongsStore(),selModel = this.getRecentlyPlayedScroller().getSelectionModel();// The data should already be filtered on the serverside but since we// are loading static data we need to do this after we loaded all the datastore.clearFilter();store.filter('station', request.params.station);store.sort('played_date', 'ASC');selModel.select(store.last());},
It hits the selModel.select which selModel is equivalent to
We have an event in Song.js that says invoke OnSelect method:this.control({'recentlyplayedscroller': {selectionchange: this.onSongSelect}});
In OnSelect method in Song.js tells us to go update SongInfo:
onSongSelect: function(selModel, selection) {this.getSongInfo().update(selection[0]);}
SongInfo update method:
update: function(record) {
var data = record ? record.data : {};
However, this MVC app example for mobile Sencha is great.
Create your first EXTJS Object
What is a Store along with a Store/Proxy –
Model grid example
Reference your view anywhere in MVC
Sencha extjs4 learning
Viewport is a specialized container representing the viewable application area, to simply make a single child item occupy all available space, use fit layout, To display one "active" item at full size from a choice of several child items, use card layout.
Components may be added to a Container through the items config option at the time the Container is created, or they may be added dynamically via the add method.
* Base class of any component is Ext.container.Container -GUIDE working with LAYOUTS/CONTAINERS
* Can specify child
items of a Container, or dynamically adding Components to a Container
* All Components are registered with the Ext.ComponentManager on construction
* Components created with an id may be accessed globally using Ext.getCmp
* The
xtype configuration option can be used to optimize Component creation and rendering. It serves as a shortcut to the full componet name.
* You can define your own xtype on a custom component by specifying the alias config option with a prefix of
* a
layout default Auto scheme Certain layout managers allow dynamic addition of child components. Those that do include Ext.layout.container.Card, Ext.layout.container.Anchor,Ext.layout.container.VBox, Ext.layout.container.HBox, and Ext.layout.container.Table.
* Ext.panel.Panel extend a Container have properties like closeable To enable the close tool to simply hide a Panel for later re-use, configure the Panel with
closeAction: 'hide'.
* Instead of using assigned ids, use the itemId config, and ComponentQuery which provides selector-based searching for Sencha Components analogous to DOM querying
* http://docs.sencha.com/ext-js/4-0/#/api/Ext.tab.Panel-method-down
* http://docs.sencha.com/ext-js/4-0/#!/api/Ext.ComponentQuery
The Flux Capacitor
It's been a while since I have blogged. But, better late than never. I wanted to record my new knowledge on DataFlux which was entirely new to me before Tuesday. Dataflux has an office here in the triangle and was acquired by SAS in the year 2000. The current version of the Data Management Studio is 2.2 The lifecycle consists of Plan (define/discover), Act (design/execute), Monitor (Evaluate/Control). The different components in the Dataflux products are the Dataflux Data Management Studio , Web Studio, Federated Server (outbound connections, virtualization, multiple data sources), Data Management Server (jobs, alerts, triggers). The data management repository consists of the rps file and the propitiatory files.
To create a new repository, go to the Administration riser on the left, find repository definition tree, right click and select new.
QKB (QualityKnowledge Base) – houses schemes, definitions, etc. ~ what names should look like. It can be found under repository definitions, should be set as default
The Data riser is where you can explore tables and ODBC connections.
Data Collections is where you group like fields
Field Match, Table Match, Identification Analysis
Higher sensitivty, less likely match
Data profiling – look for errors with frequencies and patterns
Analysis report – what is right
create a standardization scheme
phrase or identification analysis
Java Reporting
http://jasperforge.org/projects/jasperreports – The world's most powerful and widely used embeddable Java reporting library for report designers and developers. [getting started]
prompt> cd \program files
prompt> cd jasperreports-<ver>\demo\samples
prompt> dir
prompt> cd barbecue
prompt> ant –p
prompt> ant javac
– Compiles the java source files of the test application
prompt> ant compile
– Compiles the XML report design and produces the .jasper file
prompt> ant fill
– Fills the compiled report design with data and produces the .jrprint file.
prompt> ant viewDesign
http://jasperforge.org/projects/ireport – iReport gives administrators and report designers total control over the contents as well as the look and feel of every report
Jasper reports includes some nice samples and tutorials:
More On GoogleTV and the lockdown
From newteevee is an article about what you can see on GoogleTV from the web in your livingroom .
Mark Cuban writes in with a comment on bnet post and says:
Content owners still have a right to control what devices they want their content seen on and how its seen. Putting something on a website does not make it public domain
From dragonpointtvs is a post taking on Cuban's points.
An interesting point in all of this is the bandwith by Netflix and other streaming option:
The language will shortly be changing, just as it has for mobile network users, where "unlimited" is basically gone now, and virtually all data plans have either a soft or hard cap.
Google TV is Out!
Danny Sullivan has shared his Google TV experience. He bought a Sony Blu-ray player that is Google TV-capable for $400 at Best Buy. It seems the networks now do not want you watching content available online on your PC with a Google TV device As another article on blocked content with Google TV says:
Google TV isn't stripping the video off the sites. It's not inserting its own ads into the content. It's not knocking down firewalls, eating small children nor sacrificing animals. It's simply letting you use a web browser, exactly as you'd use a web browser on a Windows or Mac computer.
I don't know about you, but there has been litigation/settlements over sites who aggregate content that was written by others. Now, this is a different scenario where Google has money to be made in the adverstising arena by simply wrapping the networks content. This seems no different than a web site that aggregates a feed they do not own on their site. Where as Netflix pays the networks for their content and charges for it, Google TV content would be a free ride for the comsumer. Marc Cuban gives you his thoughts on this fact.
Another interesting point about Google TV 's "open platform" is by Mark Suster who thinks Google might impact video in a similar way the print industry has been affected by the web:
it would be an understatement to say that traditional media is skeptical about Google's benevolence and many fear a world in which video content margins are crushed in the way that print & music have been with the primary beneficiary having been Google.
But as much as I would like to drive down to Best Buy and get the Google TV Blue Ray player, just keep in mind that Google TV is not the only game in town.
Flash-y Droids
Steve Jobs has a HATE relationship with the Adobe Flash technology on Apple's media devices. However, the Android platform has not shut its doors to it depite security issues with it, as its available for download. HTML5 is on the horizon and claims to provide a rich multimedia experience without the dreaded plugin download. I would think with HTML5 would have flash beat on the android. Not so much says CNN. However, dull version Flash on Android is available with only the 2.2 version of Google's operating system.
Media Hub-a-dub-dub
News of the Media Hub from Sprint
A new system software update for Sprint's Samsung Epic 4G gives this high-end Android OS smartphone support for the Media Hub, a service for renting and buying movies and TV shows that was unveiled just last week.
The new iTunes-like service is getting started with content from NBC Universal, Paramount, and MTV Networks. TV episodes sell for $1.99, movie rentals cost $2.99 to $3.99, while movie sales cost $9.99 to $17.99.
Google TV you say?
With Apple TV, you can stream from your apple device to your television. Such as, Pay-per-view of TV shows (for the networks who are on board), or movies from Netflix. But, what is Google TV? How do they compare?
This site states what we think it is:
Based on what has been circulating around the net it appears that Google TV has formed a partnership with both Sony as well as NetFlix to offer streaming on demand video in the best quality possible. Movie Downloads will be in 1080 p HD resolution.
In addition, Google TV Boxes will be pre-installed with Google Chrome for web surfing, will have the ability to utilize and run Android applications. Google TV will integrate into your television, computer and cloud platforms rather seamlessly. Web applications like Twitter, Google's online photo sharing and storage service will also be included.
As Tim says:
Apple TV / Google TV are throwing down the challenge to all Cable providers. The goal is to ditch your cable boxes, and Blu-ray and instead view live streams direct from the internet directly through TV monitors. This will have a significant impact on the cable television as we know it. It's only a matter of time television will be an old dusty device that our children's grand-parents still view due in part Web mania is still a fad…
The twitterville facelift
Yesterday I heard that there was big news coming out of twitterville. A press conference of some sort I heard was taking place. Over the past year or so the twitter thing has really grew on me. Especially, since I have been blogging since the early 2000s, I like the microblogging concept. Anyway, here is timeline of the news about the #newtwitter. Some of the early adopters are not so happy about the tweeting changes.
More info:
Composition Over Inheritence Rules
We should avoid inheritance if we can. Just like this post says:
The difference between is-a and has-a relationships is well known and a fundamental part of OOAD, but what is less well known is that almost every is-a relationship would be better off re-articulated as a has-a relationship
Other good practice that was mentioned in software was http://www.kitchaiyong.net/2010/02/solid-principle.html
Social Media is Killing Feed Aggregation
The world of web content is changing before us. Just this week, the N.Y Times has gone on the record and indicated :
"We Will Stop Printing The New York Times Sometime In The Future".
The way we get news has been for a long time been changing. Some companies have had for while a problem on how we use their content.
With the way the content is shared and presented, there is bound to be people who wan't a piece of the $$$ pie. Here is a good post on some of the types of news aggregation, and some of the litigation/settlements in the misunderstandings on who has a right to publish the data. Or even, who owns the data. On the outs is the RSS feed reader.
The 21st Century Architecture at NFJS
I took just about the whole series of the 21st Century architecture at NFJS 2010 with Brian Sletten. Services (i.e. SOA) is not dead, however expensive is. Avoid the center down approach, and instead use the ecosystem based approach. Invest in the RESTful style. A little complicated, but you are investing in the future. Rest is not about behavior, but about information. It is not a SOAP replacement. Rest gives the freedom to negotiate in the format you like (i.e atom,rss, etc). Leonard Richardson introduced the Rest Maturity Model with Soap being level 0, URL resources level 1, http level 2, and hypermedia level 3. For example, twitter uses alot of JSON and not hypermedia. Some properties to consider with REST is performance (i.e. maybe the first request requires the greatest server hit, and subsequent requests do not), scalability (how it handles the load and scles down for different devices), stateless (part of request), uniform interface (don't need WSDL), minimize layering. Rest Triangle : Npuns, Verbs, Representations. The important http methods with REST include : Get is a state transfer from server of a resource (i.e. web page), Head is constrained version of Get. Info about resource (i.e. header), Post is where accept by the server at this time an information resource, don't know if it is recieved by server. (i.e form handling) create and update. Example in early days was usenet news, Put is do know resource. Overwrite idempotent record, Patch is more explecit version of Post, Delete is idempotent, Options ask if allowed to do something. An overview of Http return codes : 200s everything is cool, 204 no response, 300s good stewards (more information), 303 non-networkable address, 400s you screwed up, 500s server in bad state try again laterGood book is Rest In Practice. Artucles: InfoQ on Rest , Rest for Java Developers, Restlets , Net Kernal , The future is Rest . JSR 311 : http://www.infoq.com/news/2008/09/jsr311-approved
Semantic web has public and private link information. Microformats standard, but no common model. RDF is new enabling technology to focus on concepts that provides a global guide to webs of data.Information has a context so people can use it. Purl.org web site example that uses foaf (friend of a friend) with birthday handle. DBpedia data set. Gleaning Resource Descriptions from Dialects of Languages (GRDDL) W3C recommendation structured content. RRFa is RDF attributes (metadata). RDFa is a way to label content to describe a specific type of information, such as a restaurant review, an event, a person, or a product listing. These information types are called entities. Each entity has a number of properties . Freebase , Adaptive Blue. The Curie processing / RDFa spec. The Open Graph protocol enables any web page to become a rich object in a social graph. Enables any web page to have the same functionality as a Facebook Page. The Web Ontology for eCommerce can be found at Good Relations (see best buy). Semantic Web at InfoQueue . Rdfa split. ODF use of RDFA . Books: Pull: The Power of the Semantic Web to Transform Your Business. CommonTag. RDFa test page. RDFa distiller. rdfa.info web site. RDFa parser for fragments. Details on Whitehouse. gov site that uses RDFa .Taxonomy blog. Basics, Long tail
RDF triple , librdf.org/query , rdf about ,rdf-sparql-query , linked data , mulgara.org , sparql query , twinkle, govtrack sparql , reyvu.com with twinkle , relfinder with Kill Bill. Lastly, google supports RDFA
jQuery basics
I am in the process of learning about jQuery. I have used some dojo, and recently most my work on client side has been in GWT . I figured the best place to start is in a slide share. As well, there is a jQuery fundamentals, an online book. jQuery in Action is also online. As the first chapter says :
If you've spent any time at all trying to add dynamic functionality to your pages, you've found that you're constantly following a pattern of selecting an element or group of elements and operating upon those elements in some fashion. You could be hiding or revealing the elements, adding a CSS class to them, animating them, or modifying their attributes.
This javascript library make it easier to accomplish these routine blocks of code in your client code.
To collect a group of elements, we use the simple syntax:
Known as a wrapper or a wrapped set.
Mobile Dev Multi Platform
The iPhone Developer Program License Agreement clause 331 shuts out adobe from iphone , but Phone Gap "which let developers write JavaScript code that runs in WebKit inside a native iPhone app wrapper" is approved and can continue.
The tutorial(s) for Droids is where I decided where to start learning about Phone Gap .
Using phonegap guide on windows , I got Ruby186 with 0.9.1 phonegap-android , and execute command with git (unix) bash:
$ c:/ruby186/bin/ruby droidgap c:/appdev/java/android-sdk-windows/ TestGap TestGap.com.example "c:/www/" "c:/aocapps3"
Other resources:
- Getting-started-with-Android-PhoneGap-in-Eclipse
- Android Adventure
- Phone Gap Development (both)
- Multiplatform Mobile (both)
a good presentation by Brian LeRoux of Nitobi for Ben & Dion on Phone Gap:
- native app fragmentation : "Every Android device had a different screen resolution. Every hardware feature had to be checked, since every Android device had different hardware configurations"
- dom manipulation for cross rowser incompatibilities
- offline storage
- Phone gap internals for apple's platform uses the public sdk and objective C .
- How you get your app to work for multiplatforms. Mobile web is the solution. Write once, get everywhere using web.
- write web apps use phone gap to package applications
- iphone devcamp aug 2008- instantiate web view call out from javscript api to native object c, only was throw url browser
- gap://
- geo, camera, sensor, vibration, sound, video, contacts, compass,anything browser can do
- phonegap.jss www folder and index.html
- starting point , can still do native at same time
- compatiblity among platforms : mobile spec written in Qunit which is async
Phone Gap tutorial(s) for Iphone:
- Jessie Macfadyen tutorial
- Jonathan's Stark's Book with Phone Gap coverage
- Quick Start Guide
- Phone Gap vs Titanium
Cross Platform Titanium and Phone Gap
NFJS 2010 Java Agility Event Series Part 2
EasyMobile Development by Pratik Patel : JQTouch , App Accelerator Titanium , WebKit, Phone Gap , Building iPhone Apps with HTML, CSS, and JavaScript by Jonathan Stark, Aptana
jQuery byNathan Schutta : jQuery Fundamentals , jquery.com, jqueryui.com. More on topic from jquery tuts
Testing web layer: yuitest , js spec , qunit, jsunit ,jslint
Apple Touch-down celebration
There was Big new today by Apple . Here is quick rundown of Steve Job's state of the union address.
Ipod touch is not an Iphone without a phone, its an iPhone without the contract .
The cloud centric set top box called AppleTV that integrates (AirTunes) with the Ipad for $99 :
"Apple TV, which will be available within a month, will also display shows, movies, photos and music streamed over Wi-Fi from other devices – computers with iTunes installed, as well as iPhones, iPads and the iPod Touch. For example, an iPad owner could start watching a movie on the tablet, then walk into the living room and, with a few taps, finish watching it on the TV screen."
Apple 99 cent rentals
Apple announces Ping, the social network for music built into iTunes. Don't forget the GameCenter either
NFJS 2010 Java Agility Event Series
Resarch Triangle Software Symposium
(August 27 – 29, 2010) at Marriot Hotel.
I attended No Fluff Just Stuff 2010. I will cover what I learned in this blog post.
Collections By Ted Neward: The collection API is seperated by the interfaces, implementation, and the algorithims. Although a Map contains key/value pairs, it is not a collection. This was something Joshua Bloch fought for, and ten years later it still makes sense. Use of initializing collections to null was a mistake. Its better to initialize it to a zero sized collection value (i.e. new ArrayList()). Of coure, certain collections are synchronized where others are not. Refer to the book Java Concurrency in Practice which is a good for learning about thread safe issues. Note of Google Collections (now called Guava).Lastly, use for loops for iteration.
OSGI by Craig Walls : Modularity spec for Java is OSGI. Bundle lifecycle is installed, resolved (everything i need), starting, active (running). Everything defaults to private unless you tell it otherwise. Fragments are partial bundles. You don't write manifest files yourself. Tools such as Bnd or Bundlor. Apparently OSGI didn't incorporate JPA (see apache Arries) into it and because of that the springsource community realized that they did not have resources among itslef to take it to new level. As a result, it was taken to a new open source community to get help with it. Eclipse Gemini is the new project. Also, the Spring DM server is now Eclipse Virgo . Other projects include Apache Felix, Paxrunner. See Book Modular Java. See www.habuma.com/osgi/osgi-examples.html
Groovy On GAE (gaelyk) by Tim Berglund : The session started with a discussion of the book The Shallows which covers what the interent does to our brains. This framework is for small quick web applications (page centric). Mention of suitable and non-suitable architectures. Its syntax like coding jsps. Small size war files. Application server in cloud, Data store (big table noSql), Authentication, caaching (MemCache), XMPP (IM), Email, Task Queue, Image API, URL fetching, OAuth, Blobstore. github link . Mention of Dr. Laurie Williams and Pair programming.
Html5 by Brian Sletten : Despite what this website says, HTML5 by w3 is here. There is an ie enabling script even as mentioned here. Microsoft will support HTML5 in their browsers in ie9, and in a sense will be aiding in the phase out of the flash technology. With html5, the multimedia experience is achieved without the plugin that is neccesary with flash. The recourse for flash is supporting html5. Especially, since Steve Jobs changed the licensing agreement not allowing the Apple software to cross compile for adobe. As this html5 preview shows, the new section and article tags are part of the new standard, and replace the need for div tags to achieve this. html5 has a tool to create outlines of html5 conent. The new visual elements progress , meter (shows measurement within a range), details (dropdown with detailed info), input (such as time,date), canvas coordinate system. edspencer has a nice site covering html5 topics like Canvas, web storage api . A chrome html5 demo. The site html5 tutorial is a nice resource such as its canvas cheat cheat. The Codec Hell situation in which Google tried to move theVP8 codec along. The audio part of html5. html5 video player demo , and here is an example of html5 video that can be rotated , and more. The geolocation demo. The offline storage demo. Web workers/socket chat. Lastly, quake on html5. Some other html5 goodies: http://html5boilerplate.com/ , page in chrome http://www.thewildernessdowntown.com/index.html. Silverlight doom ?
Battle Android
In the news lately is the lawsuit of Oracle vs Google over the JVM with the Android platform. I recently jumped on the Droid bandwagon with the purchase of Ed Burnette's book Hello Android which was updated for Android 2.2. Also, this week I attended the @tridroid meeting here in the area.
In the Burnette book, his first chapter is dedicated to getting started with the sdk and the eclipse plugin (https://dl-ssl.google.com/android/eclipse) and the emulator. Much like this blog post and the android developer Hello World.
What Is Pectin
Built for GWT, Pectin makes use of the Presentation Model perspective . By this, Andrew Pietsch, has implemented a library that handles a customized domain or state logic. Here is the demo.
"data up" – frameworks that map the form data from domain bean definition(i.e struts) . The data is collected in regard to the bean definition. There is no business logic based on the User Interface in this model. Moreover, the UI is passive, and the logic is on the server side.
"bottom down" – the "data up" does not work well for GWT, since most of the logic moves to the client, and the server side is just a thin DAO wrapper. Pectin works with the domain bean without being constrained by it.
- View : may implement view or delegate to presenter model
- Bindings : binding widgets to model
- Presentation Model (with plugins) : data and handlers required by view, whereas plugins add additional state to data
- Adapters : creating ValueModel's from your domain data (dirty data or not)
- Domain – the data
Value model in Presentation model: provides access and mutation methods (get/set) and notifications when the value is modified using a (gin/juice like) declarative style api. (ValueModel , MutableValueModel)
FieldModels are a ValueModel that hold a reference back to the form that created it.
Related [MVP]
Rest Explained
link :
That is the Best description of Rest Ive read! Now I get it – I used to think it was just another competing way of getting information like RPC, SOAP, etc. But I understand from your article that it is a universal way of mapping information
- Roy Fielding's name is on the HTTP specification.
- The HTTP protocol capabilities are not always utilized.
- http address tells you the location of something anywhere in the world
- REST is an architectural style. It defines a resource which the web address points to. Each resource are simply concepts
- A web page is a representation of a resource. There are many other formats for resources. Therefore, browser can prompt for a certain representation of a concept. Thus, the URL or web address to "the something" can be thought of as a noun.
- Rest allows you to assign verbs to the nouns in away that makes sense (get,put,delete).
HTML5 Fever
HTML 5 is in the headlines, and up until now, I haven't been following as closely as I should have (i.e. m.youtube.com)
- The Apple html5 showcase
- Google's Html5 Rocks
To get up to speed on the technology, this is a nice overview of html5 .
There is a html5 showcase running on Google's AppEngine gwthtml5.appspot.com via http://www.ongwt.com/post/2010/05/10/html5-slides-:-GWT-Version
GWT+ html5 : http://code.google.com/events/io/2010/sessions.html#GWT video: http://tinyurl.com/26ppnjg
Google App Engine learnings
The Google App Engine framework
On project click properties -> Google -> App Engine -> Configure SDK
For me, C:\eclipse\plugins\com.google.appengine.eclipse.sdkbundle.1.3.0_1.3.0.v200912141120\appengine-java-sdk-1.3.0\
"Trying a Demo Application" : the SDK is located in your Eclipse installation directory, under
plugins/com.google.appengine.eclipse.sdkbundle_VERSION/, where
VERSIONis a version identifier for the SDK.
120> appengine-java-sdk-1.3.0\bin\dev_appserver.cmd appengine-java-sdk-1.3.0\dem
my applicatiion id is dmbgwt
JMS Intro
JMS ~ high load where you can add queue's in front of it to handle weight
Asysnchronous , Message Oriented Middleware
JMS Message Type
Text Message,ObjectMessage,MapMessage..
Queue point to point messaging
Topic – publish /subscribe messaging
A Session is created from the Connection. Unit of work, transactional capability. Responsible for creation of various JMS message types.
Producer (put message on), Consumer (pull message off)
Apache MQ
Destination – point to point or topic are examples
Spring has a JmsTemplate : delegates to collaborators to handle some of work
Message Converter – conver from objects to messages (SimpleMessageConverter)
DestinationResolver – resolve destination names (DynamicDestinationResolver or JNDIDestinationResolver)
Sending messages – one line methods or callback methods
producer call back or session callbacks
MessageDrivenBeans wait for the message. MessageConverters can be used on recption side.
JMS MessageListener aysnchronous reception
Spring has light light weight mechanism for listen for messages, as compared to EJB
SimpleMessageListenerContainer or DefaultMessageListenerContainer
Spring supports 2 phase commit
Testing in Spring 3.0 much better. Use @Setup or @Test , @RunWith @ContextConfiguration annotations.
What is AOP
- Capture functionality used throughout app in a single, reusable way, e.g. transaction, logging, security.
- Transaction management, logging, security are cross cutting concerns cutting across multiple objects.
- AOP is the implementation of these cross cutting concern.
Join point: a point in the execution of a program such as a method call or a field assignment. e.g., method1 in Class A and method2 in Class B are the join points that require transaction related advice.
Pointcut: An expression that selects one or more join points. Advice can be associated with a pointcut expression and runs at any join point method.
Advice: Code that is executed at a particular join point that has been selected by a Poincut. Different types of advices are "around," "before" and "after" advice.
Aspect: A module that encapsulates pointcuts and advice. e.g., transaction, security, logging in this case.
Spring AOP uses aspectJ expression language: http://www.eclipse.org/aspectj
designator (* package.Class.method*(..))
@Before @AfterReturning @AfterThrowing @After @Around
ACID: Atomic, Consistent, Isolated, Durable
ACEGI – former name for spring security ~ every other letter (missing B,D,F,H)
Core Spring via Interface21~SpringSource~VMWare
I am taking the Core Spring Class by VMWARE with Chris Lacy (http://www.chrislacy.net/).
I will note some of the key information I see over the four days.
Building software:
- Spring
- Springsource Tool Suite
- Groovy with NFJS speaker Jeff Brown joining SpringSource
- Spring Roo an application quickstart
Running software
- Spring tc Server is an enterprise version of Tomcat
- Spring DM server an OSGI server built on eclipse
- Spring Source ERS server is an enterprise version of Http server
Previous entries on Spring: DIP, Exceptions , Testing , Spring 2.0 , IBatis Spring , Web Flow
Palm Pre Battery
The Palm Pre , released in summer of 2009, has been my first splash into the smart phone pool. Up to this point, the device known as the Sprint Krzr was the best thing I had ever put my fingers on, since sliced bread. Oh, how the world has changed in a year. Ever since I received my Palm Pre, Apple has put out a new version of its phone that allows you to run multiple applications at the same time, just like the Palm Pre. Moreover, the Android open source operating system rolled out, and appears to be a major player in the smart phone space. Truth be told, I like all the nifty features and applications that my Palm Pre provides. However, the battery is a serious problem. I can't go more than breakfast to dinner without charging the phone. Otherwise, you can forget about getting in touch with me. This is beyond annoying when you are out of pocket, and unable to charge your phone. I found the answer this weekend to the problem. The answer is an extended Palm Pre Battery.
Palm Pre Extended Battery You Tube Video
GWT quiz question
GWT wiki
GWT Best Of 8/21
A basic GWT menu example
gwt 2.0 preview
authentication example
Mr Bloch at Google
GWT future
GWT Atchitecture anyone?
This video begins the subject of GWT design choices. The video touches on a few thing like the :
- HandlerManager class in GWT 1.6
- GwtMocking
- MVP and testing the presenter
- EventBus
This was found on this post – http://stackoverflow.com/questions/1234389/whats-your-recommendation-for-architecting-gwt-applications-mvc-mvp-or-custom
Since I am mainly just familiar with MVC , lets get into MVP…
From this Model-View-Presenter post, it illustrates their are two flavors of the MVP:
a) Dolphin Smalltalk's MVP – http://martinfowler.com/eaaDev/SupervisingPresenter.html
b) Passive View – http://martinfowler.com/eaaDev/PassiveScreen.html
View – widgets, responds to user actions, turns to the presenter to handle these user actions
Presenter – presentation logic, tightly coupled with the view, commands the model, changes presentation according to the application rules.
Model – business objects , doesn't know anything about View/Presenter.
"in MVC there is controller for every widget, and every widget on the screen surface is called view. In MVP on the other hand, due to the elimination of the controller, there is no sentiment for a single widget and the screen itself is called view."
also see : Use MVP , MVP based Component Library, GWT MVP Sample, eventbus and mock tests
Some clarifications for me. Seems Ext – GWT is also known as GXT (found on this page which talks about JSON vs RPC, to spaghtetti code)
Another interesting thing is the post on difference between a toolkit vs framework
- gxt mvc
- gwt tiger
- http://blog.project-sierra.de/archives/907
- http://blog.e-nunes.com.br/2009/07/gwt-and-mvp-model-view-presenter.html
- http://www.smartclient.com/smartgwt/
- http://www.smartclient.com/smartgwt/showcase/
- http://www.alittlemadness.com/2008/04/24/ext-discovers-step-2-of-the-slashdot-business-model/
- http://thompsonng.blogspot.com/2009/04/smartgwtgxt.ht
- http://www.theserverside.com/news/thread.tss?thread_id=52007
Google Tech Group
Noticed there is a Google Technology Group (GTUG) in the Triangle. Their Twitter feed is http://twitter.com/trigtug
Their You Tube Group http://www.youtube.com/user/gtugs
Exception Scenarios
Its been a while since I chimed in on the topic of Exceptions:
Checked : (java.lang.Exception). This type of exception represents useful information about the operation of a legally specified request that the caller may have had no control over and that the caller needs to be informed about. With checked exceptions, Java language forces us to document all the anticipated ways in which control might exit a method:
Unchecked : (java.lang.RuntimeException). These are exceptions that occur as a result of programming errors that the program could not be expected to catch.
Now, it is time to talk about the Exception Handling capabilities with DAOs in the Spring Framework
SQL Exception Translator – sql exception can be translated to a DataAccessException using the translate method
The method HibernateDaoSupport :: convertHibernateAccessException – convert the given HibernateException to an appropriate exception from the org.springframework.dao hierarchy.
SessionFactoryUtils : public static DataAccessException convertHibernateAccessException(HibernateException ex) { if (ex instanceof JDBCConnectionException) { return new DataAccessResourceFailureException(ex.getMessage(), ex); } if (ex instanceof SQLGrammarException) { return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex); } if (ex instanceof DataException) { return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex); } if (ex instanceof LockAcquisitionException) { return new CannotAcquireLockException(ex.getMessage(), ex); } if (ex instanceof ConstraintViolationException) { return new DataIntegrityViolationException(ex.getMessage(), ex); } if (ex instanceof JDBCException) { return new HibernateJdbcException((JDBCException) ex); } if (ex instanceof PropertyValueException) { return new DataIntegrityViolationException(ex.getMessage(), ex); } if (ex instanceof PersistentObjectException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } if (ex instanceof TransientObjectException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } if (ex instanceof ObjectDeletedException) { return new InvalidDataAccessApiUsageException(ex.getMessage(), ex); } if (ex instanceof QueryException) { return new HibernateQueryException((QueryException) ex); } if (ex instanceof UnresolvableObjectException) { return new HibernateObjectRetrievalFailureException((UnresolvableObjectException) ex); } if (ex instanceof WrongClassException) { return new HibernateObjectRetrievalFailureException((WrongClassException) ex); } if (ex instanceof NonUniqueResultException) { return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1); } if (ex instanceof StaleObjectStateException) { return new HibernateOptimisticLockingFailureException((StaleObjectStateException) ex); } if (ex instanceof StaleStateException) { return new HibernateOptimisticLockingFailureException((StaleStateException) ex); } // fallback return new HibernateSystemException(ex); }
Testing through Spring with rollbacks
If you download the spring framework with dependencies, one of the modules included is the spring-test.
– Convenient jar file combining all standard modules (except for the test module and the Spring MVC support)
– Also includes the AOP Alliance interfaces (as a convenience)!
– Does not include contents of spring-aspects.jar, spring-test.jar and spring-webmvc*.jar!
– Contents: test context framework, JUnit support, JNDI mocks, Servlet API mocks, Portlet API mocks
– Dependencies: spring-core, (spring-context, spring-jdbc, spring-web, JUnit, Servlet API, Portlet API)
As the spring documentation mentions, for unit testing transactional systems you can achieve rollback of your tests pretty easily:
Typically you will extend the subclass, AbstractTransactionalDataSourceSpringContextTests. This class also requires that a DataSource bean definition – again, with any name – be present in the application context. It creates a JdbcTemplate instance variable, that is useful for convenient querying, and provides handy methods to delete the contents of selected tables (remember that the transaction will roll back by default, so this is safe to do).
This problem was identified with MySql.
Nice article here on spring test
This link tells us about the spring testing method calls
AbstractTransactionalDataSourceSpringContextTests superclass provides the following services: Injects test dependencies, meaning that we don't need to perform application context lookups. Injection uses autowiring by type. Executes each test method in its own transaction, which is automatically rolled back by default. This means that even if tests insert or otherwise change database state, there is no need for a teardown or cleanup script. If you want a transaction to commit--unusual, but useful if you want a particular test to populate the database, for example--you can call the setComplete() method inherited from AbstractTransactionalSpringContextTests. This will cause the transaction to commit instead of roll back. There is also convenient ability to end a transaction before the test case ends, through calling the endTransaction() method. This will roll back the transaction by default, and commit it only if setComplete() had previously been called. Provides useful inherited protected fields, such as a JdbcTemplate that can be used to verify database state after test operations, or verify the results of queries performed by application code. An ApplicationContext is also inherited, and can be used for explicit lookup if necessary.
All the Spring Test Life Cycle Methods
- getConfigLocations
- setDataSource
- setTransactionManager
- onSetUpBeforeTransaction
- onSetUpInTransaction
- onTearDownInTransaction
- endTransaction
- onTearDownAfterTransaction
Now onto the 2.5 way of testing:
org.springframework.test.context – Spring TestContext Framework which provides annotation-driven unit and integration testing support that is agnostic of the actual testing framework in use.
Spring 2.5 continues this rich and convenient testing framework, while now removing the requirement that your unit tests extend Spring framework tests. Instead of subclassing, it uses java annotations.
Related links:
The IBatis Model
Been a while since I started first looking at IBatis. The Spring Framework has a sample application named JPetstore (available in the core download) that gives you an example of IBatis, Spring, and Struts 1.x .
Different Spring Ibatis SQLMaps approaches:
Use Of Annotations
Implementing DAOs based on plain iBATIS API
<bean id="transactionManager"
<property name="dataSource" ref="dataSource"/>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:/sqlmap-config.xml"/>
<property name="dataSource" ref="dataSource"/>
<?xml version="1.0″ encoding="UTF-8″?>
<!DOCTYPE sqlMapConfig PUBLIC
"-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
<settings defaultStatementTimeout="5″ />
<sqlMap resource="MyType.xml" />
You can actually omit the 'transaction-manager' attribute in the <tx:annotation-driven/> tag if the bean name of the PlatformTransactionManager that you want to wire in has the name 'transactionManager'.
<!– Instructs Spring to perfrom declarative transaction managemenet on annotated classes –>
public void setSqlMapClient(SqlMapClient sqlMapClient) {
iBatisTemplate = new SqlMapClientTemplate(sqlMapClient);
@@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
– The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class. However, please note that the mere presence of the @Transactional annotation is not enough to actually turn on the transactional behavior.
public MyType insertMyType(MyType myType) {
MyType myType = null;
myType= (MyType) iBatisTemplate.insert("insertIntoMyType", MyType;
return myType;
Use Of Spring's DaoSupport Class
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation" value="classpath:/sqlmap-config.xml"/>
<property name="dataSource" ref="dataSource"/>
<?xml version="1.0″ encoding="UTF-8″?>
<!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
<settings useStatementNamespaces="true" />
<sqlMap resource="person.xml" />
PersonDaoIbatisImpl extends SqlMapClientDaoSupport
public void addPerson(Person person) {
Long id = (Long) this.getSqlMapClientTemplate().insert("person.insert",
- org.springframework.orm.ibatis.support.SqlMapClientDaoSupport – Instead of a plain SqlMapClient, you can also pass a preconfigured SqlMapClientTemplate instance in. This allows you to share your SqlMapClientTemplate configuration for all your DAOs
Spring Web Flow Beginner – Part Two
As a total beginner to Spring Web Flow, the main thing I have noticed in going through the material is that there is quite a difference between the 1.x and the new release 2.0.
Web Flow | Spring Web Flow Forum
- Spring WF 1.X API | Spring WF 1.X Reference Guide | Spring WF Practical Intro | Spring WF 1.X Reference Apps | Spring 1.X WF YouTube | Spring WF1 Wiki Article | Spring WF 1 Examined | Spring WF 1 Starter
- Spring WF 1 with Grails
- Spring WF 1 – Struts2
There seems to be in package org.springframework.webflow.action a FlowAction and a FlowExecutor class. As well, the ExternalContext class which is credited to allowing WF to be decoupled from Servlet API .
- Spring WF 2.0.X API | Spring WF 2.0.X Reference Guide | Spring WF 2.0.X Reference Apps | Spring 2 WF Example
I do not see a FlowAction or FlowExecutor in org.spring.webflow.action package like in webflow 1.
Instead, lets look at what we have from the example Spring Flow 2.0 Example application.
To use annotations for the transactions within the example, we do the following:
- Put an tag tx:annotation-driven in the spring config file
- Put @Transactional annotation in the services classes
@Transactional – The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class. However, please note that the mere presence of the @Transactional annotation is not enough to actually turn on the transactional behavior.
You can actually omit the 'transaction-manager' attribute in the <tx:annotation-driven/> tag if the bean name of the PlatformTransactionManager that you want to wire in has the name 'transactionManager'.
<!– Instructs Spring to perfrom declarative transaction managemenet on annotated classes –>
<!– Drives transactions using local JPA APIs –>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
The LocalContainerEntityManagerFactoryBean can be configured with all Persistent Unit information like is done here.
@PersistenceUnit – annotated on EntityManagerFactory instances are thread-safe
<!– Creates a EntityManagerFactory for use with the Hibernate JPA provider and a simple in-memory data source populated with test data –>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!– Deploys a in-memory datasource –>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="url" value="jdbc:hsqldb:mem:tutorialSwf"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
<!– Activates annotation-based bean configuration –>
Mapping URLs to Handlers – maps request URLs to handlers. A simple way to create URL mapping rules is to define one as follows:
<!– Maps request URIs to controllers –>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<prop key="/f/*">flowController</prop>
<property name="defaultHandler">
<!– Selects view names to render based on the request URI: e.g. /main selects "main" –>
<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
The Flow Handler manages executions of a single flow definition. Above the handler selects view based on the URI in a default handler. To Implement one, extend
Flow Controller – The FlowHandler MVC integration approach, you define one handler per flow. This is overkill in the cases where default flow handling rules are sufficient. Web controller for the Spring web MVC framework that routes incoming requests to one or more managed web flows. Requests into the web flow system are managed using a configurable
<!– Handles requests mapped to the Spring Web Flow system –>
<bean id="flowController" class="org.springframework.webflow.mvc.servlet.FlowController"/>
The flow executor is the core Web Flow configuration element. Flow execution listeners are also defined in the flow executor.
<!– Executes flows: the central entry point into the Spring Web Flow system –>
<webflow:flow-executor id="flowExecutor">
<webflow:listener ref="jpaFlowExecutionListener"/>
FlowRegistry – placed where you register your flows
flow-builder-services attribute – customize the services used to build the flows in a registry…When the tag is defined, you only need to reference the services you want to customize.
<!– The registry of executable flow definitions –>
<webflow:flow-registry id="flowRegistry" flow-builder-services="facesFlowBuilderServices">
<webflow:flow-location-pattern value="/WEB-INF/flows/**/*.xml"/>
flow scoped persistence context – provides isolation of intermediate edits by only committing changes to the database at the end of flow execution. This pattern is often used in conjunction with an optimistic locking strategy to protect the integrity of data modified in parallel by multiple users.
@PersistenceContext – annotated on EntityManager instances are not thread safe
<flow xmlns="http://www.springframework.org/schema/webflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/webflow http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
configure the correct FlowExecutionListener in this case for JPA
<!– Installs a listener that manages JPA persistence contexts for flows that require them –>
<bean id="jpaFlowExecutionListener" class="org.springframework.webflow.persistence.JpaFlowExecutionListener">
<constructor-arg ref="entityManagerFactory"/>
<constructor-arg ref="transactionManager"/>
Here is how they handle the view:
<!– Maps logical view names to Facelet templates (e.g. 'search' to '/WEB-INF/search.xhtml' –>
<bean id="faceletsViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.faces.mvc.JsfView"/>
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".xhtml"/>
Or a simple ViewResolver
The IDE Challenge
I have been an Eclipse user most of my Java career. Though, I do have limited experience with Visual Age, Forte, JBuilder, and Netbeans. In the Eclipse space, it has been WSAD, MyEclipse, Eclipse WTP (2.x,3.2, Europa 3.3), and RAD 6/7.
Part of NFJS exposed me to IntelliJ. Here is one take on this IDE.
The Spring Stack 2008 – Part1
Spring 2.0 introduced support for various annotations for configuration purposes, such as:
- @Transactional – The @Transactional annotation may be placed before an interface definition, a method on an interface, a class definition, or a public method on a class. However, please note that the mere presence of the @Transactional annotation is not enough to actually turn on the transactional behavior.
- @Required – used to mark a property as being 'required-to-be-set' (i.e. an annotated (setter) method of a class must be configured to be dependency injected with a value)
- @PersistenceContext – annotated on EntityManager instances are not thread safe
- @PersistenceUnit – annotated on EntityManagerFactory instances are thread-safe
Thus, to use annotations for the transactions for my purposes, I do the following:
- Put an tag tx:annotation-driven in the config file (i.e applicationContext.xml)
- Put @Transactional annotation in the services class implementation that contains operations on the entity manager
Spring 2.5 introduces support for a complete set of configuration annotations:
- @Autowired in combination with support for the JSR-250 annotations @Resource
- @PostConstruct
- @PreDestroy
Spring Web Flow Beginner
As part my learnings of what is new with the Spring Framework, I found a nice Spring Flow 2.0 Example (with JSF and JPA).
The Spring Web Flow 2.0.2 release ( by Erwin Vervaet and Keith Donald ) comes as a separate download from the basic Spring functionality in 2.5.5.
On the Spring Web Flow (SWF) vision from 1.x to 2.x :
"[in 1.0] the SWF controller engine cared for one half of the web request lifecycle; the half related to request processing, often called the action phase. The other half, the render phase, was pushed off on the caller: either Spring MVC, Struts, or JSF front controllers
The downside of this approach is it makes it difficult to apply application control logic during the view rendering phase
Beginning with Web Flow 2.0 M2, the entire web request lifecycle is now under the control of Spring Web Flow, including the view rendering phase.
the ability for the SWF engine to communicate with external systems and conversational contexts over HTTP (embedding the proper flow execution callback URL in the redirect that is sent to the external system)"
Also, note that getting these Spring Flow 2.x reference sample projects are easy to get a hold of. In the download of Web Flow is a projects/build-spring-webflow directory where you can run ant. It will build Web Flow along with the .war files for the sample projects (ant 1.7 and Java 5 are required to build).
There is a Struts2 plugin for Spring Web Flow called struts2webflow
As far as further examples than the ones above, I found some web flow 2.x examples at this site spring by example.
Spring flow 1.0 showed that it could easily integrate with struts. These sample (1.x) applications can also be found on Java Passion Site. A good 1.x reference is the Practical ntroduction . All the samples projects are Spring IDE projects that importable into Eclipse (see springide or plugin central for spring ide).
Here in the 1.x struts example:
Our first action in the jsp is as follows:
Birth Date
This action in the struts config says:
<action path="/flowAction" name="actionForm" scope="request" type="org.springframework.webflow.executor.struts.FlowAction"/>
We also bind to the Action Form:
<form-bean name="actionForm" type="org.springframework.web.struts.SpringBindingActionForm"/>
In the webflow-config.xml we define the flow registry:
<flow:executor id="flowExecutor" registry-ref="flowRegistry"/>
<!– Creates the registry of flow definitions for this application –>
<flow:registry id="flowRegistry">
<flow:location path="/WEB-INF/birthdate.xml"/>
<flow:location path="/WEB-INF/birthdate-alternate.xml"/>
Start State : the first state in the flow
<start-state idref="enterBirthdate" />
View State: selects a view to render
<view-state id="enterBirthdate" view="birthdateForm">
When the execution of the flow starts, enter the enterBirthdate state. Then select the birthdateForm view for display to the user, and pause the flow of execution until a user event happens.
Render Action: initializes the form object.
<action bean="formAction" method="setupForm" />
For view state, above Initializes the backing "form object" by invoking the setupForm method for formAction.
Note that the action was defined in the webflow-config.xml (instance of spring-webflow-config-1.0.xsd)
<bean id="formAction" class="org.springframework.webflow.samples.birthdate.BirthDateFormAction" />
Transition: Each View state must define a transition that leads to another state
<transition on="submit" to="processBirthdateFormSubmit" />
Action state: logic that needs to be executed in context of the request, once executed the result flow is returned which the flow may respond to.
<action-state id="processBirthdateFormSubmit">
<action bean="formAction" method="bindAndValidate">
<attribute name="validatorMethod" value="validateBirthdateForm" />
transition on="success" to="enterCardInformation" />
<transition on="error" to="enterBirthdate" />
Related Links for Basic info on JSF:
- Introducing Java Server Faces (JSF) to 4GL Developers
- JSRs: 127, 252 (1.2)
- An Introduction to JSF
- JSF Hello World
Derby Again
I have used derby a while back. Several years later, I wanted to get it installed again on my machine.
In short, Derby is the Java Database that IBM contributed to the open source community. It was known then as cloudscape.
I start off by getting the bin download from the derby database
create DERBY_HOME environment variable : C:\JAVA\derby10\db-derby-10.2.2.0-bin\
Make sure I have my JAVA_HOME environment variable properly set
add to the PATH: C:\JAVA\derby10\db-derby-10.2.2.0-bin\bin\
from the command line:
ij is the derby sql client command line
ij>connect 'jdbc:derby://localhost:1527/mydb;
C:\JAVA\derby10\db-derby-10.2.2.0-bin\demo\programs\simple>set CLASSPATH=.;%DERB
C:\JAVA\derby10\db-derby-10.2.2.0-bin\demo\programs\simple>java org.apache.derby
.tools.sysinfo -cp embedded SimpleApp.class
Derby embedded engine library (derby.jar)
user-specified class (SimpleApp)
SUCCESS: All Derby related classes found in class path.
get ibm jars for derby
C:\JAVA\derby10\db-derby-10.2.2.0-bin\demo\programs\simple>set CLASSPATH=.;%DERB
C:\JAVA\derby10\db-derby-10.2.2.0-bin\demo\programs\simple>java SimpleApp jccjdb
SimpleApp starting in jccjdbc mode.
Loaded the appropriate driver.
Connected to and created database derbyDB
Created table derbyDB
Inserted 1956 Webster
Inserted 1910 Union
Updated 1956 Webster to 180 Grand
Updated 180 Grand to 300 Lakeshore
Verified the rows
Dropped table derbyDB
Closed result set and statement
Committed transaction and closed connection
SimpleApp finished
/* the default framework is embedded*/
public String framework = "embedded";
public String driver = "org.apache.derby.jdbc.EmbeddedDriver";
public String protocol = "jdbc:derby:";
public static void main(String[] args)
new SimpleApp().go(args);
void go(String[] args)
/* parse the arguments to determine which framework is desired*/
System.out.println("SimpleApp starting in " + framework + " mode.");
The driver is installed by loading its class.
In an embedded environment, this will start up Derby, since it is not already running.
System.out.println("Loaded the appropriate driver.");
Connection conn = null;
Properties props = new Properties();
props.put("user", "user1");
props.put("password", "user1");
The connection specifies create=true to cause
the database to be created. To remove the database,
remove the directory derbyDB and its contents.
The directory derbyDB will be created under
the directory that the system property
derby.system.home points to, or the current
directory if derby.system.home is not set.
conn = DriverManager.getConnection(protocol +
"derbyDB;create=true", props);
System.out.println("Connected to and created database derbyDB");
Creating a statement lets us issue commands against
the connection.
Statement s = conn.createStatement();
We create a table, add a few rows, and update one.
private void parseArguments(String[] args)
int length = args.length;
for (int index = 0; index < length; index++)
if (args[index].equalsIgnoreCase("jccjdbcclient"))
framework = "jccjdbc";
driver = "com.ibm.db2.jcc.DB2Driver";
protocol = "jdbc:derby:net://localhost:1527/";
if (args[index].equalsIgnoreCase("derbyclient"))
framework = "derbyclient";
driver = "org.apache.derby.jdbc.ClientDriver";
protocol = "jdbc:derby://localhost:1527/";
NFJS In Links
The Vietnam Of Computer Science
Jacobsen : Use Cases and Aspects
Clay Shirky : "Its Turtles All the Way Up"
Ted Neward on Rest vs Soap
REST: Get, Post, Put, Delete
Roy Fielding : Architectural Styles & the Design of Network-based Software Architectures
Bob Mcwhirter : the founder of drools (jboss rules) and codehaus
Jess is another rules platform
Habits of Effective Programmers
Darshan Arney takes on: ' The Top software developers are more productive than average software developers not by a factor of 10x or 100x or even 1000x but by 10,000x.'
Book – TopGrading
Raymond : The Cathedral and the Bazaar
Dijkstra: Computer Science is no more about computers than astronomy is about telescopes.
Neal Ford – Thoughtworks
Brian Goetz – Sun
Brian Sam-Bodden – Integrallis
Venkat Subramaniam – Relevance
Starting at about 12:00 tommorow I'll be arriving at NoFluffJustStuff conference – also known as the Research Triangle Software Symposium. This is put on by Jay Zimmerman and his cast of notable experts from the software industry.
There are a lot of good choices on the menu.
JPA Examples
jpa spec jsr 317
open jpa manual
In an applicationserver, EntityManager instances are typically injected, rendering the EntityManagerFactory unnecessary.
- Persistence : contains static helper methods to obtain EntityManagerFactory
instances in a vendor-neutral fashion.
- EntityManagerFactory: is a factory for Entity-Manager
- EntityManager: is the primary JPA interface used by applications.Each EntityManager manages a set of persistent objects, and has APIs to insert new objects and delete existing ones. EntityManagers also act as factories for Query instances.
- Entity: persistent objects that represent datastore records.
- Query: Query interface is implemented by each JPA vendor to find persistent objects that
meet certain criteria. JPA standardizes support for queries using both the Java Persistence Query Language (JPQL) and the Structured Query Language (SQL). You obtain Query instances from an EntityManager.
JPA uses a version field in your entities to detect concurrent modifications to the same datastore record. When the JPA runtime detects an attempt to concurrently modify the same record, it throws an exception to the transaction attempting to commit last. This prevents overwriting the previous commit with stale data.
private int version;
JPA introduces another form of object identity, called entity identity or persistent identity. Entity identity tests whether two persistent objects represent the same state in the datastore.
roller 4 + planet
In this post I will cover getting started with the Roller4.0 blogging software including setting up the planet (aggregation server).
Anyway, I am using the mysql database (5.0.41 community edition) with roller 4
(best available) which i placed in Tomcat's webapps directory naming the folder roller4_0 .
I am using tomcat 5.5 with java5.
Setup: Tomcat's common/classes folder have placed file roller-custom.properties:
Important: You need to put the mysql driver, and two other jars into Tomcats's common/lib directory:
- mysql-connector-java-3.1.13-bin
- activation (obtained from my java 5 lib folder)
- mail (obtained from my java 5 lib folder)
After starting Tomcat, I go to the main screen via url http://localhost:8080/roller4_0/index.jsp
which says I have a successful connection but have no tables . So I click the button to create the tables.
Then, I get the page to create users and the blog.
Yes, you need a planet-custom properties (roller-custom.properties in common/classes) file…
I set up a blog which i called planet which I give a theme of
roller front page…
My weblog template now has
## 1) SITE-WIDE entries (the default)
##set($pager = $site.getWeblogEntriesPager($since, $maxResults))
#set($pager = $planet.getAggregationPager($since, $maxResults))
## The below pager code should work against either
I thought).enable "Enable aggregated site-wide frontpage" (this is on by default)
PlanetModel in the 'rendering.siteModels' list.If you want Planet aggregations to be available to all blogs you can
put the model in the 'rendering.pageModels' list.
individual blogs via the blog's Preferences->Settings page."
cache.dir= /mycache/planetcache
# Tasks which are enabled. Only tasks listed here will be run.
# Set of page models specifically for site-wide rendering
named planet.aggregator.cache.dir, but the planet.properties file
looks like it uses cache.dir
Struts2 Trainings
One of the struts 2 sample applications is the Mailreader application which has training course via Struts from Square One site .
Building Web Applications
Building Struts 2 Applications [ Welcome] [More …]
Struts 2 components
Action Handler, Result Handler, Custom Tags
Interceptor : bring custom code into call stack
- Timer Interceptor
- Prepare (able) – If the Action implements Preparable, calls its prepare method.
value stack : stack of objects that expression language can pull from
- Action instance pushed onto stack
Validating Input (More …)
Request Lifecycle in Struts 2 applications
- User Sends request: User sends a request to the server for some resource.
- FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
- Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.
- Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving the data from database.
- Output rendering: Then the Result render the output.
- Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.
Struts 2 Big Picture
The diagram depicts the architecture of Struts 2 Framework. It shows the the initial request goes to the Servlet container, which is then passed through a standard filer chain.
- ActionContextCleanUp filter: The ActionContextCleanUp filter is optional. It is useful when integrating other technologies such as SiteMesh Plugin.
- FilterDispatcher: the required FilterDispatcher is called, which in turn consults the ActionMapper to determine if the request should invoke an action. If the ActionMapper determines that an Action should be invoked, the FilterDispatcher delegates control to the ActionProxy.
- ActionProxy: The ActionProxy consults the Configuration Files manager, which is initialized via the struts.xml file. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action.
- Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSP or FreeMarker to be rendered. While rendering, the templates can use the Struts Tags provided by the framework. Some of those components will work with the ActionMapper to render proper URLs for additional requests.
- Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file.
- If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.
If you install the war on an application server (like tomcat ) you can easily run the sample projtect. Here is the struts 201 slides
Th version I have of the application mentions: "For more about the MailReader, including alternate implementations and a set of formal Use Cases, please visit the Struts University MailReader site" .
- MailReader Database Worksheet (Struts University)
- MailReader Object Model (Struts University)
- MailReader Tour (Struts University)
- MailReader Use Cases (Struts University)
The full source code for MailReader is available as svn site, binaries, nightlies
Other Struts2 Trainings include Migrating to Struts2 the and JPA .
A Roller 4.o experience
Just last week, I learned about what's new with Roller in 4.0
Thought it was finally time to try my own installation after being a one time user of this Roller platform on JRoller as user on http://www.jroller.com/interjavanet/ . I had forgotten my password over on that blog, and it did not seem to be stright forward on how you get your password reset.
Did I mention that Roller is now on Apache at http://roller.apache.org ?
They have their own wiki now at http://cwiki.apache.org/confluence/display/ROLLER
Anyway, I am using the mysql database (5.0.41 community edition) with roller 4
(apache-roller-src-4.0-rc9) which i placed in Tomcat's webapps directory naming the folder roller4_0 .
I am using tomcat 5.5 with java5.
Setup: Tomcat's common/classes folder have placed file roller-custom.properties:
Important: You need to put the mysql driver, and two other jars into Tomcats's common/lib directory:
- mysql-connector-java-3.1.13-bin
- activation (obtained from my java 5 lib folder)
- mail (obtained from my java 5 lib folder)
AFter starting Tomcat, I go to the main screen via url http://localhost:8080/roller4_0/index.jsp
which says I have a successful connection but have no tables . So I click the button to create the tables.
Then, I get the page to create users and the blog.
References :
Roller n Struts2
Just noticed that Dave Johnson has upgraded Roller in version 4.o to use Struts2 and OpenJPA.
After learning about Webwork last year, I played with using Struts2 examples in a 1.4.x environment.
More web 2.0
Last week was the conference, this week comes people trying to define it. My best definition would be netvibes.com
A checkpoint on Web 2.0 in the enterprise
As such, the situational application would be another web 2.0 concept. this article defines it great.
"where small groups and departments developed their own applications independent of the corporate IT department. Today more and more end users who are not professional programmers are developing web applications that better fit their own needs. A simple example is a wiki, where the users can create and modify the pages and their content. No programmer has to decide ahead of time what the topics of interest will be or the structure and layout of the pages. The users evolve something over time that suites their needs within the time budget they have to invest in the site."
REST is another buzzwodr like this slide presentation that explains it.

subset: commoncrawl