Ads Header

Monday, September 8, 2014

To get the value of the selected radioName item of a form called 'myForm'

Here is how:

$('input[name=radioName]:checked', '#myForm').val()

How to generate ebay affilication link

Today, I am trying to find out how to generate the ebay affilicate link after I use ebay api to get the items, here looks like a solution, and it works:

Affiliate Tracking

Affiliates earn money from eBay for driving traffic to eBay. For more information, see eBay Partner Network.
eBay knows that a sale came from your application because you include your affiliate ID in your API calls. Affiliate tracking is enabled for all of the search calls in the Finding API.
Affiliate-related fields, which are included in a call request using the affiliate container, enable the tracking of user activity. The affiliate container has the following fields: networkIdtrackingId, and customId. If you are registered with eBay Partner Network, the networkId is 9 and the trackingId is the Campaign ID. The Campaign ID is given to you by eBay Partner Network.
The networkId specifies the third party who is your tracking partner. When specifying affiliate details, this field is required. Not all partners are valid for all sites.
The trackingId specifies an ID to identify you to your tracking partner. The value you specify is obtained from your tracking partner. For eBay Partner Network, the trackingId is the Campaign ID ("campid") provided by eBay Partner Network. A Campaign ID is a 10-digit, unique number to be used for associating traffic. A Campaign ID is valid across all programs to which you have been accepted.
The customId need not be specified. You can define a customId (up to 256 characters) if you want to leverage it to better monitor your marketing efforts. If you are using the eBay Partner Network, and you provide a customId, it will be contained in the tracking URL returned by eBay Partner Network.
The following example shows sample input with the affiliate container:

Sample Input for Affiliate Tracking (XML)

... <affiliate>   <trackingId>1234567899</trackingId>   <networkId>9</networkId>   <customId>234</<customId> </AffiliateTrackingDetails> ... 
The following example shows how to specify your affiliate tracking details in a URL:

Sample Input for Affiliate Tracking (URL)

...&affiliate.trackingId=1234567899&affiliate.networkId=9&affiliate.customId=234... 
When you use the AffiliateTrackingDetails container, a URL is returned that includes information for tracking user activity.
The following example shows a sample URL returned after you specified a TrackingPartnerCode of 9 in the AffiliateTrackingDetails container:
Sample Output URL For Affiliate Tracking
<viewItemURL>   http://rover.ebay.com/rover/1/711-53200-19255-0/1?campid=1234567899&customid=234&toolid=0&mpre=http%3A%2F%2F   cgi.ebay.com%2FWhite-Apple-iPod-M9245LL-A_W0QQitemZ170001978557QQcmdZViewItemQQptZLH_DefaultDomain_0%3Fhash%3D   item170001978557 </viewItemURL> 
For more information about the Affiliate Program, see eBay Partner Network.

Online Regex test tool http://regexr.com

This tool can test and do the replacement for your regex expressions, another good and free tool online!

View JSON object online through tool http://jsonviewer.stack.hu/

Today I am trying to find a tool which can help me understand the JSON result from google shop, and I find this online JSON object tool is really wonderful and handy! Want to share it with all of you:

Design thinking

Overview

Design thinking has come to be defined as combining empathy for the context of a problem, creativity in the generation of insights and solutions, and rationality in analyzing and fitting various solutions to the problem context.[2] According to Tim Brown, CEO and president of IDEO, the goal of Design Thinking is "matching people’s needs with what is technologically feasible and viable as a business strategy" [3] The premise of teaching Design Thinking is that by knowing about how to successfully approach and solve difficult, multi-dimentional problems, more specifically; effective methods to ideate, select and execute solutions, individuals and businesses will be able to improve their own problem solving processes and skills. There is also significant academic interest in understanding how designers think and design cognition.[4] The first formal academic research symposium on Design Thinking was organized at Delft University of Technology, The Netherlands, in 1991, and has developed into a regular series.[5]

Origins of the term

(For a detailed evolution, see History, below.)
The notion of design as a "way of thinking" in the sciences can be traced to Herbert A. Simon's 1969 book The Sciences of the Artificial,[6] and in design engineering to Robert McKim's 1973 book Experiences in Visual Thinking.[7] Rolf Faste expanded on McKim's work at Stanford in the 80's and 90's,[8][9] teaching "design thinking" as a method of creative action."[10] Peter Rowe's 1987 book Design Thinking, which described methods and approaches used by architects and urban planners, was a significant early usage of the term in the design research literature.[11] "Design Thinking" was adapted for business purposes by Faste's Stanford colleague David M. Kelley, who founded IDEO in 1991.[12]Richard Buchanan's 1992 article, entitled "Wicked Problems in Design Thinking",[13] expressed a broader view of "design thinking" as addressing intractable human concerns through design.
Design Thinking Example Video

Solution-based thinking

Design thinking is a formal method for practical, creative resolution of problems and creation of solutions, with the intent of an improved future result. In this regard it is a form of solution-based, or solution-focused thinking; starting with a goal (a better future situation) instead of solving a specific problem. By considering both present and future conditions and parameters of the problem, alternative solutions may be explored simultaneously. Cross asserted that this type of thinking most often happens in the built, or artificial, environment (as in artifacts).[14]
This approach differs from the analytical scientific method, which begins with thoroughly defining all the parameters of the problem in order to create a solution. Design Thinking identifies and investigates with both known and ambiguous aspects of the current situation in order to discover hidden parameters and open alternative paths which may lead to the goal. Because Design Thinking is iterative, intermediate "solutions" are also potential starting points of alternative paths, including redefining of the initial problem.

Bryan Lawson Architects vs. Engineers, 1979

In 1972, psychologist, architect and design researcher Bryan Lawson created an empirical study to understand the difference between problem-based solvers and solution-based solvers. He took two groups of students – final year students in architecture and post-graduate science students – and asked them to create one-story structures from a set of colored blocks. The perimeter of the building was to optimize either the red or the blue color, however, there were unspecified rules governing the placement and relationship of some of the blocks.
Lawson found that:
The scientists adopted a technique of trying out a series of designs which used as many different blocks and combinations of blocks as possible as quickly as possible. Thus they tried to maximize the information available to them about the allowed combinations. If they could discover the rule governing which combinations of blocks were allowed they could then search for an arrangement which would optimize the required color around the design. By contrast, the architects selected their blocks in order to achieve the appropriately colored perimeter. If this proved not to be an acceptable combination, then the next most favorably colored block combination would be substituted and so on until an acceptable solution was discovered.[15]
Nigel Cross concluded from Lawson's studies that scientific problem solving was done by analysis, while "designers" problem solve through synthesis.[14] Kelley and Brown argue the Design Thinking utilizes both analysis and synthesis.

Analysis versus synthesis

The terms analysis and synthesis come from (classical) Greek and mean literally "to loosen up" and "to put together" respectively. In general, analysis is defined as the procedure by which we break down an intellectual or substantial whole into parts or components. Synthesis is defined as the opposite procedure: to combine separate elements or components in order to form a coherent whole. However, analysis and synthesis, as scientific methods, always go hand in hand; they complement one another. Every synthesis is built upon the results of a preceding analysis, and every analysis requires a subsequent synthesis in order to verify and correct its results.[16]

Divergent thinking versus convergent thinking

Design Thinkers also use divergent thinking and convergent thinking to explore many possible solutions. Divergent thinking is the ability to offer different, unique or variant ideas adherent to one theme while convergent thinking is the ability to find the "correct" solution to the given problem. Design thinking encourages divergent thinking to ideate many solutions (possible or impossible) and then uses convergent thinking to prefer and realize the best resolution.

Design thinking as a process for problem-solving

Unlike analytical thinking, design thinking is a process which includes the "building up" of ideas, with few, or no, limits on breadth during a "brainstorming" phase. This helps reduce fear of failure in the participant(s) and encourages input and participation from a wide variety of sources in the ideation phases. The phrase Outside the box thinking has been coined to describe one goal of the brainstorming phase and is encouraged, since this can aid in the discovery of hidden elements and ambiguities in the situation and discovering potentially faulty assumptions.
One version of the design thinking process has seven stages: define, research, ideate, prototype, choose, implement, and learn.[6] Within these seven steps, problems can be framed, the right questions can be asked, more ideas can be created, and the best answers can be chosen. The steps aren't linear; can occur simultaneously and be repeated. A more simplified expression of the process is Robert McKim's phrase; "Express-Test-Cycle".
Define
  • Decide what issue you are trying to resolve.
  • Agree on who the audience is.
  • Prioritize this project in terms of urgency.
  • Determine what will make this project successful.
  • Establish a glossary of terms.
Research
  • Review the history of the issue; remember any existing obstacles.
  • Collect examples of other attempts to solve the same issue.
  • Note the project supporters, investors, and critics.
  • Talk to your end-users, that brings you the most fruitful ideas for later design.
  • Take into account thought leaders' opinions.
Ideation
  • Identify the needs and motivations of your end-users.
  • Generate as many ideas as possible to serve these identified needs.
  • Log your brainstorming session.
  • Do not judge or debate ideas.
  • During brainstorming, have one conversation at a time.
Prototype
  • Combine, expand, and refine ideas.
  • Create multiple drafts.
  • Seek feedback from a diverse group of people, include your end users.
  • Present a selection of ideas to the client.
  • Reserve judgement and maintain neutrality.
  • Create and present actual working prototype(s)
Choose
  • Review the objective.
  • Set aside emotion and ownership of ideas.
  • Avoid consensus thinking.
  • Remember: the most practical solution isn't always the best.
  • Select the powerful ideas.
Implement
  • Make task descriptions.
  • Plan tasks.
  • Determine resources.
  • Assign tasks.
  • Execute.
  • Deliver to client.
Learn
  • Gather feedback from the consumer.
  • Determine if the solution met its goals.
  • Discuss what could be improved.
  • Measure success; collect data.
  • Document.
Although design is always influenced by individual preferences, the design thinking method shares a common set of traits, mainly; Creativity, Ambidextrous thinking,[9] Teamwork, User-Centerdness (Empathy), Curiosity and Optimism.
An alternative, five phase, description of the process, as described by Hasso Plattner, is;
  • (re)Define the Problem - Design Never Ends
  • Needfinding and Benchmarking - Understand the users, design space
  • Bodystorm - Ideate
  • Prototype - Build
  • Test - Learn
The path thru these process steps is not strictly circular. Plattner states; "While the stages are simple enough, the adaptive expertise required to chose the right inflection points and appropriate next stage is a high order intellectual activity that requires practice and is learnable."[17]

Attributes of design thinking

Rules

Plattner asserts that there are four rules to Design Thinking;[18]
  • The Human Rule: All Design Activity Is Ultimately Social in Nature
  • The Ambiguity Rule: Design Thinkers Must Preserve Ambiguity
  • The Re-design Rule: All Design Is Re-design
  • The Tangibility Rule: Making Ideas Tangible Always Facilitates Communication

Wicked problems

Design Thinking is especially useful when addressing what Buchanan referred to as "wicked problems". Wicked problems which are ill-defined or tricky, as opposed to wicked in the sense of malicious.[19] With ill-defined problems, both the problem and the solution are unknown at the outset of the problem-solving exercise. This is as opposed to "tame" or "well-defined" problems where the problem is clear, and the solution is available through some technical knowledge.[20]
For wicked problems, the general thrust of the problem may be clear, however considerable time and effort is spent in order to clarify the requirements. A large part of the problem solving activity, then, consists of problem definition and problem shaping.[11]

The A-Ha moment

The "A-Ha Moment" is the moment where there is suddenly a clear forward path.[21] It is the point in the cycle where synthesis and divergent thinking, analysis and convergent thinking, and the nature of the problem all come together and an appropriate resolution has been captured. Prior to this point, the process may seem nebulous, hazy and inexact. At this point, the path forward is so obvious that in retrospect it seems odd that it took so long to recognize it. After this point, the focus becomes more and more clear as the final product is constructed.[22]

Resistance, fear and the devil's advocate

There are factors which can slow or halt the Design Thinking process; Fear, Resistance and Playing the Devil's Advocate. These attitudes introduce destructive negativity.
Fear of failure or criticism may prevent someone from even beginning apply methods and processes to achieve their goals. Both have psychological effects which divert someone from focusing on solutions and shifting their focus to doubts of self-worth, anxieties of "will it be good enough," or procrastination..."[23]
Resistance can inhibit Design Thinking by reprioritizing the main goal and shifting efforts to other tasks which may need to be done. [24] Donald Schön talks about the resistance of students towards their professors and the resistance of professors towards students in the learning process.[25]
Playing the "Devil's Advocate" is constant nay-saying; making authoritative assertions as to why every proposed solution will not work. It is an embodiment of negative criticism. Devil's Advicates kill projects by shifting the focus from potential solutions to hypercritical issues with ambiguous effects. The goal is to stop further ideation towards a solution, which, according to Tom and Dave Kelley, ought to be "banned from the room".[26]

Methods and process

Design methods and design process are often used interchangeably, but there are significant differences between the two.
Design methods are techniques, rules, or ways of doing things which are employed within a design discipline. The methods for Design Thinking include interviewing, creating user profiles, looking at other existing solutions, creating prototypes, mind-mapping, asking questions like the "Five-Whys" and situational analysis.
Because of Design Thinking's parallel nature, there are many different paths thru the phases. This is part of the reason Design Thinking may seem to be "fuzzy" or "ambiguous" when compared to more analytical, Cartesian methods of science and engineering.
Some early Design Processes stemmed from Soft Systems Methodology in the 1960s. Koberg and Bagnall's wrote The All New Universal Traveller in 1972 and presented a circular, seven-step process to problem-solving. These seven steps could be done lineally or in feed-back loops.[27] Stanford's d.school developed an updated seven step process in 2007.[28] Other expressions of design processes have been proposed, including a three-step simplified triangular process (or the six-part, less simplified pyramid) by Bryan Lawson[15] and Hugh Dubberly's e-book How Do You Design: A compendium of models.[29]

The use of visual analogy in design thinking and learning

Ill-defined problems often contain higher-order and obscure relationships. Design Thinking can address these thru the use of analogies. An understanding of the expected results, or lack of domain-related knowledge for the task, may be developed by correlating different internal representations, such as images, to develop an understanding of the obscure or ill defined elements of the situation. The process involves several complex cognitive mechanisms, as the design task often has elements in multiple cognitive domains; visual, mathematical, auditory or tactile, requiring the usage of multiple "languages", like visual thinking.

Differences from science and humanities

Although many design fields have been categorized as laying between Science and the Arts and Humanities, design may be seen as its own distinct way of understanding the world, based on solution-based problem solving, problem shaping, synthesis, and appropriateness in the built environment.
One of the first Design Science theorists, John Chris Jones, postulated that design was different than the arts, sciences and mathematics in the 1970s. In response to the question 'is designing an art, a science or a form of mathematics' Jones responded:
The main point of difference is that of timing. Both artists and scientists operate on the physical world as it exists in the present (whether it is real or symbolic), while mathematicians operate on abstract relationships that are independent of historical time. Designers, on the other hand, are forever bound to treat as real that which exists only in an imagined future and have to specify ways in which the foreseen thing can be made to exist.[30]
Design can be seen as its own culture in education, with its own methods and ways of thinking which can be systematically taught in both K-12 and higher education. Nigel Cross sets out to show the differences between the humanities, the sciences, and design in his paper "Designerly Ways of Knowing". He observed that:
The phenomenon of study in each culture is
  • in the sciences: the natural world
  • in the humanities: human experience
  • in design: the artificial world
The appropriate methods in each culture are
  • in the sciences: controlled experiment, classification, analysis
  • in the humanities: analogy, metaphor, evaluation
  • in design: modeling, pattern-forming, synthesis
The values of each culture are
  • in the sciences: objectivity, rationality, neutrality, and a concern for 'truth'
  • in the humanities: subjectivity, imagination, commitment, and a concern for 'justice'
  • in design: practicality, ingenuity, empathy , and a concern for 'appropriateness'[14]

The language of design

Designers communicate in a visual[31] or an object language.[14] Symbols, signs, and metaphors are used through the medium of sketching, diagrams and technical drawings to translate abstract requirements into concrete objects. The way designers communicate, then, is through understanding this way of coding design requirements in order to produce built products.[32]

Design thinking in business

Design thinking has two common interpretations in the business world:[citation needed]
  1. Designers bringing their methods into business - by either taking part themselves in business process, or training business people to use design methods.
  2. Designers achieving innovative outputs, for example: 'the iPod is a great example of design thinking.'
The first has been described by Tim Brown, CEO of IDEO, at a TED lecture,[33] though his blog[34] also considers an element of the second.
The limits of the first kind of design thinking in business are also being explored. Not all problems yield to design thinking alone, where it may be a 'temporary fix'.[35] Design thinking companies including IDEO and Sense Worldwide are responding to this by building business thinking capabilities.[36]
In organization and management theory, design thinking forms part of the Architecture/Design/Anthropology (A/D/A) paradigm, which characterizes innovative, human-centered enterprises. This paradigm also focuses on a collaborative and iterative style of work and an abductive mode of thinking, compared to practices associated with the more traditional Mathematics/Economics/Psychology (M/E/P) management paradigm.[37]
Companies that integrate the principles of design thinking in their innovation processes often share a certain mindset or are striving to cultivate a more creative and human-centred company culture.

How To Make iPhone Apps – An XCode 5 Tutorial For Beginners

Welcome to part 4 of my series on How To Make iPhone Apps with no programming experience – where we’ll turn even the non-programmer into an iOS developer! Here’s the article index for the entire series in case you missed it.
This is an XCode tutorial for beginners so we’ll be going through where to download XCode 5 and introduce you to the main parts of the development environment. By the end of this article, you’ll have a basic understanding of how to navigate the development environment and how to create your first XCode project.

Updated Sept 24, 2013: This article was updated for XCode 5. If you’re on XCode 4, everything in this guide still applies even though the look and feel may be different from XCode 5.

1. Where Can You Download XCode?

The easiest way to get XCode is through the Mac App Store. Click the link to go to the listing.
You can also download it manually if you don’t have the Mac App Store. Just visit the Apple Developer page for XCode.

2. Demystifying The XCode Interface

The diagram below is from the Apple Documentation for XCode. If your interface looks different, make sure you have XCode 5 and not an earlier version.
XCode 5 User Interface
The reason this is a great diagram is because it lets me refer to these different sections of the interface and you can refer back to this diagram to see what I’m talking about!
As you can see from the diagram, there are 4 major areas: the Navigator, Editor, Debug Area and Utility Area.
Keep in mind that you can adjust the size of each of those panes by hovering your cursor over the boundaries of each area and dragging.
You can also show and hide the various areas as needed via the “View” buttons in the upper right hand corner:
XCode View Toggle
This can be helpful, for example, when you’re writing code and you don’t need the debugger area or the utility area. Then you can use the View buttons to hide those 2 panes to give your editor more visible space.
Alright, let’s go through the Navigator area now!

3. The Navigator Area

In this pane, there are a bunch of different navigators that you can switch between using the Navigator selector bar (refer to diagram). The three navigators that you will use a lot are the Project, Search and Issue navigators.
Project Navigator
This is where you’ll see all the files associated with your project.
XCode 5 Project Navigator
Within the project navigator, you can also create “Groups” to organize your files in. The gotcha is that when you create a Group in the project navigator (by right clicking and choose Create Group), it doesn’t actually create a folder in the file system; it will only exist in your XCode project so while creating Groups here will organize your file in XCode, it won’t organize the actual files sitting on your hard drive. That’s why I prefer to create the actual directories on my hard drive, organize the files and then drag them back into the XCode project.
You can also right click on the project navigator and create new files or add existing files to your project. Or you can drag folders or files from your computer directly onto the project navigator and will popup a dialog asking how you want to add the files.
If you click on a file in the project navigator, it will display the file’s contents in the Editor area. If you double click a file instead, it will open a new window which can be useful when you have dual monitors.
The root node of the project navigator is your XCode project file (indicated by the blue icon). If you click that, the project properties will open in the editor area.
XCode Project Settings
Search Navigator
With the search navigator tab, you can easily look for pieces of text in your project.
XCode Search Navigator
You’ll find yourself using this a lot when you’re looking for a specific property, method or variable and you can’t remember exactly where it is.
Issue Navigator
The issue navigator shows you all the problems with your app.
XCode Issue Navigator
When you build and compile your application to test, if there are some problems where XCode can’t build your app, it will halt and show you the red colored errors in the issue navigator. You can click on an error and it will show you in the editor area which file and line it’s failing at.
It will also show yellow Warnings in the issue navigator. Although resolving warnings is not necessary for building your app, they’re warnings that there may be potential issues.

4. The Editor Area

The editor area is where we’ll probably be spending most of our time! This is where all the coding happens.
XCode Editor Area
As mentioned in the project navigator section, when you click a file there, it will open the contents in this editor area for you to edit the contents. However, that’s not the only way to navigate to different code files.
Navigation within the editor area
There are these little back and forward arrows in the upper left corner of the editor area. Unfortunately these arrows aren’t labeled in the trusty XCode interface diagram at the beginning of this article so I’ll call them “XCode back and forward arrows” and show you an image of them here:
XCode Editor Area Back and Forward Arrows
These guys are actually pretty useful. They act like the back and forward buttons on your browser and they let you navigate to previously viewed files.
Another way to quickly get to the file you need is to use the Jump Bar (see diagram). The jump bar allows you to quickly drill down through your groups and find the file you need. It looks like a breadcrumb at the top of the editor area but when you click a segment of it, it will open up a menu with other groups in that hierarchy level:
XCode Editor Area Jump Bar
If you click the tail segment of the jump bar (which is the current file you’re looking at), it will open up a menu showing you all the methods in the file which is not only useful to jump to another area within the file, but it will show you at a glance what methods are available in this file.
XCode Editor Area Jump Bar Method Menu
That does it for navigation within the editor area however, it still has some tricks up its sleeve.
Three types of editor views
The editor area has three different views and you can toggle between them with the set of buttons in the upper right hand corner:
XCode Editor Area View Buttons
The left most button is for the single editor pane view which is good for the small laptop screen if I don’t have an external monitor.
The middle button is the Assistant Editor view which will show you the accompanying file to the file you’re currently looking at. It looks like a two pane view. For example, if you’re looking at the implementation file for a class, the right pane will show you the header file for that class. Each pane also has independent jump bars, so you can also use that to change what file each pane is displaying.
XCode 5 Assistent Editor View
The right most button is the Version Editor view where you can compare two files. Personally, I haven’t found myself using this view so I can’t speak too much about it. Here’s the section for it in the Apple Documentation.
Interface Builder View
So far we’ve been talking about editing code files and writing code, however XCode has interface builder integrated in and when you’re viewing the Storyboard or a XIB file, the editor area will turn into a visual designer.
XCode 5 Editor Area XIB Interface Builder
We’ll be actually using this visual designer view in the next part of the series so we’ll talk about the various elements of it then.
Finding and replacing within the file
Just hit Command-F to bring up a search popup in the upper right corner that will look for whatever you type in within the current file. This is also a great way to jump to various areas of your file. You can also use this popup to do replacements within your file.
Jumping to definitions
If you’re looking at some code and you see a classname that you want to jump to the definition of, you can hold down Command and click the classname to quickly jump to that file.
The breakpoint gutter
The breakpoint gutter (see diagram at top) is where you can click to set breakpoints at certain lines of code. When you set a breakpoint, you’ll see a blue indicator appear. To turn off a breakpoint, just click the blue indicator again and it will dim out.
XCode 5 Editor Area Breakpoint
If you want to completely remove the breakpoint, you can click and drag the blue indicator off of the breakpoint gutter.
To view a list of all the breakpoints that are set in your project, there’s a “breakpoint navigator” tab in the Navigator area.
There’s also a global toggle to turn breakpoints on or off at the top of the editor area which we’ll see when we review the toolbar.
Don’t worry if you can’t remember everything right now. We’ll be working with all of these areas and when you start coding, this will all become second nature to you after a week.

5. The Utility Area

The XCode utility area is comprised of two panes: the inspector pane and the library pane.
XCode Utility Area
The Inspector pane will give you details about the file you’ve got highlighted in your project navigator. However, when you’re looking at a XIB file, the inspector pane will show you the different attributes that you can modify for a selected element.
XCode XIB Inspector Pane
The library pane won’t be very useful either until you’re looking at a XIB file. When you’re using the Interface Builder part of XCode, you can drag UI elements from the library pane onto the editor area to add that element to your user interface.
If I’m editing code files, I’ll usually hide the whole Utility Area to give my editor more space because I don’t need the inspector pane or the library pane.

6. The Debug Area

The debug area will show you console output and the state of various variables when you run your application.
XCode Debug Area
You’ll be using this a lot while debugging your code and trying to figure out why things aren’t working out the way you expect them to! I’ll need to write a separate XCode debugger tutorial because there’s too much to mention here.

7. The Toolbar

We’ve talked about some of the buttons on this tool bar already. Let’s start from the left.
XCode Toolbar
The left-most button is the run button. This will build and run your application and launch your app in the iOS Simulator. The button beside it will stop the execution of your application and return you to XCode.
If you click and hold down the Run button, you’ll get more options to run your app:
XCode Run Options
Test to run your unit tests if you have them in your project.
Profile to measure various aspects of your application such as performance, memory usage and more.
Analyze to let XCode analyze your code and check for potential leaks or bad practices.
You can read more about these actions in the Apple iOS Documentation.
The dropdown beside the Stop button indicates which build target you want to run (in most cases, you’ll have only 1) and you can also choose if you want to run it under the iPhone or iPad simulators (or different version if you have them installed). The selection “iOS device” is to run your app on your device if you have it plugged in and properly provisioned (which needs a whole tutorial in itself!).
XCode Run Target
And finally in the far right side of the toolbar, we have the editor view buttons, the buttons to toggle various XCode panels on or off and the Organizer button.

8. The XCode Organizer

The Organizer is located in the menu entry Window -> Organizer (or keyboard shortcut ⌘ ⇧ 2) and it brings up a separate window called the Organizer. There are several different purposes of the organizer and we’ll highlight them below.
For Xcode 4 users: The organizer button is located on the far right of the Xcode toolbar rather than a menu option.
The XCode Organizer Window
Devices
There are a lot of things you can do in the devices tab that I can’t list them all. However, the main uses are to manage your provisioning profiles on your system AND on various devices. We haven’t talked about provisioning profiles yet, but they’re important for deploying your app on actual physical iOS devices. I’ll need to create a separate tutorial for that.
You can look at crash log from devices, enable development use for various connected devices and more.
Check the Apple Documentation for more features of the devices tab.
Repositories
This only applies to XCode 4.
In XCode 5, Repositories are now managed in XCode->Preferences->Accounts

In the repositories tab, you’ll be able to manage local and remote repos that you have set up for your projects.
Projects
In the projects tab, you can see a list of projects you’ve opened before so you can quickly open them again and you’ll be able to manage derived data and snapshots of your projects as well.
Archives
In the archives tab, you can manage your archives for various projects. You would archive your app when you want to deploy it to the store or distribute it in some other manner.
Documentation
This is only for XCode 4.
In XCode 5, Repositories are now managed in XCode->Preferences->Downloads

You can view various iOS SDK documentation here.

9. The iOS Simulator

XCode 5 comes bundled with a wonderful iOS Simulator for you to test your application on. In fact, you can use the iOS simulator for most of your development and then find a device to test on when you’re nearly done.
The XCode iOS Simulator
You can actually do a lot with the simulator including:
-Device rotation
-Simulating various GPS coordinates
-Device shake
-Simulating low memory scenarios
If you want to test various network or low bandwidth conditions, there’s a tool called Charles Proxy that works brilliantly. I’ve written a Charles Proxy Tutorial that you can read.

Let’s Summarize

In this part of the series, I’ve acquainted you to the various areas of XCode.

Now you understand:
-The Navigator, Editor, Utility, Debug and Toolbar Areas of XCode!
-The various code editing features of the editor area!
-The XCode organizer!
-The iOS Simulator!

What’s Next?

We’re going to put what we’ve learned into practice in the next part of the tutorial series. We’ll build a simple demo app that will use the XCode areas and features that we talked about today as well as the Interface Builder bits.
We’ll also implement the MVC pattern with a real example so you can solidify your understanding of what was discussed in this tutorial.
Now you have all the basic ingredients to start iOS app development. Get ready to start making some iOS applications!

REST with Java (JAX-RS) using Jersey - Tutorial

RESTful web services with Java (Jersey / JAX-RS)
This tutorial explains how to develop RESTful web services in Java with the JAX-RS reference implementation Jersey.
In this tutorial Eclipse 4.4 (Luna), Java 1.6, Tomcat 6.0 and JAX-RS 2.0 (with Jersey 2.11) is used.

1. REST - Representational State Transfer

1.1. What is REST?

REST is an architectural style which is based on web-standards and the HTTP protocol. REST was first described by Roy Fielding in 2000.
In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods.
In a REST based architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modifies the REST resources.
Every resource should support the HTTP common operations. Resources are identified by global IDs (which are typically URIs).
REST allows that resources have different representations, e.g., text, XML, JSON etc. The REST client can ask for a specific representation via the HTTP protocol (content negotiation).

1.2. HTTP methods

The PUT, GET, POST and DELETE methods are typical used in REST based architectures.
The following table gives an explanation of these operations.

  • GET defines a reading access of the resource without side-effects. The resource is never changed via a GET request, e.g., the request has no side effects (idempotent).
  • PUT creates a new resource. It must also be idempotent.
  • DELETE removes the resources. The operations are idempotent. They can get repeated without leading to different results.
  • POST updates an existing resource or creates a new resource.

1.3. RESTFul web services

A RESTFul web services are based on HTTP methods and the concept of REST. A RESTFul web service typically defines the base URI for the services, the supported MIME-types (XML, text, JSON, user-defined, ...) and the set of operations (POST, GET, PUT, DELETE) which are supported.

2. JAX-RS with Jersey

2.1. JAX-RS

Java defines REST support via the Java Specification Request (JSR) 311. This specification is called JAX-RS (The Java API for RESTful Web Services). JAX-RS uses annotations to define the REST relevance of Java classes.

2.2. JAX-RS

Jersey is the reference implementation for the JSR 311 specification.
The Jersey implementation provides a library to implement Restful webservices in a Java servlet container.
On the server side Jersey provides a servlet implementation which scans predefined classes to identify RESTful resources. In your web.xml configuration file your register this servlet for your web application.
The Jersey implementation also provides a client library to communicate with a RESTful webservice.
The base URL of this servlet is:

http://your_domain:port/display-name/url-pattern/path_from_rest_class 

This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.
A REST web application consists, therefore, out of data classes (resources) and services. These two types are typically maintained in different packages as the Jersey servlet will be instructed via the web.xml to scan certain packages for data classes.
JAX-RS supports the creation of XML and JSON via the Java Architecture for XML Binding (JAXB).
JAXB is described in the JAXB Tutorial .

2.3. JAX-RS annotations

The most important annotations in JAX-RS are listed in the following table.

Table 1. JAX-RS annotations
Annotation Description
@PATH(your_path) Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml configuration file.
@POST Indicates that the following method will answer to an HTTP POST request.
@GET Indicates that the following method will answer to an HTTP GET request.
@PUT Indicates that the following method will answer to an HTTP PUT request.
@DELETE Indicates that the following method will answer to an HTTP DELETE request.
@Produces(MediaType.TEXT_PLAIN[, more-types]) @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain") is produced. Other examples would be "application/xml" or "application/json".
@Consumes(type[, more-types]) @Consumes defines which MIME type is consumed by this method.
@PathParam Used to inject values from the URL into a method parameter. This way you inject, for example, the ID of a resource into the method to get the correct object.


The complete path to a resource is based on the base URL and the @PATh annotation in your class.

http://your_domain:port/display-name/url-pattern/path_from_rest_class 

3. Jersey

Download the Jersey distribution as zip file from the Jersey download site.
The zip contains the Jersey implementation JAR and its core dependencies. It does not provide dependencies for third party JARs beyond those for JSON support and JavaDoc.

4. Web container

For this tutorial you can use any web container, for example Tomcat or the Google App Engine.
If you want to use Tomcat as servlet container please see Eclipse WTP and Apache Tomcat for instructions on how to install and use Eclipse WTP and Apache Tomcat.
Alternative you could also use the Google App Engine for running the server part of the following REST examples. If you use the Google App Engine, you do not have to install and configure Tomcat.

Tip

If you are using GAE/J, you have to create App Engine projects instead of Dynamic Web Project. The following description is based on Apache Tomcat.

5. Prerequisites

The following description assumes that you are familiar with creating web applications in Eclipse. See Eclipse WTP development for an introduction into creating web applications with Eclipse.

6. Create your first RESTful Webservice

6.1. Create a project with Jersey libraries

Create a new Dynamic Web Project called com.vogella.jersey.first.


Ensure that you create the web.xml deployment descriptor.




Copy all JARs from your Jersey download into the WEB-INF/lib folder.


6.2. Java Class

Create the following class.

package com.vogella.jersey.first;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

// Plain old Java Object it does not extend as class or implements 
// an interface

// The class registers its methods for the HTTP GET request using the @GET annotation. 
// Using the @Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML. 

// The browser requests per default the HTML MIME type.

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

  // This method is called if TEXT_PLAIN is request
  @GET
  @Produces(MediaType.TEXT_PLAIN)
  public String sayPlainTextHello() {
    return "Hello Jersey";
  }

  // This method is called if XML is request
  @GET
  @Produces(MediaType.TEXT_XML)
  public String sayXMLHello() {
    return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
  }

  // This method is called if HTML is request
  @GET
  @Produces(MediaType.TEXT_HTML)
  public String sayHtmlHello() {
    return "<html> " + "<title>" + "Hello Jersey" + "</title>"
        + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
  }

} 

This class register itself as a get resource via the @GET annotation. Via the @Produces annotation it defines that it delivers the text and the HTML MIME types. It also defines via the @Path annotation that its service is available under the hello URL.
The browser will always request the HTML MIME type. To see the text version, you can use tool like curl.

6.3. Define Jersey Servlet dispatcher

You need to register Jersey as the servlet dispatcher for REST requests. Open the file web.xml and modify it to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.vogella.jersey.first</display-name>
 <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
     <!-- Register resources and providers under com.vogella.jersey.first package. -->
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.vogella.jersey.first</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

The parameter com.sun.jersey.config.property.package defines in which package Jersey will look for the web service classes. This property must point to your resources classes. The URL pattern defines the part of the base URL your application will be placed.

6.4. Run your rest service

Run you web application in Eclipse. See Eclipse WTP for details on how to run dynamic web applications.
You should be able to access your resources under the following URL: http://localhost:8080/com.vogella.jersey.first/rest/hello

Result of the Jersey service

This name is derived from the "display-name" defined in the web.xml file, augmented with the servlet-mapping URL-pattern and the hello @Path annotation from your class file. You should get the message "Hello Jersey".
The browser requests the HTML representation of your resource. In the next chapter we are going to write a client which will read the XML representation.

7. Create a client

Jersey contains a REST client library which can be used for testing or to build a real client in Java. Alternatively, you could use Apache HttpClient to create a client.
Create a new Java project de.vogella.jersey.first.client and add the Jersey JARs to the project and the project build path. Create the following test class.

package de.vogella.jersey.first.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Fluent interfaces
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
    // Get plain text
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
    // Get XML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
    // The HTML
    System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));

  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.first").build();
  }

} 

8. RESTful web services and JAXB

JAX-RS supports the automatic creation of XML and JSON via JAXB. For an introduction into XML please see Java and XML - Tutorial. For an introduction into JAXB please see JAXB. You can continue this tutorial without reading these tutorials, but they contain more background information.

8.1. Create project

Create a new Dynamic Web Project called de.vogella.jersey.jaxb and copy all Jersey JARs into the WEB-INF/lib folder.
Create your domain class.

package de.vogella.jersey.jaxb.model;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
// JAX-RS supports an automatic mapping from JAXB annotated class to XML and JSON
// Isn't that cool?
public class Todo {
  private String summary;
  private String description;
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }

  
} 

Create the following resource class. This class simply returns an instance of the Todo class.

package de.vogella.jersey.jaxb;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import de.vogella.jersey.jaxb.model.Todo;

@Path("/todo")
public class TodoResource {
  // This method is called if XMLis request
  @GET
  @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
  public Todo getXML() {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo");
    todo.setDescription("This is my first todo");
    return todo;
  }
  
  // This can be used to test the integration with the browser
  @GET
  @Produces({ MediaType.TEXT_XML })
  public Todo getHTML() {
    Todo todo = new Todo();
    todo.setSummary("This is my first todo");
    todo.setDescription("This is my first todo");
    return todo;
  }

} 

Change web.xml to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  id="WebApp_ID" version="2.5">
  <display-name>de.vogella.jersey.jaxb</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>de.vogella.jersey.jaxb</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

Run you web application in Eclipse and validate that you can access your service. Your application should be available under the following URL.

http://localhost:8080/de.vogella.jersey.jaxb/rest/todo 

8.2. Create a client

Create a new Java project de.vogella.jersey.jaxb.client and add the Jersey JARs to the project and the project build path. Create the following test class.

package de.vogella.jersey.jaxb.client;


import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class Test {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // Get XML
    System.out.println(service.path("rest").path("todo").accept(MediaType.TEXT_XML).get(String.class));
    // Get XML for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_JSON).get(String.class));
    // Get JSON for application
    System.out.println(service.path("rest").path("todo").accept(MediaType.APPLICATION_XML).get(String.class));
  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.jaxb").build();
  }

} 

9. CRUD RESTful webservice

This section creates a CRUD (Create, Read, Update, Delete) restful web service. It will allow to maintain a list of TODOs in your web application via HTTP calls.

9.1. Project

Create a new dynamic project called de.vogella.jersey.todo and add the Jersey libs. Change the web.xml file to the following.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>de.vogella.jersey.todo</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>de.vogella.jersey.todo.resources</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app> 

Create the following data model and a Singleton which serves as the data provider for the model. We use the implementation based on an enumeration. Please see the link for details. The Todo class is annotated with a JAXB annotation. See Java and XML to learn about JAXB.

package de.vogella.jersey.todo.model;


import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Todo {
  private String id;
  private String summary;
  private String description;
  
  public Todo(){
    
  }
  public Todo (String id, String summary){
    this.id = id;
    this.summary = summary;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getSummary() {
    return summary;
  }
  public void setSummary(String summary) {
    this.summary = summary;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }
  
  
} 


package de.vogella.jersey.todo.dao;

import java.util.HashMap;
import java.util.Map;

import de.vogella.jersey.todo.model.Todo;

public enum TodoDao {
  instance;
  
  private Map<String, Todo> contentProvider = new HashMap<String, Todo>();
  
  private TodoDao() {
    
    Todo todo = new Todo("1", "Learn REST");
    todo.setDescription("Read http://www.vogella.com/tutorials/REST/article.html");
    contentProvider.put("1", todo);
    todo = new Todo("2", "Do something");
    todo.setDescription("Read complete http://www.vogella.com");
    contentProvider.put("2", todo);
    
  }
  public Map<String, Todo> getModel(){
    return contentProvider;
  }
  
} 

9.2. Create a simple HTML form

The REST service can be used via HTML forms. The following HTML form will allow to post new data to the service. Create the following page called create_todo.html in the WebContent folder.

<!DOCTYPE html>
<html>
 <head>
  <title>Form to create a new resource</title>
 </head>
<body>
  <form action="../de.vogella.jersey.todo/rest/todos" method="POST">
  <label for="id">ID</label>
  <input name="id" />
  <br/>
  <label for="summary">Summary</label>
  <input name="summary" />
  <br/>
  Description:
  <TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
  <br/>
  <input type="submit" value="Submit" />
  </form>
</body>
</html> 

9.3. Rest Service

Create the following classes which will be used as REST resources.

package de.vogella.jersey.todo.resources;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import de.vogella.jersey.todo.dao.TodoDao;
import de.vogella.jersey.todo.model.Todo;

public class TodoResource {
  @Context
  UriInfo uriInfo;
  @Context
  Request request;
  String id;
  public TodoResource(UriInfo uriInfo, Request request, String id) {
    this.uriInfo = uriInfo;
    this.request = request;
    this.id = id;
  }
  
  //Application integration     
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public Todo getTodo() {
    Todo todo = TodoDao.instance.getModel().get(id);
    if(todo==null)
      throw new RuntimeException("Get: Todo with " + id +  " not found");
    return todo;
  }
  
  // for the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public Todo getTodoHTML() {
    Todo todo = TodoDao.instance.getModel().get(id);
    if(todo==null)
      throw new RuntimeException("Get: Todo with " + id +  " not found");
    return todo;
  }
  
  @PUT
  @Consumes(MediaType.APPLICATION_XML)
  public Response putTodo(JAXBElement<Todo> todo) {
    Todo c = todo.getValue();
    return putAndGetResponse(c);
  }
  
  @DELETE
  public void deleteTodo() {
    Todo c = TodoDao.instance.getModel().remove(id);
    if(c==null)
      throw new RuntimeException("Delete: Todo with " + id +  " not found");
  }
  
  private Response putAndGetResponse(Todo todo) {
    Response res;
    if(TodoDao.instance.getModel().containsKey(todo.getId())) {
      res = Response.noContent().build();
    } else {
      res = Response.created(uriInfo.getAbsolutePath()).build();
    }
    TodoDao.instance.getModel().put(todo.getId(), todo);
    return res;
  }
  
  

} 


package de.vogella.jersey.todo.resources;


import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import de.vogella.jersey.todo.dao.TodoDao;
import de.vogella.jersey.todo.model.Todo;


// Will map the resource to the URL todos
@Path("/todos")
public class TodosResource {

  // Allows to insert contextual objects into the class, 
  // e.g. ServletContext, Request, Response, UriInfo
  @Context
  UriInfo uriInfo;
  @Context
  Request request;


  // Return the list of todos to the user in the browser
  @GET
  @Produces(MediaType.TEXT_XML)
  public List<Todo> getTodosBrowser() {
    List<Todo> todos = new ArrayList<Todo>();
    todos.addAll(TodoDao.instance.getModel().values());
    return todos; 
  }
  
  // Return the list of todos for applications
  @GET
  @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
  public List<Todo> getTodos() {
    List<Todo> todos = new ArrayList<Todo>();
    todos.addAll(TodoDao.instance.getModel().values());
    return todos; 
  }
  
  
  // retuns the number of todos
  // use http://localhost:8080/de.vogella.jersey.todo/rest/todos/count
  // to get the total number of records
  @GET
  @Path("count")
  @Produces(MediaType.TEXT_PLAIN)
  public String getCount() {
    int count = TodoDao.instance.getModel().size();
    return String.valueOf(count);
  }
  
  @POST
  @Produces(MediaType.TEXT_HTML)
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  public void newTodo(@FormParam("id") String id,
      @FormParam("summary") String summary,
      @FormParam("description") String description,
      @Context HttpServletResponse servletResponse) throws IOException {
    Todo todo = new Todo(id,summary);
    if (description!=null){
      todo.setDescription(description);
    }
    TodoDao.instance.getModel().put(id, todo);
    
    servletResponse.sendRedirect("../create_todo.html");
  }
  
  
  // Defines that the next path parameter after todos is
  // treated as a parameter and passed to the TodoResources
  // Allows to type http://localhost:8080/de.vogella.jersey.todo/rest/todos/1
  // 1 will be treaded as parameter todo and passed to TodoResource
  @Path("{todo}")
  public TodoResource getTodo(@PathParam("todo") String id) {
    return new TodoResource(uriInfo, request, id);
  }
  
} 

This TodosResource uses the @PathParam annotation to define that the id is inserted as parameter.

9.4. Run

Run you web application in Eclipse and test the availability of your REST service under: http://localhost:8080/de.vogella.jersey.todo/rest/todos. You should see the XML representation of your TODO items.


To see the count of TODO items use http://localhost:8080/de.vogella.jersey.todo/rest/todos/count to see an exiting TODO use "http://localhost:8080/de.vogella.jersey.todo/rest/todos/{id}", e.g., http://localhost:8080/de.vogella.jersey.todo/rest/todos/1 to see the TODO with ID 1. We currently have only TODOs with the ids 1 and 2, all other requests will result in an HTTP error code.
Please note that with the browser you can only issue HTTP GET requests. The next chapter will use the Jersey client libraries to issue get, post and delete.

9.5. Create a client

Create a new Java project called de.vogella.jersey.todo.client. Create a lib folder and place all Jersey libraries in this folder. Add the JARs to the classpath of the project.
Create the following class.

package de.vogella.jersey.todo.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.representation.Form;

import de.vogella.jersey.todo.model.Todo;

public class Tester {
  public static void main(String[] args) {
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client.resource(getBaseURI());
    // create one todo
    Todo todo = new Todo("3", "Blabla");
    ClientResponse response = service.path("rest").path("todos")
        .path(todo.getId()).accept(MediaType.APPLICATION_XML)
        .put(ClientResponse.class, todo);
    // Return code should be 201 == created resource
    System.out.println(response.getStatus());
    // Get the Todos
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.TEXT_XML).get(String.class));
    // Get JSON for application
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_JSON).get(String.class));
    // Get XML for application
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

    // Get the Todo with id 1
    System.out.println(service.path("rest").path("todos/1")
        .accept(MediaType.APPLICATION_XML).get(String.class));
    // get Todo with id 1
    service.path("rest").path("todos/1").delete();
    // Get the all todos, id 1 should be deleted
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

    // create a Todo
    Form form = new Form();
    form.add("id", "4");
    form.add("summary", "Demonstration of the client lib for forms");
    response = service.path("rest").path("todos")
        .type(MediaType.APPLICATION_FORM_URLENCODED)
        .post(ClientResponse.class, form);
    System.out.println("Form response " + response.getEntity(String.class));
    // Get the all todos, id 4 should be created
    System.out.println(service.path("rest").path("todos")
        .accept(MediaType.APPLICATION_XML).get(String.class));

  }

  private static URI getBaseURI() {
    return UriBuilder.fromUri("http://localhost:8080/de.vogella.jersey.todo").build();
  }
} 

9.6. Using the REST service via HTML page

The above example contains a form which calls a post method of your rest service.

9.7. Using the rest service via X

Usually every programming language provides libraries for creating HTTP get, post, put and delete requests. For Java this is the project Apache HttpClient.

10. Support this website

This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this tutorial is distributed under the Eclipse Public License. See the vogella License page for details on the terms of reuse.
Writing and updating these tutorials is a lot of work. If this free community service was helpful, you can support the cause by giving a tip as well as reporting typos and factual errors.

10.1. Thank you