SlideShare a Scribd company logo
 Whiteboard
 Quizzes
 Shared
 Articles
 HOME
 TUTORIALS LIBRARY
 CODING GROUND
 IMAGE EDITOR
Run your first JSP program in Apache Tomcat Server
amit2012, Posted on October 15, 2012, filed in: Web Design
This post will give you description about how you can run your project using Apache Tomcat Server.
I would like to define these terms before proceeding:
 Apache Tomcat Server(Jakarta Tomcat): It is an open source web server and servlet container developed by the Apache Software
Foundation (ASF). It implements the Java Servlet and the JavaServer Pages (JSP) specifications and provides a pure Java HTTP web
server environment for java code to run.
 JavaServerPages(JSP): It is a technology that helps in creating dynamically generated web pages.
Step1
Install Java.
Step2
Install Apache Tomcat
At the time of installation, it will by-default recognize JRE path.
(under installed java location directory)
Step3
Now Go-To:
 Start
 Programs
 APACHE TOMCAT
 MONITOR TOMCAT
Step4
An icon will appear on the taskbar, this icon will automatically appear after following above step:
Step5
Click on that icon and START TOMCAT, you can see the following dialog box:
Step6
Now open Mozilla Firefox(or any other browser)
Step7
Type http://localhost:8080/ on address bar and press enter.
The same can be seen here:
Step8
It will show tomcat, as shown in above window.
(if not, then try again, may be a problem in installation or you’re not following above steps correctly
Step9
Now, go to:
 C:drive
 Programs Files
 Apache Software Foundation
 tomcat
 web-apps
(or navigate where you have installed APACHE TOMCAT)
Step10
Open web-apps and “copy your project” or “make new folder”, which you want to run in JSP.
Example: amit2012PROJECT
Now, go back :
 Tomcat
 Root
 Copy Web-inf from root
 Paste this “web-inf” in your project folder i.e. amit2012PROJECT
Step11
Create a text file and name it as first.jsp, use the code shown below:
<html>
<head>
<title>blog post:ApacheTomcatServer</title>
</head>
<body>
<%-- START --%>
<%
out.println("UserName = amit2012, ");
out.println("Running first program in JSP.");
%>
<%-- END --%>
</body>
</html>
It includes HTML tags and encloses a JSP scriptlet which is a fragment of Java code that is run when the user requests the page.
Step12
Now for running your folder [ Eg. amit2012PROJECT as shown above]
http://localhost:8080/foldername.extension in any WebBrowser i.e:
http://localhost:8080/amit2012PROJECT/first.jsp
The Project will run successfully, as shown below:
Now, you can successfully try running JSP with ApacheTomcatServer.
Skip to content
AVILYNE TECHNOLOGIES
Innovations in Information Technology
AN ANDROID REST CLIENT AND TOMCAT REST
WEBSERVICE
by Mark 83 Commentson An Android REST Client and Tomcat REST Webservice
Project Overview
This post will describe simple client-server communications between an Android app and a web service using REST
techniques, particularly GET and POST. For this demo, we will be sending and receiving data for a simple Java class
called Person, which includes a firstName, lastName and email address. The data stored in an instance of this class will
be transmitted from our web service in JSON format.
NOTE: This post is a work in progress and will be updated and corrected, as time permits.
Prerequisites
This demo assumes that you have a version of Eclipse that can create a “Dynamic Web Project”, and that you have an
instance of the Tomcat servlet container that you can control through Eclipse. This demo also assumes that you have the
Android SDK, at least one Android Virtual Device (AVD), and have the Eclipse ADT plugin.
Another important requirement is that your Android device needs to be on the same network as your Tomcat server. The
simplest way to do this would be to make sure you are running your emulator on the same computer that is running
Tomcat.
About REST
REST – “Representational State Transfer” is a technique that makes use of standard web protocols for the implementation
of a web service. A RESTful web service uses the standard HTTP GET PUT DELETE and POST actions to submit, retrieve
or modify server-side data.
Commonly, in a REST web service, the standard HTTP actions are used as follows:
 GET – retrieves or queries for data, usually using passed criteria
 PUT – creates a new entry, record
 DELETE – removes a resource
 POST- updates a resource or creates a resource
The data that is transmitted uses standard MIME types, including images, video, text, html, XML and JSON.
A key feature of a REST service is its use of URI paths as query parameters. For example, a fictional web service for a book
library might return a list of Civil War history books with this URI:
http://librarywebservice.com/books/history/CivilWar
Or, for magazines about tennis:
http://librarywebservice.com/magazines/sports/tennis
These are the absolute basics. REST has become a very popular replacement to SOAP for the development of web services.
Download the Jersey Jars
For the web server, this demo will use Tomcat, and will make use of a reference implementation of the JSR 311 Java
library, otherwise known as “jersey”. The Jersey API can significantly streamline the development of a RESTful web
service, and much of its ease comes from the use of annotations.
The home page, and the place to download the required jars for jersey can be found here. As of the writing of this post, the
jars will be found in a zip called jersey-archive-1.12.zip . Please download this zip and expand it to a folder where you can
find those jars.
Create a “Dynamic Web Project” in Eclipse
In Eclipse, select “File”->”New…”->”Project” and use the filter to find “Dynamic Web Project”
I have Apache Tomcat 7 running on my laptop, and have previously configured a connection between Tomcat and Eclipse.
The Dynamic web module version I am using is 3.0, but this tutorial can work with version 2.5.
Click “Next” and define your context root. That is the starting-point URL for your web service. With the context root
shown in the screenshot below, the resulting URL on my laptop will be http://localhost:8080/RestWebServiceDemo .
Also, have Eclipse generate a web.xml deployment descriptor.
Add Jersey Jars to Project
You will need to import the jars that you’ve downloaded from http://jersey.java.net into the WEB-INF/lib folder. Right
click that folder (WebContent/WEB-INF/lib) and select Import…
I’ve simply thrown in all the jars into that folder for the purposes of this tutorial. Crude, but effective. The smart thing
would be to only use the jars you need. I’ll eventually circle back to that some day.
Update Project Build Path to Include Jersey Jars
Now that the jars are in the WEB-INF/lib folder, you will need to configure the project to include these jars in its build
path. From within your project in the Package Explorer on the left of your Eclipse screen, right click to select “Build Path”-
>”Configure Build Path…”
On the “Libraries” tab, click on “Add External JARS…” and select the jars that are now in your project’s WEB-INF/lib
path.
Create the POJO Person class
Within the src folder, create a package called com.avilyne.rest.model, and in that package, create a Java class
called Person. Note, in the code shown below, the @XmlRootElement annotation. This tells Jersey that this would be
the root object of any generated XML (or JSON) representation of this class. This might not be very useful for this class,
but if you had a compound class, you’d be able to control what the XML or JSON output would look like by the addition of
annotations like this.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.avilyne.rest.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Person() {
id = -1;
firstName = "";
lastName = "";
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
email = "";
}
public Person(long id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
private long id;
private String firstName;
private String lastName;
private String email;
}
Create the PersonResource class
Again, in the src folder, create a new package calledcom.avilyne.rest.resource, and in that package create a class
calledPersonResource. (We are separating our data model from our controller).
The PersonResource class will be the interface between a Person object and the web. When a client requests a Person
object, the PersonResource will handle the request and return the appropriate object.
Note, in the code below, the annotations. The @Path(“/person”) annotation allows us to define the URI that will have
access to this resource. It will be something along the lines of http://RestServerDemo/rest/person, but this will be
explained in more detail as we map this code in our web.xml file.
The @Context annotation allows us to inject, in this example, UriInfo and Request objects into our PersonResource
object. Our code can inspect those injected objects for any desired Context information.
?
1
2
3
4
5
6
7
8
9
10
11
// The @Context annotation allows us to have certain contextual objects
// injected into this class.
// UriInfo object allows us to get URI information (no kidding).
@Context
UriInfo uriInfo;
// Another "injected" object. This allows us to use the information that's
// part of any incoming request.
// We could, for example, get header information, or the requestor's address.
@Context
Request request;
The @GET annotation lets us specify what method will be called when a client issues a GET to the webservice. Similar
logic applies to the @POST annotation. Note that the actual method name will not be a part of the client’s URI.
Also note that more than one method has a @GET annotation. The first @GET is simply there so that, when we start our
service, we can use a browser to retrieve some sort of response that indicates the service is running. Technically, instead of
producing TEXT_PLAIN, the first GET could have produced a TEXT_HTML page.
?
1
2
3
4
5
6
// Basic "is the service running" test
@GET
@Produces(MediaType.TEXT_PLAIN)
public String respondAsReady() {
return "Demo service is ready!";
}
The @Path annotation lets us append a parameter onto our URI. Using the example from earlier, the hypothetical URI
would be http://RestServerDemo/rest/person/sample .
?
1
2
3
4
5
6
7
8
9
@GET
@Path("sample")
@Produces(MediaType.APPLICATION_JSON)
public Person getSamplePerson() {
System.out.println("Returning sample person: " + person.getFirstName() + " " + person.getLastName());
return person;
}
Note that paths do NOT need to be literal. One can have a path parameter as a variable, e.g. @Path(“{id}”) would refer
to a person whose id value matched the passed URI value. http://RestServerDemo/rest/person/1 should return a person
whose id is 1.
The @Produces annotation allows us to define how the output from our resource should be transmitted to our client.
Note that, for the getSamplePerson() method, we return a person object, and the annotation lets us tell Jersey to format
and transmit that person as a JSON object.
The method with the @POST annotation also includes a @Consumesannotation. As you can guess, this method is called
in response to a client’s POST request. The data for the “person” object being transmitted from the client is not a JSON
object, but is a collection of Name-Value pairs. The @Consumes annotation allows us to specify that the data passed from
the client is an array of these pairs, and we can pull out the values we want from that array.
?
1
2
3
4
5
6
7
8
9
10
// Use data from the client source to create a new Person object, returned in JSON format.
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Person postPerson(
MultivaluedMap<String, String> personParams
) {
String firstName = personParams.getFirst(FIRST_NAME);
String lastName = personParams.getFirst(LAST_NAME);
String email = personParams.getFirst(EMAIL);
11
12
13
14
15
16
17
18
19
20
21
22
23
System.out.println("Storing posted " + firstName + " " + lastName + " " + email);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
System.out.println("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEmail(
return person;
}
For each of the methods in this PersonResource, I’ve added a System.out.println() as a crude way of letting us see when a
request is being processed. There are probably more elegant ways of doing this (Logging, for one), and one would almost
never include a System.out.println in a production service. This is just a demo.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.avilyne.rest.resource;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Request;
import com.avilyne.rest.model.Person;
@Path("/person")
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class PersonResource {
private final static String FIRST_NAME = "firstName";
private final static String LAST_NAME = "lastName";
private final static String EMAIL = "email";
private Person person = new Person(1, "Sample", "Person", "sample_person@jerseyrest.com");
// The @Context annotation allows us to have certain contextual objects
// injected into this class.
// UriInfo object allows us to get URI information (no kidding).
@Context
UriInfo uriInfo;
// Another "injected" object. This allows us to use the information that's
// part of any incoming request.
// We could, for example, get header information, or the requestor's address.
@Context
Request request;
// Basic "is the service running" test
@GET
@Produces(MediaType.TEXT_PLAIN)
public String respondAsReady() {
return "Demo service is ready!";
}
@GET
@Path("sample")
@Produces(MediaType.APPLICATION_JSON)
public Person getSamplePerson() {
System.out.println("Returning sample person: " + person.getFirstName() + " " + person.getLastName());
return person;
}
// Use data from the client source to create a new Person object, returned in JSON format.
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Person postPerson(
MultivaluedMap<String, String> personParams
) {
String firstName = personParams.getFirst(FIRST_NAME);
String lastName = personParams.getFirst(LAST_NAME);
String email = personParams.getFirst(EMAIL);
System.out.println("Storing posted " + firstName + " " + lastName + " " + email);
person.setFirstName(firstName);
person.setLastName(lastName);
person.setEmail(email);
System.out.println("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEm
return person;
}
}
Create or Edit the WebContentWEB-INFweb.xml file
In our web.xml file, we want to direct all requests to a servlet called Jersey REST Service. We will also tell this service
where to find the resources that we want to make available to our client app.
Update the web.xml file (or create it, in WebContentWEB-INFweb.xml, if it does not exist) to match the XML shown
below.
The XML defines the Jersey REST Service from the com.sun.jersey.spi.container.ServletContainer class. That class, as you
might guess, is in one of the Jersey Jars. The init-param section allows us to tell that servletcontainer to use the classes
found in the com.avilyne.rest.resource package for the mapping of URIs to java code.
In the servlet-mapping section, we create a global url-pattern, which essentially says that any request that goes
to /rest/ will attempt to be mapped to the appropriate methods.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?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_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>JerseyRESTServer</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>com.avilyne.rest.resource</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 the WebService
Run the completed project as a service on your Tomcat servlet container. The actual URL for the service will vary slightly,
depending partly on the name of your project. I called my project JerseyRESTServer, and here is the URL for the web
service on my computer:
http://localhost:8080/JerseyRESTServer/rest/person
Correction! Paul, a recent commenter, has pointed out that the URL should actually be:
http://localhost:8080/RestWebServiceDemo/rest/person
RestWebServiceDemo is the context root that we defined when we first started this project. I’ll mention that I built a
few versions of this project before writing this post, so unfortunately some of the images show a URL from an earlier
version of the project.
If I bring up this on a browser, it returns with this:
If I add the “sample” path to the URL, like this:
http://localhost:8080/RestWebServiceDemo/rest/person/sample
The web service returns a JSON object:
?
1 {"email":"sample_person@jerseyrest.com","firstName":"Sample","id":"1","lastName":"Person"}
I would recommend that you make sure you can retrieve this sample person before you create the Android client app.
Create an Android Client App
Create a new Android project, calling it something like AndroidRESTClient. I used API level 10 for this project, but one
can probably use a lower level API, if required. Android HttpClient requests have been around since the earliest days of
the OS. Use com.avilyne.android as the package for the main activity.
Edit the reslayoutmain.xml File
The interface will be very simple, having three labels and three edit controls for firstName, lastName and email address. It
will also have three buttons – one to GET, one to POST, and one to clear the controls.
The main.xml file should look like this:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
style=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/firstName" >
</TextView>
<EditText
android:id="@+id/first_name"
android:layout_width="wrap_content"
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:layout_span="2" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
style=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/lastName" >
</TextView>
<EditText
android:id="@+id/last_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:layout_span="2" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
style=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/email" >
</TextView>
<EditText
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
android:inputType="textEmailAddress"
android:layout_span="2" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/bn_retrieve"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="retrieveSampleData"
android:text="@string/retrieve" />
<Button
android:id="@+id/bn_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="postData"
android:text="@string/post" />
<Button
android:id="@+id/bn_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clearControls"
android:text="@string/clear" />
</TableRow>
</TableLayout>
91
92
93
Note that an onClick method is defined for each button.
Edit the resvaluesstrings.xml file
?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="firstName">First Name</string>
<string name="lastName">Last name</string>
<string name="email">Email</string>
<string name="retrieve">Retrieve</string>
<string name="post">Post</string>
<string name="clear">Clear</string>
<string name="app_name">AndroidRESTClient</string>
</resources>
Edit the AndroidRESTClientActivity.java file
Discuss the WebServiceTask, and the handleResponse() method.
The full source code for the Android client is listed below, but I want to highlight a few items in the code that you should
be aware of. On my home network, the computer running the service on Tomcat is at IP address 192.168.1.9. On your
network, the address will most definitely be different. If you are running the Android client and the Tomcat service on the
same computer, you can get away with using “localhost” in your Android code.
(CORRECTION: (Thanks ABa) Actually, you *can’t* use “localhost”. “Localhost” in this context would refer to the Android
device itself. Use the IP address of the computer on your network that is running the Tomcat service. See
thisStackOverflow link for details.)
?
1
2
3
public class AndroidRESTClientActivity extends Activity {
private static final String SERVICE_URL = "http://192.168.1.9:8080/RestWebServiceDemo/rest/person";
For this tutorial, the most important code is the internal “WebServiceTask” class, which is extended from an “AsyncTask”
class. An AsyncTask class descendant allows a process to run in a separate thread. If our communication with our service
were on the Android app’s main thread, the user interface would lock up as the process was waiting for results from the
server.
One can define the types of parameters that are passed to one’s instance of the AsyncTask. (more on that later). The
communication with the web service occurs in the WebServiceTask’s “doInBackground()” code. This code uses Android’s
HttpClient object, and for the GET method, uses HttpGet, and for the POST method, uses HttpPost.
The AsyncTask class includes two other methods that one has the option to overwrite. One is onPreExecute(), which one
can use to prepare for the background process, and the other is onPostExecute(), which one can use to do any required
clean-up after the background process is complete. This code overrides those methods to display and remove a progress
dialog.
The background task also includes two timeout options. One is a timeout period for the actual connection to the service,
and the other is a timeout period for the wait for the service’s response.
?
1
2
3
4
5
6
package com.avilyne.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
public class AndroidRESTClientActivity extends Activity {
private static final String SERVICE_URL = "http://192.168.1.9:8080/RestWebServiceDemo/rest/person";
private static final String TAG = "AndroidRESTClientActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public void retrieveSampleData(View vw) {
String sampleURL = SERVICE_URL + "/sample";
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "GETting data...");
wst.execute(new String[] { sampleURL });
}
public void clearControls(View vw) {
EditText edFirstName = (EditText) findViewById(R.id.first_name);
EditText edLastName = (EditText) findViewById(R.id.last_name);
EditText edEmail = (EditText) findViewById(R.id.email);
edFirstName.setText("");
edLastName.setText("");
edEmail.setText("");
}
public void postData(View vw) {
EditText edFirstName = (EditText) findViewById(R.id.first_name);
EditText edLastName = (EditText) findViewById(R.id.last_name);
EditText edEmail = (EditText) findViewById(R.id.email);
String firstName = edFirstName.getText().toString();
String lastName = edLastName.getText().toString();
String email = edEmail.getText().toString();
if (firstName.equals("") || lastName.equals("") || email.equals("")) {
Toast.makeText(this, "Please enter in all required fields.",
Toast.LENGTH_LONG).show();
return;
}
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Posting data...");
wst.addNameValuePair("firstName", firstName);
wst.addNameValuePair("lastName", lastName);
wst.addNameValuePair("email", email);
// the passed String is the URL we will POST to
wst.execute(new String[] { SERVICE_URL });
}
public void handleResponse(String response) {
EditText edFirstName = (EditText) findViewById(R.id.first_name);
EditText edLastName = (EditText) findViewById(R.id.last_name);
EditText edEmail = (EditText) findViewById(R.id.email);
edFirstName.setText("");
edLastName.setText("");
edEmail.setText("");
try {
JSONObject jso = new JSONObject(response);
String firstName = jso.getString("firstName");
String lastName = jso.getString("lastName");
String email = jso.getString("email");
edFirstName.setText(firstName);
edLastName.setText(lastName);
edEmail.setText(email);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
}
private void hideKeyboard() {
InputMethodManager inputManager = (InputMethodManager) AndroidRESTClientActivity.this
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
AndroidRESTClientActivity.this.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
@Override
protected void onPreExecute() {
hideKeyboard();
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
@Override
protected void onPostExecute(String response) {
handleResponse(response);
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
return total.toString();
}
}
}
(Code discussion, with excerpts, here)
Update the AndroidManifest.xml
Since this app needs to communicate via the internet, one must give the app the appropriate permissions.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avilyne.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidRESTClientActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Running the Android Client App
This screenshot shows the Android client app with its blank screen.
If one presses the “Retrieve” button, the web service will respond:
The Android client’s controls should get populated with the retrieved Person:
Here I’ve modified the values on my Android client screen, and pressed the “Post” button:
The web service responds to the post:
Hopefully, this will give you some idea of how to build an Android client that communicates with a web service using
REST.
Step by Step Guide to Setup and Install Apache
Tomcat Server in Eclipse Development Environment
(IDE)
SHORT LINK:
http://crunfy.m
Last Updated on January 16th, 2015 by Crunchify 6 Comments
Eclipse is a very powerful development environment for Java. Mainly for Web Development project you need Web
Server. Apache Tomcat is the best production ready web container.
By default when you download Eclipse IDE, it doesn’t come with Tomcat install with it. In this tutorial we will go over all detailed
steps to configure Apache Tomcat successfully in Eclipse environment.
Step-1
Download Apache Tomcat from this link. I’m using version 8.0.15 .
Step-2
Extract it to Document folder.
Step-3
 Open Eclipse Environment
 Click on Servers Tab
 Click on No servers are available. Click this link to create a new server...
 Click Tomcat v8.0 Server and Next
Step-4
Select Apache installation Directory and click Finish .
Step-5
You should see Tomcat v8.0 Server at localhost [Stopped, Republish] under Servers tab. Double click on it verify
HTTP ports information. By default HTTP port is 8080.
Step-6
Now right click on Server and click Start .
Console output:
Tomcat startup log
1
2
INFO: Initialization processed in 499 ms
Jan 05, 2015 9:09:28 PM org.apache.catalina.core.StandardService startInternal
3
4
5
6
7
8
9
10
11
INFO: Starting service Catalina
Jan 05, 2015 9:09:28 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.15
Jan 05, 2015 9:09:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jan 05, 2015 9:09:29 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jan 05, 2015 9:09:29 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 262 ms
It should be up and running on port 8080 and you could visit default page using URL: http://localhost:8080/
WEDNESDAY, 26 AUGUST 2015
Xcode 7 iOS Create Basic Segue
.
Basic Segue
Basic Segue
.
Posted by razi mahmood at 01:38 2 comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
SATURDAY, 22 AUGUST 2015
Official iOS Swift Apps Development Tutorial
-
A) GETTING STARTED
1. Introduction
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html#//apple_ref/doc/u
id/TP40015214-CH2-SW1
2. Learn the Swift essentials
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson1.html#//apple_ref/do
c/uid/TP40015214-CH3-SW1
B) BUILDING THE UI
1. Build a Basic UI
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson2.html#//apple_ref/do
c/uid/TP40015214-CH5-SW1
2. Connect the UI to Code
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson3.html#//apple_ref/do
c/uid/TP40015214-CH22-SW1
3. Work with View Controllers
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/do
c/uid/TP40015214-CH6-SW1
4. Implement a Custom Control
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/do
c/uid/TP40015214-CH6-SW1
5. Define your Data Model
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson6.html#//apple_ref/do
c/uid/TP40015214-CH20-SW1
C) WORKING WITH TABLE VIEWS
1. Create a Table View
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson6.html#//apple_ref/do
c/uid/TP40015214-CH20-SW1
2. Implement Navigation
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson8.html#//apple_ref/do
c/uid/TP40015214-CH16-SW1
3. Implement Edit and Delete Behavior
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson9.html#//apple_ref/do
c/uid/TP40015214-CH9-SW1
4. Persist Data
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html#//apple_ref/d
oc/uid/TP40015214-CH14-SW1
-
Posted by razi mahmood at 19:19 1 comment:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Official Android Apps Development Tutorial
-
A. BUILDING YOUR FIRST APP
0) Introduction
https://developer.android.com/training/basics/firstapp/index.html
1) Creating an Android Project
https://developer.android.com/training/basics/firstapp/creating-project.html
2) Running your app
https://developer.android.com/training/basics/firstapp/running-app.html
3) Building a Simple User Interface
https://developer.android.com/training/basics/firstapp/building-ui.html
4) Starting another Activity
https://developer.android.com/training/basics/firstapp/starting-activity.html
B. ADDING THE ACTION BAR
0) Introduction
https://developer.android.com/training/basics/actionbar/index.html
1) Setting Up the Action Bar
https://developer.android.com/training/basics/actionbar/setting-up.html
2) Adding Action Buttons
https://developer.android.com/training/basics/actionbar/adding-buttons.html
3) Styling the Action Bar
https://developer.android.com/training/basics/actionbar/styling.html
4) Overlaying the Action Bar
https://developer.android.com/training/basics/actionbar/overlaying.html
-
Posted by razi mahmood at 19:12 No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
iOS Swift Basic Tutorial
-
Tutorials from RayWenderlich.com.
1) http://www.raywenderlich.com/75601/learn-to-code-ios-apps-with-swift-tutorial-1
2) http://www.raywenderlich.com/75919/learn-to-code-ios-apps-with-swift-tutorial-2
3) http://www.raywenderlich.com/76044/learn-to-code-ios-apps-with-swift-tutorial-3
4) http://www.raywenderlich.com/77176/learn-to-code-ios-apps-with-swift-tutorial-4
5) http://www.raywenderlich.com/78264/learn-to-code-ios-apps-with-swift-tutorial-5
-
Posted by razi mahmood at 18:50 No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
UIWebView example using swift in ios
-
UIWebView object is used the load and display the web content into your application, safari browser is the primary example
for ios webview. for more reference you can go through apple documentation for uiwebview.
Open the Xcode, create new project and select the Single View Application template,
In the next screen, enter the Product Name as “UIWebView Example”, then enter the company identifier details. Select Swift in
Language field and Universal in Devices option, Then press next and create the project.
ADDING UIWEBVIEW TO VIEW
We can add the UIWebView to View using two methods, first one is adding the uiwebview into storyboard and another one is
programatically create uiwebview and adding into the view. first we will add the uiwebview into storyboard viewcontroller.
Open the Main.storyboard file, then at the right bottom of the Xcode you can find ios webview object in the utility area, drag and
drop the uiwebview into storyboard viewcontroller page.
Now, uiwebview added into Main.storyboard ViewController page and looks like below.
Then, click the assistance editor to link the Storyboard ViewController page to viewcontroller.swift by adding the uiwebview
reference.
Then press the control key click the storyboard uiwebview drag into viewcontroller.swift file and place next to viewcontroller
class file, as shown in the below.
UIWEBVIEW LOAD URL
Open the ViewController.swift file and change the below code snippet into the viewDidLoad() function. Here we are generating
the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview.
1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = NSURL (string: "http://www.sourcefreeze.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);
}
Next, Build and Run the application you will get the output like below.
UIWEBVIEW LOAD LOCAL HTML
As like online web page, we can load the local html file into webview. this is the base of hybrid application development using
PhoneGap/Cordova. first we have to add the html file using File–>New–>File or Press Command + N, it will open the window
like below. then select the Empty file name it as home.html add it into project.
Next, add the below code html code snippet into the home.html file.
1
2
3
4
5
6
7
<html>
<head>
8
</head>
<body>
<br />
<h2> Welcome SourceFreeze!!!</h2>
</body>
</html>
then, go to the ViewController.swift file, modify the viewDidLoad method like below code snippet.
1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
let myRequest = NSURLRequest(URL: localfilePath!);
myWebView.loadRequest(myRequest);
}
Next, Build and Run the application you will get the output like below.
UIWEBVIEW LOADHTMLSTRING
Other then direct URL we can load HTML String into UIWebView, we have to pass the htmlstring into loadHTMLString method
like the below code snippet, replace this code in the viewDidLoad method.
1
2
3
4
5
6
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var htmlString:String! = "<br /><h2>Welcome to SourceFreeze!!!</h2>"
myWebView.loadHTMLString(htmlString, baseURL: nil)
}
then build and run the application, you will get the output like below.
UIWEBVIEW RUNNING JAVASCRIPT
Like loading the direct html strings into uiwebview, can able to access or run the direct javascript methods into uiwebview
using stringByEvaluatingJavaScriptFromString method. the below code will get the html page title
using stringByEvaluatingJavaScriptFromString.
1
2
let htmlTitle = myWebView.stringByEvaluatingJavaScriptFromString("document.title");
println(htmlTitle)
UIWEBVIEW LOADDATA
Instead of web pages, we can also load the document files into iOS WebView like .pdf, .txt, .doc etc.. loadData method is used
to load NSData into webview. Replace the below code snippet into the viewDidLoad.
1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let localFilePath = NSBundle.mainBundle().pathForResource("home", ofType:"txt");
let data = NSFileManager.defaultManager().contentsAtPath(localFilePath!);
myWebView.loadData(data!, MIMEType: "application/txt", textEncodingName: "UTF-8", baseURL: nil);
}
UIWEBVIEW PROPERTIES
UIWebView scalesPageToFit
it is the boolean property used scale the every webpage loaded into uiwebview, if YES the webpage is allow users to perform
zoom in and zoom out operations. if NO user zooming is disabled, by default the value is NO.
UIWebView Detection
Detection property is used to analyze the loaded webpages having any links, email or phone numbers. and events(added to
calendar).
UIWebView keyboardDisplayRequiresUserAction
it is boolean variable, this property is set to YES, the user must explicitly tap the input elements in the web view to display the
keyboard. When set to be NO, a focus event on an element causes the input view to be displayed and associated with that
element automatically and the default value of the property is YES.
UIWEBVIEW NAVIGATION OPERATIONS:
uiwebview allow back, forward and reload to the webpage that already loaded.
goBack() – is used load the previous web page
goForward() – is used load forward web page.
reload() – is used to reload current web page.
stopLoading() – is used to stop the web content.
1
2
3
4
5
6
7
mywebView.goBack(); // uiwebview navigate back
mywebView.goForward(); // uiwebview navigate forward
mywebView.reload(); // to refresh the uiwebview
mywebView.stopLoading(); // to stop the loading from uiwebview
canGoBack – it is read only property used to know about is current webpage is can able to go back. for example if we are
loaded webpage into first time we are not able to go back.
canGoForward – it is read only property used to know about is current webpage is can able to go forward.
loading – it is the read only property, used to check the webview is loading or not, If YES the webview is loading otherwise NO.
CREATE UIWEBVIEW PROGRAMMATICALLY
Instead of create the uiweview using storyboard, we can create the uiwebview programmatically using the below code. Here
we are generating the NSURLRequest using NSURL object, then passing the request to webview it will load the requested
URL into webview next add the uiwebview into viewcontroller view.
1
2
3
4
5
6
override func viewDidLoad() {
super.viewDidLoad()
let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width,
UIScreen.mainScreen().bounds.height))
myWebView.loadRequest(NSURLRequest(URL: NSURL(string: "http://www.sourcefreeze.com")!))
self.view.addSubview(myWebView)
}
then build and run the project will get the output like below.
-
copied from: http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/
Sendi
ng a
pdf
file to
client
from
serve
r
throu
gh
web
servic
e
Shashank
Acharya
Greenhorn
posted 12/23/2010 11:26:54 AM
Joined: Mar
20, 2010
Posts: 21
I like...
Hello friends,
Can anyone solve my question as I am new to webservice.
My question is
I want to build a web service which when called from client side
sends pdf files to client.
Now can some one please solve my error.
Now my web service & code looks likes this.
Code:-
Main Class from which web service is created:-
?
1
2
3
4
5
6
package com.uks.webservice;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import sun.misc.BASE64Encoder;
public class SendPDFImpl implements SendPDF {
@Override
public String[] sendPDF() {
String[] pdfFile = new String[2];
BASE64Encoder encoder = new BASE64Encoder();
File file = new File(
"C:/eclipse/workspace/AIPWebService/src/test.pdf");
DataHandler dh = new DataHandler(new FileDataSource(file));
String readLine = null;
byte[] data = new byte[(int) file.length()];
int offset = 0;
int numRead = 0;
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
InputStream stream = null;
try {
System.out.println("Web Service Called Successfully");
stream = dh.getInputStream();
// BufferedReader bufferedReader = new BufferedReader(
// new InputStreamReader(stream));
while (offset < data.length
&& (numRead = stream.read(data, offset, data.length
- offset)) >= 0) {
offset += numRead;
}
readLine = encoder.encode(data);
// while ((readLine = bufferedReader.readLine()) != null) {
System.out.println("'Reading File............................");
System.out.println("n");
System.out.println("Data Reading Successful");
pdfFile[0] = file.getName();
pdfFile[1] = readLine;
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return pdfFile;
}
}
And Now My Android Code.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.uks.android.webservice;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
public class PDFActivity extends Activity {
private final String METHOD_NAME = "sendPDF";
private final String NAMESPACE = "http://webservice.uks.com/";
private final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
private final String URL = "http://192.168.1.123:8080/AIPWebService/services/SendPDFImpl";
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textViewOne = (TextView) findViewById(R.id.textViewOne);
TextView textViewTwo = (TextView) findViewById(R.id.textViewTwo);
try {
SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(soapObject);
textViewOne.setText("Web Service Started");
AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL);
httpTransport.call(SOAP_ACTION, envelope);
34
35
36
37
38
39
40
41
42
43
44
45
46
47
SoapObject result = (SoapObject) envelope.getResponse();
textViewTwo.setText(result.toString());
// Object result = envelope.getResponse();
// FileOutputStream outputStream = openFileOutput(name, mode)
} catch (Exception e) {
e.printStackTrace();
}
}
}
Please help me.
Thanks in Advance.
Tomcat + other things

More Related Content

What's hot

Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Java servlets
Java servletsJava servlets
Java servlets
lopjuan
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
Jafar Nesargi
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
Syed Shahul
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 

What's hot (20)

Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Java servlets
Java servletsJava servlets
Java servlets
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlets
ServletsServlets
Servlets
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 

Viewers also liked

Viewers also liked (15)

Combining content based and collaborative filtering
Combining content based and collaborative filteringCombining content based and collaborative filtering
Combining content based and collaborative filtering
 
Content based recommendation systems
Content based recommendation systemsContent based recommendation systems
Content based recommendation systems
 
uae views on big data
  uae views on  big data  uae views on  big data
uae views on big data
 
Cs548 s15 showcase_web_mining
Cs548 s15 showcase_web_miningCs548 s15 showcase_web_mining
Cs548 s15 showcase_web_mining
 
Introduction to recommendation system
Introduction to recommendation systemIntroduction to recommendation system
Introduction to recommendation system
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
Sql developer usermanual_en
Sql developer usermanual_enSql developer usermanual_en
Sql developer usermanual_en
 
Big data-analytics-2013-peer-research-report
Big data-analytics-2013-peer-research-reportBig data-analytics-2013-peer-research-report
Big data-analytics-2013-peer-research-report
 
Sun==big data analytics for health care
Sun==big data analytics for health careSun==big data analytics for health care
Sun==big data analytics for health care
 
Chapter 2 research methodlogy
Chapter 2 research methodlogyChapter 2 research methodlogy
Chapter 2 research methodlogy
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
Android chapter18 c-internet-web-services
Android chapter18 c-internet-web-servicesAndroid chapter18 c-internet-web-services
Android chapter18 c-internet-web-services
 
Personalizing the web building effective recommender systems
Personalizing the web building effective recommender systemsPersonalizing the web building effective recommender systems
Personalizing the web building effective recommender systems
 
Database development connection steps
Database development connection stepsDatabase development connection steps
Database development connection steps
 
Full xml
Full xmlFull xml
Full xml
 

Similar to Tomcat + other things

DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
Akankshaji
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
Adil Jafri
 
php-and-zend-framework-getting-started
php-and-zend-framework-getting-startedphp-and-zend-framework-getting-started
php-and-zend-framework-getting-started
tutorialsruby
 

Similar to Tomcat + other things (20)

Developing Java Web Applications
Developing Java Web ApplicationsDeveloping Java Web Applications
Developing Java Web Applications
 
Jdbc
JdbcJdbc
Jdbc
 
Oracle Endeca Developer's Guide
Oracle Endeca Developer's GuideOracle Endeca Developer's Guide
Oracle Endeca Developer's Guide
 
Cis 274 intro
Cis 274   introCis 274   intro
Cis 274 intro
 
Java EE 02-First Servlet
Java EE 02-First ServletJava EE 02-First Servlet
Java EE 02-First Servlet
 
Servlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtpServlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtp
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
Oracle EBS 12.1.3 : Integrate OA Framework BC4J components within java concur...
 
JSR 168 Portal - Overview
JSR 168 Portal - OverviewJSR 168 Portal - Overview
JSR 168 Portal - Overview
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Soap Component
Soap ComponentSoap Component
Soap Component
 
How to use soap component
How to use soap componentHow to use soap component
How to use soap component
 
Maven: Managing Software Projects for Repeatable Results
Maven: Managing Software Projects for Repeatable ResultsMaven: Managing Software Projects for Repeatable Results
Maven: Managing Software Projects for Repeatable Results
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Cocoapods and Most common used library in Swift
Cocoapods and Most common used library in SwiftCocoapods and Most common used library in Swift
Cocoapods and Most common used library in Swift
 
Class 1
Class 1Class 1
Class 1
 
Class 1
Class 1Class 1
Class 1
 
php-and-zend-framework-getting-started
php-and-zend-framework-getting-startedphp-and-zend-framework-getting-started
php-and-zend-framework-getting-started
 

Recently uploaded

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 

Tomcat + other things

  • 1.  Whiteboard  Quizzes  Shared  Articles  HOME  TUTORIALS LIBRARY  CODING GROUND  IMAGE EDITOR Run your first JSP program in Apache Tomcat Server amit2012, Posted on October 15, 2012, filed in: Web Design This post will give you description about how you can run your project using Apache Tomcat Server. I would like to define these terms before proceeding:
  • 2.  Apache Tomcat Server(Jakarta Tomcat): It is an open source web server and servlet container developed by the Apache Software Foundation (ASF). It implements the Java Servlet and the JavaServer Pages (JSP) specifications and provides a pure Java HTTP web server environment for java code to run.  JavaServerPages(JSP): It is a technology that helps in creating dynamically generated web pages. Step1 Install Java. Step2 Install Apache Tomcat At the time of installation, it will by-default recognize JRE path. (under installed java location directory) Step3 Now Go-To:  Start  Programs  APACHE TOMCAT  MONITOR TOMCAT
  • 3. Step4 An icon will appear on the taskbar, this icon will automatically appear after following above step: Step5 Click on that icon and START TOMCAT, you can see the following dialog box:
  • 4. Step6 Now open Mozilla Firefox(or any other browser) Step7 Type http://localhost:8080/ on address bar and press enter. The same can be seen here:
  • 5. Step8 It will show tomcat, as shown in above window. (if not, then try again, may be a problem in installation or you’re not following above steps correctly Step9 Now, go to:  C:drive  Programs Files  Apache Software Foundation  tomcat  web-apps (or navigate where you have installed APACHE TOMCAT) Step10 Open web-apps and “copy your project” or “make new folder”, which you want to run in JSP. Example: amit2012PROJECT Now, go back :  Tomcat  Root  Copy Web-inf from root  Paste this “web-inf” in your project folder i.e. amit2012PROJECT
  • 6. Step11 Create a text file and name it as first.jsp, use the code shown below: <html> <head> <title>blog post:ApacheTomcatServer</title> </head> <body> <%-- START --%> <% out.println("UserName = amit2012, "); out.println("Running first program in JSP."); %> <%-- END --%>
  • 7. </body> </html> It includes HTML tags and encloses a JSP scriptlet which is a fragment of Java code that is run when the user requests the page. Step12 Now for running your folder [ Eg. amit2012PROJECT as shown above] http://localhost:8080/foldername.extension in any WebBrowser i.e: http://localhost:8080/amit2012PROJECT/first.jsp The Project will run successfully, as shown below:
  • 8. Now, you can successfully try running JSP with ApacheTomcatServer. Skip to content AVILYNE TECHNOLOGIES Innovations in Information Technology AN ANDROID REST CLIENT AND TOMCAT REST WEBSERVICE by Mark 83 Commentson An Android REST Client and Tomcat REST Webservice
  • 9. Project Overview This post will describe simple client-server communications between an Android app and a web service using REST techniques, particularly GET and POST. For this demo, we will be sending and receiving data for a simple Java class called Person, which includes a firstName, lastName and email address. The data stored in an instance of this class will be transmitted from our web service in JSON format. NOTE: This post is a work in progress and will be updated and corrected, as time permits. Prerequisites This demo assumes that you have a version of Eclipse that can create a “Dynamic Web Project”, and that you have an instance of the Tomcat servlet container that you can control through Eclipse. This demo also assumes that you have the Android SDK, at least one Android Virtual Device (AVD), and have the Eclipse ADT plugin. Another important requirement is that your Android device needs to be on the same network as your Tomcat server. The simplest way to do this would be to make sure you are running your emulator on the same computer that is running Tomcat. About REST REST – “Representational State Transfer” is a technique that makes use of standard web protocols for the implementation of a web service. A RESTful web service uses the standard HTTP GET PUT DELETE and POST actions to submit, retrieve or modify server-side data. Commonly, in a REST web service, the standard HTTP actions are used as follows:  GET – retrieves or queries for data, usually using passed criteria  PUT – creates a new entry, record  DELETE – removes a resource  POST- updates a resource or creates a resource
  • 10. The data that is transmitted uses standard MIME types, including images, video, text, html, XML and JSON. A key feature of a REST service is its use of URI paths as query parameters. For example, a fictional web service for a book library might return a list of Civil War history books with this URI: http://librarywebservice.com/books/history/CivilWar Or, for magazines about tennis: http://librarywebservice.com/magazines/sports/tennis These are the absolute basics. REST has become a very popular replacement to SOAP for the development of web services. Download the Jersey Jars For the web server, this demo will use Tomcat, and will make use of a reference implementation of the JSR 311 Java library, otherwise known as “jersey”. The Jersey API can significantly streamline the development of a RESTful web service, and much of its ease comes from the use of annotations. The home page, and the place to download the required jars for jersey can be found here. As of the writing of this post, the jars will be found in a zip called jersey-archive-1.12.zip . Please download this zip and expand it to a folder where you can find those jars. Create a “Dynamic Web Project” in Eclipse
  • 11. In Eclipse, select “File”->”New…”->”Project” and use the filter to find “Dynamic Web Project”
  • 12. I have Apache Tomcat 7 running on my laptop, and have previously configured a connection between Tomcat and Eclipse. The Dynamic web module version I am using is 3.0, but this tutorial can work with version 2.5.
  • 13.
  • 14. Click “Next” and define your context root. That is the starting-point URL for your web service. With the context root shown in the screenshot below, the resulting URL on my laptop will be http://localhost:8080/RestWebServiceDemo . Also, have Eclipse generate a web.xml deployment descriptor. Add Jersey Jars to Project
  • 15. You will need to import the jars that you’ve downloaded from http://jersey.java.net into the WEB-INF/lib folder. Right click that folder (WebContent/WEB-INF/lib) and select Import…
  • 16. I’ve simply thrown in all the jars into that folder for the purposes of this tutorial. Crude, but effective. The smart thing would be to only use the jars you need. I’ll eventually circle back to that some day. Update Project Build Path to Include Jersey Jars Now that the jars are in the WEB-INF/lib folder, you will need to configure the project to include these jars in its build path. From within your project in the Package Explorer on the left of your Eclipse screen, right click to select “Build Path”-
  • 18. On the “Libraries” tab, click on “Add External JARS…” and select the jars that are now in your project’s WEB-INF/lib path. Create the POJO Person class Within the src folder, create a package called com.avilyne.rest.model, and in that package, create a Java class called Person. Note, in the code shown below, the @XmlRootElement annotation. This tells Jersey that this would be the root object of any generated XML (or JSON) representation of this class. This might not be very useful for this class, but if you had a compound class, you’d be able to control what the XML or JSON output would look like by the addition of annotations like this. ?
  • 19. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.avilyne.rest.model; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Person { public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Person() { id = -1; firstName = ""; lastName = "";
  • 20. 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 email = ""; } public Person(long id, String firstName, String lastName, String email) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.email = email; } private long id; private String firstName; private String lastName; private String email; } Create the PersonResource class Again, in the src folder, create a new package calledcom.avilyne.rest.resource, and in that package create a class calledPersonResource. (We are separating our data model from our controller). The PersonResource class will be the interface between a Person object and the web. When a client requests a Person object, the PersonResource will handle the request and return the appropriate object. Note, in the code below, the annotations. The @Path(“/person”) annotation allows us to define the URI that will have access to this resource. It will be something along the lines of http://RestServerDemo/rest/person, but this will be explained in more detail as we map this code in our web.xml file.
  • 21. The @Context annotation allows us to inject, in this example, UriInfo and Request objects into our PersonResource object. Our code can inspect those injected objects for any desired Context information. ? 1 2 3 4 5 6 7 8 9 10 11 // The @Context annotation allows us to have certain contextual objects // injected into this class. // UriInfo object allows us to get URI information (no kidding). @Context UriInfo uriInfo; // Another "injected" object. This allows us to use the information that's // part of any incoming request. // We could, for example, get header information, or the requestor's address. @Context Request request; The @GET annotation lets us specify what method will be called when a client issues a GET to the webservice. Similar logic applies to the @POST annotation. Note that the actual method name will not be a part of the client’s URI. Also note that more than one method has a @GET annotation. The first @GET is simply there so that, when we start our service, we can use a browser to retrieve some sort of response that indicates the service is running. Technically, instead of producing TEXT_PLAIN, the first GET could have produced a TEXT_HTML page. ? 1 2 3 4 5 6 // Basic "is the service running" test @GET @Produces(MediaType.TEXT_PLAIN) public String respondAsReady() { return "Demo service is ready!"; } The @Path annotation lets us append a parameter onto our URI. Using the example from earlier, the hypothetical URI would be http://RestServerDemo/rest/person/sample . ?
  • 22. 1 2 3 4 5 6 7 8 9 @GET @Path("sample") @Produces(MediaType.APPLICATION_JSON) public Person getSamplePerson() { System.out.println("Returning sample person: " + person.getFirstName() + " " + person.getLastName()); return person; } Note that paths do NOT need to be literal. One can have a path parameter as a variable, e.g. @Path(“{id}”) would refer to a person whose id value matched the passed URI value. http://RestServerDemo/rest/person/1 should return a person whose id is 1. The @Produces annotation allows us to define how the output from our resource should be transmitted to our client. Note that, for the getSamplePerson() method, we return a person object, and the annotation lets us tell Jersey to format and transmit that person as a JSON object. The method with the @POST annotation also includes a @Consumesannotation. As you can guess, this method is called in response to a client’s POST request. The data for the “person” object being transmitted from the client is not a JSON object, but is a collection of Name-Value pairs. The @Consumes annotation allows us to specify that the data passed from the client is an array of these pairs, and we can pull out the values we want from that array. ? 1 2 3 4 5 6 7 8 9 10 // Use data from the client source to create a new Person object, returned in JSON format. @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Person postPerson( MultivaluedMap<String, String> personParams ) { String firstName = personParams.getFirst(FIRST_NAME); String lastName = personParams.getFirst(LAST_NAME); String email = personParams.getFirst(EMAIL);
  • 23. 11 12 13 14 15 16 17 18 19 20 21 22 23 System.out.println("Storing posted " + firstName + " " + lastName + " " + email); person.setFirstName(firstName); person.setLastName(lastName); person.setEmail(email); System.out.println("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEmail( return person; } For each of the methods in this PersonResource, I’ve added a System.out.println() as a crude way of letting us see when a request is being processed. There are probably more elegant ways of doing this (Logging, for one), and one would almost never include a System.out.println in a production service. This is just a demo. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.avilyne.rest.resource; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import javax.ws.rs.core.Request; import com.avilyne.rest.model.Person; @Path("/person")
  • 24. 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 public class PersonResource { private final static String FIRST_NAME = "firstName"; private final static String LAST_NAME = "lastName"; private final static String EMAIL = "email"; private Person person = new Person(1, "Sample", "Person", "sample_person@jerseyrest.com"); // The @Context annotation allows us to have certain contextual objects // injected into this class. // UriInfo object allows us to get URI information (no kidding). @Context UriInfo uriInfo; // Another "injected" object. This allows us to use the information that's // part of any incoming request. // We could, for example, get header information, or the requestor's address. @Context Request request; // Basic "is the service running" test @GET @Produces(MediaType.TEXT_PLAIN) public String respondAsReady() { return "Demo service is ready!"; } @GET @Path("sample") @Produces(MediaType.APPLICATION_JSON) public Person getSamplePerson() { System.out.println("Returning sample person: " + person.getFirstName() + " " + person.getLastName()); return person; } // Use data from the client source to create a new Person object, returned in JSON format.
  • 25. 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Person postPerson( MultivaluedMap<String, String> personParams ) { String firstName = personParams.getFirst(FIRST_NAME); String lastName = personParams.getFirst(LAST_NAME); String email = personParams.getFirst(EMAIL); System.out.println("Storing posted " + firstName + " " + lastName + " " + email); person.setFirstName(firstName); person.setLastName(lastName); person.setEmail(email); System.out.println("person info: " + person.getFirstName() + " " + person.getLastName() + " " + person.getEm return person; } } Create or Edit the WebContentWEB-INFweb.xml file In our web.xml file, we want to direct all requests to a servlet called Jersey REST Service. We will also tell this service where to find the resources that we want to make available to our client app.
  • 26. Update the web.xml file (or create it, in WebContentWEB-INFweb.xml, if it does not exist) to match the XML shown below. The XML defines the Jersey REST Service from the com.sun.jersey.spi.container.ServletContainer class. That class, as you might guess, is in one of the Jersey Jars. The init-param section allows us to tell that servletcontainer to use the classes found in the com.avilyne.rest.resource package for the mapping of URIs to java code. In the servlet-mapping section, we create a global url-pattern, which essentially says that any request that goes to /rest/ will attempt to be mapped to the appropriate methods. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>JerseyRESTServer</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>com.avilyne.rest.resource</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>
  • 27. Run the WebService Run the completed project as a service on your Tomcat servlet container. The actual URL for the service will vary slightly, depending partly on the name of your project. I called my project JerseyRESTServer, and here is the URL for the web service on my computer: http://localhost:8080/JerseyRESTServer/rest/person Correction! Paul, a recent commenter, has pointed out that the URL should actually be: http://localhost:8080/RestWebServiceDemo/rest/person RestWebServiceDemo is the context root that we defined when we first started this project. I’ll mention that I built a few versions of this project before writing this post, so unfortunately some of the images show a URL from an earlier version of the project. If I bring up this on a browser, it returns with this: If I add the “sample” path to the URL, like this: http://localhost:8080/RestWebServiceDemo/rest/person/sample The web service returns a JSON object: ? 1 {"email":"sample_person@jerseyrest.com","firstName":"Sample","id":"1","lastName":"Person"} I would recommend that you make sure you can retrieve this sample person before you create the Android client app.
  • 28. Create an Android Client App Create a new Android project, calling it something like AndroidRESTClient. I used API level 10 for this project, but one can probably use a lower level API, if required. Android HttpClient requests have been around since the earliest days of the OS. Use com.avilyne.android as the package for the main activity. Edit the reslayoutmain.xml File The interface will be very simple, having three labels and three edit controls for firstName, lastName and email address. It will also have three buttons – one to GET, one to POST, and one to clear the controls. The main.xml file should look like this: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tableLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:shrinkColumns="*" android:stretchColumns="*" > <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView style="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/firstName" > </TextView> <EditText android:id="@+id/first_name" android:layout_width="wrap_content"
  • 29. 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 android:layout_height="wrap_content" android:inputType="textCapWords" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView style="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/lastName" > </TextView> <EditText android:id="@+id/last_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textCapWords" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView style="" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/email" > </TextView> <EditText android:id="@+id/email" android:layout_width="wrap_content" android:layout_height="wrap_content"
  • 30. 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 android:inputType="textEmailAddress" android:layout_span="2" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/bn_retrieve" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="retrieveSampleData" android:text="@string/retrieve" /> <Button android:id="@+id/bn_post" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="postData" android:text="@string/post" /> <Button android:id="@+id/bn_clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="clearControls" android:text="@string/clear" /> </TableRow> </TableLayout>
  • 31. 91 92 93 Note that an onClick method is defined for each button. Edit the resvaluesstrings.xml file ? 1 2 3 4 5 6 7 8 9 10 11 12 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="firstName">First Name</string> <string name="lastName">Last name</string> <string name="email">Email</string> <string name="retrieve">Retrieve</string> <string name="post">Post</string> <string name="clear">Clear</string> <string name="app_name">AndroidRESTClient</string> </resources> Edit the AndroidRESTClientActivity.java file Discuss the WebServiceTask, and the handleResponse() method. The full source code for the Android client is listed below, but I want to highlight a few items in the code that you should be aware of. On my home network, the computer running the service on Tomcat is at IP address 192.168.1.9. On your network, the address will most definitely be different. If you are running the Android client and the Tomcat service on the same computer, you can get away with using “localhost” in your Android code.
  • 32. (CORRECTION: (Thanks ABa) Actually, you *can’t* use “localhost”. “Localhost” in this context would refer to the Android device itself. Use the IP address of the computer on your network that is running the Tomcat service. See thisStackOverflow link for details.) ? 1 2 3 public class AndroidRESTClientActivity extends Activity { private static final String SERVICE_URL = "http://192.168.1.9:8080/RestWebServiceDemo/rest/person"; For this tutorial, the most important code is the internal “WebServiceTask” class, which is extended from an “AsyncTask” class. An AsyncTask class descendant allows a process to run in a separate thread. If our communication with our service were on the Android app’s main thread, the user interface would lock up as the process was waiting for results from the server. One can define the types of parameters that are passed to one’s instance of the AsyncTask. (more on that later). The communication with the web service occurs in the WebServiceTask’s “doInBackground()” code. This code uses Android’s HttpClient object, and for the GET method, uses HttpGet, and for the POST method, uses HttpPost. The AsyncTask class includes two other methods that one has the option to overwrite. One is onPreExecute(), which one can use to prepare for the background process, and the other is onPostExecute(), which one can use to do any required clean-up after the background process is complete. This code overrides those methods to display and remove a progress dialog. The background task also includes two timeout options. One is a timeout period for the actual connection to the service, and the other is a timeout period for the wait for the service’s response. ? 1 2 3 4 5 6 package com.avilyne.android; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList;
  • 33. 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; public class AndroidRESTClientActivity extends Activity { private static final String SERVICE_URL = "http://192.168.1.9:8080/RestWebServiceDemo/rest/person"; private static final String TAG = "AndroidRESTClientActivity"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
  • 34. 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 public void retrieveSampleData(View vw) { String sampleURL = SERVICE_URL + "/sample"; WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "GETting data..."); wst.execute(new String[] { sampleURL }); } public void clearControls(View vw) { EditText edFirstName = (EditText) findViewById(R.id.first_name); EditText edLastName = (EditText) findViewById(R.id.last_name); EditText edEmail = (EditText) findViewById(R.id.email); edFirstName.setText(""); edLastName.setText(""); edEmail.setText(""); } public void postData(View vw) { EditText edFirstName = (EditText) findViewById(R.id.first_name); EditText edLastName = (EditText) findViewById(R.id.last_name); EditText edEmail = (EditText) findViewById(R.id.email); String firstName = edFirstName.getText().toString(); String lastName = edLastName.getText().toString(); String email = edEmail.getText().toString(); if (firstName.equals("") || lastName.equals("") || email.equals("")) { Toast.makeText(this, "Please enter in all required fields.", Toast.LENGTH_LONG).show(); return; }
  • 35. 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Posting data..."); wst.addNameValuePair("firstName", firstName); wst.addNameValuePair("lastName", lastName); wst.addNameValuePair("email", email); // the passed String is the URL we will POST to wst.execute(new String[] { SERVICE_URL }); } public void handleResponse(String response) { EditText edFirstName = (EditText) findViewById(R.id.first_name); EditText edLastName = (EditText) findViewById(R.id.last_name); EditText edEmail = (EditText) findViewById(R.id.email); edFirstName.setText(""); edLastName.setText(""); edEmail.setText(""); try { JSONObject jso = new JSONObject(response); String firstName = jso.getString("firstName"); String lastName = jso.getString("lastName"); String email = jso.getString("email"); edFirstName.setText(firstName); edLastName.setText(lastName); edEmail.setText(email); } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage(), e); }
  • 36. 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 } private void hideKeyboard() { InputMethodManager inputManager = (InputMethodManager) AndroidRESTClientActivity.this .getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow( AndroidRESTClientActivity.this.getCurrentFocus() .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } private class WebServiceTask extends AsyncTask<String, Integer, String> { public static final int POST_TASK = 1; public static final int GET_TASK = 2; private static final String TAG = "WebServiceTask"; // connection timeout, in milliseconds (waiting to connect) private static final int CONN_TIMEOUT = 3000; // socket timeout, in milliseconds (waiting for data) private static final int SOCKET_TIMEOUT = 5000; private int taskType = GET_TASK; private Context mContext = null; private String processMessage = "Processing..."; private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); private ProgressDialog pDlg = null; public WebServiceTask(int taskType, Context mContext, String processMessage) { this.taskType = taskType;
  • 37. 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 this.mContext = mContext; this.processMessage = processMessage; } public void addNameValuePair(String name, String value) { params.add(new BasicNameValuePair(name, value)); } private void showProgressDialog() { pDlg = new ProgressDialog(mContext); pDlg.setMessage(processMessage); pDlg.setProgressDrawable(mContext.getWallpaper()); pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER); pDlg.setCancelable(false); pDlg.show(); } @Override protected void onPreExecute() { hideKeyboard(); showProgressDialog(); } protected String doInBackground(String... urls) { String url = urls[0]; String result = ""; HttpResponse response = doResponse(url); if (response == null) { return result; } else {
  • 38. 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 try { result = inputStreamToString(response.getEntity().getContent()); } catch (IllegalStateException e) { Log.e(TAG, e.getLocalizedMessage(), e); } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage(), e); } } return result; } @Override protected void onPostExecute(String response) { handleResponse(response); pDlg.dismiss(); } // Establish connection and socket (data retrieval) timeouts private HttpParams getHttpParams() { HttpParams htpp = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT); HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT); return htpp; } private HttpResponse doResponse(String url) {
  • 39. 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 // Use our connection and data timeouts as parameters for our // DefaultHttpClient HttpClient httpclient = new DefaultHttpClient(getHttpParams()); HttpResponse response = null; try { switch (taskType) { case POST_TASK: HttpPost httppost = new HttpPost(url); // Add parameters httppost.setEntity(new UrlEncodedFormEntity(params)); response = httpclient.execute(httppost); break; case GET_TASK: HttpGet httpget = new HttpGet(url); response = httpclient.execute(httpget); break; } } catch (Exception e) { Log.e(TAG, e.getLocalizedMessage(), e); } return response; } private String inputStreamToString(InputStream is) { String line = ""; StringBuilder total = new StringBuilder(); // Wrap a BufferedReader around the InputStream BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  • 40. 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 try { // Read response until the end while ((line = rd.readLine()) != null) { total.append(line); } } catch (IOException e) { Log.e(TAG, e.getLocalizedMessage(), e); } // Return full string return total.toString(); } } }
  • 41. (Code discussion, with excerpts, here) Update the AndroidManifest.xml Since this app needs to communicate via the internet, one must give the app the appropriate permissions. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.avilyne.android" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".AndroidRESTClientActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  • 42. Running the Android Client App This screenshot shows the Android client app with its blank screen.
  • 43. If one presses the “Retrieve” button, the web service will respond:
  • 44. The Android client’s controls should get populated with the retrieved Person:
  • 45. Here I’ve modified the values on my Android client screen, and pressed the “Post” button:
  • 46. The web service responds to the post: Hopefully, this will give you some idea of how to build an Android client that communicates with a web service using REST. Step by Step Guide to Setup and Install Apache Tomcat Server in Eclipse Development Environment (IDE) SHORT LINK: http://crunfy.m Last Updated on January 16th, 2015 by Crunchify 6 Comments
  • 47. Eclipse is a very powerful development environment for Java. Mainly for Web Development project you need Web Server. Apache Tomcat is the best production ready web container. By default when you download Eclipse IDE, it doesn’t come with Tomcat install with it. In this tutorial we will go over all detailed steps to configure Apache Tomcat successfully in Eclipse environment. Step-1 Download Apache Tomcat from this link. I’m using version 8.0.15 .
  • 48.
  • 49. Step-2 Extract it to Document folder.
  • 50.
  • 51. Step-3  Open Eclipse Environment  Click on Servers Tab  Click on No servers are available. Click this link to create a new server...  Click Tomcat v8.0 Server and Next
  • 52.
  • 53. Step-4 Select Apache installation Directory and click Finish .
  • 54.
  • 55. Step-5 You should see Tomcat v8.0 Server at localhost [Stopped, Republish] under Servers tab. Double click on it verify HTTP ports information. By default HTTP port is 8080. Step-6 Now right click on Server and click Start .
  • 56. Console output: Tomcat startup log 1 2 INFO: Initialization processed in 499 ms Jan 05, 2015 9:09:28 PM org.apache.catalina.core.StandardService startInternal
  • 57. 3 4 5 6 7 8 9 10 11 INFO: Starting service Catalina Jan 05, 2015 9:09:28 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/8.0.15 Jan 05, 2015 9:09:29 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-nio-8080"] Jan 05, 2015 9:09:29 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-nio-8009"] Jan 05, 2015 9:09:29 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 262 ms It should be up and running on port 8080 and you could visit default page using URL: http://localhost:8080/ WEDNESDAY, 26 AUGUST 2015
  • 58. Xcode 7 iOS Create Basic Segue . Basic Segue
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75. . Posted by razi mahmood at 01:38 2 comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest SATURDAY, 22 AUGUST 2015 Official iOS Swift Apps Development Tutorial - A) GETTING STARTED 1. Introduction https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/index.html#//apple_ref/doc/u
  • 76. id/TP40015214-CH2-SW1 2. Learn the Swift essentials https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson1.html#//apple_ref/do c/uid/TP40015214-CH3-SW1 B) BUILDING THE UI 1. Build a Basic UI https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson2.html#//apple_ref/do c/uid/TP40015214-CH5-SW1 2. Connect the UI to Code https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson3.html#//apple_ref/do c/uid/TP40015214-CH22-SW1 3. Work with View Controllers https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/do c/uid/TP40015214-CH6-SW1 4. Implement a Custom Control https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson4.html#//apple_ref/do c/uid/TP40015214-CH6-SW1 5. Define your Data Model https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson6.html#//apple_ref/do c/uid/TP40015214-CH20-SW1 C) WORKING WITH TABLE VIEWS
  • 77. 1. Create a Table View https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson6.html#//apple_ref/do c/uid/TP40015214-CH20-SW1 2. Implement Navigation https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson8.html#//apple_ref/do c/uid/TP40015214-CH16-SW1 3. Implement Edit and Delete Behavior https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson9.html#//apple_ref/do c/uid/TP40015214-CH9-SW1 4. Persist Data https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson10.html#//apple_ref/d oc/uid/TP40015214-CH14-SW1 - Posted by razi mahmood at 19:19 1 comment: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
  • 78. Official Android Apps Development Tutorial - A. BUILDING YOUR FIRST APP 0) Introduction https://developer.android.com/training/basics/firstapp/index.html 1) Creating an Android Project https://developer.android.com/training/basics/firstapp/creating-project.html 2) Running your app https://developer.android.com/training/basics/firstapp/running-app.html
  • 79. 3) Building a Simple User Interface https://developer.android.com/training/basics/firstapp/building-ui.html 4) Starting another Activity https://developer.android.com/training/basics/firstapp/starting-activity.html B. ADDING THE ACTION BAR 0) Introduction https://developer.android.com/training/basics/actionbar/index.html 1) Setting Up the Action Bar https://developer.android.com/training/basics/actionbar/setting-up.html 2) Adding Action Buttons https://developer.android.com/training/basics/actionbar/adding-buttons.html 3) Styling the Action Bar https://developer.android.com/training/basics/actionbar/styling.html 4) Overlaying the Action Bar https://developer.android.com/training/basics/actionbar/overlaying.html - Posted by razi mahmood at 19:12 No comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
  • 80. iOS Swift Basic Tutorial - Tutorials from RayWenderlich.com. 1) http://www.raywenderlich.com/75601/learn-to-code-ios-apps-with-swift-tutorial-1 2) http://www.raywenderlich.com/75919/learn-to-code-ios-apps-with-swift-tutorial-2 3) http://www.raywenderlich.com/76044/learn-to-code-ios-apps-with-swift-tutorial-3 4) http://www.raywenderlich.com/77176/learn-to-code-ios-apps-with-swift-tutorial-4
  • 81. 5) http://www.raywenderlich.com/78264/learn-to-code-ios-apps-with-swift-tutorial-5 - Posted by razi mahmood at 18:50 No comments: Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest UIWebView example using swift in ios - UIWebView object is used the load and display the web content into your application, safari browser is the primary example for ios webview. for more reference you can go through apple documentation for uiwebview. Open the Xcode, create new project and select the Single View Application template,
  • 82. In the next screen, enter the Product Name as “UIWebView Example”, then enter the company identifier details. Select Swift in Language field and Universal in Devices option, Then press next and create the project.
  • 83. ADDING UIWEBVIEW TO VIEW We can add the UIWebView to View using two methods, first one is adding the uiwebview into storyboard and another one is programatically create uiwebview and adding into the view. first we will add the uiwebview into storyboard viewcontroller. Open the Main.storyboard file, then at the right bottom of the Xcode you can find ios webview object in the utility area, drag and drop the uiwebview into storyboard viewcontroller page.
  • 84. Now, uiwebview added into Main.storyboard ViewController page and looks like below.
  • 85. Then, click the assistance editor to link the Storyboard ViewController page to viewcontroller.swift by adding the uiwebview reference.
  • 86. Then press the control key click the storyboard uiwebview drag into viewcontroller.swift file and place next to viewcontroller class file, as shown in the below.
  • 88. Open the ViewController.swift file and change the below code snippet into the viewDidLoad() function. Here we are generating the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview. 1 2 3 4 5 6 7 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.
  • 89. let url = NSURL (string: "http://www.sourcefreeze.com"); let requestObj = NSURLRequest(URL: url!); myWebView.loadRequest(requestObj); } Next, Build and Run the application you will get the output like below.
  • 90.
  • 91. UIWEBVIEW LOAD LOCAL HTML As like online web page, we can load the local html file into webview. this is the base of hybrid application development using PhoneGap/Cordova. first we have to add the html file using File–>New–>File or Press Command + N, it will open the window like below. then select the Empty file name it as home.html add it into project. Next, add the below code html code snippet into the home.html file. 1 2 3 4 5 6 7 <html> <head>
  • 92. 8 </head> <body> <br /> <h2> Welcome SourceFreeze!!!</h2> </body>
  • 93. </html> then, go to the ViewController.swift file, modify the viewDidLoad method like below code snippet. 1 2 3 4 5 6 7 override func viewDidLoad() { super.viewDidLoad()
  • 94. // Do any additional setup after loading the view, typically from a nib. let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html"); let myRequest = NSURLRequest(URL: localfilePath!); myWebView.loadRequest(myRequest); }
  • 95. Next, Build and Run the application you will get the output like below.
  • 96.
  • 97. UIWEBVIEW LOADHTMLSTRING Other then direct URL we can load HTML String into UIWebView, we have to pass the htmlstring into loadHTMLString method like the below code snippet, replace this code in the viewDidLoad method. 1 2 3 4 5 6 override func viewDidLoad() { super.viewDidLoad()
  • 98. // Do any additional setup after loading the view, typically from a nib. var htmlString:String! = "<br /><h2>Welcome to SourceFreeze!!!</h2>" myWebView.loadHTMLString(htmlString, baseURL: nil) } then build and run the application, you will get the output like below.
  • 99.
  • 100. UIWEBVIEW RUNNING JAVASCRIPT Like loading the direct html strings into uiwebview, can able to access or run the direct javascript methods into uiwebview using stringByEvaluatingJavaScriptFromString method. the below code will get the html page title using stringByEvaluatingJavaScriptFromString. 1 2 let htmlTitle = myWebView.stringByEvaluatingJavaScriptFromString("document.title"); println(htmlTitle) UIWEBVIEW LOADDATA
  • 101. Instead of web pages, we can also load the document files into iOS WebView like .pdf, .txt, .doc etc.. loadData method is used to load NSData into webview. Replace the below code snippet into the viewDidLoad. 1 2 3 4 5 6 7 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib.
  • 102. let localFilePath = NSBundle.mainBundle().pathForResource("home", ofType:"txt"); let data = NSFileManager.defaultManager().contentsAtPath(localFilePath!); myWebView.loadData(data!, MIMEType: "application/txt", textEncodingName: "UTF-8", baseURL: nil); } UIWEBVIEW PROPERTIES
  • 103. UIWebView scalesPageToFit it is the boolean property used scale the every webpage loaded into uiwebview, if YES the webpage is allow users to perform zoom in and zoom out operations. if NO user zooming is disabled, by default the value is NO. UIWebView Detection Detection property is used to analyze the loaded webpages having any links, email or phone numbers. and events(added to calendar). UIWebView keyboardDisplayRequiresUserAction it is boolean variable, this property is set to YES, the user must explicitly tap the input elements in the web view to display the keyboard. When set to be NO, a focus event on an element causes the input view to be displayed and associated with that element automatically and the default value of the property is YES. UIWEBVIEW NAVIGATION OPERATIONS: uiwebview allow back, forward and reload to the webpage that already loaded. goBack() – is used load the previous web page goForward() – is used load forward web page. reload() – is used to reload current web page. stopLoading() – is used to stop the web content.
  • 104. 1 2 3 4 5 6 7 mywebView.goBack(); // uiwebview navigate back mywebView.goForward(); // uiwebview navigate forward
  • 105. mywebView.reload(); // to refresh the uiwebview mywebView.stopLoading(); // to stop the loading from uiwebview canGoBack – it is read only property used to know about is current webpage is can able to go back. for example if we are loaded webpage into first time we are not able to go back. canGoForward – it is read only property used to know about is current webpage is can able to go forward. loading – it is the read only property, used to check the webview is loading or not, If YES the webview is loading otherwise NO. CREATE UIWEBVIEW PROGRAMMATICALLY
  • 106. Instead of create the uiweview using storyboard, we can create the uiwebview programmatically using the below code. Here we are generating the NSURLRequest using NSURL object, then passing the request to webview it will load the requested URL into webview next add the uiwebview into viewcontroller view. 1 2 3 4 5 6 override func viewDidLoad() { super.viewDidLoad() let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
  • 108.
  • 109. - copied from: http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/ Sendi ng a pdf file to client from serve r throu gh web servic e Shashank Acharya Greenhorn posted 12/23/2010 11:26:54 AM
  • 110. Joined: Mar 20, 2010 Posts: 21 I like... Hello friends, Can anyone solve my question as I am new to webservice. My question is I want to build a web service which when called from client side sends pdf files to client. Now can some one please solve my error. Now my web service & code looks likes this. Code:- Main Class from which web service is created:- ? 1 2 3 4 5 6 package com.uks.webservice; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream;
  • 111. 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import javax.activation.DataHandler; import javax.activation.FileDataSource; import sun.misc.BASE64Encoder; public class SendPDFImpl implements SendPDF { @Override public String[] sendPDF() { String[] pdfFile = new String[2]; BASE64Encoder encoder = new BASE64Encoder(); File file = new File( "C:/eclipse/workspace/AIPWebService/src/test.pdf"); DataHandler dh = new DataHandler(new FileDataSource(file)); String readLine = null; byte[] data = new byte[(int) file.length()]; int offset = 0; int numRead = 0;
  • 112. 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 InputStream stream = null; try { System.out.println("Web Service Called Successfully"); stream = dh.getInputStream(); // BufferedReader bufferedReader = new BufferedReader( // new InputStreamReader(stream)); while (offset < data.length && (numRead = stream.read(data, offset, data.length - offset)) >= 0) { offset += numRead; } readLine = encoder.encode(data); // while ((readLine = bufferedReader.readLine()) != null) { System.out.println("'Reading File............................"); System.out.println("n"); System.out.println("Data Reading Successful"); pdfFile[0] = file.getName(); pdfFile[1] = readLine;
  • 113. 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 stream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return pdfFile; } }
  • 114. And Now My Android Code. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.uks.android.webservice; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.AndroidHttpTransport; public class PDFActivity extends Activity { private final String METHOD_NAME = "sendPDF"; private final String NAMESPACE = "http://webservice.uks.com/"; private final String SOAP_ACTION = NAMESPACE + METHOD_NAME; private final String URL = "http://192.168.1.123:8080/AIPWebService/services/SendPDFImpl";
  • 115. 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textViewOne = (TextView) findViewById(R.id.textViewOne); TextView textViewTwo = (TextView) findViewById(R.id.textViewTwo); try { SoapObject soapObject = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.setOutputSoapObject(soapObject); textViewOne.setText("Web Service Started"); AndroidHttpTransport httpTransport = new AndroidHttpTransport(URL); httpTransport.call(SOAP_ACTION, envelope);
  • 116. 34 35 36 37 38 39 40 41 42 43 44 45 46 47 SoapObject result = (SoapObject) envelope.getResponse(); textViewTwo.setText(result.toString()); // Object result = envelope.getResponse(); // FileOutputStream outputStream = openFileOutput(name, mode) } catch (Exception e) { e.printStackTrace(); } } } Please help me. Thanks in Advance.