addheader

Thursday, 9 July 2015

Restful Webservie with Angular js login applicaiton




  Restful Webservice with angular

    JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    HIBERNATE-ANNOTATIONS     SPRING-IOC       SPRING –AOP-SCHEMABASED   

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 



Project structure:



     Rest api service class:
-----------------------------------------------



@Path("user")
@Component
public class UserApiResource {
   
private  UserReadPlatformService userReadPlatformService;
private UserWriteplatformService userWriteplatformService;
private final UserRepository userRepository;
@Autowired
public UserApiResource( final UserReadPlatformService userReadPlatformService,final UserRepository userRepository,
        final UserWriteplatformService userWriteplatformService){
    this.userReadPlatformService=userReadPlatformService;
    this.userRepository =  userRepository;
    this.userWriteplatformService = userWriteplatformService;
}
@GET
@Path("list")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public List<User>  getUsersList(){
    List<User> users=this.userReadPlatformService.retrieveUserList();
    return users;
}

@GET
@Path("{id}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public User getUserDetails(@PathParam("id") long id) {
        User user = null;
        try {
            user = userReadPlatformService.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

@POST
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Status createUser(String json){
    System.out.println(json);
    Status status = this.userWriteplatformService.createUser(json);
    return status;
   
}


@PUT
@Path("changepassword/{id}")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public  Status changePassword(@PathParam("id") long id, String jsonData) {
    try {
       
        Status status = this.userWriteplatformService.changePassword(jsonData,id);
       
        return status;
    } catch (Exception e) {
        return new Status(0, e.toString());
    }
}

@POST
@Path("login")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Status login(String login) {
        try {
            JSONObject json = new  JSONObject(login);
            String username = json.getString("username");
            String password = json.getString("password");
            String loginType = json.getString("loginType");
            System.out.println(login);
            Status status = userReadPlatformService.authantication(new Login(username,password,loginType));
            System.err.println(status.getLogin().getEmail());
            return status;
        } catch (Exception e) {
            // e.printStackTrace();
            return new Status(0, e.toString());
        }

    }

}


Reposotory class:
-----------------------------


UserRepository  .java

public interface UserRepository  extends
JpaRepository<User, Long>,
JpaSpecificationExecutor<User>{

}

Entity class:
-------------------------------
User.java
-------------
@Entity
@Table(name = "users")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    @Column(name = "id")
    private long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;
   
    @Column(name = "username")
    private String username;
   
    @Column(name = "password")
    private String password;

}

Service class :

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

UserWriteplatformServiceImpl.java
------------------------------------------------

@Service
public class UserWriteplatformServiceImpl implements UserWriteplatformService{
   
    private final UserRepository  userRepository;
   
@Autowired
public UserWriteplatformServiceImpl(final UserRepository  userRepository){
    this.userRepository = userRepository;
   
}

public Status createUser(String json) {
try {
    JSONObject jsonObject = new JSONObject(json);
    final String firstName = jsonObject.getString("firstName");
    final String lastName = jsonObject.getString("lastName");
    final String username = jsonObject.getString("username");
    final String email = jsonObject.getString("email");
    final String phone = jsonObject.getString("phone");
   
    User user = new User(null,firstName, lastName, email, phone,StringConstants.STATUS_PENDING,username,"N");
    this.userRepository.save(user);
    //this.sendMail(StringConstants.ACTION_REGISTER,user);
    return new Status(1,"User Created Successfully..! Need to approve by Admin");
   
   
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return new Status(0,"User Creation Failed");
}catch (DataIntegrityViolationException e) {
    return new Status(0,"User name is already taken....");
}
   
    }

public Status changePassword(String jsonData, long id) {   
   
JSONObject json;
try {

    json = new  JSONObject(jsonData);
    String oldPassword = json.getString("oldpassword");
    String newPassword = json.getString("newpassword");
    User user = this.userRepository.findOne(id);
    if(user != null && oldPassword.equalsIgnoreCase(user.getPassword())){
        user.setPassword(newPassword);
        user.setIsPwdChanged("Y");
        this.userRepository.save(user);
       
        }else{
           
        throw new PasswordWrongException();
    }
    return new Status(1,"Success");
} catch (JSONException e) {
    e.printStackTrace();
    return new Status(0,"Fail");
}

}

Rest configutaiotn in web.xml

---------------------------------------------
<web-app>
    <display-name>Utility Manager Service</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:applicationContext.xml
        </param-value>
    </context-param>

 <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/service/*</url-pattern>
    </filter-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.fm.fmrecruit.api</param-value>
        </init-param>
        <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>/service/*</url-pattern>
    </servlet-mapping>


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


Angular js project structure:
-------------------------------------







Resister.control.js
-----------------------------
 (function () {
    'use strict';

    angular
        .module('app')
        .controller('RegisterController', RegisterController);

    RegisterController.$inject = ['UserService', '$location', '$rootScope', 'FlashService'];
    function RegisterController(UserService, $location, $rootScope, FlashService) {
        var vm = this;

        vm.register = register;

        function register() {
            vm.dataLoading = true;
        if(vm.regType == 'user'){
            UserService.Create(vm.user)
                .then(function (response) {
                console.log(response);
                    if (response.data.code ==1) {
                        FlashService.Success(response.data.message, true);
                        $location.path('/login');
                    } else {
                        FlashService.Error(response.data.message);
                        vm.dataLoading = false;
                    }
                });
                }else{
                UserService.CreateAdmin(vm.user)
                .then(function (response) {
                console.log(response);
                    if (response.data.code ==1) {
                        FlashService.Success(response.data.message, true);
                        $location.path('/login');
                    } else {
                        FlashService.Error(response.data.message);
                        vm.dataLoading = false;
                    }
                });
                }
        }
    }

})();

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

register.view.html
----------------------------



<div class="col-md-6 col-md-offset-3" ng-controller="RegisterController">
    <h2>Register</h2>
    <div ng-show="vm.error" class="alert alert-danger">{{vm.error}}</div>
    <form name="form" ng-submit="vm.register()" role="form">
     <div class="form-group" ng-class="{ 'has-error': form.firstName.$dirty && form.firstName.$error.required }">
            <label for="username">Registration Type</label>
           <div class="controls" style="margin-top:5px;">
                                          <input type="radio" ng-model="vm.regType" value="user" >User
                                          &nbsp;&nbsp;&nbsp;    &nbsp;&nbsp;&nbsp;
                                          <input type="radio" ng-model="vm.regType" value="admin">Admin
                                        </div>
        </div>
        <div class="form-group" ng-class="{ 'has-error': form.firstName.$dirty && form.firstName.$error.required }">
            <label for="username">First name</label>
            <input type="text" name="firstName" id="firstName" class="form-control" ng-model="vm.user.firstName" required />
            <span ng-show="form.firstName.$dirty && form.firstName.$error.required" class="help-block">First name is required</span>
        </div>
        <div class="form-group" ng-class="{ 'has-error': form.lastName.$dirty && form.lastName.$error.required }">
            <label for="username">Last name</label>
            <input type="text" name="lastName" id="Text1" class="form-control" ng-model="vm.user.lastName" required />
            <span ng-show="form.lastName.$dirty && form.lastName.$error.required" class="help-block">Last name is required</span>
        </div>
        <div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
            <label for="username">Username</label>
            <input type="text" name="username" id="username" class="form-control" ng-model="vm.user.username" required />
            <span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
        </div>
        <div ng-if="vm.regType == 'admin'" class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
            <label for="password">Password</label>
            <input type="password" name="password" id="password" class="form-control" ng-model="vm.user.password" required />
            <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
        </div>
        <div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }">
            <label for="password">Email</label>
            <input type="email" name="email" id="email" class="form-control" ng-model="vm.user.email" required />
            <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">email is required</span>
        </div>
         <div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$error.required }">
            <label for="password">Phone</label>
            <input type="phone" name="phone" id="phone" class="form-control" ng-model="vm.user.phone" required />
            <span ng-show="form.phone.$dirty && form.phone.$error.required" class="help-block">phone is required</span>
        </div>
        <div class="form-actions">
            <button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
                <a href="#/login" class="btn btn-link">Cancel</a>
        </div>
    </form>
</div>




















Saturday, 16 March 2013

web services Introduction



Introduction to web services:

 

TUTIORALS FROM MADHAV:

     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT.... 




1.What are web services?
2.Types of web servicesa

What are web services?


  •   Web services are client and server applications that communicate over the World Wide Web (WWW) hyper text transfer protocol (HTTP)
  •   As described by the www consortium (W3C), web services provide a standard means of interoperating between software applications running on a variety of platform and frameworks.
  •  Web services are characterized by great interoperability and extensibility, as well as the machine-process able descriptions,
  • Web services can be combined in a loosely coupled way to achieve complex operations.
  •  Programs providing simple services can interactive with each other to deliver sophisticated added value services.

Types of web services:


The two types:
1.big web services
2.restful web services.

  • In java, jax-ws provides the functionally for big web services.
  •   Big web services use XML messages that follow the simple object access protocol (SOAP) standard, an xml language defining a message architecture and message formats.
  •   Such systems often contain a machine-readable description of the operations offered by the service, written in the web services description language (WSDL),and xml language for defining interfaces syntactically.
  •   The soap message format and the WSDL interface definition language have gained widespread adoption.
  •  Many development tools, such as netbeans IDE, can reduce the complexity of developing web service applications. 
  •   A SOAP –based design must include the following elements.
  •   A format contract must be established to describe the interface that the web service offers.
  • WSDL can be used to describe the details of the contract, which may include messages,Operations, bindings, and the location of the web services
  •  In java EE6 ,JAX-RS provides the functionality for representational state transfer(restful) web services.
  •   Rest is well suited for basic, ad hoc integration scenarios.





TUTIORALS FROM MADHAV:

     JAVA-SERVLETS     JAVA-JDBC     JAVA-JSP       HIBERNATE-SHCEMABASED 

    SPRING-AOP-ANNOTATIONS      SPRING -DAO     SPRIN-MVC     SPRING-SECUTITY

     SPRING-DATA-JPA     REST-WEB-SERVICE     STRUTS2HIBERNATE    GWT....

 Related topics: