Browse Source

增加OAuth2 通用service实现

zhou-hao 7 years ago
parent
commit
d052afbfdb
13 changed files with 486 additions and 2 deletions
  1. 1 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/pom.xml
  2. 46 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/AbstractOAuth2CrudService.java
  3. 8 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2CrudService.java
  4. 11 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2DeleteService.java
  5. 12 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2InsertService.java
  6. 32 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2QueryByEntityService.java
  7. 10 2
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2ServiceSupport.java
  8. 24 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2UpdateService.java
  9. 150 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/AbstractOAuth2CrudServiceTests.java
  10. 100 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/MockOAuth2Request.java
  11. 59 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/MockOAuth2Response.java
  12. 20 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/TestEntity.java
  13. 13 0
      hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/TestEntityService.java

+ 1 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/pom.xml

@@ -22,5 +22,6 @@
             <artifactId>hsweb-authorization-oauth2-client</artifactId>
             <version>${project.version}</version>
         </dependency>
+
     </dependencies>
 </project>

+ 46 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/AbstractOAuth2CrudService.java

@@ -0,0 +1,46 @@
+package org.hswebframework.web.service.oauth2;
+
+import org.hswebframework.utils.ClassUtils;
+import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@SuppressWarnings("unchecked")
+public abstract class AbstractOAuth2CrudService<E, PK> implements OAuth2CrudService<E, PK> {
+
+    private Class<E> entityType;
+
+    private Class<PK> primaryKeyType;
+
+    private OAuth2RequestService oAuth2RequestService;
+
+    public AbstractOAuth2CrudService() {
+        entityType = (Class) ClassUtils.getGenericType(this.getClass(), 0);
+        primaryKeyType = (Class) ClassUtils.getGenericType(this.getClass(), 1);
+    }
+
+    @Override
+    public OAuth2RequestService getRequestService() {
+        return oAuth2RequestService;
+    }
+
+    @Override
+    public abstract String getServiceId();
+
+    @Override
+    public abstract String getUriPrefix();
+
+    @Override
+    public Class<E> getEntityType() {
+        return entityType;
+    }
+
+    @Override
+    public Class<PK> getPrimaryKeyType() {
+        return primaryKeyType;
+    }
+
+    @Autowired
+    public void setoAuth2RequestService(OAuth2RequestService oAuth2RequestService) {
+        this.oAuth2RequestService = oAuth2RequestService;
+    }
+}

+ 8 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2CrudService.java

@@ -0,0 +1,8 @@
+package org.hswebframework.web.service.oauth2;
+
+public interface OAuth2CrudService<E, PK> extends OAuth2QueryService<E, PK>
+        , OAuth2QueryByEntityService<E>
+        , OAuth2DeleteService<PK>
+        , OAuth2InsertService<E, PK>
+        , OAuth2UpdateService<E, PK> {
+}

+ 11 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2DeleteService.java

@@ -0,0 +1,11 @@
+package org.hswebframework.web.service.oauth2;
+
+import org.hswebframework.web.service.DeleteService;
+import org.hswebframework.web.service.InsertService;
+
+public interface OAuth2DeleteService<PK> extends DeleteService<PK>, OAuth2ServiceSupport {
+    @Override
+    default int deleteByPk(PK pk) {
+        return createRequest("/" + pk).delete().as(Integer.class);
+    }
+}

+ 12 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2InsertService.java

@@ -0,0 +1,12 @@
+package org.hswebframework.web.service.oauth2;
+
+import com.alibaba.fastjson.JSON;
+import org.hswebframework.web.service.InsertService;
+import org.hswebframework.web.service.UpdateService;
+
+public interface OAuth2InsertService<E, PK> extends InsertService<E, PK>, OAuth2ServiceSupport {
+    @Override
+    default PK insert(E data) {
+        return createRequest("/").requestBody(JSON.toJSONString(data)).post().as(getPrimaryKeyType());
+    }
+}

+ 32 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2QueryByEntityService.java

@@ -0,0 +1,32 @@
+package org.hswebframework.web.service.oauth2;
+
+import com.alibaba.fastjson.JSONObject;
+import org.hswebframework.web.commons.entity.Entity;
+import org.hswebframework.web.commons.entity.PagerResult;
+import org.hswebframework.web.service.QueryByEntityService;
+
+import java.util.List;
+
+public interface OAuth2QueryByEntityService<E> extends QueryByEntityService<E>, OAuth2ServiceSupport {
+
+    @Override
+    default PagerResult<E> selectPager(Entity param) {
+        JSONObject result = createRequest("/", param).get().as(JSONObject.class);
+        return PagerResult.of(result.getInteger("total"), result.getJSONArray("data").toJavaList(getEntityType()));
+    }
+
+    @Override
+    default List<E> select(Entity param) {
+        return createRequest("/no-paging", param).get().asList(getEntityType());
+    }
+
+    @Override
+    default int count(Entity param) {
+        return createRequest("/count", param).get().as(Integer.class);
+    }
+
+    @Override
+    default E selectSingle(Entity param) {
+        return createRequest("/single", param).get().as(getEntityType());
+    }
+}

+ 10 - 2
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2ServiceSupport.java

@@ -1,6 +1,7 @@
 package org.hswebframework.web.service.oauth2;
 
 
+import org.hswebframework.web.WebUtil;
 import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
 import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
 import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
@@ -13,13 +14,20 @@ public interface OAuth2ServiceSupport {
 
     String getUriPrefix();
 
-   <E> Class<E> getEntityType();
+    <E> Class<E> getEntityType();
+
+    <PK> Class<PK> getPrimaryKeyType();
 
     default OAuth2Session createSession() {
         return getRequestService().create(getServiceId()).byClientCredentials();
     }
 
     default OAuth2Request createRequest(String uri) {
-        return createSession().request(getUriPrefix()+uri);
+        return createSession().request(getUriPrefix() + uri);
+    }
+
+    default OAuth2Request createRequest(String uri, Object param) {
+        return createSession().request(getUriPrefix() + uri)
+                .params(WebUtil.objectToHttpParameters(param));
     }
 }

+ 24 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/main/java/org/hswebframework/web/service/oauth2/OAuth2UpdateService.java

@@ -0,0 +1,24 @@
+package org.hswebframework.web.service.oauth2;
+
+import com.alibaba.fastjson.JSON;
+import org.hswebframework.web.service.UpdateService;
+
+import java.util.List;
+
+public interface OAuth2UpdateService<E, PK> extends UpdateService<E, PK>, OAuth2ServiceSupport {
+
+    @Override
+    default int updateByPk(PK id, E data) {
+        return createRequest("/" + id).requestBody(JSON.toJSONString(data)).put().as(Integer.class);
+    }
+
+    @Override
+    default int updateByPk(List<E> data) {
+        return createRequest("/batch").requestBody(JSON.toJSONString(data)).put().as(Integer.class);
+    }
+
+    @Override
+    default PK saveOrUpdate(E e) {
+        return createRequest("/").requestBody(JSON.toJSONString(e)).patch().as(getPrimaryKeyType());
+    }
+}

+ 150 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/AbstractOAuth2CrudServiceTests.java

@@ -0,0 +1,150 @@
+package org.hswebframework.web.service.oauth2;
+
+import com.alibaba.fastjson.JSON;
+import org.hswebframework.web.BusinessException;
+import org.hswebframework.web.authorization.oauth2.client.OAuth2RequestService;
+import org.hswebframework.web.authorization.oauth2.client.OAuth2SessionBuilder;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Session;
+import org.hswebframework.web.commons.entity.PagerResult;
+import org.hswebframework.web.commons.entity.param.QueryParamEntity;
+import org.hswebframework.web.controller.message.ResponseMessage;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+import static org.mockito.Mockito.*;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AbstractOAuth2CrudServiceTests {
+
+    @Mock
+    private OAuth2RequestService requestService;
+
+    @Mock
+    private OAuth2SessionBuilder sessionBuilder;
+
+    @Mock
+    private OAuth2Session oAuth2Session;
+
+    @InjectMocks
+    private TestEntityService testEntityService;
+
+    @Before
+    public void init() {
+        TestEntity entity = TestEntity.builder().build();
+        entity.setBoy(true);
+        entity.setCreateTime(new Date());
+        entity.setName("test");
+        entity.setId("test");
+
+        when(oAuth2Session.request("/test/")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("get", ResponseMessage.ok(PagerResult.of(1, Arrays.asList(entity))))));
+
+
+        when(oAuth2Session.request("/test/test")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("get", ResponseMessage.ok(entity))
+                        , whenRequest("put", ResponseMessage.ok(1))
+                        , whenRequest("delete", ResponseMessage.ok(1)))
+        );
+
+        when(oAuth2Session.request("/test/all")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("get", ResponseMessage.ok(Arrays.asList(entity)))
+                ));
+
+        when(oAuth2Session.request("/test/ids")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("get", ResponseMessage.ok(Arrays.asList(entity)))
+                ));
+
+        when(oAuth2Session.request("/test/batch")).thenReturn(
+                createFixedResponseRequest(
+                        whenRequest("put", ResponseMessage.error(400, "名称不能为空"))
+                ));
+
+        when(sessionBuilder.byClientCredentials()).thenReturn(oAuth2Session);
+
+        when(requestService.create(anyString())).thenReturn(sessionBuilder);
+
+    }
+
+    private OAuth2Request createFixedResponseRequest(OAuth2MethodRequest... requests) {
+        return new MockOAuth2Request((method) -> {
+            for (OAuth2MethodRequest request : requests) {
+                if (request.getMethod().equals(method)) {
+                    return new MockOAuth2Response(request.getResponse());
+                }
+            }
+            return new MockOAuth2Response(ResponseMessage.error(404, "not found").toString());
+        });
+    }
+
+    @Test
+    public void testCUD() {
+        TestEntity entity = testEntityService.selectByPk("test");
+        Assert.assertNotNull(entity);
+
+        int i = testEntityService.updateByPk("test", entity);
+        Assert.assertEquals(i, 1);
+
+        i = testEntityService.deleteByPk("test");
+        Assert.assertEquals(i, 1);
+
+        try {
+            testEntityService.updateByPk(Arrays.asList(entity));
+            Assert.assertTrue(false);
+        } catch (BusinessException e) {
+            Assert.assertEquals(e.getMessage(), "名称不能为空");
+        }
+
+    }
+
+    @Test
+    public void testQuery() {
+        PagerResult<TestEntity> result = testEntityService.selectPager(new QueryParamEntity().where("name", "test"));
+        System.out.println(JSON.toJSONString(result));
+
+        TestEntity entity = testEntityService.selectByPk("test");
+        Assert.assertNotNull(entity);
+        Assert.assertTrue(entity.isBoy());
+        Assert.assertEquals(entity.getName(), "test");
+
+        System.out.println(JSON.toJSONString(entity));
+
+        List<TestEntity> all = testEntityService.select();
+
+        System.out.println(JSON.toJSONString(all));
+
+    }
+
+    interface OAuth2MethodRequest {
+        String getMethod();
+
+        String getResponse();
+    }
+
+    public OAuth2MethodRequest whenRequest(String method, Object json) {
+        return new OAuth2MethodRequest() {
+            @Override
+            public String getMethod() {
+                return method;
+            }
+
+            @Override
+            public String getResponse() {
+                return JSON.toJSONString(json);
+            }
+        };
+    }
+}

+ 100 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/MockOAuth2Request.java

@@ -0,0 +1,100 @@
+package org.hswebframework.web.service.oauth2;
+
+import lombok.extern.slf4j.Slf4j;
+import org.hswebframework.web.authorization.oauth2.client.request.OAuth2Request;
+import org.hswebframework.web.authorization.oauth2.client.request.TokenExpiredCallBack;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+@Slf4j
+public class MockOAuth2Request implements OAuth2Request {
+
+
+    private Function<String,OAuth2Response> responseGetter;
+
+
+    public MockOAuth2Request(Function<String,OAuth2Response> responseGetter) {
+        this.responseGetter = responseGetter;
+    }
+
+    @Override
+    public OAuth2Request onRefreshTokenExpired(TokenExpiredCallBack refreshTokenExpiredCallBack) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request onTokenExpired(TokenExpiredCallBack callback) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request param(String name, Object value) {
+        log.info("set param :{}={}", name, value);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request params(Map<String, String> params) {
+        log.info("set params :{}", params);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request requestBody(String value) {
+        log.info("set request body :{}", value);
+        return this;
+    }
+
+    @Override
+    public OAuth2Request header(String name, String value) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request cookie(String cookie) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request contentType(String contentType) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request accept(String accept) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Request timeout(long millisecond, Consumer<OAuth2Request> timeoutCallBack) {
+        return this;
+    }
+
+    @Override
+    public OAuth2Response get() {
+        return responseGetter.apply("get");
+    }
+
+    @Override
+    public OAuth2Response put() {
+        return responseGetter.apply("put");
+    }
+
+    @Override
+    public OAuth2Response post() {
+        return responseGetter.apply("post");
+    }
+
+    @Override
+    public OAuth2Response delete() {
+        return responseGetter.apply("delete");
+    }
+
+    @Override
+    public OAuth2Response patch() {
+        return responseGetter.apply("patch");
+    }
+}

+ 59 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/MockOAuth2Response.java

@@ -0,0 +1,59 @@
+package org.hswebframework.web.service.oauth2;
+
+import org.hswebframework.web.authorization.oauth2.client.request.ResponseConvertHandler;
+import org.hswebframework.web.authorization.oauth2.client.response.OAuth2Response;
+import org.hswebframework.web.authorization.oauth2.client.response.ResponseConvert;
+import org.hswebframework.web.authorization.oauth2.client.simple.provider.HswebResponseConvertSupport;
+import org.hswebframework.web.authorization.simple.builder.SimpleAuthenticationBuilderFactory;
+import org.hswebframework.web.authorization.simple.builder.SimpleDataAccessConfigBuilderFactory;
+import org.hswebframework.web.oauth2.core.ErrorType;
+
+import java.util.List;
+import java.util.function.BiConsumer;
+
+public class MockOAuth2Response implements OAuth2Response {
+
+    private String result;
+
+    private ResponseConvertHandler handler = new HswebResponseConvertSupport(new SimpleAuthenticationBuilderFactory(new SimpleDataAccessConfigBuilderFactory()));
+
+
+    public MockOAuth2Response(String result) {
+        this.result = result;
+    }
+
+    @Override
+    public String asString() {
+        return result;
+    }
+
+    @Override
+    public byte[] asBytes() {
+        return result.getBytes();
+    }
+
+    @Override
+    public <T> T as(ResponseConvert<T> convert) {
+        return convert.convert(this);
+    }
+
+    @Override
+    public <T> T as(Class<T> type) {
+        return handler.convert(this, type);
+    }
+
+    @Override
+    public <T> List<T> asList(Class<T> type) {
+        return handler.convertList(this, type);
+    }
+
+    @Override
+    public int status() {
+        return 200;
+    }
+
+    @Override
+    public OAuth2Response onError(BiConsumer<OAuth2Response, ErrorType> onError) {
+        return this;
+    }
+}

+ 20 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/TestEntity.java

@@ -0,0 +1,20 @@
+package org.hswebframework.web.service.oauth2;
+
+import lombok.*;
+import org.hswebframework.web.commons.entity.SimpleGenericEntity;
+
+import java.util.Date;
+
+@Getter
+@Setter
+@Builder
+@NoArgsConstructor
+@AllArgsConstructor
+public class TestEntity extends SimpleGenericEntity<String> {
+    private static final long serialVersionUID = 6405200441627288263L;
+    private String name;
+
+    private boolean boy;
+
+    private Date createTime;
+}

+ 13 - 0
hsweb-commons/hsweb-commons-service/hsweb-commons-service-oauth2/src/test/java/org/hswebframework/web/service/oauth2/TestEntityService.java

@@ -0,0 +1,13 @@
+package org.hswebframework.web.service.oauth2;
+
+public class TestEntityService extends AbstractOAuth2CrudService<TestEntity,String>{
+    @Override
+    public String getServiceId() {
+        return "test";
+    }
+
+    @Override
+    public String getUriPrefix() {
+        return "/test";
+    }
+}