1. 程式人生 > >ServiceComb實戰 (3)comb實戰

ServiceComb實戰 (3)comb實戰

ServiceComb實戰 (3)combDemo
步驟一、配置POM

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>cn.qchcolud</groupId>
	<artifactId>combDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>combDemo</name>
	<description>Demo project for ServiceComb-Spring</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.12.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<dependency>
			<groupId>org.apache.servicecomb</groupId>
			<artifactId>spring-boot-starter-provider</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.10.5</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.10.5</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.10.5</version>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.8.1</version>
</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.apache.servicecomb</groupId>
				<artifactId>java-chassis-dependencies</artifactId>
				<version>1.0.0-m2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.5.12.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/bin</outputDirectory>
                            <classifier>exec</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Class-Path>.</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
		</plugins>
	</build>


</project>

步驟二、application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/combDemo?useSSL=false
spring.datasource.username=root
spring.datasource.password=1234
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

步驟三、工程原始碼


package cn.qchcolud.combDemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.servicecomb.springboot.starter.provider.EnableServiceComb;


@SpringBootApplication
@EnableServiceComb
public class CombDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(CombDemoApplication.class, args);
	}
}

package cn.qchcolud.combDemo.dto;

public class UserDTO {
	  private String name;
	  private String password;
	  public String getName() {
	    return name;
	  }
	  public String getPassword() {
	    return password;
	  }
	  public UserDTO() {
	  }
	  public UserDTO(String name, String password) {
	    this.name = name;
	    this.password = password;
	  }
	}
package cn.qchcolud.combDemo.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "T_User")
public class UserEntity {
  @Id
  private String name;

  private String password;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public UserEntity() {
  }

  public UserEntity(String name, String password) {
    this.name = name;
    this.password = password;
  }
}
package cn.qchcolud.combDemo.jwt;


import java.time.ZonedDateTime;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import static io.jsonwebtoken.SignatureAlgorithm.HS512;


@Component
public class JwtTokenStore implements TokenStore {
  private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenStore.class);

  private final String secretKey;

  private final int secondsToExpire;

  public JwtTokenStore() {
    this.secretKey = "someSecretKeyForAuthenticagggggggggggggggggggggtiondfgdgfdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd";
    this.secondsToExpire = 60 * 60 * 24;
  }

  public JwtTokenStore(String secretKey, int secondsToExpire) {
    this.secretKey = secretKey;
    this.secondsToExpire = secondsToExpire;
  }

  @Override
  public String generate(String userName) {
    return Jwts.builder().setSubject(userName)
        .setExpiration(Date.from(ZonedDateTime.now().plusSeconds(secondsToExpire).toInstant()))
        .signWith(HS512, secretKey).compact();
  }

  @Override
  public boolean validate(String token) {
    try {
      return StringUtils.isNotEmpty(Jwts.parser()
       .setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject());
    } catch (JwtException | IllegalArgumentException e) {
      LOGGER.info("validateToken token : " + token + " failed", e);
    }
    return false;
  }
}
package cn.qchcolud.combDemo.jwt;

public interface TokenStore {
	  String generate(String userName);

	  boolean validate(String token);
	}
package cn.qchcolud.combDemo.repository;

import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;

import cn.qchcolud.combDemo.entity.UserEntity;

@Repository
public interface UserRepository extends PagingAndSortingRepository<UserEntity, Long> {
  UserEntity findByName(String name);
}
package cn.qchcolud.combDemo.service;

import org.springframework.http.ResponseEntity;

import cn.qchcolud.combDemo.dto.UserDTO;

public interface UserService {
	  ResponseEntity<Boolean> logon(UserDTO user);
	  ResponseEntity<Boolean> login(UserDTO user);
	}

package cn.qchcolud.combDemo.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.servicecomb.provider.rest.common.RestSchema;

import org.apache.servicecomb.swagger.invocation.exception.InvocationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.qchcolud.combDemo.dto.UserDTO;
import cn.qchcolud.combDemo.entity.UserEntity;
import cn.qchcolud.combDemo.jwt.TokenStore;
import cn.qchcolud.combDemo.repository.UserRepository;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static org.springframework.http.HttpHeaders.AUTHORIZATION;



@RestSchema(schemaId = "user")
@RequestMapping(path = "/")
public class UserServiceImpl implements UserService {
  private final UserRepository repository;

  private final TokenStore tokenStore;

  @Autowired
  public UserServiceImpl(UserRepository repository, TokenStore tokenStore) {
    this.repository = repository;
    this.tokenStore = tokenStore;
  }

  @Override
  @PostMapping(path = "logon")
  public ResponseEntity<Boolean> logon(@RequestBody UserDTO user) {
    if (validateUser(user)) {
      UserEntity dbUser = repository.findByName(user.getName());
      if (dbUser == null) {
        UserEntity entity = new UserEntity(user.getName(), user.getPassword());
        repository.save(entity);
        return new ResponseEntity<>(true, HttpStatus.OK);
      }
      throw new InvocationException(BAD_REQUEST, "user name had exist");
    }
    throw new InvocationException(BAD_REQUEST, "incorrect user");
  }

  @Override
  @PostMapping(path = "login")
  public ResponseEntity<Boolean> login(@RequestBody UserDTO user) {
	  
	  
	  System.out.println("-->"+user.getName()+"--"+user.getPassword());
    if (validateUser(user)) {
      UserEntity dbUser = repository.findByName(user.getName());
      if (dbUser != null) {
        if (dbUser.getPassword().equals(user.getPassword())) {
          String token = tokenStore.generate(user.getName());
          HttpHeaders headers = generateAuthenticationHeaders(token);
          //add authentication header
          return new ResponseEntity<>(true, headers, HttpStatus.OK);
        }
        throw new InvocationException(BAD_REQUEST, "wrong password");
      }
      throw new InvocationException(BAD_REQUEST, "user name not exist");
    }
    throw new InvocationException(BAD_REQUEST, "incorrect user");
  }

  private boolean validateUser(UserDTO user) {
    return user != null && StringUtils.isNotEmpty(user.getName()) && StringUtils.isNotEmpty(user.getPassword());
  }

  private HttpHeaders generateAuthenticationHeaders(String token) {
    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION, token);
    return headers;
  }
}