Programming

Java Jar files; Java Libraries; JSON lib;

Java Jar files and Uses

JAR:  aopalliance-repackaged-2.2.0.jar 

Usage: aop alliance will be internally used by

Note : Google Guice Core is a powerful library released by Google for dependency injection, this works with java 6 and above ( download )

JAR:  apache-mime4j-0.6.jar

Usage: apache mime will be used for mime message parsing. This jar internally used by 

  • commons-io
  • commons-logging
  • junit like testing libraries
  • log4j 

JAR : commons-io

Usage – commons io provides utility classes, stream implementations, file filters,file comparators, endian transformation classes

JAR : asm-3.3.jar

Usage : asm jar will be used to analyse the byte code and analyse the frameworks

Note: asm is used by certain code generation libraries like cglib

JAR : gson-2.3.jar 

Usage : gson used to convert java objects into json object. Can be used in struts and springs to convert java objects. ( Documentation )

 JAR : persistence-api-1.0.jar

 Usage : The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications

Dependencies :

  • Servlet-API
  • Javax.inject 

JAR : hk2-api-2.2.0.jar 

Usage : This is called hundred kilobyte kernal for glassfish server, It forma the core glassfish server architecture

 

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Hibernate NoSuchBeanDefinitionException : Java Hibernate Exception

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.cess.service.Employee.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=EmployeeServiceImpl)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:949) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:818) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:730) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) … 25 more

Solution – 

This issue is a strange issue in hibernate autowire for bean objects, the solution will be as follows but no technical description why so ? 🙂

@Autowired
@Qualifier("EmployeeServiceImpl")
EmployeeService employeeService;  //EmployeeService is an interface


			




Change the above @Qualifier as below 
@Qualifier("employeeServiceImpl")

Note : the only change is instead of capital E in EmployeeServiceImpl, it should be small 'e' employeeServiceImpl
If it is reverse case then do make it Capital .

Hibernate QueryException : could not resolve property:

Hibernate QueryException :  could not resolve property:

org.hibernate.QueryException: could not resolve property: DP of: com.cess.pojo.Customer
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:67)
at org.hibernate.persister.entity.AbstractPropertyMapping.toType(AbstractPropertyMapping.java:61)
at org.hibernate.persister.entity.AbstractEntityPersister.getSubclassPropertyTableNumber(AbstractEntityPersister.java:1402)
at org.hibernate.persister.entity.BasicEntityPropertyMapping.toColumns(BasicEntityPropertyMapping.java:54)
at org.hibernate.persister.entity.AbstractEntityPersister.toColumns(AbstractEntityPersister.java:1377)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumns(CriteriaQueryTranslator.java:457)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getColumnsUsingProjection(CriteriaQueryTranslator.java:417)
at org.hibernate.criterion.SimpleExpression.toSqlString(SimpleExpression.java:68)
at org.hibernate.loader.criteria.CriteriaQueryTranslator.getWhereCondition(CriteriaQueryTranslator.java:357)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:113)
at org.hibernate.loader.criteria.CriteriaJoinWalker.(CriteriaJoinWalker.java:82)
at org.hibernate.loader.criteria.CriteriaLoader.(CriteriaLoader.java:91)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1577)
at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:306)
at com.cess.dao.impl.CusomerDaoImpl$1.execute(CustomerDaoImpl.java:77)
at com.cess.framework.TransactionWrapper.run(TransactionWrapper.java:41)
at com.cess.dao.impl.CustomerDaoImpl.getCustomers(CustomerDaoImpl.java:43)
at com.cess.service.impl.CustomerServiceImpl.getCustomers(customerServiceImpl.java:39)
at com.cess.controller.CustomerController.Customers(CustomerController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:746)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:687)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)

			




Solution –
Instead of using nested paths directly in Criteria API (unlike HQL), create nested criteria instances and use aliases on each “entity.property”
Example –







Criteria criteria = sessionObject
.createCriteria(Customer.class, "C")
.createAlias("C.department", "D")
.createAlias("D.Section", "S")
.createAlias("S.SubSection", "SB")

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:383)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.IllegalStateException: Ambiguous mapping found. Cannot map '/project' bean method
public java.util.ArrayList com.cess.controller.UserProjectController.UserProject(com.cess.pojo.Class)
to {[/get],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already '/userinfo' bean method
public java.lang.String com.cess.controller.UserController.userInfo(com.cess.pojo.User) mapped.
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.registerHandlerMethod(AbstractHandlerMethodMapping.java:179)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:145)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:107)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:87)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:150)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 22 more

Solution
If your controller class are as follows








			




@Controller("/userinfo")
public class UserController {
@RequestMapping(method=RequestMethod.POST)
 public String userInfo(@RequestBody User user){
 }
}

@Controller("/userproject") 
public class UserProjectController {

@RequestMapping(method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){
  }
}

//Then Use value Element of @RequestMapping as follows
@Controller
public class UserController {
 
 @RequestMapping(value = "/getuserinfo", method=RequestMethod.POST)
 
  public String userInfo(@RequestBody User user){

  }
}


@Controller
public class UserProjectController {
 //Note value in both controller requestMapping should be different
 
 @RequestMapping(value = "/getuserproject",method=RequestMethod.POST)
  public String userProject(@RequestBody UserProject userProject){

  }
}

Understanding of computer Memory With a C Program

Memory is one of the important resource , we can say its a crucial resource in computers. In a limited amount of memory an operating system tries to satisfy all the applications and the need of memory.

Let us try to understand how a memory looks – the theory and an example simple program to understand the concept in a better way.

Memory –

 memory

 Understanding Of Memory

When we say a memory is allocated for an instance ! How exactly you visualise the memory and allocation ?

A memory is array of smallest unit of space which is nothing but a byte of space location. If a variable holds an integer, float or any type of data, it occupies certain set of such memory locations. Typically it looks like below.

Array of memory locations

In the above memory structure we can see how data is stored in memory.

The String “XYZ” , the number 15 , it looks like at location 12, number 15 is stored, starting from location 21, string XYZ is stored.

If I dig into the depth of it, every thing in computers will be converted into binary , so ‘X’ will be converted into binary which occupies 8 bits , similarly each character will be converted to its ASCII and the ASCII value will be converted to binary ( Ref – http://sticksandstones.kstrom.com/appen.html )

Let us consider one example and try to fill the memory locations 

char subjects[3][2][25] ;

The above character multidimensional array will holds 2 subjects of 3 semesters each of length 25 characters.

subjects[0] -> will give you 2 subjects of first sem, each subject of 25 characters.

subjects[1] -> will give you 2 subjects of second sem, each subject of 25 characters.

If I assign the subjects to this array , the subject names in memory looks like below

charArrayinMemory

For better understanding just check the below diagram of memory layout

Memory Layout

 

Introduction to Struts

Struts is an open source web application framework which will be used to develop the web-
based applications. Struts framework was implemented based on 3 popular design patterns.

  • MVC design pattern.
  • Front Controller design pattern.
  • Application Controller design pattern.

MVC design pattern :-

There are 3 layers in MVC Design pattern

I.  Presentation Layer

II.  Controller Layer

III.  Model Layer

Capture1

I Presentation Layer :-

It contains the presentation logic and can be implemented with JSP or with any other presentation frameworks like flex, velocity etc. Struts Presentation Layer contains following components.

1)     JSPs/HTMLs
2)      Struts custom tags
3)      Form Beans
4)      Message Bundles

1)     JSPs/HTMLs:

In struts presentation layer JSPs will be used to display the data to the client and also used to receive the input data from the client.

2)      Struts custom tags:

Apache has implemented various custom tags for the struts based application development and are categorized as follows.

  • Html tag libraries
  • Bean tag libraries
  • Logic tag libraries
  • Tiles tag libraries
  • Template tag libraries
  • Nested tag libraries
  1. Form Beans:

Form bean is a simple java bean styled class which stores the data. When we are writing the form bean java class, the bean class must be a subclass of one of the following.

  • ActionForm
  • DynaActionForm
  • ValidatorForm
  • DynaValidatorForm
  • ValidatorActionForm
  • DynaValidatorActionForm

 

  1. Message Bundles:

Message Bundles are nothing but property files which contain key value pair. Mainly message bundles will be used to achieve i18n (internationalization).

II Controller Layer :-

The Controller portion of the application is focused on receiving requests from the client (typically a user running a web browser), deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. Following are the various components which we use in struts controller layer.   

   i)   ActionServlet

   ii)  RequestProcessor

   iii)  Action class

 i) ActionServlet:

ActionServlet is the one and only servlet for the entire struts application which is implemented based on Front controller design pattern and this servlet is loaded during server startup time. ActionServlet is responsible for receiving all incoming request and delegating to RequestProcessor. It also initialize the struts-config.xml file.

 ii)  RequestProcessor

RequestProcessor is responsible for processing all incoming request. It is implemented on Application Controller Design pattern. RequestProcessor is responsible for identifying the incoming action class and its form bean, it is also responsible for managing life cycle of form bean. After getting response, it manages to return to corresponding jsp by using ActionForward.

iii)  Action class

Action Class is the beginning of application’s business logic.

III Model Layer : –

Since there are no predefined components for model layer in struts like presentation layer and controller layer, so struts will not deal with model layer. But struts allows us to make use of any of the following model layer.

i)    Simple JDBC component

ii)   DAO + Hibernate

iii)  DAO + JDBC

iv)  Spring

v)   Web services     etc…

STRUTS FLOW

Capture1flow diagram showing struts flow

Steps for the flow         

  • When we submit the request after entering value in jsp form, request will be submitted to ActionServlet which is configured in web.xml.
  • This ActionServlet is responsible for initializing struts-config.xml and this struts-config.xml file is     configured in web.xml.
  • ActionServlet delegates the request to RequestProcessor
  • RequestProcessor takes the incoming request uri and tries to find the matching <action> tag in struts-config.xml. If no matching action is found, then client will get “cannot retrieve mapping for action”.
  • Once matching action is found for the incoming request uri, then corresponding “name” will be taken and tries to find the corresponding <form-bean> under <form-beans> configuration. If no matching <form-bean> is found then client will get the error called “cannot retrieve definition for form beans”.
  •  Once matching is found, RequestProcessor is responsible for managing form-bean life cycle.
  •  RequestProcessor takes the <action> “type” which is Action java class and create the instance    for the first time. With that Action class instance, execute() method  will be called.
  •  Once execute() method is completed ActionForward will be returned to RequestProcessor with      the forward name associated with the ActionForward object and RequestProcessor will try to  identify corresponding <forward> inside struts-config.xml file.
  •  Once the forward is found then its path will be taken and will be forwarded to the client.
  •   RequestProcessor takes the <action> “type” which is Action java class and create the instance     for the first time. With that Action class instance, execute() method  will be called.
  •  Once execute() method is completed ActionForward will be returned to RequestProcessor with  the forward name associated with the ActionForward object and RequestProcessor will try to  identify corresponding <forward> inside struts-config.xml file.
  •  Once the forward is found then its path will be taken and will be forwarded to the client.

 

Swift – Apple’s New Programming Language

Apple is awesome 🙂 , they always look towards something new ! Objective C is pretty old , yeah its 20+ years old now, so Apple thought its time to change now, and we have Swift with us now.

All About Swift you should know

Swift is a multi-paradigm programming language developed by Apple for use with iOS and OS X. Designed to replace Objective C, work began on Swift in 2010 and the first mobile app was debuted in June 2014 at the Worldwide Developers Conference. Despite its goal of replacing Objective C, Swift is capable of working flawlessly alongside the more dated Objective C language while using the Cocoa and Cocoa Touch frameworks. Swift adopts safe programming patterns and adds modern features to make programming easier, modern, powerful, expressive, and flexible.

Apple laid the foundation for Swift by advancing its existing compiler, debugger, and framework infrastructure. Memory management was simplified with Automatic Reference Counting (ARC). The framework stack, built on the solid base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C itself has evolved to support blocks, collection literals, and modules, enabling framework adoption of modern language technologies without disruption. With this groundwork, they introduce a new language Swift for the future of Apple software development.

It is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language. It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app.

What are the requirements?

  • Developer access to Xcode 6 beta
  • A Mac computer that can run Xcode 6
  • Work with Xcode’s new .playground file

How is Swift Efficient?

Fast : Swift was built to be fast. Compiles and optimizes with the advanced code analysis in LLVM compiler included in Xcode 6 beta, and uses the Objective-C runtime, allowing Objective-C, Objective-C++ and Swift code to run within a single program.

This creates high-performance apps by transforming Swift code is into optimized native code, in turn to get the most out of modern Mac, iPhone, and iPad hardware.

Complete platform : It provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand from the frameworks with swift.

Safe by design : Eliminate huge categories of bugs, crashes, and security holes. Swift pairs increased type safety with type inference, restricts direct access to pointers, and automatically manages memory using ARC, making it easy for you to use Swift and create secure, stable software. Other language safety related features include mandatory variables initialization, automatic bounds checking to prevent overflows, conditionals break by default, and elimination of pointers to direct memory by default.

Modern : Write, debug, and maintain less code, with an easy to write and read syntax, and no headers to maintain. Swift includes optionals, generics, closures, tuples, and other modern language features. Inspired by and improving upon Objective-C, Swift code feels natural to read and write.

Interactive: Use Swift interactively to experiment with your ideas and see instant results.

Unified : A complete replacement for both the C and Objective-C languages. Swift provides full object-oriented features, and includes low-level language primitives such as types, flow control, and operators

How Swift works?

  • You don’t need to import a separate library for functionality like input/output or string handling.
  • Code written at global scope is used as the entry point for the program, so you don’t need a main function.
  • You also don’t need to write semicolons at the end of every statement.
  • Swift provides its own versions of all fundamental C and Objective-C types, including Int for integers; Double and  Float for floating-point values; Bool for Boolean values; and String for textual data. Swift also provides powerful versions of the two primary collection types, Array and Dictionary.
  • Swift uses variables to store and refer to values by an identifying name. Swift also makes extensive use of variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that do not need to change.
  • Use let to make a constant and var to make a variable.
  • The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

let constantValue = 88

  • A constant or variable must have the same type as the value you want to assign to it.
  • However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type.
  •  In the example below, the compiler infers that myVariable is an integer because its initial value is a integer.

var myVariable = 44

myVariable = 63

  • If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.

let integerConstant = 65

let doubleConstant = 65.0

let explicitDoubleConstant: Double = 70

  • Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.

let widthString = "The width is "

let widthValue = 94

let widthLabel = widthString + String(widthValue)

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples."

let fruitSummary = "I have \(apples + oranges) pieces of fruit."

  • Collection Types

Swift provides two collection types, known as arrays and dictionaries, for storing collections of values. Arrays store ordered lists of values of the same type. Dictionaries store unordered collections of values of the same type, which can be referenced and looked up through a unique identifier (also known as a key).

  • Arrays :

Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets.

The example below creates an array called shoppingList to store String values. The shoppingList variable is declared as “an array of String values”, written as String[].

var shoppingList: String[] = ["Eggs", "Milk"]

// shoppingList has been initialized with two initial items

To find out the number of items in an array, check its read-only count property,

println("The shopping list contains \(shoppingList.count) items.")

// prints “The shopping list contains 2 items.”

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

if shoppingList.isEmpty {

     println(“The shopping list is empty.”)

} else {

     println(“The shopping list is not empty.”)

}

// prints “The shopping list is not empty.”

You can add a new item to the end of an array by calling the array’s append method:

shoppingList.append("Flour")

// shoppingList now contains 3 items, and someone is making pancakes

Alternatively, add a new item to the end of an array with the addition assignment operator (+=):

shoppingList += "Baking Powder"

// shoppingList now contains 4 items

You can also append an array of compatible items with the addition assignment operator (+=):

shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

// shoppingList now contains 7 items

Retrieve a value from the array by using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array:

var firstItem = shoppingList[0]

// firstItem is equal to “Eggs”

Note that the first item in the array has an index of 0, not 1. Arrays in Swift are always zero-indexed.

You can use subscript syntax to change an existing value at a given index:

shoppingList[0] = "Six eggs"

// the first item in the list is now equal to “Six eggs” rather than “Eggs”

You can also use subscript syntax to change a range of values at once, even if the replacement set of values has a different length than the range you are replacing. The following example replaces “Chocolate Spread”, “Cheese”, and “Butter” with “Bananas” and “Apples”:

shoppingList[4...6] = ["Bananas", "Apples"]

// shoppingList now contains 6 items

To insert an item into the array at a specified index, call the array’s insert(atIndex:) method:

shoppingList.insert("Maple Syrup", atIndex: 0)

// shoppingList now contains 7 items

// “Maple Syrup” is now the first item in the list

Remove an item from the array with the removeAtIndex method. This method removes the item at the specified index and returns the removed item (although you can ignore the returned value if you do not need it):

let mapleSyrup = shoppingList.removeAtIndex(0)

// the item that was at index 0 has just been removed

// shoppingList now contains 6 items, and no Maple Syrup

// the mapleSyrup constant is now equal to the removed “Maple Syrup” string

Iterating Over an Array

You can iterate over the entire set of values in an array with the for-in loop:

for iteminshoppingList {

      println(item)

}

If you need the integer index of each item as well as its value, use the global enumerate function to iterate over the array instead. The enumerate function returns a tuple for each item in the array composed of the index and the value for that item. You can decompose the tuple into temporary constants or variables as part of the iteration:

for (index, value) inenumerate(shoppingList) {

       println(“Item \(index + 1): \(value)”)

}// Item 1: Six eggs

  • Dictionary :

A dictionary is a container that stores multiple values of the same type. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order. You use a dictionary when you need to look up values based on their identifier

Swift’s dictionary type is written as Dictionary<KeyType, ValueType>,where KeyType is the type of value that can be used as a dictionary key, and ValueType is the type of value that the dictionary stores for those keys.

The only restriction is that KeyType must be hashable—that is, it must provide a way to make itself uniquely representable. All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and all of these types can be used as the keys of a dictionary.

In a dictionary literal, the key and value in each key-value pair are separated by a colon. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets:

[key 1: value 1, key 2: value 2, key 3: value 3]

var airports: Dictionary<String, String> = [“TYO”: “Tokyo”, “DUB”: “Dublin”]

The airports dictionary is declared as having a type of Dictionary<String, String>, which means “aDictionary whose keys are of type String, and whose values are also of type String”.

You access and modify a dictionary through its methods and properties, or by using subscript syntax. As with an array, you can find out the number of items in a Dictionary by checking its read-only count property:

println("The dictionary of airports contains \(airports.count) items.")

// prints “The dictionary of airports contains 2 items.”

You can add a new item to a dictionary with subscript syntax. Use a new key of the appropriate type as the subscript index, and assign a new value of the appropriate type:

airports["LHR"] = "London"

// the airports dictionary now contains 3 items

You can also use subscript syntax to change the value associated with a particular key:

airports["LHR"] = "London Heathrow"

// the value for “LHR” has been changed to “London Heathrow”

As an alternative to subscripting, use a dictionary’s updateValue(forKey:) method to set or update the value for a particular key. Like the subscript examples above, the updateValue(forKey:) method sets a value for a key if none exists, or updates the value if that key already exists. Unlike a subscript, however, the updateValue(forKey:) method returns the old value after performing an update. This enables you to check whether or not an update took place.

The updateValue(forKey:) method returns an optional value of the dictionary’s value type. For a dictionary that stores String values, for example, the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed:

if letoldValue = airports.updateValue("Dublin International", forKey: "DUB") {

      println(“The old value for DUB was \(oldValue).”)

}

// prints “The old value for DUB was Dublin.”

You can use subscript syntax to remove a key-value pair from a dictionary by assigning a value of nil for that key:

airports["APL"] = "Apple International"

// “Apple International” is not the real airport for APL, so delete it

airports[“APL”] = nil

// APL has now been removed from the dictionary

Alternatively, remove a key-value pair from a dictionary with the removeValueForKey method. This method removes the key-value pair if it exists and returns the removed value, or returns nil if no value existed:

if letremovedValue = airports.removeValueForKey("DUB") {

    println(“The removed airport’s name is \(removedValue).”)

} else {

    println(“The airports dictionary does not contain a value for DUB.”)

}

// prints “The removed airport’s name is Dublin International.”

Iterating Over a Dictionary

You can iterate over the key-value pairs in a dictionary with a for-in loop. Each item in the dictionary is returned as a (key, value) tuple, and you can decompose the tuple’s members into temporary constants or variables as part of the iteration:

for (airportCode, airportName) inairports {

    println(“\(airportCode): \(airportName)”)

}

// TYO: Tokyo

// LHR: London Heathrow

For more about the for-in loop, see For Loops.

You can also retrieve an iteratable collection of a dictionary’s keys or values by accessing its keys and values properties:

for airportCodeinairports.keys {

   println(“Airport code: \(airportCode)”)

}

// Airport code: TYO

// Airport code: LHR

for airportNameinairports.values {

     println(“Airport name: \(airportName)”)

}

// Airport name: Tokyo

// Airport name: London Heathrow

  • To create an empty array or dictionary, use the initializer syntax.

let emptyArray = String[]()

let emptyDictionary = Dictionary<String, Float>()

  • If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.

shoppingList = [] // Went shopping and bought everything.

  • Swift introduces advanced types not found in Objective-C. These include tuples, which enable you to create and pass around groupings of values. Tuples can return multiple values from a function as a single compound value.
  • Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nilpointers in Objective-C and are at the heart of many of Swift’s most powerful features.
  • Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process

Web Services – Chapter 2

RESTFul Web Services – A First Step

Before starting with RESTFul web services , one must be knowing the basics of web services, We have studied basics of web services in our previous chapter, Once you learn basics, it will be great to go ahead.

As we discussed in previous chapter Web services plays a major role in future of web. We will try to learn how the things will be developed, we will have a hands on with development of web services using java. Before starting with web service development we will like to give step-by-step guide for java setup.

We need java sdk installed, tomcat server installed and eclipse as an IDE for development. Web services can be developed with PHP, C# .net , Ruby on Rails. Since our team is comfortable with java, we would like to write further chapters targeting java for the same.

Set-up for Mac Users
Install Java sdk
1> Download jdk 7 from the link

2> Double click on .dmg file , which opens a window and double click on package file as shown in the fig below.

jdk dmg img

3> Click continue in the installation window

4> Enter user name and password of your system

Install tomcat
1> Download tomcat from the link
(Download the zipped file – zip (pgp, md5) )

2> Unarchive the tomcat folder from your download folder.

3> Open the terminal and execute the following commands

These commands are used just to move the tomcat folder into /user/local folder.

sudo mkdir -p /usr/local

sudo mv ~//apache-tomcat-7.0.47 /usr/local

(Usually it will be sudo mv ~/Downloads/apache-tomcat-7.0.47 /usr/local)

4> Create symbolic link for the tomcat – this helps to keep tomcat updated when we get latest tomcat updates.
First create tomcat folder
sudo rm -f /Library/Tomcat

Create symbolic link of tomcat
sudo ln -s /usr/local/apache-tomcat-7.0.47 /Library/Tomcat

5> To make tomcat executable, the ownership of the folder must be changed
sudo chown -R <your_username> /Library/Tomcat

6> To start and stop tomcat we need to run the scripts, to set the execute permission to scripts run the below command

The installation of tomcat is done!
Check whether tomcat starts smoothly or not by starting tomcat with the script
Screen Shot 2014-06-04 at 8.50.01 pm
knowledgecess:~ cess$ /Library/Tomcat/bin/startup.sh

Using CATALINA_BASE: /Library/Tomcat
Using CATALINA_HOME: /Library/Tomcat
Using CATALINA_TMPDIR: /Library/Tomcat/temp
Using JRE_HOME: /Library/Java/Home
Using CLASSPATH: /Library/Tomcat/bin/bootstrap.jar:/Library/Tomcat/bin/tomcat-juli.jar

knowledgecess:~ cess$ /Library/Tomcat/bin/shutdown.sh
Using CATALINA_BASE: /Library/Tomcat
Using CATALINA_HOME: /Library/Tomcat
Using CATALINA_TMPDIR: /Library/Tomcat/temp
Using JRE_HOME: /Library/Java/Home
Using CLASSPATH:
/Library/Tomcat/bin/bootstrap.jar:/Library/Tomcat/bin/tomcat-juli.jar
knowledgecess:~ cess$

In our next chapter let us try to create a sample on web services in Java.

Web Services – Chapter 1

We know a typical client-server communication model , where a client request for useful data and server responds with the valid data over network. The way of communication might differ based on the type of software running at server side, which means if a server is just an ftp server then one has to get the file by running an ftp command, if the type of resource is just a static html page then a simple http get request is sufficient and the communication can be achieved with a suitable communication protocol. The concept of web service gives real boost to the mode of communication between client and server. The client server model becoming more complex than ever with awesome facilities over the internet. Web services are identified as latest technological changes that is enriching the world of business. Software modules written on any language can talk to each other to transfer a set of resources over the internet. This was not the case before web services, with the help of web services both client and server became loosely coupled. With this overview of web services, let us define the web services and understand the concept in depth.

Definition Of Web Services –

Web service is a mode of communication between two devices provided by a software system running at network address over the web, designed and developed to support interoperable machine-to-machine communication over the internet.

The term interoperable in the above definition means a lot when we discuss about web services. The simplest meaning of interoperability is working together, irrespective of the type of communicating devices , both the devices should be able to share the information by exchanging data in the form of specific data format or communication protocols to produce a meaningful result.

To make the concept more clear , let us take an example which describes where and how web services sits in the entire process of communication.

-Assume that you have a set of huge data stored in your server, the data which is collected from your extensive research on physics. If you would like to share your data to the external world in a very meaningful structured way then you can’t just post every data on your website. Because sharing data in a web site is not a structured way , structured way means according to me , share every bit of data but one should use it as per their need.

If one wants data related to astrophysics could be able to fetch only related data, if one wants data related to modern physics could be able to fetch only related data. To achieve this the only best approach is web services.

Develop a software module that query the related set of data from your server and responds to the client by sending only that piece of information. The client here may be of any kind, It might be a mobile application, tablet application, desktop application or web application. Irrespective of the type of client, your software module responds the right information as per the incoming request. Let us understand this with the help of architectural diagram.

Web Services – Architectural Diagram

Architecture Web Services

 

Above diagram is self explanatory which describe about 5 modules , the important point that is clear from the architecture is, a web service software module deployed in the server is capable to process request from any type of client and serve the requested information, this is what we call as interoperability. Web services hence take the web technology to the next level.

How is that Practical –

So far what we discussed is just a theoretical approach of understanding web services. Being a software developer you will be interested to learn how to develop/consume web services. Web services can be developed using any server side

language , Java, C# .net, PHP , Ruby On Rails etc.There are mainly two types of web services SOAP Services and RESTFul services.

1. SOAP Services – Web services can be developed by adopting SOAP protocol , where client-server communication happens by describing the details with WSDL ( Web Service Definition Language ). An XML language will be used to define the message format , which will be sent across the network.

2. RESTFul Services – Representational State Transfer is an information transfer , the services responds to the request with a help of unique service URL and set of data as input for the service. XML is not mandatory , the data can be passed either in plain text or JSON format.

We will learn development of RESTFul web services using Java in our next chapter.