Saturday, November 8, 2014

Writing comments on Script - JavaScript/Angular

/*global define*/

(function () {

    /**
     * @ngdoc load configuration urls
     * @name cat.CONFIG
     */

    // force script to be run in strict mode
    'use strict';

    // define dependencies
    var dependencies = ['cat'];

    define(dependencies, function (CatModule) {
        // define constant values for configuration
        var CONFIG = {
            // base url for catbor applcation
            'BASE': '/cat-application/catbor/',
            // root url for services
            'SERVICES': '/cat-presentation/services/'
        };

        // add defined congiguration constants to the module
        CatModule.constant('CONFIG', CONFIG);

    });

}());

=========
/*global define*/

(function () {

    /**
     * @ngdoc load header controller for module
     * @name cat.HeaderCtrl
     */

    // force script to be run in strict mode
    'use strict';

    // define dependencies
    var dependencies = ['cat',
                        'components/search/search-controller',
                        'common/js/services/rest-client',
                        'common/js/services/session-service'];

    define(dependencies, function (CatModule) {

        /**
         * @ngdoc Initialize header controller.
         * @name cat.HeaderCtrl
         * @requires RestClient, SessionService
         *
         * @description
         * Header controller for the UI header
         */
        function HeaderCtrl(RestClient, SessionService, $rootScope) {
            var vm = this;

            // set RestClient
            vm.RestClient = RestClient;
            // set SessionService
            vm.SessionService = SessionService;
            // set $rootScope
            vm.rootScope = $rootScope;

            // set groupName from localStorage
            vm.groupName = localStorage.groupName;
            // set username from localStorage
            vm.username = localStorage.username;
            // set fullName from localStorage
            vm.fullName = localStorage.fullName;
            // set regionName from localStorage
            vm.regionName = localStorage.regionName;
            // set lastLogin from localStorage
            vm.lastLogin = localStorage.lastLogin;

            // if localStorage productList is available, set productList from localStorage
            if (localStorage.productList) {
                vm.products = JSON.parse(localStorage.productList);
            }

        }

        /**
         * @ngdoc method
         * @name logout
         * @methodOf cat.HeaderController
         *
         * @description
         * Logout the user
         */
        HeaderCtrl.prototype.logout = function () {
            // make the request to logout from the application.
            var vm = this,
                response = vm.RestClient.sendRequest('logout', null, null, 'GET');

            // if logout is successful, then endSession.
            response.then(function (response) {
                if (response.data === 'true') {
                    vm.SessionService.endSession();
                }
            });
        };

        // add defined header controller to the module
        CatModule.controller('HeaderCtrl', HeaderCtrl);

    });

}());

=========

/**
         * @ngdoc controller
         * @name cat.MainCtrl
         * @requires SessionService, $state
         *
         * @description
         * Main controller for the whole application
         */
        function MainCtrl($state, ngDialog, $rootScope, RestClient, SessionService) {
            var vm = this;

            // set SessionService
            vm.SessionService = SessionService;
            // set $state
            vm.state = $state;
            // set ngDialog
            vm.ngDialog = ngDialog;
            // set $rootScope
            vm.rootScope = $rootScope;
            // set RestClient
            vm.restClient = RestClient;

            // on catching sessionActive , set sessionActive
            $rootScope.$on('sessionActive', function (event, data) {
                vm.sessionActive = data;
            });


            // on catching state-change, set state-change
            $rootScope.$on('state-change', function (event, data) {
                // calling outage message notifier
                vm.getOutageMessageNotification(data);
            });

            // if active session is found, direct to Home page
            if (vm.sessionActive) {
                $state.go('Home');
            }
        }


 /**
         * @ngdoc method
         * @name openDialog
         * @methodOf cat.main.mainctrl
         *
         * @description
         * open dialog window.
         */
        MainCtrl.prototype.openDialog = function (url) {
            var vm = this;

            // if service has and active seesion open dialog window.
            if (vm.SessionService.sessionActive.get()) {
                vm.ngDialog.open({
                    template: url + '.html'
                });
            } else {
                // close all dialog windows.
                vm.ngDialog.closeAll();
            }
        };



/**
         * @ngdoc method
         * @name getOutageMessageNotification
         * @methodOf cat.main.mainctrl
         *
         * @description
         * Popping up the outage if it is a product.
         */
        MainCtrl.prototype.getOutageMessageNotification = function (productName) {
            var vm = this,
                response,
                messageData,
                messageFromTime,
                messageToTime,
                path,
                productId;

            // check whether service has active session.
            if (vm.SessionService.sessionActive.get()) {
                //get the productId for the given product name, from product map which returns after calling the session service.
                productId = vm.SessionService.productMap[productName];
                // check whether productId is available.
                if (productId) {
                    // Dummy ID for now.
                    path = productId + '/' + localStorage.userId; // productId + '/' + vm.userId;
                    // send request to accessActiveOutageMessage service to get the message.
                    response = vm.restClient.sendRequest("accessActiveOutageMessage", null, path, 'GET');

                    // validate response and create message
                    response.then(function (response) {

                        // if status is success get the message text from response bind for Notification.
                        if (response.status === 200) {
                            if (response.data) {
                                messageData = response.data.messageText;

                                // Need to bind this via the Notification directive.
                                vm.rootScope.$emit('notifications', messageData, 'success');
                            }
                        }
                    });
                }
            }
        };


==========

define(dependencies, function (CatModule) {

        // convert input for upper case.
        function capitalize() {
            function filter(input, scope) {
                if (input) {
                    // convert input to lowercase
                    input = input.toLowerCase();

                    return input.substring(0, 1).toUpperCase() + input.substring(1);
                }
            }

            return filter;
        }

        // add capitalize function to the module
        CatModule.filter('capitalize', capitalize);

    });

========

*global define*/

(function () {

    /**
     * @ngdoc overview
     * @name cat.balance
     *
     * @description
     * return balance module.
     */

    // force script to be run in strict mode
    'use strict';

    // define dependencies
    var dependencies = ['angular'];

    define(dependencies, function (angular) {

        return angular.module('cat.balance', []);

    });

}());

Thursday, November 6, 2014

Java Updates

Java 5
--------
Features added: 
- Generics: provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). 
- Metadata: also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. 
- Autoboxing/unboxing: automatic conversions between primitive types (such as int) and primitive wrapper classes (such as integer). 
- Enumerations: the enum keyword creates a typesafe, ordered list of values (such as day.monday, day.tuesday, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). 
- Swing: new skinnable look and feel, called synth. 
- Var args: the last parameter of a method can now be declared using a type name followed by three dots (e.g. Void drawtext(string... Lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type. 
- Enhanced for each loop: the for loop syntax is extended with special syntax for iterating over each member of either an array or any iterable, such as the standard collection classesfix the previously broken semantics of the java memory model, which defines how threads interact through memory. 
- Automatic stub generation for rmi objects. 
- Static imports concurrency utilities in package java.util.concurrent. 
- Scanner class for parsing data from various input streams and buffers. 
- Assertions 
- StringBuilder class (in java.lang package) 
- Annotations

Java 6
----------
Features added: 
- Support for older win9x versions dropped. 
- Scripting lang support: Generic API for integration with scripting languages, & built-in mozilla javascript rhino integration 
- Dramatic performance improvements for the core platform, and swing. 
- Improved web service support through JAX-WS JDBC 4.0 support 
- Java compiler API: an API allowing a java program to select and invoke a java compiler programmatically. 
- Upgrade of JAXB to version 2.0: including integration of a stax parser. 
- Support for pluggable annotations 
- Many GUI improvements, such as integration of swingworker in the API, table sorting and filtering, and true swing double-buffering (eliminating the gray-area effect).

Jav 7
--------
Features Added: 
Support for dynamically-typed languages (InvokeDynamic): Extensions to the JVM, the Java language, and the Java SE API to support the implementation of dynamically-typed languages at performance levels near to that of the Java language itself
- Strict class-file checking: Class files of version 51 (SE 7) or later must be verified with the typechecking verifier; the VM must not fail over to the old inferencing verifier.
- Small language enhancements (Project Coin): A set of small language changes intended to simplify common, day-to-day programming tasks: Strings in switch statements, try-with-resources statements, improved type inference for generic instance creation ("diamond"), simplified varargs method invocation, better integral literals, and improved exception handling (multi-catch)
- Upgrade class-loader architecture: A method that frees the underlying resources, such as open files, held by a URLClassLoader
- Concurrency and collections updates: A lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, concurrent linked double-ended queues, and thread-local pseudo-random number generators.
- Internationalization Upgrade: Upgrade on Unicode 6.0, Locale enhancement and Separate user locale and user-interface locale.
- More new I/O APIs for the Java platform (NIO.2), NIO.2 filesystem provider for zip/jar archives, SCTP, SDP, TLS 1.2 support.
- Security & Cryptography implemented Elliptic-curve cryptography (ECC).
- Upgrade to JDBC 4.1 and Rowset 1.1.
- XRender pipeline for Java 2D, Create new platform APIs for 6u10 graphics features, Nimbus look-and-feel for Swing, Swing JLayer component, Gervill sound synthesizer.
- Upgrade the components of the XML stack to the most recent stable versions: JAXP 1.4, JAXB 2.2a, and JAX-WS 2.2.
- Enhanced MBeans.

Tuesday, October 7, 2014

What is a LAMP stack ?

That simply means using Linux, Apache, MySQL and PHP as your Operating System, Web Server, Database, and Programming Language respectively.



Since all these come together in a LAMP package, which you can download and install, they call it a stack.


Below is one comment i came across in net
---
The reason they call it a stack is because each level derives off it's base layer. Your Operating system, Linux, is the base layer. Then Apache, your web daemon sits on top of your OS. Then your database stores all the information served by your web daemon, and PHP (or any P* scripting language) is used to drive and display all the data, and allow for user interaction.
Don't be overly concerned with the term 'stack'. People really just mean software suite or bundle, but you're using it just fine I am sure as you are.

Other terms
----
WAMP, "Windows, Apache, MySQL, and PHP", an application server platform.WAMP

LYME 

http://en.wikipedia.org/wiki/LYME_(software_bundle)

LYME and LYCE are solution stacks composed entirely of free and open-source software to build high-availability heavy duty dynamic web pages. The stacks are composed of:

Monday, June 9, 2014

REST HTTP methods mapping with respect to CRUD operations

Create = PUT with a new URI
         POST to a base URI returning a newly created URI
Read   = GET
Update = PUT with an existing URI
Delete = DELETE
PUT can map to both Create and Update depending on the existence of the URI used with the PUT.
POST maps to Create.
Correction: POST can also map to Update although it's typically used for Create. POST can also be a partial update so we don't need the proposed PATCH method.

Thursday, June 5, 2014

is invalid; nested exception is org.xml.sax.SAXParseException: The prefix "jaxws" for element "jaxws:endpoint" is not bound.

 you will get following error
--------------


org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 33 in XML document from ServletContext resource [/WEB-INF/cxf.xml] is inva
lid; nested exception is org.xml.sax.SAXParseException: The prefix "jaxws" for element "jaxws:endpoint" is not bound.
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
        at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:124)
        at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:93)
        at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130
)
        at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397)
        at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
        at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
        at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
        at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4206)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:943)
        at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:778)
        at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:504)
        at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
        at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
        at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
        at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
        at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
        at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
        at org.apache.catalina.core.StandardService.start(StandardService.java:525)
        at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
        at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
        at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Caused by: org.xml.sax.SAXParseException: The prefix "jaxws" for element "jaxws:endpoint" is not bound.
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:310)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2755)

        at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
        at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
        at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:235)
        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
        at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)
        at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)
        ... 37 more
Jun 5, 2014 4:43:18 PM org.apache.catalina.core.StandardContext start


----------------------

xml  here cxf.xml has missed the xml name spcae for jaxws

xmlns:jaxws="http://cxf.apache.org/jaxws"


-------------

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
                        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

























address="/bookshelfservice" />








How I Explained REST to My Wife

How I Explained REST to My Wife

Ryan Tomayko

Sunday, December 12, 2004

Translations of the following dialog available in JapaneseFrenchVietnameseItalianSpanish,Portuguese, and Chinese. Huge thanks to YAMAMOTO YoheiKarl DubostjishinBarbzTordekEdgard Arakakikeven lw, respectively. If you know of additional translations, please leave a comment with the location.

Wife: Who is Roy Fielding?

Ryan: Some guy. He's smart.

Wife: Oh? What did he do?

Ryan: He helped write the first web servers and then did a ton of research explaining why the web works the way it does. His name is on the specification for the protocol that is used to get pages from servers to your browser.

Wife: How does it work?

Ryan: The web?

Wife: Yeah.

Ryan: Hmm. Well, it's all pretty amazing really. And the funny thing is that it's all very undervalued. The protocol I was talking about, HTTP, it's capable of all sorts of neat stuff that people ignore for some reason.

Wife: You mean http like the beginning of what I type into the browser?

Ryan: Yeah. That first part tells the browser what protocol to use. That stuff you type in there is one of the most important breakthroughs in the history of computing.

Wife: Why?

Ryan: Because it is capable of describing the location of something anywhere in the worldfrom anywhere in the world. It's the foundation of the web. You can think of it like GPS coordinates for knowledge and information.

Wife: For web pages?

Ryan: For anything really. That guy, Roy Fielding, he talks a lot about what those things point to in that research I was talking about. The web is built on an architectural style called REST. REST provides a definition of a resource, which is what those things point to.

Wife: A web page is a resource?

Ryan: Kind of. A web page is a representation of a resource. Resources are just concepts. URLs--those things that you type into the browser...

Wife: I know what a URL is..

Ryan: Oh, right. Those tell the browser that there's a concept somewhere. A browser can then go ask for a specific representation of the concept. Specifically, the browser asks for the web page representation of the concept.

Wife: What other kinds of representations are there?

Ryan: Actually, representations is one of these things that doesn't get used a lot. In most cases, a resource has only a single representation. But we're hoping that representations will be used more in the future because there's a bunch of new formats popping up all over the place.

Wife: Like what?

Ryan: Hmm. Well, there's this concept that people are calling Web Services. It means a lot of different things to a lot of different people but the basic concept is that machines could use the web just like people do.

Wife: Is this another robot thing?

Ryan: No, not really. I don't mean that machines will be sitting down at the desk and browsing the web. But computers can use those same protocols to send messages back and forth to each other. We've been doing that for a long time but none of the techniques we use today work well when you need to be able to talk to all of the machines in the entire world.

Wife: Why not?

Ryan: Because they weren't designed to be used like that. When Fielding and his buddies started building the web, being able to talk to any machine anywhere in the world was a primary concern. Most of the techniques we use at work to get computers to talk to each other didn't have those requirements. You just needed to talk to a small group of machines.

Wife: And now you need to talk to all the machines?

Ryan: Yes - and more. We need to be able to talk to all machines about all the stuff that's on all the other machines. So we need some way of having one machine tell another machine about a resource that might be on yet another machine.

Wife: What?

Ryan: Let's say you're talking to your sister and she wants to borrow the sweeper or something. But you don't have it - your Mom has it. So you tell your sister to get it from your Mom instead. This happens all the time in real life and it happens all the time when machines start talking too.

Wife: So how do the machines tell each other where things are?

Ryan: The URL, of course. If everything that machines need to talk about has a corresponding URL, you've created the machine equivalent of a noun. That you and I and the rest of the world have agreed on talking about nouns in a certain way is pretty important, eh?

Wife: Yeah.

Ryan: Machines don't have a universal noun - that's why they suck. Every programming language, database, or other kind of system has a different way of talking about nouns. That's why the URL is so important. It let's all of these systems tell each other about each other's nouns.

Wife: But when I'm looking at a web page, I don't think of it like that.

Ryan: Nobody does. Except Fielding and handful of other people. That's why machines still suck.

Wife: What about verbs and pronouns and adjectives?

Ryan: Funny you asked because that's another big aspect of REST. Well, verbs are anyway.

Wife: I was just joking.

Ryan: It was a funny joke but it's actually not a joke at all. Verbs are important. There's a powerful concept in programming and CS theory called polymorphism. That's a geeky way of saying that different nouns can have the same verb applied to them.

Wife: I don't get it.

Ryan: Well.. Look at the coffee table. What are the nouns? Cup, tray, newspaper, remote. Now, what are some things you can do to all of these things?

Wife: I don't get it...

Ryan: You can get them, right? You can pick them up. You can knock them over. You can burn them. You can apply those same exact verbs to any of the objects sitting there.

Wife: Okay... so?

Ryan: Well, that's important. What if instead of me being able to say to you, "get the cup," and "get the newspaper," and "get the remote"; what if instead we needed to come up with different verbs for each of the nouns? I couldn't use the word "get" universally, but instead had to think up a new word for each verb/noun combination.

Wife: Wow! That's weird.

Ryan: Yes, it is. Our brains are somehow smart enough to know that the same verbs can be applied to many different nouns. Some verbs are more specific than others and apply only to a small set of nouns. For instance, I can't drive a cup and I can't drink a car. But some verbs are almost universal like GET, PUT, and DELETE.

Wife: You can't DELETE a cup.

Ryan: Well, okay, but you can throw it away. That was another joke, right?

Wife: Yeah.

Ryan: So anyway, HTTP--this protocol Fielding and his friends created--is all about applying verbs to nouns. For instance, when you go to a web page, the browser does an HTTP GET on the URL you type in and back comes a web page.

Web pages usually have images, right? Those are separate resources. The web page just specifies the URLs to the images and the browser goes and does more HTTP GETs on them until all the resources are obtained and the web page is displayed. But the important thing here is that very different kinds of nouns can be treated the same. Whether the noun is an image, text, video, an mp3, a slideshow, whatever. I can GET all of those things the same way given a URL.

Wife: Sounds like GET is a pretty important verb.

Ryan: It is. Especially when you're using a web browser because browsers pretty much justGET stuff. They don't do a lot of other types of interaction with resources. This is a problem because it has led many people to assume that HTTP is just for GETing. But HTTP is actually ageneral purpose protocol for applying verbs to nouns.

Wife: Cool. But I still don't see how this changes anything. What kinds of nouns and verbs do you want?

Ryan: Well the nouns are there but not in the right format.

Think about when you're browsing around amazon.com looking for things to buy me for Christmas. Imagine each of the products as being nouns. Now, if they were available in a representation that a machine could understand, you could do a lot of neat things.

Wife: Why can't a machine understand a normal web page?

Ryan: Because web pages are designed to be understood by people. A machine doesn't care about layout and styling. Machines basically just need the data. Ideally, every URL would have a human readable and a machine readable representation. When a machine GETs the resource, it will ask for the machine readable one. When a browser GETs a resource for a human, it will ask for the human readable one.

Wife: So people would have to make machine formats for all their pages?

Ryan: If it were valuable.

Look, we've been talking about this with a lot of abstraction. How about we take a real example. You're a teacher - at school I bet you have a big computer system, or three or four computer systems more likely, that let you manage students: what classes they're in, what grades they're getting, emergency contacts, information about the books you teach out of, etc. If the systems are web-based, then there's probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc. Right now, getting the URL through the browser gives you a web page. If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. It would also make it quite a bit easier for each of the systems to talk to each other. Or, you could build a state or country-wide system that was able to talk to each of the individual school systems to collect testing scores. The possibilities are endless.

Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.

Wife: So this is what you and all the computer people are working on now? Deciding what the data should look like?

Ryan: Sadly, no. Instead, the large majority are busy writing layers of complex specifications for doing this stuff in a different way that isn't nearly as useful or eloquent. Nouns aren't universal and verbs aren't polymorphic. We're throwing out decades of real field usage and proven technique and starting over with something that looks a lot like other systems that have failed in the past. We're using HTTP but only because it helps us talk to our network and security people less. We're trading simplicity for flashy tools and wizards.

Wife: Why?

Ryan: I have no idea.

Wife: Why don't you say something?

Ryan: Maybe I will.

Tuesday, May 20, 2014

Hibernate – One-To-Many Example


1. “One-to-many” example

This is a one-to-many relationship table design, a STOCK table has many occurrences STOCK_DAILY_RECORD table.
one to many table relationship
See MySQL table scripts
DROP TABLE IF EXISTS `stock`;
CREATE TABLE `stock` (
  `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `STOCK_CODE` VARCHAR(10) NOT NULL,
  `STOCK_NAME` VARCHAR(20) NOT NULL,
  PRIMARY KEY (`STOCK_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
  UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8;
 
 
DROP TABLE IF EXISTS `mkyongdb`.`stock_daily_record`;
CREATE TABLE  `mkyongdb`.`stock_daily_record` (
  `RECORD_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `PRICE_OPEN` FLOAT(6,2) DEFAULT NULL,
  `PRICE_CLOSE` FLOAT(6,2) DEFAULT NULL,
  `PRICE_CHANGE` FLOAT(6,2) DEFAULT NULL,
  `VOLUME` BIGINT(20) UNSIGNED DEFAULT NULL,
  `DATE` DATE NOT NULL,
  `STOCK_ID` INT(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`RECORD_ID`) USING BTREE,
  UNIQUE KEY `UNI_STOCK_DAILY_DATE` (`DATE`),
  KEY `FK_STOCK_TRANSACTION_STOCK_ID` (`STOCK_ID`),
  CONSTRAINT `FK_STOCK_TRANSACTION_STOCK_ID` FOREIGN KEY (`STOCK_ID`) 
  REFERENCES `stock` (`STOCK_ID`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8;
2. create model classes to map for tables

we already have a Stock.java class which was made under package package com.mkyong.common;
 first let's rename it to package com.mkyong.stock;
 so we have better packaging structure
 you have to do few modifications to support the one to many relationship
 
 or else you can make new Stock.java in new package
 
 
 ---------
 
 package com.mkyong.stock;

import static javax.persistence.GenerationType.IDENTITY;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "mkyong", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements Serializable {

/**
*/
private static final long serialVersionUID = 7029806795746254329L;
private Integer stockId;
private String stockCode;
private String stockName;

public Stock() {

}

public Stock(String stockCode, String stockName) {
this.stockCode = stockCode;
this.stockName = stockName;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return stockId;
}

public void setStockId(Integer stockId) {
this.stockId = stockId;
}

@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
public String getStockCode() {
return stockCode;
}

public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}

@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
public String getStockName() {
return stockName;
}

public void setStockName(String stockName) {
this.stockName = stockName;
}
}


-----------------------------------

for StockDailyRecord  create another java class






Errors
----------

1. AppOneToMany.java stockDailyRecords.setStock(stock);  was giving error, mapping to wrong Stock.java
previously on common package.
Reason : StockDailyRecord.java , I have imported import com.mkyong.common.Stock;
so the setter was mapped to com.mkyong.common.Stock;

2. Error in running application 
------------------------------

Hibernate one to many (Annotation)
May 20, 2014 4:11:34 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:11:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:11:34 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:11:34 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:11:34 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:11:34 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.AnnotationException: Use of the same entity name twice: Stock
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.mkyong.util.HibernateUtil.(HibernateUtil.java:8)
at com.mkyong.AppOneToMany.main(AppOneToMany.java:15)
Caused by: org.hibernate.AnnotationException: Use of the same entity name twice: Stock
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:402)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:586)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3435)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3389)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1341)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1731)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
... 2 more
Caused by: org.hibernate.DuplicateMappingException: duplicate import: Stock refers to both com.mkyong.stock.Stock and com.mkyong.common.Stock (try using auto-import="false")
at org.hibernate.cfg.Configuration$MappingsImpl.addImport(Configuration.java:2582)
at org.hibernate.cfg.annotations.EntityBinder.bindEntity(EntityBinder.java:395)
... 9 more

-------------------
Reason : I have included two entries in the "hibernate.cfg.xml"
  
 
 
  
  If you can see above , I have two entries for Stock.java   and
  
  Error itself gives asuggestion to 
  duplicate import: Stock refers to both com.mkyong.stock.Stock and com.mkyong.common.Stock (try using auto-import="false")
  
  solution 1 :First i try with removing one record, 
  execute
  
  ------------------ i still hvae an error--------------
  
  Hibernate one to many (Annotation)
May 20, 2014 4:18:52 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:18:52 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:18:52 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:18:52 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:18:52 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:18:52 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.mkyong.stock.Stock.stockDailyRecords[com.mkyong.stock.StockDailyRecord]
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at com.mkyong.util.HibernateUtil.(HibernateUtil.java:8)
at com.mkyong.AppOneToMany.main(AppOneToMany.java:15)
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.mkyong.stock.Stock.stockDailyRecords[com.mkyong.stock.StockDailyRecord]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1204)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:735)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:670)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1591)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1366)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1731)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
... 2 more

-----------------------
Reason to happen this error
http://stackoverflow.com/questions/4956855/hibernate-problem-use-of-onetomany-or-manytomany-targeting-an-unmapped-clas
Your annotations look fine. Here are the things to check:

make sure the annotation is javax.persistence.Entity, and not org.hibernate.annotations.Entity. The former makes the entity detectable. The latter is just an addition.

if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic entity

make sure you don't have multiple ScopeTopic classes in different packages, and you've imported the wrong one.


So I deleted all the classes Stock.java which was previously put inside to com.mkyong.common; package
I have been using it's references and I deleted all the references from App2.java and StockDetail.java classes

and it's runs fine
----------------

output will be 

---------------

Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: insert into mkyong.stock_daily_record (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) values (?, ?, ?, ?, ?, ?)
Done

-----------

if you need full detail output

-------------------------------------------------------------

Hibernate one to many (Annotation)
May 20, 2014 4:55:34 PM org.hibernate.annotations.common.Version
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
May 20, 2014 4:55:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
May 20, 2014 4:55:34 PM org.hibernate.cfg.Environment
INFO: HHH000206: hibernate.properties not found
May 20, 2014 4:55:34 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
May 20, 2014 4:55:34 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
May 20, 2014 4:55:34 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mkyong]
May 20, 2014 4:55:35 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
May 20, 2014 4:55:35 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 20, 2014 4:55:35 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 20, 2014 4:55:35 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 20, 2014 4:55:35 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)
Hibernate: insert into mkyong.stock_daily_record (DATE, PRICE_CHANGE, PRICE_CLOSE, PRICE_OPEN, STOCK_ID, VOLUME) values (?, ?, ?, ?, ?, ?)
Done








------------------------------------------------