martes, 20 de diciembre de 2016

PHP Create your own MVC

Siguiendo un webinario de como desarrollar un Model View Controller en PHP, se desarrolla este laboratorio. la fuente es PHP Create Your Own MVC, que consta de 11 videos, del canal de youtube JREAM. Se considera que se conoce la OOP en PHP.

  Se emplea netbeans como IDE, utiliza una base de datos en MySQL, tiene control de usuarios con password SHA256. utiliza control de session default y AJAX para la actualización de datos de la pantalla de panel de control.

  Para hacer el ruteo se emplea las funcionalidades del archivo .htaccess de Apache para redireccionar la dirección url de forma que se mande a llamar controlador/metodo/parametro/parametro/parametro...
así el controlador se encargara de llamar la vista para mostrar resultados o el modelo para actualizar información en la base de datos.
  La estructura de archivos tendrá un subdirectorio controllers, models, views donde se encontraran los archivos php que gestionaran las entradas al ser direccionados a estos subdirectorios.


El Diagrama de clases extraido con la herramienta phuml es el siguiente:



Ya desarrollado e instalado el MVC en PHP,  los pasos para arrancarlo en linux


la aplicación tiene una base de datos ,con cuatro tablas, user, person, data, note. La tabla user contiene los datos de seguridad y acceso de usuarios, maneja un campo de password varchar(64) que tiene encriptado el password en SHA256, y el nivel de permisos de acceso (default,admin, owner). la tabla person tiene datos básicos de la persona. la tabla data tiene texto básico al cual todos los usuarios pueden acceder y actualizar. la table note tiene datos que solo son actualizados por el usuario con el que se haya accesado.

con un poco de css se le da forma a los diálogos de captura.





Procedimientos básicos de arranque de aplicación en servidor linux.

service mysql start
service apache2 restart
mysql -u Beto -p
Betopass

en Github:
https://github.com/jalbertomr/MVCinPHP.git

Fecha de publicación 20/12/2016

WIFI Linux command line Conect


alternativa 1
===============================================================
sudo iwconfig wlan0 mode managed essid 'my_network' key 'XX:XX:... hex key 26 digits'
sudo dhclient -v wlan0
sudo dhclient wlan0
================================================================
alternativa 2

sudo ifconfig wlan0 up
sudo lwlist wlan0 scan
sudo iwconfig wlan0 essid ..Starbucks..
sudo iwconfig

================================================================

alternativa 3 con nmcli

sudo nmcli 'standard ubuntu tool'
sudo nmcli c
sudo nmcli c up uuid <paste uuid here>
================================================================

sudo nmcli nm wifi off
sudo rfkill unblock wlan
sudo service hostapd start (restart)
sudo nmcli nm wifi on

===============================================================
instalacion de un network manager

sudo apt-get install network-manager nerwork-manager-gnome
to verify: dpkg -l | grep network-man*

===============================================================
instalacion de algun browser

sudo apt-get install iceweasel


miércoles, 23 de noviembre de 2016

Introduction to Web Services Borrador



Introduction to Web Services (Borrador)

Web Service Tutorial
Web service is a way of communication that allows interoperability between different applications on diferent platforms, for example, a java based application on Windows can communicate with a .Net based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.
Web services are browsers and operating systems independent service, which means it can run on any browser without the need of making any changes. Web  Services take Web-applications to the next level.
The World Wide Web Consortium (W3C) has defined the web services. According to W3C, “Web Services are the message-based design frequently found on the Web and in the enterprise software. The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and others.”
Lets say, you are a java developer and you can publish your functions on the internet or lan through java web service so any other developer (lets say .Net developer) can access your function.
Why you need to learn web services:
Reuse already developed(old) functionality into new software:
Lets understand with very simple example. Lets say you are developing a finance software for a company on java and you have old .net software which manages salary of employees. So rather than developing new software for employee part, you can use old software and for other parts like infrastructure you can develop your own functionalities.
Usability:
   Web Services allow the bussines logic of many different systems to be exposed over the Web. This gives your application the freedom to chose the Web Services that they need. Instead of re-inventing the wheel for each client, you need only include additional application-specific business logic on the client-side. This allows you to develop services and/or client-side code using the languages and tools that you want.
Interoperability:
This is the most important benefit of Web Services. Web Services typically work outside of private networks, offering developers a non-proprietary route to their solutions.Web Services also let developers use their preferred programming languages. In addition, thanks to the use of standards-based communications methods, Web Services are virtually platform-independent.
Loosely Coupled:
Each service exists independently of the other services that make up the application. Individual pieces of the application to be modified without impacting unrelated areas.
Ease of integration:
Data is isolated between applications creating ’silos’. Web Services act as glue between these and enable easier communications within and across organisations.
Deployability:
  Web Services are deployed over standard Internet technologies. This makes it possible to deploy Web Services even over the fire wall to servers running on the Internet on the other side of the globe. Also thanks to the use of proven community standards, underlying security (such as SSL) is already built-in.
Some jargons used in Web Services:
Simple Object Access Protocol (SOAP)
SOAP is a protocol specification for exchanging structured information in the implementation of Web services in computer networks. It relies on XML as its message format.
Web Service Description Language (WSDL)
WSDL stands for Web Service Description Language. It is an XML file that describes
the technical details of how to implement a web service, more specifically the URI,
port, method names, arguments, and data types. Since WSDL is XML, it is both
human-readable and machine-consumable, which aids in the ability to call and bind to
services dynamically.
Elements of WSDL are:
Description:
It is the root element of a WSDL 2.0 file. It usually contains a set of name space declarations which are used throughout the WSDL file.
Types:
The WSDL types element describes the data types used by your web service.Data types are usually specified by XML schema.It can be described in any language as long as your web services API supports it.
Binding:
The WSDL binding element describes how your web service is bound to a protocol. In other words, how your web service is accessible. To be accessible, the web service must be reachable using some network protocol. This is called "binding" the web service to the protocol.
Interface:
The WSDL interface element describes the operations supported by your web service.It is similar to methods in programming language.Client can only call one opertion per request. 
Service:
It describes the endpoint of your web service. In other words, the address where the web service can be reached.
Endpoint:
The endpoint element describes the address of the web service. The endpoint binding attribute describes what binding element this endpoint uses.i.e. protocol with which you will access web service. The address attribute describes the URI at which you can access the service.
Message:
The message element describes the data being exchanged between the Web service providers and consumers.
·    <?xml version="1.0" encoding="UTF-8"?>  
·  <wsdl:definitions targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns:apachesoap="http://xml.apache.org/xml-soap" xmlns:impl="http://webservices.javapostsforlearning.arpit.org" xmlns:intf="http://webservices.javapostsforlearning.arpit.org" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">  
·  <!--WSDL created by Apache Axis version: 1.4  
·  Built on Apr 22, 2006 (06:55:48 PDT)-->  
·   <wsdl:types>  
·    <schema elementFormDefault="qualified" targetNamespace="http://webservices.javapostsforlearning.arpit.org" xmlns="http://www.w3.org/2001/XMLSchema">  
·     <element name="sayHelloWorld">  
·      <complexType>  
·       <sequence>  
·        <element name="name" type="xsd:string"/>  
·       </sequence>  
·      </complexType>  
·     </element>  
·     <element name="sayHelloWorldResponse">  
·      <complexType>  
·       <sequence>  
·        <element name="sayHelloWorldReturn" type="xsd:string"/>  
·       </sequence>  
·      </complexType>  
·     </element>  
·    </schema>  
·   </wsdl:types>  
·     <wsdl:message name="sayHelloWorldRequest">  
·        <wsdl:part element="impl:sayHelloWorld" name="parameters"/>  
·     </wsdl:message>  
·     <wsdl:message name="sayHelloWorldResponse">  
·        <wsdl:part element="impl:sayHelloWorldResponse" name="parameters"/>  
·     </wsdl:message>  
·     <wsdl:portType name="HelloWorld">  
·        <wsdl:operation name="sayHelloWorld">  
·           <wsdl:input message="impl:sayHelloWorldRequest" name="sayHelloWorldRequest"/>  
·           <wsdl:output message="impl:sayHelloWorldResponse" name="sayHelloWorldResponse"/>  
·        </wsdl:operation>  
·     </wsdl:portType>  
·     <wsdl:binding name="HelloWorldSoapBinding" type="impl:HelloWorld">  
·        <wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>  
·        <wsdl:operation name="sayHelloWorld">  
·           <wsdlsoap:operation soapAction=""/>  
·           <wsdl:input name="sayHelloWorldRequest">  
·              <wsdlsoap:body use="literal"/>  
·           </wsdl:input>  
·           <wsdl:output name="sayHelloWorldResponse">  
·              <wsdlsoap:body use="literal"/>  
·           </wsdl:output>  
·        </wsdl:operation>  
·     </wsdl:binding>  
·     <wsdl:service name="HelloWorldService">  
·        <wsdl:port binding="impl:HelloWorldSoapBinding" name="HelloWorld">  
·           <wsdlsoap:address location="http://localhost:8080/SimpleSOAPExample/services/HelloWorld"/>  
·        </wsdl:port>  
·     </wsdl:service>  
·  </wsdl:definitions>  
Univesal Description, Discovery and Integration (UDDI):
UDDI stands for Universal Description, Discovery and Integration.It is a directory service. Web services can register with a UDDI and make themselves available through it for discovery
Web services design approaches:
Contract last or Buttom up approach:
When using contract last approach,you first write your java code then you create web service contract(WSDL) .There are various kinds of tools which can generate WSDL on the basis of java code.
Contract first or Top down approach:
It  is reverse of contract first.Here you first define web service contract.You define all the elements of WSDL first then after that you create your java logic.
Top 20 Web services interview questions
1.- What are web services?
Web services are ways of communication between two application over network. It allows you to expose business logic using API.
For example:
Lets say you are java developer, you can create web services and expose API over internet and any other developer (lets say .net developer) can access it.
2.- What are features of web services?
- Interoperatibility
- Reuse already developed(old) functionality into new software
- Loossely Coupled
- Extensibility
3.- What are different types of web services?
- SOAP
- Restful web services
4.- What is SOAP?
SOAP stands for Simple access protocol. It is protocol to exchange information using request and response in XML format over transport protocol such as HTTP, SMTP etc.
5.- What are important componets for SOAP?
- SOAP Simple Object Access Protocol
- WSDL Web Services Description Language
- UDDI  Universal Description, Discovery and Integration
6.- What is WSDL?
-          Port/ Endpoint – URL of the web service
-          Input message format
-          Output message format
-          Security protocol that needs to be followed
-          Which protocol the web service uses.
7.- What is UDDI?
UDDI stands for Universal Description, Discovery and Integration. It is a directory service. Web service provider can register themselves with a UDDI and make themselves available through it for discovery.
8.- What is JAX-WS?
JAX-WS stands for  Java API for XML Web Services. JAX-WS is standard XML based java API which is used to create SOAP web services.
9.- What are some important annotations for JAX-WS?
- @WebService
       - @WebMethod
      - @SOAPBinding

10.- What do you mean by end point in terms of SOAP?
End point is nothing but URL which other application can use to access it.
For example:
11.- How can you access WSDL for web service?
You just need to put ?wsdl at the end of the endpoint URL.
For example:
End point:http://localhost:8080/WS/HelloWorld
12.- What is wsimport?
wsimport is utility which generates java classes from WSDL. It is part of JDK 6.
13.- What is sun-jaxws.xml file?
This file provides endpoint details about JAX-WS web service which is deployed on tomcat. It is available at WEB-INF directory.
For example:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <endpoints xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime" version="2.0">  
  3.   <endpoint  
  4.      name="HelloWorldWS"  
  5.      implementation="org.arpit.javapostsforlearning.webservice.HelloWorldImpl"  
  6.      url-pattern="/HelloWorldWS"/>  
  7. </endpoints>   

14.- What are Restful web services?
In the web services terms, REpresentational State Transfer (REST) is a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. Web services client uses that URI to access the resource.
15.-  What are HTTP methods that can be used with Restful web services?
Mainly used HTTP methods are GET, POST, PUT, DELETE, HEAD and OPTIONS
16.- What is JAX-RS?
Java API for RESTful Web Services (JAX-RS), is a set of APIs to develop RESP service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.
17.- What are some important annotations which you use to create Restful web services?
Some important annotations which are used for creating web services are:
@Path : This is used to set path for URI at class level or method level
@GET, @POST, @PUT, @DELETE  There are annotations corresponds to HTTP methods
@Produces(MediaType.TEXT_XML [,more-types ]):  @Produces defines which MIME type is delivered by a method.
@PathParam  Used to inject values from the URL into a method parameter.
@Consumes(MediaType.TEXT_XML) : @Consumed defines which MIME type will be consumed by the method.
18.- What are ways to test SOAP web services?
For testing SOAP:
SOAPUI
For testing Restful web services:
-          Postman for chrome browser
-          Poster for firefox
19.- How to choose between REST and SOAP web services?
- If you want to implement web services in less time, go with REST
- If you know your client beforehand, then you can choose SOAP. If you are not aware about clients then go with REST.
20.- What are differences between SOAP and REST web services.
Parameter
SOAP
REST
Acronym
SOAP stands for simple object access protocol
REST stands for REpresentational State Transfer
Protocol vs Architectural style
SOAP is a standard protocol to create web services
Rest is architectural style to create web services.
Contract
Client and Server are bind with WSDL contract
There is no contract between client and Server.
Format Support
SOAP supports only XML format
REST web services supports XML, json and plain text etc.
Maintainability
SOAP web services are hard to maintain as if we do any changes in WSDL , we need to create client stub again
REST web services are generally easy to maintain.
Service interfaces vs URI
SOAP uses Service interfaces to expose business logic
Rest uses URI to expose business logic
Security
SOAP has its own security : WS-security
Rest inherits its security from underlying transport layer.
Bandwidth

SOAP requires more bandwidth and resources as it uses XML messages to exchange information
REST requires less bandwith and resources. It can use JSON also.
Learning curve
SOAP web services are hard to learn as you need to understand WSDL , client stub
REST web services are easy to understand as you need to annotate plain java class with JAX-RS annotations to use various HTTP methods.

SOAP web service tutorial
Simple Object Access Protocol (SOAP) is a standard protocol specification for message exchange based on XML.  Communication between the web service and client happens using XML messages.
A simple web service architecture have two components
-          Client
-          Service Provider

                                                           Internet    function1 and function2 are Available over internet



Client                                                Service Provider  { function1()
                                                                                            Function2()
                                                                                          }

So in above diagram, how client will communicate to service provider. So in order to communicate, client must know some information for e.g.

- Location of web services
- Functions available, signature and return types of function.
- Communication protocol
- Input Output formats

Service provider will create a standard XML file which will have all above information. So if this file is given to client, then client will be able to access web service. This XML file is called WSDL.

What is WSDL?

WSDL stand for Web Service Description Language. It is an XML file that describes the technical details of how to implement a web service, more specifically the URI, port, method names, arguments, and data types. Since WSDL is XML, it is both human-readable and machine-consumable, which aids in the ability to call and bind to service dynamically. Using  this WSDL file we can understand thinks like,

-          Port/ Endpoint – URL of the web service
-          Input message format
-          Output message format
-          Security protocol that needs to be followed
-          Which protocol the web service uses.
Ways to access web service:
-          If Service provider knows client: if service provider knows its client then it will provide its wsdl to client and client will be able to access web service.
                                                           Internet    function1 and function2 are Available over internet



Client  ---   Using WSDL client      ---à                           Service Provider  { function1()
                    Access web service                                                                          function2()
                                                                                                                            }
            ß        Service provider give WSDL to client   --

-          Service Provider register its WSDL to UDDI and client can access it from UDDI: Universal Description, Discovery and Integration. It is a Directory service. Web services can register with a UDDI and make themselves available through it for discovery. So following steps are involved.
 1.- Service provider register with UDDI.
 2.- Client searches for service in UDDI.
 3.- UDDI returns all service providers offering that service.
 4.- Client chooses service provider
 5.- UDDI returns WSDL of chosen service provider.
 6.- Using WSDL of service provider, client accesses web services.

                                                           Internet    function1 and function2 are Available over internet



Client  ---   6      ---à                           Service Provider  { function1()
                                                                                             function2()
                      2 à                                                                                                          }
                      ß   3                             UDDI    ß 1   --
                             4 à
                    ß    5

RESTful web service introduction
REST is an architectural style which was brought in by Roy Fielding in 2000 in his doctoral thesis.
In the web services terms, REpresentational State Transfer (REST) is  a stateless client-server architecture in which the web services are viewed as resources and can be identified by their URIs. (Uniform Resource Identifier) Web service clients that want to use these resources access via globally defined set of remote methods that describe the action to be performed on the resource.
It consists of two components
REST server which provides access to the resources and a
REST client which accesses and modify the REST resources.
In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol. REST isn't protocol specific, but when people talk about REST they usually mean REST over HTTP.
The response from server is considered as the representation of the resources. This representation can be generated from one resource or more number of resources.

      Client              à Request a resource using URI  à                          Resource
                            ß Response= representation of Resource ß          RESTful web service server
                                 (XML, JSON, plain text, png, etc)
REST allows that resources have different representations, e.g.xml, json etc. The rest client can ask for specific representation via the HTTP protocol.

HTTP methods:
RESTful web services use HTTP protocol methods for the operations they perform.Methods are:
GET: It defines a reading access of the resource without side-effects.This operation is idempotent i.e.they can be applied multiple times without changing the result
PUT: It is generally used for updating resouce.It must also be idempotent.
DELETE: It removes the resources. The operations are idempotent i.e. they can get repeated without leading to different results.
POST: It is used for creating a new resource. It is not idempotent.
Idempotent: means result of multiple successful request will not change state of resource after initial application
For example : 
Delete is idempotent method because when you first time use delete, it will delete the resource (initial application) but after that, all other request will have no result because resource is already deleted.

Post is not idempotent method because when you use post to create resource , it will keep creating resource for each new request, so result of multiple successful request will not be same.

Features of RESTful web services:
Resource identification through URI: Resources are identified by their URIs (typically links on internet). So, a client can directly access a RESTful Web Services using the URIs of the resources (same as you put a website address in the browser’s address bar and get some representation as response).
Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE.
Client-Server: A clear separation concerns is the reason behind this constraint. Separating concerns between the Client and Server helps improve portability in the Client and Scalability of the server components.
Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Named resources - the system is comprised of resources which are named using a URL.
Interconnceted resource representations – the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.

Layered components –  intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.
Self-descriptive messages : Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others.

SOAP web service example in java using eclipse
In this post,we will create hello world SOAP web service example in eclipse.Eclipse provides good API for creating web services.Eclipse will do all work for you-creating WSDL,stub,endpoints etc.
Steps for creating web services in eclipse:

1.Create new dynamic web project and name it "SimpleSOAPExample".

 2.Create new package named "org.arpit.javapostsforlearning.webservices"
3.Create a simple java class named "HelloWorld.java"

package org.arpit.javapostsforlearning.webservices;

public class HelloWorld {

    public String sayHelloWorld(String name)
    {
        return "Hello world from "+ name;
    }
}

4.Right click on project->new->web service


 5.Click on next.

In service implementation text box,write fully qualified class name of above created class(HelloWorld.java) and move both above slider to maximum level (i.e. Test service and Test Client level) and click on finish.You are done!!A new project named "SimpleSOAPExampleClient" will be created in your work space.


6.
Click on start server.
7.After clicking start server,eclipse will open test web service API.With this test API,you can test your web service.


You are done!!.But to understand more about web services,you need to explore more.You can explore above created "SimpleSOAPExampleClient" and learn more about web services.

Source code :

click to begin
6.2 MB .zip
In next post,you will see JAXWS web service example.
Problems:

Solución:
  Se desintala Postgres y todos sus components, ya que su instalación incluye componentes como servicios web mismos que ocupan lo puertos.
  En otra prueba se deshace el proyecto y se rehace, pero no se puede arrancar el Tomcat v5.0 nuevamente, con el mensaje de Several ports (8005…. , se resetea la maquina y se soluciona el problema.

SOAP Web Service – Writing a Web Service Client Stub generation using eclipse
1.- Create a Java Project
And a new class IPLocationFinder, in a new packages named org.beto.test
Now we open a command windows to create data stub from WSDL URI, this with the tool wsimport
C:\Users\Bext>wsimport
Missing WSDL_URI
Usage: wsimport [options] <WSDL_URI>
where [options] include:
  -b <path>                 specify jaxws/jaxb binding files or additional schemas
                            (Each <path> must have its own -b)
  -B<jaxbOption>            Pass this option to JAXB schema compiler
  -catalog <file>           specify catalog file to resolve external entity refe
rences
                            supports TR9401, XCatalog, and OASIS XML Catalog for
mat.
  -d <directory>            specify where to place generated output files
  -extension                allow vendor extensions - functionality not specifie
d
                            by the specification.  Use of extensions may
                            result in applications that are not portable or
                            may not interoperate with other implementations
  -help                     display help
  -httpproxy:<host>:<port>  specify a HTTP proxy server (port defaults to 8080)
  -keep                     keep generated files
  -p <pkg>                  specifies the target package
  -quiet                    suppress wsimport output
  -s <directory>            specify where to place generated source files
  -target <version>         generate code as per the given JAXWS spec version
                            Defaults to 2.2, Accepted values are 2.0, 2.1 and 2.
2
                            e.g. 2.0 will generate compliant code for JAXWS 2.0
spec
  -verbose                  output messages about what the compiler is doing
  -version                  print version information
  -wsdllocation <location>  @WebServiceClient.wsdlLocation value
  -clientjar <jarfile>      Creates the jar file of the generated artifacts alon
g with the
                            WSDL metadata required for invoking the web service.


Extensions:
  -XadditionalHeaders              map headers not bound to request or response
message to
                                   Java method parameters
  -Xauthfile                       file to carry authorization information in the format
                                   http://username:password@example.org/stock?ws
dl
  -Xdebug                          print debug information
  -Xno-addressing-databinding      enable binding of W3C EndpointReferenceType t
o Java
  -Xnocompile                      do not compile generated Java files
  -XdisableSSLHostnameVerification disable the SSL Hostname verification while f
etching
                                   wsdls

Examples:
  wsimport stock.wsdl -b stock.xml -b stock.xjb
  wsimport -d generated http://example.org/stock?wsdl
We use this tool in order to create code from the WSDL
Create a temp subdirectory to work on it
C:\Users\Bext\temp>wsimport http://www.webservicex.net/geoipservice.asmx?WSDL
parsing WSDL...


[WARNING] Ignoring SOAP port "GeoIPServiceSoap12": it uses non-standard SOAP 1.2
 binding.
You must specify the "-extension" option to use this binding.
  line 197 of http://www.webservicex.net/geoipservice.asmx?WSDL

[WARNING] ignoring port "GeoIPServiceHttpGet": no SOAP address specified. try ru
nning wsimport with -extension switch.
  line 200 of http://www.webservicex.net/geoipservice.asmx?WSDL

[WARNING] ignoring port "GeoIPServiceHttpPost": no SOAP address specified. try r
unning wsimport with -extension switch.
  line 203 of http://www.webservicex.net/geoipservice.asmx?WSDL


Generating code...
Compiling code...
C:\Users\Bext\temp>
The created is
C:\Users\Bext\temp>dir net\webservicex
 Volume in drive C has no label.
 Volume Serial Number is 5447-354C

 Directory of C:\Users\Bext\temp\net\webservicex

11/19/2016  07:18 PM    <DIR>          .
11/19/2016  07:18 PM    <DIR>          ..
11/19/2016  07:18 PM             1,497 GeoIP.class
11/19/2016  07:18 PM             2,312 GeoIPService.class
11/19/2016  07:18 PM             1,233 GeoIPServiceSoap.class
11/19/2016  07:18 PM               790 GetGeoIP.class
11/19/2016  07:18 PM               502 GetGeoIPContext.class
11/19/2016  07:18 PM               898 GetGeoIPContextResponse.class
11/19/2016  07:18 PM               849 GetGeoIPResponse.class
11/19/2016  07:18 PM             1,706 ObjectFactory.class
11/19/2016  07:18 PM               328 package-info.class
               9 File(s)         10,115 bytes
               2 Dir(s)  43,624,034,304 bytes free
C:\Users\Bext\temp>
This is the basic response with any parameters, that create class files. But we want to create java files in a directory called src, so we create the src directory and apply the command wsimport with the following parameters
C:\Users\Bext\temp>wsimport -keep -s src http://www.webservicex.net/geoipservice.asmx?WSDL
parsing WSDL...
[WARNING] Ignoring SOAP port "GeoIPServiceSoap12": it uses non-standard SOAP 1.2 binding.
You must specify the "-extension" option to use this binding.
  line 197 of http://www.webservicex.net/geoipservice.asmx?WSDL

[WARNING] ignoring port "GeoIPServiceHttpGet": no SOAP address specified. try running wsimport with -extension switch.
  line 200 of http://www.webservicex.net/geoipservice.asmx?WSDL

[WARNING] ignoring port "GeoIPServiceHttpPost": no SOAP address specified. try running wsimport with -extension switch.
  line 203 of http://www.webservicex.net/geoipservice.asmx?WSDL
Generating code...
Compiling code...
C:\Users\Bext\temp>
Now, We import this files to our project. If we see a java file, this files are in package net.webservicex; so we create a package in our project with this name and copy-paste the java files creates by wsimport.


And complete IPLocationFinder.java

package org.beto.test;

import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;

public class IPLocationFinder {

       public static void main(String[] args) {
             if(args.length != 1){
                    System.out.println("Necesitas pasar una Ip Address");
             }
             else{
                    String ipAddress = args[0];
                    GeoIPService ipService = new GeoIPService();
                    GeoIPServiceSoap geoIPServiceSoap = ipService.getGeoIPServiceSoap();
                    GeoIP geoIp = geoIPServiceSoap.getGeoIP(ipAddress);
                   
                    System.out.println(geoIp.getCountryName());
             }

       }

}

Run the IPLocationFinder with parameter with a IP address which we can recover the country location.


Building SOAP Web Service in Java Using Eclipse.mp4
Inicialmente se instala java 1.8 y se instala eclipse j2ee neon, este se descarga adaptado para java 1.8, si posteriormente se desinstala de la maquina el java 1.8 y se instala java 1.7, el eclipse no corre, avisando que no esta adaptado para java 1.7,  ya que se bajo para java 1.8. con el java 1.8 el axis2-1.7.3 funciono bien.
Se require instalar axis2 para eclipse: Para ello se baja el archivo axis2-1.7.3-war.zip y se descomprime en la instalación de eclipse subdirectorio /dropins/axis2-1.7.3, también se descomprime axis2-1.7.3-bin.zip
Con java 1.7 instalado. Se instala Eclipse j2ee neon y este se adapta a este java1.7 descargando en línea el eclipse j2ee neon correspondiente. Se intenta con esta instalación el axis2-1.7.3 y no funciona, se instala entonces /dropins/axis2-1.6.2-bin
-          New Dynamic Web Project
ProjectName: DemoWebService_Server
ApacheTomcat v7.0
Version 2.5
Axis2 web services
-          New java package named controller
-            En rama WebContent – axis2-web
-          New java class named Demo
-          New Web Service de Demo
-          Configuration
-                   Server  runtime Tomcat v7.0 Server
-              Service Deployment Configuration –
-                   Web Service runtime  - Apache Axis2
-                        [next]  -> [Start server]
-          [X] Close window
-          Server -> Tomcat v7.0 Server at localhost [click][click]
-          [Stop] server
-          New Web Service
-          Browse Classes Demo select Demo – controller
-          Configuration:
-             Server  runtime Tomcat v7.0 Server
-              Service Deployment Configuration –
-                   Web Service runtime  - Apache Axis2
-                   [next]  -> [Start server]
-          [X] Close window
-          En rama DemoWebService_Server
-          Run as con [>]
-          Se abre window Run on Server
-          Seleccionar Always use this server when running this project
-          [next]
-          Add and Remove  - se remueve  WebService_Server
-          [X] close window
-          Abrir Browser en direccion localhost:8080/DemoWebService_Server
-          Click on Services
-          Click on Demo
-          Copy usr del browser
-          Parar a eclipse -> run -> Launch de Web Services Explorer
-          Se abrio  browser con wsexplorer
-          Seleccionar WSDL Main con icono superior WSDL page
-          Open WSDL
-          [go]
-          DemoSoap11Binding
-          Hello
-          [go]
-          Y en recuadro Status aparece la respuesta  helloResponse  return (string): Hello World
-          Click on source para ver SOAP Response Envelope
-          Ahora se prueban los parametros del metodo sum
-          Selecciona de la rama sum
-          Body sum a se asigna valor 1 y en b add 2
-          [go]
-          Se verifica en status -> source/form
-          Se crea un New Dynamic Web Project llamado DemoWebService_Client
-          Con Apache Tomcat V7.0, Dynamic Web Module versión 2.5, Project Facet Axis2 Web Service
-          En Sus Java Resources se crean dos Packages llamados “controller” y “ws”
-          En package controller se crea un nuevo servlet llamado DemoController
-          En el package ws se crea un nuevo web service client, con service definition http://localhost:8080/DemoWebService_Server/services/Demo?wsdl la cual se puede obtener corriendo el DemoWebService_Server el cual nos abrirá la pagina http://localhost:8080/DemoWebService_Server/ de la cual seleccionamos Services -> Demo y de Demo copiamos la URL
-          Creando el Web Service Client se le configurara Apache Tomcat V7.0, Axis2, En Axis2 Client Web Service Configuration Service Name: Demo, Port Name: DemoHttpEndpoint, Databinding ADB, Custom package name ws, despues de [finish] se crearán dos clases bajo el package ws, llamadas DemoCallbackHandler.java, DemoStub.java
-          De forma similar se crea otro web service client, en package ws, ahora partiendo de ProductWS, con serivice definition http://localhost:8080/DemoWebService_Server/services/ProductWS?wsdl, … Service Name: ProductWS, Port Name: ProductWSHttpSoap11Endpoint, Databinding ADB, Custom package name ws, despues de [finish] se crearán dos clases bajo el package ws, llamadas ProductWSCallbackHandler.java,ProductWSStub.java
-          Se hacen pruebas con PortName HttpEndpoint, HttpSoap11Endpoint, HttpSoap12Endpoint y para este ejemplo su funciona.
-          En la rama del DemoWebService_Client - WebContent, se crea un nuevo jsp llamado index.jsp al cual se le agregara el siguiente código
<title>Demo SOAP Web Service</title>
</head>
<body>
  <a href="DemoController">Demo Web Service</a>
-          </body>
En DemoController.java se modificará/agregará con el siguiente código
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ws.*;
import ws.DemoStub.*;
import ws.ProductWSStub.*;

       /**
        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
        */
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             // TODO Auto-generated method stub
             //response.getWriter().append("Served at: ").append(request.getContextPath());
             PrintWriter out = response.getWriter();
             response.setContentType("text/html");
             try {
                    DemoStub ds = new DemoStub();
                    ProductWSStub ps = new ProductWSStub();
                    //Call Hello Web Service
                    out.print(ds.hello(new Hello()).get_return());
                    //Call Sum Web Service
                    Sum s = new Sum();
                    s.setA(1);
                    s.setB(2);
                    out.print("<br>Sum: " + ds.sum(s).get_return());
                    //Call Find Web Service
                    Product p = ps.find(new Find()).get_return();
                    Find f = new Find();
                    out.print("<h3>Product Information</h3>");
                    out.print("<br>Id: " + p.getId());
                    out.print("<br>Name: " + p.getName());
                    out.print("<br>Price: " + p.getPrice());
                    out.print("<h3>List Product Information</h3>");
                    for ( Product pr : ps.findAll(new FindAll()).get_return()){
                           out.print("<br>Id: " + pr.getId());
                           out.print("<br>Name: " + pr.getName());
                           out.print("<br>Price: " + pr.getPrice());
                           out.print("<br>================");
                    }
             } catch (Exception e){
                    out.print(e.getMessage());
             }
       }

Al correr el cliente http://localhost:8080/DemoWebService_Client/ nos mostrará un link
Demo_Web_Service la hacer [click] nos muestra la siguiente página
Hello World, I am Beto
Sum: 3

Product Information


Id: p1
Name: Name 1
Price: 1000.0

List Product Information


Id: p1
Name: Name 1
Price: 1000.0
================
Id: p2
Name: Name 2
Price: 2000.0
================
Id: p3
Name: Name 3
Price: 3000.0
================



JAX-WS web service eclipse tutorial

Prerequisites:

  1. JDK 1.6
  2. Eclipse IDE
Steps  for creating JAX-WS webservice endpoint
1)      Open Eclipse IDE
2)      Create New java project named “JAXWSServer

3)      Create New package named “org.arpit.javapostforlearning.webservices”

4)      Create JAXWSService Endpoint Interface

HelloWorld.java

package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface HelloWorld {

 @WebMethod public String helloWorld(String name);
}

5)      Create JAXWSService Endpoint Implementation class.

HelloWorldImpl.java

package org.arpit.javapostsforlearning.webservice;
import javax.jws.WebService;

@WebService(endpointInterface="org.arpit.javapostsforlearning.webservice.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

 public String helloWorld(String name) {
  return "Hello world from "+name;
 }

}

6)      Create Endpoint publisher.

HelloWorldWSPublisher.java

HelloWorldWSPublisher.java

package org.arpit.javapostsforlearning.webservice;
import javax.xml.ws.Endpoint;

public class HelloWorldWSPublisher {
 public static void main(String[] args) {
  Endpoint.publish("http://localhost:8080/WS/HelloWorld",new HelloWorldImpl());
 }
}

Run above program. Your webservice is published. You can check your service wsdl at http://localhost:8080/WS/HelloWorld?wsdl

Steps for creating JAXWS Client


1)      Open eclipse and create new java project JAXWSClient


2)      Now we need to  genereate the client stubs. So open your command line, and enter the wsimport commant:

cd %project_home%/src
wsimport -s . http://localhost:8080/WS/HelloWorld?wsdl


                 you will find java classes generated and compiled under src->org->arpit->javapostsforlearning->webservices

3)      Lets create client class now
Create JAXWSClient.java under src->org.arpit.javapostsforlearning.webservices.client

package org.arpit.javapostsforlearning.webservice.client;
import org.arpit.javapostsforlearning.webservice.HelloWorld;
import org.arpit.javapostsforlearning.webservice.HelloWorldImplService;
 
public class JAXWSClient {
 
    /**
     * @author Arpit Mandliya
     */
    public static void main(String[] args) {
        
        HelloWorldImplService helloWorldService = new HelloWorldImplService();
        HelloWorld helloWorld = helloWorldService.getHelloWorldImplPort();
        System.out.println(helloWorld.helloWorld("Arpit"));
    }
}


4)      Run above program and you will get following output.

     Hello world from Arpit

    Congratulation, you have successfully created web service endpoint and client. Now in next post, we will deploy on Tomcat.

Ajustes:
  Para este ejercicio se tubo que reinstalar eclipse con java 1.7 en Sistema instalado.
Al usar el wsimport inicialmente causaba conflicto con java 1.8, y si generaba los archivos java, tenia problemas de compilación. Al proyecto se le ajusto Window -> Preferences -> java -> compiler -> JDK compliance a 1.7

JAX-WS webservice deployment on Tomcat

In previous post, we have seen how to develop JAX-WS web service endpoint and client. In this post, we will see how we can deploy web service endpoint to application server.
wsgen -s src -d build/classes -cp build/classes org.arpit.javapostsforlearning.webservice.HelloWorldImpl" then enter */
cd %project_home%

C:\Users\Bext\workspace\HelloWorldWS>wsgen -s src -d build/classes -cp build/cla
sses org.arpit.javapostsforlearning.webservice.HelloWorldImpl

warning: The apt tool and its associated API are planned to be
removed in the next major JDK release.  These features have been
superseded by javac and the standardized annotation processing API,
javax.annotation.processing and javax.lang.model.  Users are
recommended to migrate to the annotation processing features of
javac; see the javac man page for more information.

C:\Users\Bext\workspace\HelloWorldWS>

Ejecucion del servidor visto desde el browser:

Web Services

Port Name
Status
Information
HelloWorldWS
ACTIVE
Address:
http://localhost:8080/HelloWorldWS/HelloWorldWS
WSDL:
Port QName:
{http://webservice.javapostsforlearning.arpit.org/}HelloWorldImplPort
Implementation class:
org.arpit.javapostsforlearning.webservice.HelloWorldImpl

Create RESTful web services in java(JAX-RS) using jersey

In this post, we will develop RESTful web service using jersey in eclipse

Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

Jersey is the reference implementation for this specification. Jersey contains basically a REST server and a REST client. The core client can communicate with the server using jersey lib.

On the server side Jersey uses a servlet which scans predefined classes to identify RESTful resources. Via the web.xml configuration file for your web application.

The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 
This servlet analyzes the incoming HTTP request and selects the correct class and method depending on  request. This selection is based on annotations provided in the class and methods. 

Prerequisites:


1) Open eclipse.
2) Create new dynamic web project named "RESTfulWebServiceExample"


3) Now go to location where you have download jersey and go to jersey-archive-1.17->lib (En este caso se descarga jersey 2.24 jaxrs-ri-2.24)
folder.you can have all jars but for now you can copy following jars


Add all these jars to eclipse build path.
Right click on project(RESTfulWebServiceExample)->properties


4) Create new package named "org.arpit.javapostsforlearning.webservice"
5)Create  FeetToInchAndInchToFeetConversionService.java

  1. package org.arpit.javapostsforlearning.webservices;  
  2. /** 
  3. * @author Arpit Mandliya 
  4. */  
  5.    
  6. import javax.ws.rs.GET;  
  7. import javax.ws.rs.Path;  
  8. import javax.ws.rs.PathParam;  
  9. import javax.ws.rs.Produces;  
  10. import javax.ws.rs.core.MediaType;  
  11.    
  12. @Path("ConversionService")  
  13. public class FeetToInchAndInchToFeetConversionService {  
  14.      @GET  
  15.      @Path("/InchToFeet/{i}")  
  16.       @Produces(MediaType.TEXT_XML)  
  17.       public String convertInchToFeet(@PathParam("i") int i) {  
  18.    
  19.         int inch=i;  
  20.         double feet = 0;  
  21.         feet =(double) inch/12;  
  22.         
  23.         return "<InchToFeetService>"  
  24.         + "<Inch>" + inch + "</Inch>"  
  25.           + "<Feet>" + feet + "</Feet>"  
  26.          + "</InchToFeetService>";  
  27.       }  
  28.    
  29.       @Path("/FeetToInch/{f}")  
  30.       @GET  
  31.       @Produces(MediaType.TEXT_XML)  
  32.       public String convertFeetToInch(@PathParam("f") int f) {  
  33.        int inch=0;  
  34.           int feet = f;  
  35.           inch = 12*feet;  
  36.      
  37.           return "<FeetToInchService>"  
  38.             + "<Feet>" + feet + "</Feet>"  
  39.             + "<Inch>" + inch + "</Inch>"  
  40.             + "</FeetToInchService>";  
  41.       }  
  42. }  

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.

@Path(/your_path_at_method_level): Sets path to base URL + /your_path_at_class_level+ /your_path_at_method_level

@Produces(MediaType.TEXT_XML [, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/XML") is produced.

@PathParam: Used to inject values from the URL into a method parameter.This way you inject inch in convertFeetToInch method and convert that to feet.
6)Now you need to create web.xml and put it under /RESTfulWebserviceExample/WebContent/WEB-INF/

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>RESTfulWebServiceExample</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>jersey.config.server.provider.packages</param-name>
      <param-value>org.arpit.javapostsforlearning.webservices</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>

In above <param-value>,put your web service package.
8) Run project:right click on project->run as ->run on server
9) Test your REST service under: "http://localhost:8080/RESTfulWebServiceExample/rest/ConversionService/FeetToInch/2". 

Creating a Restful Web Service Client:
Create ConversionServiceClient.java under org.arpit.javapostsforlearning.websevices.client

Este es el código original con jersey 1 y algo, pero no me funcionó. Así que se rehace el código pero con jersey 2.24
  1. package org.arpit.javapostsforlearning.webservices.client;  
  2.   
  3. import javax.ws.rs.core.MediaType;  
  4. import com.sun.jersey.api.client.Client;  
  5. import com.sun.jersey.api.client.ClientResponse;  
  6. import com.sun.jersey.api.client.WebResource;  
  7. import com.sun.jersey.api.client.config.ClientConfig;  
  8. import com.sun.jersey.api.client.config.DefaultClientConfig;  
  9.   
  10. public class ConversionServiceClient {  
  11.  static final String REST_URI = "http://localhost:8080/RESTfulWebServiceExample";  
  12.  static final String INCH_TO_FEET = "/ConversionService/InchToFeet/";  
  13.  static final String FEET_TO_INCH = "/ConversionService/FeetToInch/";  
  14.   
  15.  public static void main(String[] args) {  
  16.   
  17.  int inch=12;  
  18.  int feet=2;  
  19.   
  20.  ClientConfig config = new DefaultClientConfig();  
  21.  Client client = Client.create(config);  
  22.  WebResource service = client.resource(REST_URI);  
  23.   
  24.  WebResource addService = service.path("rest").path(INCH_TO_FEET+inch);  
  25.  System.out.println("INCH_TO_FEET Response: " + getResponse(addService));  
  26.  System.out.println("INCH_TO_FEET Output as XML: " + getOutputAsXML(addService));  
  27.  System.out.println("---------------------------------------------------");  
  28.   
  29.  WebResource subService = service.path("rest").path(FEET_TO_INCH+feet);  
  30.  System.out.println("FEET_TO_INCH Response: " + getResponse(subService));  
  31.  System.out.println("FEET_TO_INCH Output as XML: " + getOutputAsXML(subService));  
  32.  System.out.println("---------------------------------------------------");  
  33.   
  34.  }  
  35.   
  36.  private static String getResponse(WebResource service) {  
  37.  return service.accept(MediaType.TEXT_XML).get(ClientResponse.class).toString();  
  38.  }  
  39.   
  40.  private static String getOutputAsXML(WebResource service) {  
  41.  return service.accept(MediaType.TEXT_XML).get(String.class);  
  42.  }  
  43. }  
Este es el código modificado con jersey 2.24

package org.arpit.javapostsforlearning.webservices.client;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientResponse;
import org.glassfish.jersey.filter.LoggingFilter;    

public class ConversionServiceClient {
static final String REST_URI = "http://localhost:8080/RESTfulWebServiceExample";
static final String INCH_TO_FEET = "/ConversionService/InchToFeet/";
static final String FEET_TO_INCH = "/ConversionService/FeetToInch/";

       public static void main(String[] args) {
            
             int inch = 15;
             int feet = 2;
             // TODO Auto-generated method stub
        Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFilter.class));
        WebTarget webTarget = client.target(REST_URI).path("rest").path(INCH_TO_FEET+inch);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_XML);
        Response response = invocationBuilder.get();

        System.out.println(response.getStatus());
        System.out.println(response.readEntity(String.class));
       }
}

Y el resultado de correr este código ConversionServiceClient.java es

1 < Content-Length: 71
1 < Content-Type: text/xml
1 < Date: Wed, 02 Nov 2016 00:51:01 GMT
1 < Server: Apache-Coyote/1.1

200
<InchToFeetService><Inch>15</Inch><Feet>1.25</Feet></InchToFeetService>

Para hacer la conversion de código se hace uso de estas referencias

https://jersey.java.net/apidocs/latest/jersey/index.html
https://jersey.java.net/documentation/latest/client.html

Version alterna de RESTful web service


RESTful Web Services - First Application

Let us start writing actual RESTful web services with Jersey Framework. Before you start writing your first example using Jersey framework, you have to make sure that you have setup your Jersey environment properly as explained in RESTful Web Services - Environment Setup tutorial. I also assume that you have a little bit working knowledge with Eclipse IDE.
So let us proceed to write a simple Jersey Application which will expose a web service method to display list of users.

Step 1 - Create Java Project:

The first step is to create a Dynamic Web Project using Eclipse IDE. Follow the option File -> New -> Project and finally select Dynamic Web Project wizard from the wizard list. Now name your project as UserManagement using the wizard window as follows:


Once your project is created successfully, you will have following content in your Project Explorer:

Step 2 - Add Required Libraries:

As a second step let us add Jersey Framework and its dependencies (libraries) in our project. Copy all jars from following directories of download jersey zip folder in WEB-INF/lib directory of the project.
·         \jaxrs-ri-2.17\jaxrs-ri\api
·         \jaxrs-ri-2.17\jaxrs-ri\ext
·         \jaxrs-ri-2.17\jaxrs-ri\lib
Now, right click on your project name UserManagement and then follow the following option available in context menu: Build Path -> Configure Build Path to display the Java Build Path window.
Now use Add JARs button available under Libraries tab to add the JARs present in WEB-INF/lib directory.


Nota de instalacion:
Se descargan las ultimas librerias de jersey, jaxrs-ri-2.24

Genera jaxrs-ri\api
jaxrs-ri\ext
jaxrs-ri\lib

Se Copian todos los jars que estan debajo de estos subdirectorios a WEB-INF/lib

Se actualiza UserManagement->Build Path -> Configure Build Path y Add Jars
Si no se configuran bien las librerias jars, manda el error en browser
HTTP Status 500 - Error instantiating servlet class org.glassfish.jersey.servlet.ServletContainer

Step 3 - Create Source Files:

Now let us create actual source files under the UserManagement project. First we need to create a package called com.tutorialspoint. To do this, right click on src in package explorer section and follow the option: New -> Package.
Next we will create UserService.java, User.java,UserDao.java files under the com.tutorialspoint package.
User.java
package com.tutorialspoint;
 
import java.io.Serializable;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User implements Serializable {
 
   private static final long serialVersionUID = 1L;
   private int id;
   private String name;
   private String profession;
 
   public User(){}
   
   public User(int id, String name, String profession){
      this.id = id;
      this.name = name;
      this.profession = profession;
   }
 
   public int getId() {
      return id;
   }
 
   @XmlElement
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   @XmlElement
   public void setName(String name) {
      this.name = name;
   }
   public String getProfession() {
      return profession;
   }
   @XmlElement
   public void setProfession(String profession) {
      this.profession = profession;
   }           
}
UserDao.java
package com.tutorialspoint;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
 
public class UserDao {
   public List<User> getAllUsers(){
      List<User> userList = null;
      try {
         File file = new File("Users.dat");
         if (!file.exists()) {
            User user = new User(1, "Mahesh", "Teacher");
            userList = new ArrayList<User>();
            userList.add(user);
            saveUserList(userList);           
         }
         else{
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            userList = (List<User>) ois.readObject();
            ois.close();
         }
      } catch (IOException e) {
         e.printStackTrace();
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
      }        
      return userList;
   }
 
   private void saveUserList(List<User> userList){
      try {
         File file = new File("Users.dat");
         FileOutputStream fos;
 
         fos = new FileOutputStream(file);
 
         ObjectOutputStream oos = new ObjectOutputStream(fos);
         oos.writeObject(userList);
         oos.close();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }   
}
UserService.java
package com.tutorialspoint;
 
import java.util.List;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
 
@Path("/UserService")
public class UserService {
 
   UserDao userDao = new UserDao();
 
   @GET
   @Path("/users")
   @Produces(MediaType.APPLICATION_XML)
   public List<User> getUsers(){
      return userDao.getAllUsers();
   }    
}
There are following two important points to note about the main program, UserService.java:
1.      First step is to specify a path for the web service using @Path annotation to UserService.
2.      Second step is to specify a path for the particular web service method using @Path annotation to method of UserService.

Step 4 - Create Web.xml configuration File:

You need to create a Web xml Configuration file which is an XML file and is used to specify Jersey framework servlet for our application.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
   id="WebApp_ID" version="3.0">
   <display-name>User Management</display-name>
   <servlet>
      <servlet-name>Jersey RESTful Application</servlet-name>
      <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
         <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.tutorialspoint</param-value>
         </init-param>
      </servlet>
   <servlet-mapping>
   <servlet-name>Jersey RESTful Application</servlet-name>
      <url-pattern>/rest/*</url-pattern>
   </servlet-mapping>  
</web-app>

Step 5 - Deploying the Program

Once you are done with creating source and web configuration files, you are ready for this step which is compiling and running your program. To do this, using Eclipse, export your application as a war file and deploy the same in tomcat. To create WAR file using eclipse, follow the option File -> export -> Web > War File and finally select project UserManagement and destination folder. To deploy war file in Tomcat, place the UserManagement.war in Tomcat Installation Directory > webapps directory and start the Tomcat.

Step 6 - Running the Program

We are using Postman, a Chrome extension, to test our webservices.
Make a request to UserManagement to get list of all the users. Put http://localhost:8080/UserManagement/rest/UserService/users in POSTMAN with GET request and see the below result.
Congratulations, you have created your first RESTful Application successfully.

RESTful web services JAXRS json example using jersey

This post is in continuation with web service tutorial (Part -8).
In previous post, we have created a very simple Restful web services(JAXRS) using jersey which returns xml. In this post, we will see Restful web services(JAXRS) using jersey which will return json as response.
Here are steps to create a simple Restful web services(JAXRS)  using jersey which will return json.

1) Create a dynamic web project using maven in eclipse named "JAXRSJsonExample"
2) We need to add jersey jars utility in the classpath. 
<dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
 </dependency>
 <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
 </dependency>

Nota: En este punto hemos instalado jersey 2.24 que no es la version del ejercicio original, por lo que modificamos en pom.xml la dependency de jersey servlet, y el jersey-json, el cual se googlea jersey-json, y nos lleva al repositorio de maven https://mvnrepository.com y buscamos el artifactid, nos da la versión y lo adaptamos a la versión que existe.

    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet-core</artifactId>
      <version>${jersey.version}</version>
    </dependency>
    <dependency>
     <groupId>com.sun.jersey</groupId>
     <artifactId>jersey-json</artifactId>
     <version>1.18</version>
    </dependency>


Algunos comandos de maven (mvn) o maven build … que nos ayudaron a encontrar el error en este caso de dependencia no hallada, fue mvn –X dependency:tree o mvn –X build,
-X      debug option
clean install
effective:pom
help:effective-pom
dependency:source downloads de sources
help:effective-settings  shows the repository location
archetype:generate

Al hacer maven –X debug install, arroja el siguiente error

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.104 s
[INFO] Finished at: 2016-11-07T12:04:19-06:00
[INFO] Final Memory: 11M/222M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5:compile (default-compile) on project JAXRSJsonExample: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5:compile (default-compile) on project JAXRSJsonExample: Compilation failure
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

Se resuelve con este cambio en el archive pom.xml

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.5</version>
  <configuration>
    <source>1.7</source>
    <target>1.7</target>
    <fork>true</fork>
    <executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac.exe</executable>
  </configuration>
</plugin>


===================== entry point
package com.example;

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

/**
 * Root resource (exposed at "myresource" path)
 */
@Path("myresource")
public class MyResource {

    /**
     * Method handling HTTP GET requests. The returned object will be sent
     * to the client as "text/plain" media type.
     *
     * @return String that will be returned as a text/plain response.
     */
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getIt() {
        return "Got it!";
    }

    @Path( "complexObject/{name}" )
    @GET
    @Produces( { MediaType.APPLICATION_JSON } )
    public ComplexObject complexObject( @PathParam( "name" ) String name ) {
        return new ComplexObject(name, System.currentTimeMillis(), 42L);
    }
}
=======================

Jersey internally uses Jackson for Json Handling, so it will be used to marshal pojo objects to JSON.
Now create pom.xml as follows:
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.arpit.java2blog</groupId>
 <artifactId>JAXRSJsonExample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>JAXRSJsonExample Maven Webapp</name>
 <url>http://maven.apache.org</url>
   <properties>
        <jersey.version>1.18.3</jersey.version>
    </properties>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
 
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-servlet</artifactId>
   <version>${jersey.version}</version>
  </dependency>
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-json</artifactId>
   <version>${jersey.version}</version>
  </dependency>

  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.2</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>JAXRSJsonExample</finalName>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.3</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>


   </plugin>
  </plugins>
 </build>

</project>

Application configuration:

3) create web.xml as below:

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>       
        <init-param>
          <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>
 
 
RESTful web services JAXRS Json Jersey Maven ejemplo
 
Este ejemplo anterior después de lograr compilarlo no corrre por que hace referencia el código package com.example, class MyResourse, hace referencia a un ComplexObject que no se muestra en el ejemplo, Así que se rehace el ejemplo donde se integra el RESTful , Jersey, Maven y respuesta en Jason. Así que al proyecto se le pone el nombre RESTfullJerseyMavenJason.
http://stackoverflow.com/questions/4687271/jax-rs-how-to-return-json-and-http-status-code-together

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.jersey.jaxb</groupId>
  <artifactId>RESTfullJerseyMavenJson</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>RESTfullJerseyMavenJson Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
       <groupId>org.glassfish.jersey.containers</groupId>
       <artifactId>jersey-container-servlet-core</artifactId>
       <version>2.24</version>
    </dependency>
    <dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-json-provider</artifactId>
    <version>2.8.4</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.pojomatic/pojomatic -->
    <dependency>
      <groupId>org.pojomatic</groupId>
      <artifactId>pojomatic</artifactId>
    </dependency>
   
   
  </dependencies>
  <build>
    <finalName>RESTfullJerseyMavenJson</finalName>
       <plugins>
       <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-compiler-plugin</artifactId>
             <version>3.5</version>
             <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <fork>true</fork>
                <executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac.exe</executable>
             </configuration>
       </plugin>
       <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-war-plugin</artifactId>
             <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
             </configuration>
       </plugin>
    </plugins>
  </build>
  <dependencyManagement>
       <dependencies>
             <dependency>
                    <groupId>org.pojomatic</groupId>
                    <artifactId>pojomatic</artifactId>
                    <version>2.0.1</version>
             </dependency>
       </dependencies>
  </dependencyManagement>
</project>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>RESTfullJerseyMavenJson</display-name>
<servlet>
  <servlet-name>Jersey REST Service</servlet-name>
  <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
   <init-param>
     <param-name>jersey.config.server.provider.packages</param-name>
     <param-value>com.jersey.jaxb,
                  com.fasterxml.jackson.jaxrs.json</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>

Todo.java

package com.jersey.jaxb;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;

@XmlRootElement
@XmlType(name = "todo")
@XmlAccessorType(XmlAccessType.FIELD)
@AutoProperty
public class Todo {

       @XmlElement(name = "summary")
       private final String summary;
      
       @XmlElement(name = "description")
       private final String description;
      
       public String getSummary() {
             return summary;
       }
      
       public String getDescription() {
             return description;
       }
      
       public Todo() {
             this(new Builder());
       }
      
       public Todo(Builder builder) {
             this.summary = builder.summary;
             this.description = builder.description;
       }
      
       @Override
       public boolean equals(Object o) {
             return Pojomatic.equals(this,  o);
       }
      
       @Override
       public int hashCode() {
              return Pojomatic.hashCode(this);
       }
      
       @Override
       public String toString() {
             return Pojomatic.toString(this);
       }
      
       public static class Builder {
             private String summary;
             private String description;
            
             public Builder summary(String summary) {
                    this.summary = summary;
                    return this;
             }
            
             public Builder description(String description) {
                    this.description = description;
                    return this;
             }
            
             public Todo build() {
                    return new Todo(this);
             }
            
       }
      
}

TodoResource.java

package com.jersey.jaxb;

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



@Path("/todo")
public class TodoResource {

       @GET
       @Produces(MediaType.APPLICATION_JSON)
       public Response getTodo() {
         Todo todo = new Todo.Builder().description("Mi Objeto Todo").summary("Creado").build();
         return Response.status(Status.OK).entity(todo).build();
       }

}



Apendice

How to create dynamic web project using maven in eclipse

In this post, we will see how to create dynamic web project using maven in eclipse. If you can also create simple java maven project in eclipse.

I am using following tools for this post.
  • eclipse-jee-mars-R-macosx-cocoa-x86_64
  • Apache tomcat 8
  • m2eclipse plugin
  • jdk 1.7

Steps for creating dynamic web project using maven in eclipse.


1) Install m2eclipse for maven plugin in eclipse. Please follow this link for installing m2eclipse plugin in eclipse.

2) goto new -> project-> Maven Project and click on next

3) You will see below screen , again click on next

4) We need to select type of archetype here.As we are creating web app here, please put following text in filter : maven-archetype-webapp


5) We need to put group id and artifact id here.

Let me tell you more about group id and artifact id.

Group id : It uniquely identifies your project among all. So it may be something like com.companyname

Artifact id : It is name of jar or war without version. it may be something like project, so here we have put artifact id as mavenWebApp

Version : Version is used for version control for artifact id. If you distribute this project, you may incrementally create different version of it.

6) You project structure should look something like below image.
7) When I have followed above steps, I was getting below error.
"The superclass "javax.servlet.http.HttpServlet" was found in java build path".


You can resolve this error using two ways.

1) you can add following dependency to pom.xml
  1. <dependency>  
  2.  <groupid>javax.servlet</groupid>  
  3.  <artifactid>javax.servlet-api</artifactid>  
  4.  <version>3.1.0</version>  
  5. </dependency>  
2) you can set target run time as Apache tomcat .
right click on project -> properties -> target runtimes

8) It 's time to do maven build.
Right click on project -> Run as -> Maven build

9)  Provide goals as clean install (given below) and click on run



10) When you run maven build, you will see below screen
11) Deploy this application to tomcat server and run it.
If you don't have tomcat server configured in eclipse, follow these steps.
Right click on project -> run as -> run on server -> choose tomcat.

12)
When you run application, you will get following output:

Bingo !! we are done with creating dynamic web project using maven in eclipse.