diff --git a/.gitignore b/.gitignore index d911719..c7f1c49 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ -**/*.iml -.idea/ -**/target/**/* -rop-client-js/**/* - +**/*.iml +.idea/ +**/target/**/* +rop-client-js/**/* +**/.project +**/.classpath +.project +**/.settings/**/* diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..211dff1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + com.rop + rop-parent + 2.0-SNAPSHOT + pom + rop parent + rest open platform + https://github.com/itstamen/rop + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git://github.com/itstamen/rop.git + scm:git:git://github.com/itstamen/rop.git + git://github.com/itstamen/rop.git + + + + + stamen + stamen + itstamen@qq.com + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + ${file.encoding} + ${file.encoding} + ${file.encoding} + + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${file.encoding} + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${file.encoding} + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.7.2 + + once + -Dfile.encoding=${file.encoding} + + + net.sourceforge.cobertura.datafile + target/cobertura/cobertura.ser + + + + + + + + + UTF-8 + 1.5 + + + + rop + rop-client + rop-core + rop-sample + + \ No newline at end of file diff --git a/rop-client/.gitignore b/rop-client/.gitignore new file mode 100644 index 0000000..f675857 --- /dev/null +++ b/rop-client/.gitignore @@ -0,0 +1,2 @@ +/target/ +/.settings/ \ No newline at end of file diff --git a/rop-client/pom.xml b/rop-client/pom.xml new file mode 100644 index 0000000..f59880a --- /dev/null +++ b/rop-client/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + + + com.rop + rop-parent + 2.0-SNAPSHOT + + + rop-client + ropClient + jar + rest open platform + + http://www.github.com + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git@github.com:itstamen/rop.git + scm:git:git@github.com:itstamen/rop.git + git@github.com:itstamen/rop.git + + + + + junit + junit + ${junit.version} + test + + + com.rop + rop-core + ${project.version} + + + com.alibaba + fastjson + 1.2.4 + test + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + ${file.encoding} + ${file.encoding} + ${file.encoding} + + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${file.encoding} + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${file.encoding} + + + + + + + UTF-8 + 1.6 + 4.3.2 + 4.12 + + \ No newline at end of file diff --git a/rop-client/src/main/java/com/rop/client/ClientRequest.java b/rop-client/src/main/java/com/rop/client/ClientRequest.java new file mode 100644 index 0000000..b11caa7 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/ClientRequest.java @@ -0,0 +1,103 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import java.io.IOException; + +/** + *
+ *   每个请求对应一个ClientRequest对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface ClientRequest { + + /** + * 设置http请求头信息 + * @param name + * @param value + * @return ClientRequest + */ + ClientRequest setHeader(String name, String value); + + /** + * 添加请求参数,默认需要签名,如果类已经标注了{@link com.rop.annotation.IgnoreSign}则始终不加入签名 + * @param paramName + * @param paramValue + * @return ClientRequest + */ + ClientRequest addParam(String paramName,Object paramValue); + + /** + * 添加请求参数,如果needSign=false表示不参于签名 + * @param paramName + * @param paramValue + * @param needSign + * @return ClientRequest + */ + ClientRequest addParam(String paramName,Object paramValue,boolean needSign); + + /** + * 清除参数列表 + * @return ClientRequest + */ + ClientRequest clearParam(); + + /** + * 使用POST发起请求 + * @param ropResponseClass + * @param methodName + * @param version + * @param + * @return CompositeResponse + */ + CompositeResponse post(Class ropResponseClass, String methodName, String version) throws IOException; + + /** + * 直接使用 ropRequest发送请求 + * @param ropRequest + * @param ropResponseClass + * @param methodName + * @param version + * @param + * @return CompositeResponse + */ + CompositeResponse post(Object ropRequest, Class ropResponseClass, String methodName, String version) throws IOException; + + /** + * 使用GET发送服务请求 + * @param ropResponseClass + * @param methodName + * @param version + * @param + * @return CompositeResponse + */ + CompositeResponse get(Class ropResponseClass, String methodName, String version) throws IOException; + + /** + * 使用GET发送ropRequest的请求 + * @param ropRequest + * @param ropResponseClass + * @param methodName + * @param version + * @param + * @return CompositeResponse + */ + CompositeResponse get(Object ropRequest, Class ropResponseClass, String methodName, String version) throws IOException; +} + diff --git a/rop-client/src/main/java/com/rop/client/CommonConstant.java b/rop-client/src/main/java/com/rop/client/CommonConstant.java new file mode 100644 index 0000000..2995875 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/CommonConstant.java @@ -0,0 +1,27 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 13-11-1 + */ +public class CommonConstant { + + public static final String ERROR_TOKEN = "@@$-ERROR_TOKEN$-@@"; + + public static final String SESSION_CHANGED = "@@SESSION_CHANGED__"; +} diff --git a/rop/src/main/java/com/rop/client/CompositeResponse.java b/rop-client/src/main/java/com/rop/client/CompositeResponse.java similarity index 51% rename from rop/src/main/java/com/rop/client/CompositeResponse.java rename to rop-client/src/main/java/com/rop/client/CompositeResponse.java index 5ad2845..1dff18b 100644 --- a/rop/src/main/java/com/rop/client/CompositeResponse.java +++ b/rop-client/src/main/java/com/rop/client/CompositeResponse.java @@ -1,43 +1,54 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client; - -import com.rop.response.ErrorResponse; - -/** - *
- *    客户端的响应,如果{@link #isSuccessful()}返回true,则调用{@link #getErrorResponse()},反之,则应该
- * 调用{@link #getSuccessResponse(Class)}
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface CompositeResponse { - - /** - * 获取错误的响应对象 - * - * @return - */ - ErrorResponse getErrorResponse(); - - /** - * 获取正确的响应对象 - * - * @param responseClass - * @param - * @return - */ - T getSuccessResponse(); - - /** - * 响应是否是正确的 - * - * @return - */ - boolean isSuccessful(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import com.rop.response.ErrorResponse; + +/** + *
+ *    客户端的响应,如果{@link #isSuccessful()}返回true,则调用{@link #getErrorResponse()},反之,则应该
+ * 调用{@link #getSuccessResponse(Class)}
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface CompositeResponse { + + /** + * 获取错误的响应对象 + * + * @return + */ + ErrorResponse getErrorResponse(); + + /** + * 获取正确的响应对象 + * + * @param responseClass + * @param + * @return + */ + T getSuccessResponse(); + + /** + * 响应是否是正确的 + * + * @return + */ + boolean isSuccessful(); +} + diff --git a/rop/src/main/java/com/rop/client/DefaultCompositeResponse.java b/rop-client/src/main/java/com/rop/client/DefaultCompositeResponse.java similarity index 57% rename from rop/src/main/java/com/rop/client/DefaultCompositeResponse.java rename to rop-client/src/main/java/com/rop/client/DefaultCompositeResponse.java index d24d578..4ca74c8 100644 --- a/rop/src/main/java/com/rop/client/DefaultCompositeResponse.java +++ b/rop-client/src/main/java/com/rop/client/DefaultCompositeResponse.java @@ -1,52 +1,63 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client; - -import com.rop.response.ErrorResponse; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultCompositeResponse implements CompositeResponse { - - private boolean successful; - - private ErrorResponse errorResponse; - - private T successRopResponse; - - public DefaultCompositeResponse(boolean successful) { - this.successful = successful; - } - - - public ErrorResponse getErrorResponse() { - return this.errorResponse; - } - - - public T getSuccessResponse() { - return this.successRopResponse; - } - - public void setErrorResponse(ErrorResponse errorResponse) { - this.errorResponse = errorResponse; - } - - public void setSuccessRopResponse(T successRopResponse) { - this.successRopResponse = successRopResponse; - } - - - public boolean isSuccessful() { - return successful; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import com.rop.response.ErrorResponse; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultCompositeResponse implements CompositeResponse { + + private boolean successful; + + private ErrorResponse errorResponse; + + private T successRopResponse; + + public DefaultCompositeResponse(boolean successful) { + this.successful = successful; + } + + + public ErrorResponse getErrorResponse() { + return this.errorResponse; + } + + + public T getSuccessResponse() { + return this.successRopResponse; + } + + public void setErrorResponse(ErrorResponse errorResponse) { + this.errorResponse = errorResponse; + } + + public void setSuccessRopResponse(T successRopResponse) { + this.successRopResponse = successRopResponse; + } + + + public boolean isSuccessful() { + return successful; + } +} + diff --git a/rop-client/src/main/java/com/rop/client/DefaultRopClient.java b/rop-client/src/main/java/com/rop/client/DefaultRopClient.java new file mode 100644 index 0000000..e9a6629 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/DefaultRopClient.java @@ -0,0 +1,487 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import org.apache.commons.lang.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.rop.MessageFormat; +import com.rop.RopMarshaller; +import com.rop.RopUnmarshaller; +import com.rop.annotation.IgnoreSign; +import com.rop.client.http.HttpClient; +import com.rop.client.http.HttpResponse; +import com.rop.client.http.JdkHttpClient; +import com.rop.config.SystemParameterNames; +import com.rop.converter.RopConverter; +import com.rop.converter.UploadFile; +import com.rop.converter.UploadFileConverter; +import com.rop.marshaller.FastjsonRopMarshaller; +import com.rop.marshaller.JaxbXmlRopMarshaller; +import com.rop.response.ErrorResponse; +import com.rop.sign.SignHandler; +import com.rop.unmarshaller.FastjsonRopUnmarshaller; +import com.rop.unmarshaller.JaxbXmlRopUnmarshaller; +import com.rop.utils.AnnotationUtils; +import com.rop.utils.Assert; +import com.rop.utils.ReflectionUtils; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultRopClient implements RopClient { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + //服务地址 + private String serverUrl; + + //应用键 + private String appKey; + + private String sessionId; + + private String appKeyName = SystemParameterNames.getAppKey(); + + private String sessionIdName = SystemParameterNames.getSessionId(); + + private String methodName = SystemParameterNames.getMethod(); + + private String versionName = SystemParameterNames.getVersion(); + + private String formatName = SystemParameterNames.getFormat(); + + private String localeName = SystemParameterNames.getLocale(); + + private String signName = SystemParameterNames.getSign(); + + private SignHandler signHandler; + + //报文格式 + private MessageFormat messageFormat = MessageFormat.JSON; + + private Locale locale = Locale.SIMPLIFIED_CHINESE; + + private HttpClient httpClient = new JdkHttpClient(); + + private RopUnmarshaller xmlUnmarshaller; + + private RopUnmarshaller jsonUnmarshaller; + + private RopMarshaller xmlMarshaller; + + private RopMarshaller jsonMarshaller; + + //请求类所有请求参数 + private Map, List> requestAllFields = new HashMap, List>(); + + //请求类所有不需要进行签名的参数 + private Map, List> requestIgnoreSignFieldNames = new HashMap, List>(); + + //键为转换的目标类型 + private static Map, RopConverter> ropConverterMap = new HashMap, RopConverter>(); + + static { + ropConverterMap.put(UploadFile.class, new UploadFileConverter()); + } + + public DefaultRopClient(String serverUrl, String appKey) { + this.serverUrl = serverUrl; + this.appKey = appKey; + } + + public DefaultRopClient(String serverUrl, String appKey, MessageFormat messageFormat) { + this.serverUrl = serverUrl; + this.appKey = appKey; + this.messageFormat = messageFormat; + } + + public DefaultRopClient(String serverUrl, String appKey, MessageFormat messageFormat, Locale locale) { + this.serverUrl = serverUrl; + this.appKey = appKey; + this.messageFormat = messageFormat; + this.locale = locale; + } + + public MessageFormat getMessageFormat() { + return messageFormat; + } + + public void setMessageFormat(MessageFormat messageFormat) { + this.messageFormat = messageFormat; + } + + public Locale getLocale() { + return locale; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public RopClient setAppKeyParamName(String paramName) { + this.appKeyName = paramName; + return this; + } + + public RopClient setSessionIdParamName(String paramName) { + this.sessionIdName = paramName; + return this; + } + + public RopClient setMethodParamName(String paramName) { + this.methodName = paramName; + return this; + } + + public RopClient setVersionParamName(String paramName) { + this.versionName = paramName; + return this; + } + + public RopClient setFormatParamName(String paramName) { + this.formatName = paramName; + return this; + } + + public RopClient setLocaleParamName(String paramName) { + this.localeName = paramName; + return this; + } + + public RopClient setSignParamName(String paramName) { + this.signName = paramName; + return this; + } + + public RopClient setSignHandler(SignHandler handler) { + this.signHandler = handler; + return this; + } + + public void addRopConvertor(RopConverter ropConverter) { + DefaultRopClient.ropConverterMap.put(ropConverter.getTargetClass(), ropConverter); + } + + public ClientRequest buildClientRequest() { + return new DefaultClientRequest(); + } + + public RopUnmarshaller getXmlUnmarshaller() { + if(xmlUnmarshaller == null){ + xmlUnmarshaller = new JaxbXmlRopUnmarshaller(); + } + return xmlUnmarshaller; + } + + public void setXmlUnmarshaller(RopUnmarshaller xmlUnmarshaller) { + this.xmlUnmarshaller = xmlUnmarshaller; + } + + public RopUnmarshaller getJsonUnmarshaller() { + if(jsonUnmarshaller == null){ + jsonUnmarshaller = new FastjsonRopUnmarshaller(); + } + return jsonUnmarshaller; + } + + public void setJsonUnmarshaller(RopUnmarshaller jsonUnmarshaller) { + this.jsonUnmarshaller = jsonUnmarshaller; + } + + public RopMarshaller getXmlMarshaller() { + if(xmlMarshaller == null){ + xmlMarshaller = new JaxbXmlRopMarshaller(); + } + return xmlMarshaller; + } + + public void setXmlMarshaller(RopMarshaller xmlMarshaller) { + this.xmlMarshaller = xmlMarshaller; + } + + public RopMarshaller getJsonMarshaller() { + if(jsonMarshaller == null){ + jsonMarshaller = new FastjsonRopMarshaller(); + } + return jsonMarshaller; + } + + public void setJsonMarshaller(RopMarshaller jsonMarshaller) { + this.jsonMarshaller = jsonMarshaller; + } + + private class DefaultClientRequest implements ClientRequest { + + private Map paramMap = new HashMap(20); + + private List ignoreSignParams = new ArrayList(); + + private Map headMap = new HashMap(); + + private DefaultClientRequest() { + paramMap.put(appKeyName, appKey); + paramMap.put(formatName, messageFormat.name()); + paramMap.put(localeName, locale.toString()); + if (sessionId != null) { + paramMap.put(sessionIdName, sessionId); + } + } + + /** + * 设置http请求头信息 + * @param name + * @param value + * @return ClientRequest + */ + public ClientRequest setHeader(String name, String value){ + headMap.put(name, value); + return this; + } + + public ClientRequest addParam(String paramName, Object paramValue) { + addParam(paramName,paramValue,false); + return this; + } + + public ClientRequest clearParam() { + paramMap.clear(); + return this; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public ClientRequest addParam(String paramName, Object paramValue, boolean ignoreSign) { + Assert.isTrue(paramName != null && paramName.length() > 0, "参数名不能为空"); + Assert.notNull(paramValue, "参数值不能为null"); + + //将参数添加到参数列表中 + String valueAsStr = paramValue.toString(); + if (ropConverterMap.containsKey(paramValue.getClass())) { + RopConverter ropConverter = ropConverterMap.get(paramValue.getClass()); + valueAsStr = (String) ropConverter.unconvert(paramValue); + } + paramMap.put(paramName, valueAsStr); + IgnoreSign typeIgnore = AnnotationUtils.findAnnotation(paramValue.getClass(), IgnoreSign.class); + if (ignoreSign || typeIgnore != null) { + ignoreSignParams.add(paramName); + } + return this; + } + + public CompositeResponse post(Class ropResponseClass, String methodName, String version) throws IOException { + Map requestParams = addOtherParamMap(methodName, version); + return post(ropResponseClass, requestParams); + } + + public CompositeResponse post(Object ropRequest, Class ropResponseClass, String methodName, String version) throws IOException { + Map requestParams = getRequestForm(ropRequest, methodName, version); + return post(ropResponseClass, requestParams); + } + + private CompositeResponse post(Class ropResponseClass, Map requestParams) throws IOException { + HttpResponse response = httpClient.post(headMap, serverUrl, requestParams); + if(response.isSuccessful()){ + String responseContent = response.getString(); + return toCompositeResponse(responseContent, ropResponseClass); + } + return new DefaultCompositeResponse(false); + } + + + public CompositeResponse get(Class ropResponseClass, String methodName, String version) throws IOException { + Map requestParams = addOtherParamMap(methodName, version); + return get(ropResponseClass, requestParams); + } + + public CompositeResponse get(Object ropRequest, Class ropResponseClass, String methodName, String version) throws IOException { + Map requestParams = getRequestForm(ropRequest, methodName, version); + return get(ropResponseClass, requestParams); + } + + private CompositeResponse get(Class ropResponseClass, Map requestParams) throws IOException { + HttpResponse response = httpClient.get(headMap, serverUrl, requestParams); + if(response.isSuccessful()){ + String responseContent = response.getString(); + return toCompositeResponse(responseContent, ropResponseClass); + } + return new DefaultCompositeResponse(false); + } + + private Map addOtherParamMap(String methodName, String version) { + paramMap.put(DefaultRopClient.this.methodName, methodName); + paramMap.put(DefaultRopClient.this.versionName, version); + String signValue = DefaultRopClient.this.signHandler.sign(paramMap, ignoreSignParams); + paramMap.put(DefaultRopClient.this.signName, signValue); + return paramMap; + } + + private CompositeResponse toCompositeResponse(String content, Class ropResponseClass) { + if(logger.isDebugEnabled()){ + logger.debug(content); + } + boolean successful = isSuccessful(content); + DefaultCompositeResponse compositeResponse = new DefaultCompositeResponse(successful); + if (MessageFormat.JSON == messageFormat) { + if (successful) { + T ropResponse = getJsonUnmarshaller().unmarshaller(content, ropResponseClass); + compositeResponse.setSuccessRopResponse(ropResponse); + } else { + ErrorResponse errorResponse = getJsonUnmarshaller().unmarshaller(content, ErrorResponse.class); + compositeResponse.setErrorResponse(errorResponse); + } + } else { + if (successful) { + T ropResponse = getXmlUnmarshaller().unmarshaller(content, ropResponseClass); + compositeResponse.setSuccessRopResponse(ropResponse); + } else { + ErrorResponse errorResponse = getXmlUnmarshaller().unmarshaller(content, ErrorResponse.class); + compositeResponse.setErrorResponse(errorResponse); + } + } + return compositeResponse; + } + + private boolean isSuccessful(String content) { + return !(content.contains(CommonConstant.ERROR_TOKEN)); + } + + private Map getRequestForm(Object ropRequest, String methodName, String version) throws IOException { + Map form = new LinkedHashMap(16); + //系统级参数 + form.put(DefaultRopClient.this.appKeyName, appKey); + form.put(DefaultRopClient.this.methodName, methodName); + form.put(DefaultRopClient.this.versionName, version); + form.put(DefaultRopClient.this.formatName, messageFormat.name()); + form.put(DefaultRopClient.this.localeName, locale.toString()); + if (sessionId != null) { + form.put(DefaultRopClient.this.sessionIdName, sessionId); + } + + //业务级参数 + form.putAll(getParamFields(ropRequest, messageFormat)); + + //对请求进行签名 + String signValue = sign(ropRequest.getClass(), form); + form.put(DefaultRopClient.this.signName, signValue); + return form; + } + + + /** + * 对请求参数进行签名 + * + * @param ropRequestClass + * @param appSecret + * @param form + * @return + */ + private String sign(Class ropRequestClass, Map form) { + List ignoreFieldNames = requestIgnoreSignFieldNames.get(ropRequestClass); + return DefaultRopClient.this.signHandler.sign(form, ignoreFieldNames); + } + + /** + * 获取ropRequest对应的参数名列表 + * + * @param ropRequest + * @param mf + * @return + * @throws IOException + */ + private Map getParamFields(Object ropRequest, MessageFormat mf) throws IOException { + if (!requestAllFields.containsKey(ropRequest.getClass())) { + parseRopRequestClass(ropRequest); + } + return toParamValueMap(ropRequest, mf); + } + + /** + * 获取ropRequest对象的对应的参数列表 + * + * @param ropRequest + * @param mf + * @return + * @throws IOException + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private Map toParamValueMap(Object ropRequest, MessageFormat mf) throws IOException { + List fields = requestAllFields.get(ropRequest.getClass()); + Map params = new HashMap(); + for (Field field : fields) { + RopConverter convertor = getConvertor(field.getType()); + Object fieldValue = ReflectionUtils.getField(field, ropRequest); + if (fieldValue != null) { + if (convertor != null) {//有对应转换器 + String strParamValue = (String) convertor.unconvert(fieldValue); + params.put(field.getName(), strParamValue); + } else if (!field.getType().isPrimitive()) { + String message = marshaller(fieldValue, mf); + params.put(field.getName(), message); + } else { + params.put(field.getName(), fieldValue.toString()); + } + } + } + return params; + } + + + private String marshaller(Object value, MessageFormat mf) throws IOException{ + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + String message; + if(MessageFormat.JSON == mf){ + getJsonMarshaller().marshaller(value, baos); + message = baos.toString("UTF-8"); + }else{ + getXmlMarshaller().marshaller(value, baos); + message = baos.toString("UTF-8"); + } + return message; + } + + private RopConverter getConvertor(Class fieldType) { + for (Map.Entry,RopConverter> entry : ropConverterMap.entrySet()) { + if (ClassUtils.isAssignable(entry.getKey(), fieldType)) { + return entry.getValue(); + } + } + return null; + } + + private void parseRopRequestClass(Object ropRequest) { + List allFields = ReflectionUtils.getFields(ropRequest.getClass()); + List ignoreSignFieldNames = ReflectionUtils.getIgnoreSignFieldNames(ropRequest.getClass()); + requestAllFields.put(ropRequest.getClass(), allFields); + requestIgnoreSignFieldNames.put(ropRequest.getClass(), ignoreSignFieldNames); + } + } +} + diff --git a/rop/src/main/java/com/rop/client/RopClient.java b/rop-client/src/main/java/com/rop/client/RopClient.java similarity index 53% rename from rop/src/main/java/com/rop/client/RopClient.java rename to rop-client/src/main/java/com/rop/client/RopClient.java index b7ea5c0..3b341df 100644 --- a/rop/src/main/java/com/rop/client/RopClient.java +++ b/rop-client/src/main/java/com/rop/client/RopClient.java @@ -1,100 +1,114 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-29 - */ -package com.rop.client; - -import com.rop.RopRequest; -import com.rop.request.RopConverter; - -import java.util.List; -import java.util.Map; - - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopClient { - - /** - * 添加自定义的转换器 - * - * @param ropConverter - */ - void addRopConvertor(RopConverter ropConverter); - - /** - * 设置method系统参数的参数名,下同 - * - * @param paramName - * @return - */ - RopClient setAppKeyParamName(String paramName); - - /** - * 设置sessionId的参数名 - * - * @param paramName - * @return - */ - RopClient setSessionIdParamName(String paramName); - - /** - * 设置method的参数名 - * - * @param paramName - * @return - */ - RopClient setMethodParamName(String paramName); - - /** - * 设置version的参数名 - * - * @param paramName - * @return - */ - RopClient setVersionParamName(String paramName); - - /** - * 设置format的参数名 - * - * @param paramName - * @return - */ - RopClient setFormatParamName(String paramName); - - /** - * 设置locale的参数名 - * - * @param paramName - * @return - */ - RopClient setLocaleParamName(String paramName); - - /** - * 设置sign的参数名 - * - * @param paramName - * @return - */ - RopClient setSignParamName(String paramName); - - /** - * 设置sessionId - * - * @param sessionId - */ - void setSessionId(String sessionId); - - /** - * 创建一个新的服务请求 - * @return - */ - ClientRequest buildClientRequest(); -} - +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import com.rop.converter.RopConverter; +import com.rop.sign.SignHandler; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopClient { + + /** + * 添加自定义的转换器 + * + * @param ropConverter + */ + void addRopConvertor(RopConverter ropConverter); + + /** + * 设置method系统参数的参数名,下同 + * + * @param paramName + * @return RopClient + */ + RopClient setAppKeyParamName(String paramName); + + /** + * 设置sessionId的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setSessionIdParamName(String paramName); + + /** + * 设置method的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setMethodParamName(String paramName); + + /** + * 设置version的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setVersionParamName(String paramName); + + /** + * 设置format的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setFormatParamName(String paramName); + + /** + * 设置locale的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setLocaleParamName(String paramName); + + /** + * 设置sign的参数名 + * + * @param paramName + * @return RopClient + */ + RopClient setSignParamName(String paramName); + + /** + * 设置sessionId + * + * @param sessionId + */ + void setSessionId(String sessionId); + + /** + * 设置签名处理接口对象 + * @param handler + * @return RopClient + */ + RopClient setSignHandler(SignHandler handler); + + /** + * 创建一个新的服务请求 + * @return + */ + ClientRequest buildClientRequest(); +} + diff --git a/rop-client/src/main/java/com/rop/client/http/HttpClient.java b/rop-client/src/main/java/com/rop/client/http/HttpClient.java new file mode 100644 index 0000000..e3b2419 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/HttpClient.java @@ -0,0 +1,110 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.io.IOException; +import java.util.Map; + +/** + * 简单的http请求客户端接口 + *

+ * @author liangruisen + * + */ +public interface HttpClient { + + /** + * 同步发送HTTP GET 请求 + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse get(String url) throws IOException; + + /** + * 同步发送HTTP GET 请求 + * @param heads + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse get(String url, Map params) throws IOException; + + /** + * 设置HTTP Header信息并同步发送HTTP GET 请求 + * @param heads + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse get(Map heads, String url) throws IOException; + + /** + * 设置HTTP Header信息并同步发送HTTP GET 请求 + * @param heads + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse get(Map heads, String url, Map params) throws IOException; + + /** + * 同步发送HTTP POST 请求 + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse post(String url) throws IOException; + + /** + * 设置HTTP Header信息并同步发送HTTP POST 请求 + * @param heads + * @param url + * @return SimpleResponse + * @throws IOException + */ + HttpResponse post(Map heads, String url) throws IOException; + + /** + * 同步发送HTTP POST 请求 + * @param url + * @param params + * @return SimpleResponse + * @throws IOException + */ + HttpResponse post(String url, Map params) throws IOException; + + /** + * 设置HTTP Header信息并同步发送HTTP POST 请求 + * @param heads + * @param url + * @param params + * @return SimpleResponse + * @throws IOException + */ + HttpResponse post(Map heads, String url, Map params) throws IOException; + + /** + * 设置HTTP Header信息并同步发送HTTP 请求 + * @param heads + * @param url + * @param method + * @param params + * @return SimpleResponse + * @throws IOException + */ + HttpResponse execute(Map heads, String url, String method, Map params) throws IOException; +} diff --git a/rop-client/src/main/java/com/rop/client/http/HttpRequest.java b/rop-client/src/main/java/com/rop/client/http/HttpRequest.java new file mode 100644 index 0000000..e32cd46 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/HttpRequest.java @@ -0,0 +1,67 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.net.URI; +import java.util.List; +import java.util.Map; + +/** + * 简单的HTTP请求接口,用于获取该次请求的信息 + * @author liangruisen + * + */ +public interface HttpRequest { + + /** + * 获取实现请求的Request对象 + * @return Object + */ + Object getRequest(); + + /** + * 获取该次请求的URI + * @return URI + */ + URI getURI(); + + /** + * 获取HTTP请求的方法名称, + * 返回 GET/POST/PUT/HEAD/OPTIONS/PATCH/DELETE/TRACE 中的一个 + * @return String + */ + String getMethod(); + + /** + * 获取指定名称的HTTP头信息的值 + * @param name + * @return String + */ + String getHeader(String name); + + /** + * 获取获取指定名称的HTTP头信息的值列表 + * @param name + * @return List + */ + List getHeaders(String name); + + /** + * 获取所有的HTTP头信息 + * @return Map> + */ + Map> getHeaders(); +} diff --git a/rop-client/src/main/java/com/rop/client/http/HttpResponse.java b/rop-client/src/main/java/com/rop/client/http/HttpResponse.java new file mode 100644 index 0000000..9b4d1d9 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/HttpResponse.java @@ -0,0 +1,107 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +/** + * 简单的HTTP请求返回结果接口,用于获取该次请求的结果信息 + * @author liangruisen + * + */ +public interface HttpResponse extends Closeable { + + /** + * 获取实现请求的Response对象 + * @return Object + */ + public Object getResponse(); + + /** + * 获取请求结果的内容字符串 + * @return String + * @throws IOException + */ + public String getString() throws IOException; + + /** + * 获取请求结果的内容字节数组 + * @return byte[] + * @throws IOException + */ + public byte[] getBytes() throws IOException; + + /** + * 获取请求结果的内容输入流 + * @return InputStream + * @throws IOException + */ + public InputStream getInputStream() throws IOException; + + /** + * 获取请求的HTTP返回状态代码 + * @return int + */ + public int getCode(); + + /** + * 获取实现请求的Request对象 + * @return Object + */ + public Object getRequest(); + + /** + * 获取请求的返回消息 + * @return String + */ + public String getMessage(); + + /** + * 获取HTTP请求的方法名称, + * 返回 GET/POST/PUT/HEAD/OPTIONS/PATCH/DELETE/TRACE 中的一个 + * @return String + */ + public String getHeader(String name); + + /** + * 获取指定名称的HTTP头信息的值 + * @param name + * @return String + */ + public List getHeaders(String name); + + /** + * 获取所有的HTTP头信息 + * @return Map> + */ + public Map> getHeaders(); + + /** + * 获取该次请求是否正确返回 + * @return boolean + */ + public boolean isSuccessful(); + + /** + * 获取协议的名称及其版本信息 + * @return String + */ + public String getProtocol(); +} diff --git a/rop-client/src/main/java/com/rop/client/http/JdkHttpClient.java b/rop-client/src/main/java/com/rop/client/http/JdkHttpClient.java new file mode 100644 index 0000000..34c1c40 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/JdkHttpClient.java @@ -0,0 +1,211 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + * 简单的http请求客户端接口jdk实现 + * + * @author liangruisen + * + */ +public class JdkHttpClient implements HttpClient { + + /** + * @see com.rop.client.http.HttpClient#get(java.lang.String) + */ + @Override + public HttpResponse get(String url) throws IOException { + return execute(null, url, "GET", null); + } + + /** + * @see com.rop.client.http.HttpClient#get(java.lang.String, java.util.Map) + */ + @Override + public HttpResponse get(String url, Map params) throws IOException { + return execute(null, url, "GET", params); + } + + /** + * @see com.rop.client.http.HttpClient#get(java.util.Map, + * java.lang.String) + */ + @Override + public HttpResponse get(Map heads, String url) throws IOException { + return execute(heads, url, "GET", null); + } + + /** + * @see com.rop.client.http.HttpClient#get(java.util.Map, java.lang.String, java.util.Map) + */ + @Override + public HttpResponse get(Map heads, String url, Map params) throws IOException { + return execute(heads, url, "GET", params); + } + + /** + * @see + * com.rop.client.http.HttpClient#post(java.lang.String) + */ + @Override + public HttpResponse post(String url) throws IOException { + return execute(null, url, "POST", null); + } + + /** + * @see com.rop.client.http.HttpClient#post(java.util.Map, + * java.lang.String) + */ + @Override + public HttpResponse post(Map heads, String url) throws IOException { + return execute(heads, url, "POST", null); + } + + /** + * @see + * com.rop.client.http.HttpClient#post(java.lang.String, + * java.util.Map) + */ + @Override + public HttpResponse post(String url, Map params) throws IOException { + return execute(null, url, "POST", params); + } + + /** + * @see com.rop.client.http.HttpClient#post(java.util.Map, + * java.lang.String, java.util.Map) + */ + @Override + public HttpResponse post(Map heads, String url, Map params) throws IOException { + return execute(heads, url, "POST", params); + } + + /** + * @see + * com.rop.client.http.HttpClient#execute(java.util.Map, + * java.lang.String, java.lang.String, java.util.Map) + */ + @Override + public HttpResponse execute(Map heads, String url, String method, Map params) + throws IOException { + JdkHttpRequest request = createRequest(heads, url, method.toUpperCase(Locale.US), params); + return execute(request); + } + + private JdkHttpResponse execute(JdkHttpRequest request) throws IOException { + HttpURLConnection connection = (HttpURLConnection) request.getUrl().openConnection(); + JdkHttpResponse response = new JdkHttpResponse(request, connection); + Map> headers = request.getHeaders(); + if (headers != null) { + for (Map.Entry> entry : headers.entrySet()) { + String name = entry.getKey(); + List list = entry.getValue(); + for (String value : list) { + connection.addRequestProperty(name, value); + } + } + } + connection.setReadTimeout(1000 * 30); + connection.setConnectTimeout(1000 * 10); + connection.setRequestMethod(request.getMethod()); + if (request.getBody() != null) { + connection.setDoOutput(true); + connection.setRequestProperty("Accept-Charset", "UTF-8"); + connection.setRequestProperty("Content-Type", request.getBody().getType()); + connection.setRequestProperty("Content-Length", String.valueOf(request.getBody().getContentSize())); + } + connection.connect(); + if (request.getBody() != null) { + request.getBody().writeTo(connection.getOutputStream()); + connection.getOutputStream().flush(); + connection.getOutputStream().close(); + } + return response; + } + + private JdkHttpRequest createRequest(Map heads, String url, String method, + Map params) throws IOException { + JdkHttpRequest request = new JdkHttpRequest(); + request.setMethod(method); + if (!isHasBodyMethod(method)) { + url = appendUrlParams(url, params); + } else { + request.setBody(parseParams(params)); + } + URL urlobj = new URL(url); + request.setUrl(urlobj); + addHeaders(request, heads); + return request; + } + + /** + * 在URL字符串后面拼接请求参数 + * @param urlstring + * @param params + * @return String + * @throws IOException + */ + public static String appendUrlParams(String urlstring, Map params) throws IOException { + if(params == null || params.isEmpty()){ + return urlstring; + } + StringBuilder buf = new StringBuilder(512); + for(Map.Entry entry : params.entrySet()){ + buf.append("&").append(entry.getKey()).append("="); + buf.append(URLEncoder.encode(entry.getValue(), "UTF-8")); + } + boolean hasParams = urlstring.indexOf("?") > 0; + if(!hasParams){ + buf.replace(0, 1, "?"); + } + buf.insert(0, urlstring); + return buf.toString(); + } + + private void addHeaders(JdkHttpRequest request, Map headers) { + if (headers == null || headers.isEmpty()) { + request.addHeader("Accept-Encoding", "gzip"); + return; + } + headers.put("Accept-Encoding", "gzip"); + for (Map.Entry entry : headers.entrySet()) { + request.addHeader(entry.getKey(), entry.getValue()); + } + } + + private JdkHttpRequestBody parseParams(Map params) throws IOException { + JdkHttpRequestBody body = new JdkHttpRequestBody(); + if (params == null || params.isEmpty()) { + return body; + } + for (Map.Entry entry : params.entrySet()) { + body.add(entry.getKey(), entry.getValue()); + } + return body; + } + + private boolean isHasBodyMethod(String method) { + return method.equals("POST") || method.equals("PATCH") || method.equals("PUT") || method.equals("DELETE"); + } +} diff --git a/rop-client/src/main/java/com/rop/client/http/JdkHttpRequest.java b/rop-client/src/main/java/com/rop/client/http/JdkHttpRequest.java new file mode 100644 index 0000000..15bf7ca --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/JdkHttpRequest.java @@ -0,0 +1,174 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; + +/** + * @author liangruisen + * + */ +public class JdkHttpRequest implements HttpRequest { + + private String method; + private URL url; + private Map> headers = new HashMap>(); + + private JdkHttpRequestBody body; + + /** + * @see com.rop.client.http.HttpRequest#getRequest() + */ + @Override + public Object getRequest() { + return this; + } + + /** + * @see com.rop.client.http.HttpRequest#getURI() + */ + @Override + public URI getURI() { + try { + return url.toURI(); + } catch (URISyntaxException e) { + } + return null; + } + + /** + * @see com.rop.client.http.HttpRequest#getMethod() + */ + @Override + public String getMethod() { + return method; + } + + /** + * @see com.rop.client.http.HttpRequest#getHeader(java.lang.String) + */ + @Override + public String getHeader(String name) { + List list = getHeaders(name); + if(list == null || list.isEmpty()){ + return ""; + } + return StringUtils.join(list, ";"); + } + + /** + * @see com.rop.client.http.HttpRequest#getHeaders(java.lang.String) + */ + @Override + public List getHeaders(String name) { + return headers.get(name); + } + + /** + * @see com.rop.client.http.HttpRequest#getHeaders() + */ + @Override + public Map> getHeaders() { + return headers; + } + + /** + * 设置http请求头信息 + * @param headers + */ + public void setHeaders(Map> headers){ + if(headers != null){ + this.headers.putAll(headers); + } + } + + /** + * 添加http请求头信息 + * @param name + * @param value + */ + public void addHeader(String name, String value){ + List list = headers.get(name); + if(list == null){ + list = new ArrayList(1); + headers.put(name, list); + } + list.add(value); + } + + /** + * 设置http请求头信息 + * @param name + * @param value + */ + public void setHeader(String name, String value){ + List list = headers.get(name); + if(list == null){ + list = new ArrayList(1); + headers.put(name, list); + }else{ + list.clear(); + } + list.add(value); + } + + /** + * 设置http请求方法 + */ + public void setMethod(String method) { + this.method = method; + } + + /** + * 获取http请求内容参数 + * @return JdkRequestBody + */ + public JdkHttpRequestBody getBody() { + return body; + } + + /** + * 设置http请求内容参数 + * @param body + */ + public void setBody(JdkHttpRequestBody body) { + this.body = body; + } + + /** + * 获取请求的链接 + * @return + */ + public URL getUrl() { + return url; + } + + /** + * 设置请求的链接 + * @param url + */ + public void setUrl(URL url) { + this.url = url; + } +} diff --git a/rop-client/src/main/java/com/rop/client/http/JdkHttpRequestBody.java b/rop-client/src/main/java/com/rop/client/http/JdkHttpRequestBody.java new file mode 100644 index 0000000..bcc8271 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/JdkHttpRequestBody.java @@ -0,0 +1,57 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URLEncoder; + +/** + * @author liangruisen + * + */ +public class JdkHttpRequestBody { + + private String type = "application/x-www-form-urlencoded"; + + private ByteArrayOutputStream content = new ByteArrayOutputStream(); + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public long getContentSize() { + return content.size(); + } + + public void writeTo(OutputStream out) throws IOException{ + content.writeTo(out); + } + + public void add(String name, String value) throws IOException{ + if(content.size() > 0){ + content.write('&'); + } + content.write(name.getBytes()); + content.write('='); + content.write(URLEncoder.encode(value, "UTF-8").getBytes()); + } +} diff --git a/rop-client/src/main/java/com/rop/client/http/JdkHttpResponse.java b/rop-client/src/main/java/com/rop/client/http/JdkHttpResponse.java new file mode 100644 index 0000000..7595204 --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/http/JdkHttpResponse.java @@ -0,0 +1,165 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.http; + +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; + +/** + * @author liangruisen + * + */ +public class JdkHttpResponse implements HttpResponse { + + public JdkHttpResponse(JdkHttpRequest request, + HttpURLConnection connection) { + super(); + this.request = request; + this.connection = connection; + } + + private JdkHttpRequest request; + + private HttpURLConnection connection; + + /** + * @see java.io.Closeable#close() + */ + @Override + public void close() throws IOException { + if(connection != null){ + connection.disconnect(); + } + } + + /** + * @see com.rop.client.http.HttpResponse#getResponse() + */ + @Override + public Object getResponse() { + return this; + } + + /** + * @see com.rop.client.http.HttpResponse#getString() + */ + @Override + public String getString() throws IOException { + return IOUtils.toString(getInputStream(), "UTF-8"); + } + + /** + * @see com.rop.client.http.HttpResponse#getBytes() + */ + @Override + public byte[] getBytes() throws IOException { + return IOUtils.toByteArray(getInputStream()); + } + + /** + * @see com.rop.client.http.HttpResponse#getInputStream() + */ + @Override + public InputStream getInputStream() throws IOException { + String contentEncoding = connection.getContentEncoding(); + if(StringUtils.isNotBlank(contentEncoding) && contentEncoding.toLowerCase(Locale.US).indexOf("gzip") >= 0){ + return new GZIPInputStream(connection.getInputStream()); + } + return connection.getInputStream(); + } + + /** + * @see com.rop.client.http.HttpResponse#getCode() + */ + @Override + public int getCode() { + try { + return connection.getResponseCode(); + } catch (IOException e) { + } + return -1; + } + + /** + * @see com.rop.client.http.HttpResponse#getRequest() + */ + @Override + public Object getRequest() { + return request; + } + + /** + * @see com.rop.client.http.HttpResponse#getMessage() + */ + @Override + public String getMessage() { + try { + return connection.getResponseMessage(); + } catch (IOException e) { + } + return ""; + } + + /** + * @see com.rop.client.http.HttpResponse#getHeader(java.lang.String) + */ + @Override + public String getHeader(String name) { + return connection.getHeaderField(name); + } + + /** + * @see com.rop.client.http.HttpResponse#getHeaders(java.lang.String) + */ + @Override + public List getHeaders(String name) { + return getHeaders().get(name); + } + + /** + * @see com.rop.client.http.HttpResponse#getHeaders() + */ + @Override + public Map> getHeaders() { + return connection.getHeaderFields(); + } + + /** + * @see com.rop.client.http.HttpResponse#isSuccessful() + */ + @Override + public boolean isSuccessful() { + int code = getCode(); + return code >= 200 && code < 300; + } + + /** + * @see com.rop.client.http.HttpResponse#getProtocol() + */ + @Override + public String getProtocol() { + return request.getUrl().getProtocol(); + } + +} diff --git a/rop-client/src/main/java/com/rop/client/sign/DigestSignHandler.java b/rop-client/src/main/java/com/rop/client/sign/DigestSignHandler.java new file mode 100644 index 0000000..f80e39d --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/sign/DigestSignHandler.java @@ -0,0 +1,136 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.sign; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Collection; +import java.util.Map; + +import com.rop.RopException; +import com.rop.sign.SignHandler; +import com.rop.utils.RopUtils; + +/** + * 消息摘要数字签名处理实现 + * @author liangruisen + */ +public class DigestSignHandler implements SignHandler { + + public DigestSignHandler() { + super(); + } + + public DigestSignHandler(String algorithm, String secret) { + super(); + this.algorithm = algorithm; + this.secret = secret; + } + + protected String secret; + + protected String algorithm = "SHA-1"; + + /** + * 产生签名 + * @see com.rop.sign.SignHandler#sign(java.util.Map) + */ + @Override + public String sign(Map paramMap) { + return sign(paramMap, null); + } + + /** + * 产生签名 + * @see com.rop.sign.SignHandler#sign(java.util.Map, java.util.Collection) + */ + @Override + public String sign(Map paramValues, Collection ignore) { + try { + StringBuilder sb = new StringBuilder(); + sb.append(secret); + sb.append(RopUtils.getSignContent(paramValues, ignore)); + sb.append(secret); + byte[] sha1Digest = getDigest(sb.toString()); + return byte2hex(sha1Digest); + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 检查签名是否正确 + * @see com.rop.sign.SignHandler#signCheck(java.lang.String, java.util.Map, java.util.Collection) + */ + @Override + public boolean signCheck(String sign, Map paramMap, Collection ignore) { + String signValue = sign(paramMap, ignore); + return signValue.equals(sign); + } + + /** + * 检查签名是否正确 + * @see com.rop.sign.SignHandler#signCheck(java.lang.String, java.util.Map) + */ + @Override + public boolean signCheck(String sign, Map paramMap) { + return signCheck(sign, paramMap, null); + } + + /** + * 获取消息的摘要 + * @param data + * @return + * @throws IOException + */ + protected byte[] getDigest(String data) throws IOException { + byte[] bytes = null; + try { + MessageDigest md = MessageDigest.getInstance(algorithm); + bytes = md.digest(data.getBytes()); + } catch (GeneralSecurityException gse) { + throw new IOException(gse.getMessage()); + } + return bytes; + } + + /** + * 二进制转十六进制字符串 + * + * @param bytes + * @return + */ + protected String byte2hex(byte[] bytes) { + StringBuilder sign = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(bytes[i] & 0xFF); + if (hex.length() == 1) { + sign.append("0"); + } + sign.append(hex.toUpperCase()); + } + return sign.toString(); + } + + public void setSecret(String secret) { + this.secret = secret; + } + + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } +} diff --git a/rop-client/src/main/java/com/rop/client/sign/HmacDigestSignHandler.java b/rop-client/src/main/java/com/rop/client/sign/HmacDigestSignHandler.java new file mode 100644 index 0000000..e36630f --- /dev/null +++ b/rop-client/src/main/java/com/rop/client/sign/HmacDigestSignHandler.java @@ -0,0 +1,81 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client.sign; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Collection; +import java.util.Map; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import com.rop.RopException; +import com.rop.utils.RopUtils; + +/** + * hmac消息摘要数字签名处理实现 + * @author liangruisen + * + */ +public class HmacDigestSignHandler extends DigestSignHandler { + + public HmacDigestSignHandler() { + super("HmacSHA1", null); + } + + public HmacDigestSignHandler(String secret) { + super("HmacSHA1", secret); + } + + public HmacDigestSignHandler(String algorithm, String secret) { + super(algorithm, secret); + } + + /** + * 产生签名 + * @see com.rop.client.sign.DigestSignHandler#sign(java.util.Map, java.util.Collection) + */ + @Override + public String sign(Map paramValues, Collection ignore) { + try { + String signContent = RopUtils.getSignContent(paramValues, ignore); + byte[] sha1Digest = getDigest(signContent); + return byte2hex(sha1Digest); + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 获取消息摘要 + * @param data + * @return + */ + protected byte[] getDigest(String data) throws IOException { + byte[] bytes = null; + try { + SecretKey secretKey = new SecretKeySpec(secret.getBytes(), algorithm); + Mac mac = Mac.getInstance(secretKey.getAlgorithm()); + mac.init(secretKey); + bytes = mac.doFinal(data.getBytes()); + } catch (GeneralSecurityException gse) { + throw new IOException(gse.toString()); + } + return bytes; + } +} diff --git a/rop-client/src/test/java/com/rop/client/DefaultRopClientTest.java b/rop-client/src/test/java/com/rop/client/DefaultRopClientTest.java new file mode 100644 index 0000000..224f803 --- /dev/null +++ b/rop-client/src/test/java/com/rop/client/DefaultRopClientTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.client; + +import org.junit.Test; + +import com.rop.client.sign.DigestSignHandler; +import com.rop.response.CommonRopResponse; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultRopClientTest { + + private RopClient ropClient = new DefaultRopClient("http://localhost:8088/router", "00001"); + + @Test + public void testPostWithSession() throws Exception { + ropClient.setSignHandler(new DigestSignHandler("SHA-1", "abcdeabcdeabcdeabcdeabcde")); + ClientRequest request = ropClient.buildClientRequest(); + CompositeResponse response = request.get(CommonRopResponse.class, "logout", "1.0"); + response.isSuccessful(); + } +} + diff --git a/rop-core/.gitignore b/rop-core/.gitignore new file mode 100644 index 0000000..f675857 --- /dev/null +++ b/rop-core/.gitignore @@ -0,0 +1,2 @@ +/target/ +/.settings/ \ No newline at end of file diff --git a/rop-core/pom.xml b/rop-core/pom.xml new file mode 100644 index 0000000..c0913a6 --- /dev/null +++ b/rop-core/pom.xml @@ -0,0 +1,149 @@ + + + 4.0.0 + + + com.rop + rop-parent + 2.0-SNAPSHOT + + + rop-core + rop core api + jar + rest open platform + + http://www.github.com + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git@github.com:itstamen/rop.git + scm:git:git@github.com:itstamen/rop.git + git@github.com:itstamen/rop.git + + + + + stamen + stamen + itstamen@qq.com + + + + + + junit + junit + ${junit.version} + test + + + org.slf4j + slf4j-api + ${slf4j.version} + + + commons-lang + commons-lang + ${commonslang.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + test + + + commons-io + commons-io + ${commonsio.version} + + + commons-codec + commons-codec + ${commonscodec.version} + + + com.alibaba + fastjson + ${fastjson.version} + test + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + ${file.encoding} + ${file.encoding} + ${file.encoding} + + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${file.encoding} + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${file.encoding} + + + + + + + UTF-8 + 1.6 + 2.4.4 + 1.6.1 + 2.4 + 2.4 + 1.9 + 4.12 + 1.2.4 + + \ No newline at end of file diff --git a/rop-core/src/main/java/com/rop/CommonConstant.java b/rop-core/src/main/java/com/rop/CommonConstant.java new file mode 100644 index 0000000..c5401b2 --- /dev/null +++ b/rop-core/src/main/java/com/rop/CommonConstant.java @@ -0,0 +1,31 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 13-11-1 + */ +public class CommonConstant { + + private CommonConstant(){ + super(); + } + + public static final String ERROR_TOKEN = "@@$-ERROR_TOKEN$-@@"; + + public static final String SESSION_CHANGED = "@@SESSION_CHANGED__"; +} diff --git a/rop-core/src/main/java/com/rop/MessageFormat.java b/rop-core/src/main/java/com/rop/MessageFormat.java new file mode 100644 index 0000000..c48dc82 --- /dev/null +++ b/rop-core/src/main/java/com/rop/MessageFormat.java @@ -0,0 +1,55 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.LoggerFactory; + +/** + * 支持的响应的格式类型 + */ +public enum MessageFormat { + + XML, JSON, STREAM; + + public static MessageFormat getFormat(String value) { + if (StringUtils.isBlank(value)) { + return XML; + } else { + try { + return MessageFormat.valueOf(value.toUpperCase()); + } catch (IllegalArgumentException e) { + LoggerFactory.getLogger(MessageFormat.class).debug(e.getMessage(), e); + return XML; + } + } + } + + public static boolean isValidFormat(String value) { + if (StringUtils.isBlank(value)) { + return true; + }else{ + try { + MessageFormat.valueOf(value.toUpperCase()); + return true; + } catch (IllegalArgumentException e) { + LoggerFactory.getLogger(MessageFormat.class).debug(e.getMessage(), e); + return false; + } + } + } + +} diff --git a/rop-core/src/main/java/com/rop/RopException.java b/rop-core/src/main/java/com/rop/RopException.java new file mode 100644 index 0000000..2e2eb51 --- /dev/null +++ b/rop-core/src/main/java/com/rop/RopException.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *   ROP的异常。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopException extends RuntimeException { + private static final long serialVersionUID = -5980800274047243722L; + + public RopException() { + } + + public RopException(String message) { + super(message); + } + + public RopException(String message, Throwable cause) { + super(message, cause); + } + + public RopException(Throwable cause) { + super(cause); + } +} + diff --git a/rop-core/src/main/java/com/rop/RopMarshaller.java b/rop-core/src/main/java/com/rop/RopMarshaller.java new file mode 100644 index 0000000..6795b92 --- /dev/null +++ b/rop-core/src/main/java/com/rop/RopMarshaller.java @@ -0,0 +1,32 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import java.io.IOException; +import java.io.OutputStream; + +/** + *
+ *   负责将请求方法返回的响应对应流化为相应格式的内容。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopMarshaller { + void marshaller(Object object, OutputStream outputStream) throws IOException; +} + diff --git a/rop-core/src/main/java/com/rop/RopUnmarshaller.java b/rop-core/src/main/java/com/rop/RopUnmarshaller.java new file mode 100644 index 0000000..b949df0 --- /dev/null +++ b/rop-core/src/main/java/com/rop/RopUnmarshaller.java @@ -0,0 +1,38 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *   对响应进行反流化
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopUnmarshaller { + + /** + * 将字符串反序列化为相应的对象 + * + * @param content + * @param objectType + * @param + * @return + */ + T unmarshaller(String content, Class objectType); +} + diff --git a/rop-core/src/main/java/com/rop/annotation/IgnoreSign.java b/rop-core/src/main/java/com/rop/annotation/IgnoreSign.java new file mode 100644 index 0000000..d1cb230 --- /dev/null +++ b/rop-core/src/main/java/com/rop/annotation/IgnoreSign.java @@ -0,0 +1,34 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + + +import java.lang.annotation.*; + +/** + *
+ *     如果标注在请求类的属性上,则表示该属性无需进行签名,如下所示:
+ * 请求对象({@link com.rop.RopRequest})中不需要签名校验的属性(默认都要签名)。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@Target({ElementType.FIELD,ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface IgnoreSign { +} diff --git a/rop-core/src/main/java/com/rop/annotation/IgnoreSignType.java b/rop-core/src/main/java/com/rop/annotation/IgnoreSignType.java new file mode 100644 index 0000000..fc51c32 --- /dev/null +++ b/rop-core/src/main/java/com/rop/annotation/IgnoreSignType.java @@ -0,0 +1,38 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +/** + *
+ *    是否需求进行签名校验.{@link #DEFAULT}是系统预留的,请不要在实际中使用
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum IgnoreSignType { + + YES, NO, DEFAULT; + + public static boolean isIgnoreSign(IgnoreSignType type) { + if (NO == type || DEFAULT == type) { + return false; + } else { + return true; + } + } +} + diff --git a/rop/src/main/java/com/rop/annotation/Temporary.java b/rop-core/src/main/java/com/rop/annotation/Temporary.java similarity index 50% rename from rop/src/main/java/com/rop/annotation/Temporary.java rename to rop-core/src/main/java/com/rop/annotation/Temporary.java index f5f8cb9..af1d883 100644 --- a/rop/src/main/java/com/rop/annotation/Temporary.java +++ b/rop-core/src/main/java/com/rop/annotation/Temporary.java @@ -1,29 +1,40 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.annotation; - -import java.lang.annotation.*; - -/** - * 默认情况下,请求对象的所有field都会作为请求参数提交,如果希望某个field不作为参数提交,可以打上{@Temporary}注解,如下所示: - *
- * 
  public class MyRopRequest implements RopRequest{ - *
 
- *
  private String field1;
- *
 
- *
  @Temporary
- *
  private String field2;
 } - *
- * - * @author 陈雄华 - * @version 1.0 - */ -@Target({ElementType.FIELD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface Temporary { - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +import java.lang.annotation.*; + +/** + * 默认情况下,请求对象的所有field都会作为请求参数提交,如果希望某个field不作为参数提交,可以打上{@Temporary}注解,如下所示: + *
+ * 
  public class MyRopRequest implements RopRequest{ + *
 
+ *
  private String field1;
+ *
 
+ *
  @Temporary
+ *
  private String field2;
 } + *
+ * + * @author 陈雄华 + * @version 1.0 + */ +@Target({ElementType.FIELD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Temporary { + +} + diff --git a/rop/src/main/java/com/rop/config/SystemParameterNames.java b/rop-core/src/main/java/com/rop/config/SystemParameterNames.java similarity index 69% rename from rop/src/main/java/com/rop/config/SystemParameterNames.java rename to rop-core/src/main/java/com/rop/config/SystemParameterNames.java index 043bb6c..94178b5 100644 --- a/rop/src/main/java/com/rop/config/SystemParameterNames.java +++ b/rop-core/src/main/java/com/rop/config/SystemParameterNames.java @@ -1,119 +1,143 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.config; - -/** - *
- *   系统级参数的名称
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SystemParameterNames { - - private static final String JSONP = "callback"; - - //方法的默认参数名 - private static final String METHOD = "method"; - - //格式化默认参数名 - private static final String FORMAT = "format"; - - //本地化默认参数名 - private static final String LOCALE = "locale"; - - //会话id默认参数名 - private static final String SESSION_ID = "sessionId"; - - //应用键的默认参数名 ; - private static final String APP_KEY = "appKey"; - - //服务版本号的默认参数名 - private static final String VERSION = "v"; - - //签名的默认参数名 - private static final String SIGN = "sign"; - - private static String method = METHOD; - - private static String format = FORMAT; - - private static String locale = LOCALE; - private static String sessionId = SESSION_ID; - - private static String appKey = APP_KEY; - - private static String version = VERSION; - - private static String sign = SIGN; - - private static String jsonp = JSONP; - - public static String getMethod() { - return method; - } - - public static void setMethod(String method) { - SystemParameterNames.method = method; - } - - public static String getFormat() { - return format; - } - - public static void setFormat(String format) { - SystemParameterNames.format = format; - } - - public static String getLocale() { - return locale; - } - - public static void setLocale(String locale) { - SystemParameterNames.locale = locale; - } - - public static String getSessionId() { - return sessionId; - } - - public static void setSessionId(String sessionId) { - SystemParameterNames.sessionId = sessionId; - } - - public static String getAppKey() { - return appKey; - } - - public static void setAppKey(String appKey) { - SystemParameterNames.appKey = appKey; - } - - public static String getVersion() { - return version; - } - - public static void setVersion(String version) { - SystemParameterNames.version = version; - } - - public static String getSign() { - return sign; - } - - public static void setSign(String sign) { - SystemParameterNames.sign = sign; - } - - public static String getJsonp() { - return jsonp; - } - - public static void setJsonp(String jsonp) { - SystemParameterNames.jsonp = jsonp; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import java.util.List; + +/** + *
+ *   系统级参数的名称
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SystemParameterNames { + + private static final String JSONP = "callback"; + + //方法的默认参数名 + private static final String METHOD = "method"; + + //格式化默认参数名 + private static final String FORMAT = "format"; + + //本地化默认参数名 + private static final String LOCALE = "locale"; + + //会话id默认参数名 + private static final String SESSION_ID = "sessionId"; + + //应用键的默认参数名 ; + private static final String APP_KEY = "appKey"; + + //服务版本号的默认参数名 + private static final String VERSION = "v"; + + //签名的默认参数名 + private static final String SIGN = "sign"; + + private static String method = METHOD; + + private static String format = FORMAT; + + private static String locale = LOCALE; + private static String sessionId = SESSION_ID; + + private static String appKey = APP_KEY; + + private static String version = VERSION; + + private static String sign = SIGN; + + private static String jsonp = JSONP; + + //默认忽略签名的参数列表 + private static List ignoreSignFieldNames; + + public static String getMethod() { + return method; + } + + public static void setMethod(String method) { + SystemParameterNames.method = method; + } + + public static String getFormat() { + return format; + } + + public static void setFormat(String format) { + SystemParameterNames.format = format; + } + + public static String getLocale() { + return locale; + } + + public static void setLocale(String locale) { + SystemParameterNames.locale = locale; + } + + public static String getSessionId() { + return sessionId; + } + + public static void setSessionId(String sessionId) { + SystemParameterNames.sessionId = sessionId; + } + + public static String getAppKey() { + return appKey; + } + + public static void setAppKey(String appKey) { + SystemParameterNames.appKey = appKey; + } + + public static String getVersion() { + return version; + } + + public static void setVersion(String version) { + SystemParameterNames.version = version; + } + + public static String getSign() { + return sign; + } + + public static void setSign(String sign) { + SystemParameterNames.sign = sign; + } + + public static String getJsonp() { + return jsonp; + } + + public static void setJsonp(String jsonp) { + SystemParameterNames.jsonp = jsonp; + } + + public static List getIgnoreSignFieldNames() { + return ignoreSignFieldNames; + } + + public static void setIgnoreSignFieldNames(List ignoreSignFieldNames) { + SystemParameterNames.ignoreSignFieldNames = ignoreSignFieldNames; + } +} + diff --git a/rop-core/src/main/java/com/rop/converter/IllegalUploadFileFormatException.java b/rop-core/src/main/java/com/rop/converter/IllegalUploadFileFormatException.java new file mode 100644 index 0000000..cc5414c --- /dev/null +++ b/rop-core/src/main/java/com/rop/converter/IllegalUploadFileFormatException.java @@ -0,0 +1,46 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +/** + *
+ *    上传文件字符串转换时发生错误
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class IllegalUploadFileFormatException extends IllegalArgumentException { + + private static final long serialVersionUID = 1L; + + public IllegalUploadFileFormatException() { + super(); + } + + public IllegalUploadFileFormatException(String s) { + super(s); + } + + public IllegalUploadFileFormatException(String message, Throwable cause) { + super(message, cause); + } + + public IllegalUploadFileFormatException(Throwable cause) { + super(cause); + } +} + diff --git a/rop-core/src/main/java/com/rop/converter/RopConverter.java b/rop-core/src/main/java/com/rop/converter/RopConverter.java new file mode 100644 index 0000000..152364b --- /dev/null +++ b/rop-core/src/main/java/com/rop/converter/RopConverter.java @@ -0,0 +1,54 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopConverter { + + /** + * 将S类型转换成T类型 + * @param source + * @return T + */ + T convert(S source); + + /** + * 将T类型转换成S类型 + * @param paramValue + * @return S + */ + S unconvert(T paramValue); + + /** + * 获取源类型 + * @return Class + */ + Class getSourceClass(); + + /** + * 获取目标类型 + * @return Class + */ + Class getTargetClass(); +} + diff --git a/rop/src/main/java/com/rop/request/UploadFile.java b/rop-core/src/main/java/com/rop/converter/UploadFile.java similarity index 52% rename from rop/src/main/java/com/rop/request/UploadFile.java rename to rop-core/src/main/java/com/rop/converter/UploadFile.java index 359e7c5..d2e0a95 100644 --- a/rop/src/main/java/com/rop/request/UploadFile.java +++ b/rop-core/src/main/java/com/rop/converter/UploadFile.java @@ -1,60 +1,72 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.request; - -import com.rop.annotation.IgnoreSign; -import org.springframework.util.FileCopyUtils; - -import java.io.File; -import java.io.IOException; - -/** - *
- *    上传的文件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@IgnoreSign -public class UploadFile { - - private String fileType; - - private byte[] content; - - /** - * 根据文件内容构造 - * - * @param content - */ - public UploadFile(String fileType, byte[] content) { - this.content = content; - this.fileType = fileType; - } - - /** - * 根据文件构造 - * @param file - */ - public UploadFile(File file) { - try { - this.content = FileCopyUtils.copyToByteArray(file); - this.fileType = file.getName().substring(file.getName().lastIndexOf('.')+1); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public String getFileType() { - return fileType; - } - - public byte[] getContent() { - return content; - } -} - - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +import com.rop.annotation.IgnoreSign; + +import java.io.File; +import java.io.IOException; + +import org.apache.commons.io.FileUtils; + +/** + *
+ *    上传的文件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@IgnoreSign +public class UploadFile { + + private String fileType; + + private byte[] content; + + /** + * 根据文件内容构造 + * + * @param content + */ + public UploadFile(String fileType, byte[] content) { + this.content = content; + this.fileType = fileType; + } + + /** + * 根据文件构造 + * @param file + */ + public UploadFile(File file) { + try { + this.content = FileUtils.readFileToByteArray(file); + this.fileType = file.getName().substring(file.getName().lastIndexOf('.')+1); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public String getFileType() { + return fileType; + } + + public byte[] getContent() { + return content; + } +} + + diff --git a/rop-core/src/main/java/com/rop/converter/UploadFileConverter.java b/rop-core/src/main/java/com/rop/converter/UploadFileConverter.java new file mode 100644 index 0000000..cd4ef7f --- /dev/null +++ b/rop-core/src/main/java/com/rop/converter/UploadFileConverter.java @@ -0,0 +1,50 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +/** + *
+ *   将以BASE64位编码字符串转换为字节数组的{@link UploadFile}对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UploadFileConverter implements RopConverter { + + + public UploadFile convert(String source) { + String fileType = UploadFileUtils.getFileType(source); + byte[] contentBytes = UploadFileUtils.decode(source); + return new UploadFile(fileType, contentBytes); + } + + + public String unconvert(UploadFile target) { + return UploadFileUtils.encode(target); + } + + + public Class getSourceClass() { + return String.class; + } + + + public Class getTargetClass() { + return UploadFile.class; + } +} + diff --git a/rop/src/main/java/com/rop/request/UploadFileUtils.java b/rop-core/src/main/java/com/rop/converter/UploadFileUtils.java similarity index 72% rename from rop/src/main/java/com/rop/request/UploadFileUtils.java rename to rop-core/src/main/java/com/rop/converter/UploadFileUtils.java index 9c0466e..c0e0e72 100644 --- a/rop/src/main/java/com/rop/request/UploadFileUtils.java +++ b/rop-core/src/main/java/com/rop/converter/UploadFileUtils.java @@ -1,77 +1,88 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-3 - */ -package com.rop.request; - -import org.apache.commons.codec.binary.Base64; - -/** - *
- *     Rop的上传文件编码格式为:
- *   fileType@BASE64编码的文件内容
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class UploadFileUtils { - - public static final char SPERATOR = '@'; - - /** - * 获取文件的类型 - * - * @param encodeFile - * @return - */ - public static final String getFileType(String encodeFile) { - int speratorIndex = encodeFile.indexOf(SPERATOR); - if (speratorIndex > -1) { - String fileType = encodeFile.substring(0, speratorIndex); - return fileType.toLowerCase(); - } else { - throw new IllegalUploadFileFormatException("文件格式不对,正确格式为:<文件格式>@<文件内容>"); - } - } - - /** - * 获取文件的字节数组 - * - * @param encodeFile - * @return - */ - public static final byte[] decode(String encodeFile) { - int speratorIndex = encodeFile.indexOf(SPERATOR); - if (speratorIndex > -1) { - String content = encodeFile.substring(speratorIndex + 1); - return Base64.decodeBase64(content); - } else { - throw new IllegalUploadFileFormatException("文件格式不对,正确格式为:<文件格式>@<文件内容>"); - } - } - - /** - * 将文件编码为BASE64的字符串 - * - * @param bytes - * @return - */ - public static final String encode(byte[] bytes) { - return Base64.encodeBase64String(bytes); - } - - /** - * 将文件编码为一个字符串 - * @param uploadFile - * @return - */ - public static final String encode(UploadFile uploadFile){ - StringBuilder sb = new StringBuilder(); - sb.append(uploadFile.getFileType()); - sb.append(SPERATOR); - sb.append(encode(uploadFile.getContent())); - return sb.toString(); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +import org.apache.commons.codec.binary.Base64; + +/** + *
+ *     Rop的上传文件编码格式为:
+ *   fileType@BASE64编码的文件内容
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UploadFileUtils { + + public static final char SPERATOR = '@'; + + /** + * 获取文件的类型 + * + * @param encodeFile + * @return + */ + public static final String getFileType(String encodeFile) { + int speratorIndex = encodeFile.indexOf(SPERATOR); + if (speratorIndex > -1) { + String fileType = encodeFile.substring(0, speratorIndex); + return fileType.toLowerCase(); + } else { + throw new IllegalUploadFileFormatException("文件格式不对,正确格式为:<文件格式>@<文件内容>"); + } + } + + /** + * 获取文件的字节数组 + * + * @param encodeFile + * @return + */ + public static final byte[] decode(String encodeFile) { + int speratorIndex = encodeFile.indexOf(SPERATOR); + if (speratorIndex > -1) { + String content = encodeFile.substring(speratorIndex + 1); + return Base64.decodeBase64(content); + } else { + throw new IllegalUploadFileFormatException("文件格式不对,正确格式为:<文件格式>@<文件内容>"); + } + } + + /** + * 将文件编码为BASE64的字符串 + * + * @param bytes + * @return + */ + public static final String encode(byte[] bytes) { + return Base64.encodeBase64String(bytes); + } + + /** + * 将文件编码为一个字符串 + * @param uploadFile + * @return + */ + public static final String encode(UploadFile uploadFile){ + StringBuilder sb = new StringBuilder(); + sb.append(uploadFile.getFileType()); + sb.append(SPERATOR); + sb.append(encode(uploadFile.getContent())); + return sb.toString(); + } +} + diff --git a/rop-core/src/main/java/com/rop/marshaller/FastjsonRopMarshaller.java b/rop-core/src/main/java/com/rop/marshaller/FastjsonRopMarshaller.java new file mode 100644 index 0000000..1ed7819 --- /dev/null +++ b/rop-core/src/main/java/com/rop/marshaller/FastjsonRopMarshaller.java @@ -0,0 +1,32 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import java.io.IOException; +import java.io.OutputStream; + +import com.alibaba.fastjson.JSON; +import com.rop.RopMarshaller; + +/** + * 使用fastjson进行json数据转换 + */ +public class FastjsonRopMarshaller implements RopMarshaller { + + public void marshaller(Object object, OutputStream outputStream) throws IOException { + outputStream.write(JSON.toJSONBytes(object)); + } +} diff --git a/rop-core/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java b/rop-core/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java new file mode 100644 index 0000000..61984c1 --- /dev/null +++ b/rop-core/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java @@ -0,0 +1,55 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import com.fasterxml.jackson.core.JsonEncoding; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rop.RopMarshaller; +import com.rop.utils.ObjectMapperUtils; + +import java.io.IOException; +import java.io.OutputStream; + +/** + *
+ *    将响应对象流化成JSON。 {@link ObjectMapper}是线程安全的。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class JacksonJsonRopMarshaller implements RopMarshaller { + + private ObjectMapper objectMapper; + + public void marshaller(Object object, OutputStream outputStream) throws IOException { + JsonGenerator jsonGenerator = getObjectMapper().getFactory().createGenerator(outputStream, JsonEncoding.UTF8); + getObjectMapper().writeValue(jsonGenerator, object); + } + + public void setObjectMapper(ObjectMapper objectMapper){ + this.objectMapper = objectMapper; + } + + private ObjectMapper getObjectMapper() throws IOException { + if (objectMapper == null) { + objectMapper = ObjectMapperUtils.getObjectMapper(); + } + return objectMapper; + } +} + diff --git a/rop/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java b/rop-core/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java similarity index 65% rename from rop/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java rename to rop-core/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java index 9d6db3c..338866b 100644 --- a/rop/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java +++ b/rop-core/src/main/java/com/rop/marshaller/JaxbXmlRopMarshaller.java @@ -1,52 +1,63 @@ -/** - * - * 日 期:12-2-27 - */ -package com.rop.marshaller; - -import com.rop.RopException; -import com.rop.RopMarshaller; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import java.io.OutputStream; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - *
- *    将对象流化成XML,每个类型对应一个{@link JAXBContext},{@link JAXBContext} 是线程安全的,但是
- * {@link Marshaller}是非线程安全的,因此需要每次创建一个。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class JaxbXmlRopMarshaller implements RopMarshaller { - - private static Map jaxbContextHashMap = new ConcurrentHashMap(); - - public void marshaller(Object object, OutputStream outputStream) { - try { - Marshaller m = buildMarshaller(object.getClass()); - m.marshal(object, outputStream); - } catch (JAXBException e) { - throw new RopException(e); - } - } - - - private Marshaller buildMarshaller(Class objectType) throws JAXBException { - if (!jaxbContextHashMap.containsKey(objectType)) { - JAXBContext context = JAXBContext.newInstance(objectType); - jaxbContextHashMap.put(objectType, context); - } - JAXBContext context = jaxbContextHashMap.get(objectType); - Marshaller marshaller = context.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); - return marshaller; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import com.rop.RopException; +import com.rop.RopMarshaller; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import java.io.OutputStream; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + *
+ *    将对象流化成XML,每个类型对应一个{@link JAXBContext},{@link JAXBContext} 是线程安全的,但是
+ * {@link Marshaller}是非线程安全的,因此需要每次创建一个。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class JaxbXmlRopMarshaller implements RopMarshaller { + + private static Map, JAXBContext> jaxbContextHashMap = new ConcurrentHashMap, JAXBContext>(); + + public void marshaller(Object object, OutputStream outputStream) { + try { + Marshaller m = buildMarshaller(object.getClass()); + m.marshal(object, outputStream); + } catch (JAXBException e) { + throw new RopException(e); + } + } + + + private Marshaller buildMarshaller(Class objectType) throws JAXBException { + if (!jaxbContextHashMap.containsKey(objectType)) { + JAXBContext context = JAXBContext.newInstance(objectType); + jaxbContextHashMap.put(objectType, context); + } + JAXBContext context = jaxbContextHashMap.get(objectType); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); + return marshaller; + } +} + diff --git a/rop/src/main/java/com/rop/response/CommonRopResponse.java b/rop-core/src/main/java/com/rop/response/CommonRopResponse.java similarity index 56% rename from rop/src/main/java/com/rop/response/CommonRopResponse.java rename to rop-core/src/main/java/com/rop/response/CommonRopResponse.java index e5256b9..3490347 100644 --- a/rop/src/main/java/com/rop/response/CommonRopResponse.java +++ b/rop-core/src/main/java/com/rop/response/CommonRopResponse.java @@ -1,42 +1,53 @@ -/** - * - * 日 期:12-2-22 - */ -package com.rop.response; - - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- *    通用的响应对象
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "response") -public class CommonRopResponse{ - - @XmlAttribute - private boolean successful = false; - - public static final CommonRopResponse SUCCESSFUL_RESPONSE = new CommonRopResponse(true); - public static final CommonRopResponse FAILURE_RESPONSE = new CommonRopResponse(false); - - public CommonRopResponse() { - } - - private CommonRopResponse(boolean successful) { - this.successful = successful; - } - - public boolean isSuccessful() { - return successful; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ *    通用的响应对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "response") +public class CommonRopResponse{ + + @XmlAttribute + private boolean successful = false; + + public static final CommonRopResponse SUCCESSFUL_RESPONSE = new CommonRopResponse(true); + public static final CommonRopResponse FAILURE_RESPONSE = new CommonRopResponse(false); + + public CommonRopResponse() { + } + + private CommonRopResponse(boolean successful) { + this.successful = successful; + } + + public boolean isSuccessful() { + return successful; + } +} + diff --git a/rop/src/main/java/com/rop/response/ErrorResponse.java b/rop-core/src/main/java/com/rop/response/ErrorResponse.java similarity index 74% rename from rop/src/main/java/com/rop/response/ErrorResponse.java rename to rop-core/src/main/java/com/rop/response/ErrorResponse.java index ed46a9a..7771e53 100644 --- a/rop/src/main/java/com/rop/response/ErrorResponse.java +++ b/rop-core/src/main/java/com/rop/response/ErrorResponse.java @@ -1,127 +1,128 @@ -/** - * - * 日 期:12-2-10 - */ -package com.rop.response; - -import com.rop.CommonConstant; -import com.rop.security.MainError; -import com.rop.security.MainErrorType; -import com.rop.security.MainErrors; -import com.rop.security.SubError; - -import javax.xml.bind.annotation.*; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class ErrorResponse{ - - @XmlAttribute - protected String errorToken = CommonConstant.ERROR_TOKEN; - - @XmlAttribute - protected String code; - - @XmlElement - protected String message; - - @XmlElement - protected String solution; - - @XmlElementWrapper(name = "subErrors") - @XmlElement(name = "subError") - protected List subErrors; - - public ErrorResponse() { - } - - public ErrorResponse(MainError mainError) { - this.code = mainError.getCode(); - this.message = mainError.getMessage(); - this.solution = mainError.getSolution(); - if (mainError.getSubErrors() != null && mainError.getSubErrors().size() > 0) { - this.subErrors = mainError.getSubErrors(); - } - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getSolution() { - return solution; - } - - public void setSolution(String solution) { - this.solution = solution; - } - - public List getSubErrors() { - return subErrors; - } - - public void setSubErrors(List subErrors) { - this.subErrors = subErrors; - } - - public void addSubError(SubError subError){ - if (subErrors == null) { - subErrors = new ArrayList(); - } - subErrors.add(subError); - } - - protected MainError getInvalidArgumentsError(Locale locale) { - return MainErrors.getError(MainErrorType.INVALID_ARGUMENTS, locale); - } - - protected void setMainError(MainError mainError) { - setCode(mainError.getCode()); - setMessage(mainError.getMessage()); - setSolution(mainError.getSolution()); - } - - public String getErrorToken() { - return errorToken; - } - - /** - * 对服务名进行标准化处理:如book.upload转换为book-upload, - * - * @param method - * @return - */ - protected String transform(String method) { - if(method != null){ - method = method.replace(".", "-"); - return method; - }else{ - return "LACK_METHOD"; - } - } - -} - +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import javax.xml.bind.annotation.*; + +import com.rop.CommonConstant; + +import java.util.ArrayList; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class ErrorResponse{ + + @XmlAttribute + protected String errorToken = CommonConstant.ERROR_TOKEN; + + @XmlAttribute + protected String code; + + @XmlElement + protected String message; + + @XmlElement + protected String solution; + + @XmlElementWrapper(name = "subErrors") + @XmlElement(name = "subError") + protected List subErrors; + + public ErrorResponse() { + super(); + } + + public ErrorResponse(MainError mainError) { + this.code = mainError.getCode(); + this.message = mainError.getMessage(); + this.solution = mainError.getSolution(); + if (mainError.getSubErrors() != null && mainError.getSubErrors().size() > 0) { + this.subErrors = mainError.getSubErrors(); + } + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getSolution() { + return solution; + } + + public void setSolution(String solution) { + this.solution = solution; + } + + public List getSubErrors() { + return subErrors; + } + + public void setSubErrors(List subErrors) { + this.subErrors = subErrors; + } + + public void addSubError(SubError subError){ + if (subErrors == null) { + subErrors = new ArrayList(); + } + subErrors.add(subError); + } + + protected void setMainError(MainError mainError) { + setCode(mainError.getCode()); + setMessage(mainError.getMessage()); + setSolution(mainError.getSolution()); + } + + public String getErrorToken() { + return errorToken; + } + + /** + * 对服务名进行标准化处理:如book.upload转换为book-upload, + * + * @param method + * @return + */ + protected String transform(String method) { + if(method != null){ + return method.replace(".", "-"); + }else{ + return "LACK_METHOD"; + } + } +} \ No newline at end of file diff --git a/rop-core/src/main/java/com/rop/response/MainError.java b/rop-core/src/main/java/com/rop/response/MainError.java new file mode 100644 index 0000000..9d743aa --- /dev/null +++ b/rop-core/src/main/java/com/rop/response/MainError.java @@ -0,0 +1,41 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface MainError { + + String getCode(); + + String getMessage(); + + String getSolution(); + + List getSubErrors(); + + MainError addSubError(SubError subError); + +} + diff --git a/rop/src/main/java/com/rop/security/MainErrorType.java b/rop-core/src/main/java/com/rop/response/MainErrorType.java similarity index 79% rename from rop/src/main/java/com/rop/security/MainErrorType.java rename to rop-core/src/main/java/com/rop/response/MainErrorType.java index 41b1fe2..0d90ae9 100644 --- a/rop/src/main/java/com/rop/security/MainErrorType.java +++ b/rop-core/src/main/java/com/rop/response/MainErrorType.java @@ -1,82 +1,93 @@ -/** - * - * 日 期:12-2-23 - */ -package com.rop.security; - -import java.util.EnumMap; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum MainErrorType { - SERVICE_CURRENTLY_UNAVAILABLE, - INSUFFICIENT_ISV_PERMISSIONS, - INSUFFICIENT_USER_PERMISSIONS, - UPLOAD_FAIL, - HTTP_ACTION_NOT_ALLOWED, - INVALID_ENCODING, - FORBIDDEN_REQUEST, - METHOD_OBSOLETED, - BUSINESS_LOGIC_ERROR, - MISSING_SESSION, - INVALID_SESSION, - MISSING_APP_KEY, - INVALID_APP_KEY, - MISSING_SIGNATURE, - INVALID_SIGNATURE, - MISSING_METHOD, - INVALID_METHOD, - MISSING_VERSION, - INVALID_VERSION, - UNSUPPORTED_VERSION, - INVALID_FORMAT, - MISSING_REQUIRED_ARGUMENTS, - INVALID_ARGUMENTS, - EXCEED_USER_INVOKE_LIMITED, - EXCEED_SESSION_INVOKE_LIMITED, - EXCEED_APP_INVOKE_LIMITED, - EXCEED_APP_INVOKE_FREQUENCY_LIMITED; - - private static EnumMap errorCodeMap = new EnumMap(MainErrorType.class); - - static { - errorCodeMap.put(MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE, "1"); - errorCodeMap.put(MainErrorType.INSUFFICIENT_ISV_PERMISSIONS, "2"); - errorCodeMap.put(MainErrorType.INSUFFICIENT_USER_PERMISSIONS, "3"); - errorCodeMap.put(MainErrorType.UPLOAD_FAIL, "4"); - errorCodeMap.put(MainErrorType.HTTP_ACTION_NOT_ALLOWED, "5"); - errorCodeMap.put(MainErrorType.INVALID_ENCODING, "6"); - errorCodeMap.put(MainErrorType.FORBIDDEN_REQUEST, "7"); - errorCodeMap.put(MainErrorType.METHOD_OBSOLETED, "8"); - errorCodeMap.put(MainErrorType.BUSINESS_LOGIC_ERROR, "9"); - errorCodeMap.put(MainErrorType.MISSING_SESSION, "20"); - errorCodeMap.put(MainErrorType.INVALID_SESSION, "21"); - errorCodeMap.put(MainErrorType.MISSING_APP_KEY, "22"); - errorCodeMap.put(MainErrorType.INVALID_APP_KEY, "23"); - errorCodeMap.put(MainErrorType.MISSING_SIGNATURE, "24"); - errorCodeMap.put(MainErrorType.INVALID_SIGNATURE, "25"); - errorCodeMap.put(MainErrorType.MISSING_METHOD, "26"); - errorCodeMap.put(MainErrorType.INVALID_METHOD, "27"); - errorCodeMap.put(MainErrorType.MISSING_VERSION, "28"); - errorCodeMap.put(MainErrorType.INVALID_VERSION, "29"); - errorCodeMap.put(MainErrorType.UNSUPPORTED_VERSION, "30"); - errorCodeMap.put(MainErrorType.INVALID_FORMAT, "31"); - errorCodeMap.put(MainErrorType.MISSING_REQUIRED_ARGUMENTS, "32"); - errorCodeMap.put(MainErrorType.INVALID_ARGUMENTS, "33"); - errorCodeMap.put(MainErrorType.EXCEED_USER_INVOKE_LIMITED, "34"); - errorCodeMap.put(MainErrorType.EXCEED_SESSION_INVOKE_LIMITED, "35"); - errorCodeMap.put(MainErrorType.EXCEED_APP_INVOKE_LIMITED, "36"); - errorCodeMap.put(MainErrorType.EXCEED_APP_INVOKE_FREQUENCY_LIMITED, "37"); - } - - public String value() { - return errorCodeMap.get(this); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import java.util.EnumMap; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum MainErrorType { + SERVICE_CURRENTLY_UNAVAILABLE, + INSUFFICIENT_ISV_PERMISSIONS, + INSUFFICIENT_USER_PERMISSIONS, + UPLOAD_FAIL, + HTTP_ACTION_NOT_ALLOWED, + INVALID_ENCODING, + FORBIDDEN_REQUEST, + METHOD_OBSOLETED, + BUSINESS_LOGIC_ERROR, + MISSING_SESSION, + INVALID_SESSION, + MISSING_APP_KEY, + INVALID_APP_KEY, + MISSING_SIGNATURE, + INVALID_SIGNATURE, + MISSING_METHOD, + INVALID_METHOD, + MISSING_VERSION, + INVALID_VERSION, + UNSUPPORTED_VERSION, + INVALID_FORMAT, + MISSING_REQUIRED_ARGUMENTS, + INVALID_ARGUMENTS, + EXCEED_USER_INVOKE_LIMITED, + EXCEED_SESSION_INVOKE_LIMITED, + EXCEED_APP_INVOKE_LIMITED, + EXCEED_APP_INVOKE_FREQUENCY_LIMITED; + + private static EnumMap errorCodeMap = new EnumMap(MainErrorType.class); + + static { + errorCodeMap.put(MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE, "1"); + errorCodeMap.put(MainErrorType.INSUFFICIENT_ISV_PERMISSIONS, "2"); + errorCodeMap.put(MainErrorType.INSUFFICIENT_USER_PERMISSIONS, "3"); + errorCodeMap.put(MainErrorType.UPLOAD_FAIL, "4"); + errorCodeMap.put(MainErrorType.HTTP_ACTION_NOT_ALLOWED, "5"); + errorCodeMap.put(MainErrorType.INVALID_ENCODING, "6"); + errorCodeMap.put(MainErrorType.FORBIDDEN_REQUEST, "7"); + errorCodeMap.put(MainErrorType.METHOD_OBSOLETED, "8"); + errorCodeMap.put(MainErrorType.BUSINESS_LOGIC_ERROR, "9"); + errorCodeMap.put(MainErrorType.MISSING_SESSION, "20"); + errorCodeMap.put(MainErrorType.INVALID_SESSION, "21"); + errorCodeMap.put(MainErrorType.MISSING_APP_KEY, "22"); + errorCodeMap.put(MainErrorType.INVALID_APP_KEY, "23"); + errorCodeMap.put(MainErrorType.MISSING_SIGNATURE, "24"); + errorCodeMap.put(MainErrorType.INVALID_SIGNATURE, "25"); + errorCodeMap.put(MainErrorType.MISSING_METHOD, "26"); + errorCodeMap.put(MainErrorType.INVALID_METHOD, "27"); + errorCodeMap.put(MainErrorType.MISSING_VERSION, "28"); + errorCodeMap.put(MainErrorType.INVALID_VERSION, "29"); + errorCodeMap.put(MainErrorType.UNSUPPORTED_VERSION, "30"); + errorCodeMap.put(MainErrorType.INVALID_FORMAT, "31"); + errorCodeMap.put(MainErrorType.MISSING_REQUIRED_ARGUMENTS, "32"); + errorCodeMap.put(MainErrorType.INVALID_ARGUMENTS, "33"); + errorCodeMap.put(MainErrorType.EXCEED_USER_INVOKE_LIMITED, "34"); + errorCodeMap.put(MainErrorType.EXCEED_SESSION_INVOKE_LIMITED, "35"); + errorCodeMap.put(MainErrorType.EXCEED_APP_INVOKE_LIMITED, "36"); + errorCodeMap.put(MainErrorType.EXCEED_APP_INVOKE_FREQUENCY_LIMITED, "37"); + } + + public String value() { + return errorCodeMap.get(this); + } +} + diff --git a/rop/src/main/java/com/rop/security/SubError.java b/rop-core/src/main/java/com/rop/response/SubError.java similarity index 51% rename from rop/src/main/java/com/rop/security/SubError.java rename to rop-core/src/main/java/com/rop/response/SubError.java index d509a30..bb8d574 100644 --- a/rop/src/main/java/com/rop/security/SubError.java +++ b/rop-core/src/main/java/com/rop/response/SubError.java @@ -1,52 +1,63 @@ -/** - * - * 日 期:12-2-12 - */ -package com.rop.security; - - -import javax.xml.bind.annotation.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "subError") -public class SubError { - - @XmlAttribute - private String code; - - @XmlElement - private String message; - - public SubError() { - } - - public SubError(String code, String message) { - this.code = code; - this.message = message; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + + +import javax.xml.bind.annotation.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "subError") +public class SubError { + + @XmlAttribute + private String code; + + @XmlElement + private String message; + + public SubError() { + } + + public SubError(String code, String message) { + this.code = code; + this.message = message; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} + diff --git a/rop/src/main/java/com/rop/security/SubErrorType.java b/rop-core/src/main/java/com/rop/response/SubErrorType.java similarity index 62% rename from rop/src/main/java/com/rop/security/SubErrorType.java rename to rop-core/src/main/java/com/rop/response/SubErrorType.java index cc9c575..56ce765 100644 --- a/rop/src/main/java/com/rop/security/SubErrorType.java +++ b/rop-core/src/main/java/com/rop/response/SubErrorType.java @@ -1,44 +1,55 @@ -/** - * - * 日 期:12-2-23 - */ -package com.rop.security; - -import java.util.EnumMap; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum SubErrorType { - ISP_SERVICE_UNAVAILABLE, - ISP_SERVICE_TIMEOUT, - - ISV_NOT_EXIST, - ISV_INVALID_PERMISSION, - ISV_MISSING_PARAMETER, - ISV_INVALID_PARAMETE, - ISV_PARAMETERS_MISMATCH; - - private static EnumMap errorKeyMap = new EnumMap(SubErrorType.class); - - static { - errorKeyMap.put(SubErrorType.ISP_SERVICE_UNAVAILABLE, "isp.xxx-service-unavailable"); - errorKeyMap.put(SubErrorType.ISP_SERVICE_TIMEOUT, "isp.xxx-service-timeout"); - - errorKeyMap.put(SubErrorType.ISV_NOT_EXIST, "isv.xxx-not-exist:invalid-yyy"); - errorKeyMap.put(SubErrorType.ISV_MISSING_PARAMETER, "isv.missing-parameter:xxx"); - errorKeyMap.put(SubErrorType.ISV_INVALID_PARAMETE, "isv.invalid-paramete:xxx"); - errorKeyMap.put(SubErrorType.ISV_INVALID_PERMISSION, "isv.invalid-permission"); - errorKeyMap.put(SubErrorType.ISV_PARAMETERS_MISMATCH, "isv.parameters-mismatch:xxx-and-yyy"); - } - - public String value() { - return errorKeyMap.get(this); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import java.util.EnumMap; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum SubErrorType { + ISP_SERVICE_UNAVAILABLE, + ISP_SERVICE_TIMEOUT, + + ISV_NOT_EXIST, + ISV_INVALID_PERMISSION, + ISV_MISSING_PARAMETER, + ISV_INVALID_PARAMETE, + ISV_PARAMETERS_MISMATCH; + + private static EnumMap errorKeyMap = new EnumMap(SubErrorType.class); + + static { + errorKeyMap.put(SubErrorType.ISP_SERVICE_UNAVAILABLE, "isp.xxx-service-unavailable"); + errorKeyMap.put(SubErrorType.ISP_SERVICE_TIMEOUT, "isp.xxx-service-timeout"); + + errorKeyMap.put(SubErrorType.ISV_NOT_EXIST, "isv.xxx-not-exist:invalid-yyy"); + errorKeyMap.put(SubErrorType.ISV_MISSING_PARAMETER, "isv.missing-parameter:xxx"); + errorKeyMap.put(SubErrorType.ISV_INVALID_PARAMETE, "isv.invalid-paramete:xxx"); + errorKeyMap.put(SubErrorType.ISV_INVALID_PERMISSION, "isv.invalid-permission"); + errorKeyMap.put(SubErrorType.ISV_PARAMETERS_MISMATCH, "isv.parameters-mismatch:xxx-and-yyy"); + } + + public String value() { + return errorKeyMap.get(this); + } +} + diff --git a/rop-core/src/main/java/com/rop/sign/SignHandler.java b/rop-core/src/main/java/com/rop/sign/SignHandler.java new file mode 100644 index 0000000..418fc6a --- /dev/null +++ b/rop-core/src/main/java/com/rop/sign/SignHandler.java @@ -0,0 +1,57 @@ +/** + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sign; + +import java.util.Collection; +import java.util.Map; + +/** + * 数字签名处理接口 + * @author liangruisen + */ +public interface SignHandler { + + /** + * 产生签名 + * @param paramMap + * @return 签名字符串 + */ + String sign(Map paramMap); + + /** + * 产生签名 + * @param paramMap + * @return 签名字符串 + */ + String sign(Map paramMap, Collection ignore); + + /** + * 检查签名是否正确 + * @param sign + * @param paramMap + * @param ignore + * @return boolean + */ + boolean signCheck(String sign, Map paramMap, Collection ignore); + + /** + * 检查签名是否正确 + * @param sign + * @param paramMap + * @return boolean + */ + boolean signCheck(String sign, Map paramMap); +} diff --git a/rop-core/src/main/java/com/rop/unmarshaller/FastjsonRopUnmarshaller.java b/rop-core/src/main/java/com/rop/unmarshaller/FastjsonRopUnmarshaller.java new file mode 100644 index 0000000..cc68cd8 --- /dev/null +++ b/rop-core/src/main/java/com/rop/unmarshaller/FastjsonRopUnmarshaller.java @@ -0,0 +1,29 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.unmarshaller; + +import com.alibaba.fastjson.JSON; +import com.rop.RopUnmarshaller; + +/** + * 使用fastjson将json数据转换成java对象 + */ +public class FastjsonRopUnmarshaller implements RopUnmarshaller { + + public T unmarshaller(String content, Class objectType) { + return JSON.parseObject(content, objectType); + } +} diff --git a/rop-core/src/main/java/com/rop/unmarshaller/JacksonJsonRopUnmarshaller.java b/rop-core/src/main/java/com/rop/unmarshaller/JacksonJsonRopUnmarshaller.java new file mode 100644 index 0000000..b79db84 --- /dev/null +++ b/rop-core/src/main/java/com/rop/unmarshaller/JacksonJsonRopUnmarshaller.java @@ -0,0 +1,56 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.unmarshaller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.rop.RopException; +import com.rop.RopUnmarshaller; +import com.rop.utils.ObjectMapperUtils; + +import java.io.IOException; + +/** + *
+ * 功能说明:使用jackson2.x将json数据转换成java对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class JacksonJsonRopUnmarshaller implements RopUnmarshaller { + + private ObjectMapper objectMapper; + + public T unmarshaller(String content, Class objectType) { + try { + return getObjectMapper().readValue(content, objectType); + } catch (IOException e) { + throw new RopException(e); + } + } + + private ObjectMapper getObjectMapper() { + if (objectMapper == null) { + objectMapper = ObjectMapperUtils.getObjectMapper(); + } + return objectMapper; + } + + public void setObjectMapper(ObjectMapper objectMapper){ + this.objectMapper = objectMapper; + } +} + diff --git a/rop/src/main/java/com/rop/client/unmarshaller/JaxbXmlRopUnmarshaller.java b/rop-core/src/main/java/com/rop/unmarshaller/JaxbXmlRopUnmarshaller.java similarity index 55% rename from rop/src/main/java/com/rop/client/unmarshaller/JaxbXmlRopUnmarshaller.java rename to rop-core/src/main/java/com/rop/unmarshaller/JaxbXmlRopUnmarshaller.java index ff5ce92..718f2c9 100644 --- a/rop/src/main/java/com/rop/client/unmarshaller/JaxbXmlRopUnmarshaller.java +++ b/rop-core/src/main/java/com/rop/unmarshaller/JaxbXmlRopUnmarshaller.java @@ -1,55 +1,65 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client.unmarshaller; - -import com.rop.RopException; -import com.rop.client.RopUnmarshaller; -import org.xml.sax.InputSource; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import java.io.StringReader; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class JaxbXmlRopUnmarshaller implements RopUnmarshaller { - - private static Map jaxbContextHashMap = new ConcurrentHashMap(); - - - public T unmarshaller(String content, Class objectType) { - try { - Unmarshaller unmarshaller = buildUnmarshaller(objectType); - StringReader reader = new StringReader(content); - new InputSource(reader); - return (T) unmarshaller.unmarshal(reader); - } catch (JAXBException e) { - throw new RopException(e); - } - - } - - private Unmarshaller buildUnmarshaller(Class objectType) throws JAXBException { - if (!jaxbContextHashMap.containsKey(objectType)) { - JAXBContext context = JAXBContext.newInstance(objectType); - jaxbContextHashMap.put(objectType, context); - } - JAXBContext context = jaxbContextHashMap.get(objectType); - Unmarshaller unmarshaller = context.createUnmarshaller(); -// unmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); -// unmarshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8"); - return unmarshaller; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.unmarshaller; + +import com.rop.RopException; +import com.rop.RopUnmarshaller; + +import org.xml.sax.InputSource; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import java.io.StringReader; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + *
+ * 功能说明:使用Jaxb将xml数据转换成java对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class JaxbXmlRopUnmarshaller implements RopUnmarshaller { + + private static Map, JAXBContext> jaxbContextHashMap = new ConcurrentHashMap, JAXBContext>(); + + + public T unmarshaller(String content, Class objectType) { + try { + Unmarshaller unmarshaller = buildUnmarshaller(objectType); + StringReader reader = new StringReader(content); + new InputSource(reader); + return objectType.cast(unmarshaller.unmarshal(reader)); + } catch (JAXBException e) { + throw new RopException(e); + } + } + + private Unmarshaller buildUnmarshaller(Class objectType) throws JAXBException { + if (!jaxbContextHashMap.containsKey(objectType)) { + JAXBContext context = JAXBContext.newInstance(objectType); + jaxbContextHashMap.put(objectType, context); + } + JAXBContext context = jaxbContextHashMap.get(objectType); + Unmarshaller unmarshaller = context.createUnmarshaller(); + return unmarshaller; + } +} + diff --git a/rop-core/src/main/java/com/rop/utils/AnnotationUtils.java b/rop-core/src/main/java/com/rop/utils/AnnotationUtils.java new file mode 100644 index 0000000..8789120 --- /dev/null +++ b/rop-core/src/main/java/com/rop/utils/AnnotationUtils.java @@ -0,0 +1,191 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.utils; + +import java.lang.annotation.Annotation; +import java.lang.reflect.AnnotatedElement; +import java.lang.reflect.Method; +import java.util.HashSet; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * General utility methods for working with annotations, handling bridge methods + * (which the compiler generates for generic declarations) as well as super methods + * (for optional "annotation inheritance"). Note that none of this is + * provided by the JDK's introspection facilities themselves. + * + *

As a general rule for runtime-retained annotations (e.g. for transaction + * control, authorization, or service exposure), always use the lookup methods + * on this class (e.g., {@link #findAnnotation(Method, Class)}, + * {@link #getAnnotation(Method, Class)}, and {@link #getAnnotations(Method)}) + * instead of the plain annotation lookup methods in the JDK. You can still + * explicitly choose between a get lookup on the given class level only + * ({@link #getAnnotation(Method, Class)}) and a find lookup in the entire + * inheritance hierarchy of the given method ({@link #findAnnotation(Method, Class)}). + * + * @author Rob Harrop + * @author Juergen Hoeller + * @author Sam Brannen + * @author Mark Fisher + * @author Chris Beams + * @author Phillip Webb + * @since 2.0 + * @see java.lang.reflect.Method#getAnnotations() + * @see java.lang.reflect.Method#getAnnotation(Class) + */ +public abstract class AnnotationUtils { + + private static transient Logger logger; + + /** + * Find a single {@link Annotation} of {@code annotationType} on the + * supplied {@link Class}, traversing its interfaces, annotations, and + * superclasses if the annotation is not present on the given class + * itself. + *

This method explicitly handles class-level annotations which are not + * declared as {@link java.lang.annotation.Inherited inherited} as well + * as meta-annotations and annotations on interfaces. + *

The algorithm operates as follows: + *

    + *
  1. Search for the annotation on the given class and return it if found. + *
  2. Recursively search through all interfaces that the given class declares. + *
  3. Recursively search through all annotations that the given class declares. + *
  4. Recursively search through the superclass hierarchy of the given class. + *
+ *

Note: in this context, the term recursively means that the search + * process continues by returning to step #1 with the current interface, + * annotation, or superclass as the class to look for annotations on. + * @param clazz the class to look for annotations on + * @param annotationType the type of annotation to look for + * @return the annotation if found, or {@code null} if not found + */ + public static A findAnnotation(Class clazz, Class annotationType) { + return findAnnotation(clazz, annotationType, new HashSet()); + } + + /** + * Perform the search algorithm for {@link #findAnnotation(Class, Class)}, + * avoiding endless recursion by tracking which annotations have already + * been visited. + * @param clazz the class to look for annotations on + * @param annotationType the type of annotation to look for + * @param visited the set of annotations that have already been visited + * @return the annotation if found, or {@code null} if not found + */ + private static A findAnnotation(Class clazz, Class annotationType, Set visited) { + Assert.notNull(clazz, "Class must not be null"); + + if (isAnnotationDeclaredLocally(annotationType, clazz)) { + try { + return clazz.getAnnotation(annotationType); + } + catch (Exception ex) { + // Assuming nested Class values not resolvable within annotation attributes... + logIntrospectionFailure(clazz, ex); + return null; + } + } + + for (Class ifc : clazz.getInterfaces()) { + A annotation = findAnnotation(ifc, annotationType, visited); + if (annotation != null) { + return annotation; + } + } + + try { + for (Annotation ann : clazz.getDeclaredAnnotations()) { + if (!isInJavaLangAnnotationPackage(ann) && visited.add(ann)) { + A annotation = findAnnotation(ann.annotationType(), annotationType, visited); + if (annotation != null) { + return annotation; + } + } + } + } + catch (Exception ex) { + // Assuming nested Class values not resolvable within annotation attributes... + logIntrospectionFailure(clazz, ex); + return null; + } + + Class superclass = clazz.getSuperclass(); + if (superclass == null || superclass.equals(Object.class)) { + return null; + } + return findAnnotation(superclass, annotationType, visited); + } + + /** + * Determine whether an annotation for the specified {@code annotationType} is + * declared locally on the supplied {@code clazz}. The supplied {@link Class} + * may represent any type. + *

Note: This method does not determine if the annotation is + * {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity + * regarding inherited annotations, consider using + * {@link #isAnnotationInherited(Class, Class)} instead. + * @param annotationType the Class object corresponding to the annotation type + * @param clazz the Class object corresponding to the class on which to check for the annotation + * @return {@code true} if an annotation for the specified {@code annotationType} + * is declared locally on the supplied {@code clazz} + * @see Class#getDeclaredAnnotations() + * @see #isAnnotationInherited(Class, Class) + */ + public static boolean isAnnotationDeclaredLocally(Class annotationType, Class clazz) { + Assert.notNull(annotationType, "Annotation type must not be null"); + Assert.notNull(clazz, "Class must not be null"); + boolean declaredLocally = false; + try { + for (Annotation ann : clazz.getDeclaredAnnotations()) { + if (ann.annotationType().equals(annotationType)) { + declaredLocally = true; + break; + } + } + } + catch (Exception ex) { + // Assuming nested Class values not resolvable within annotation attributes... + logIntrospectionFailure(clazz, ex); + } + return declaredLocally; + } + + /** + * Determine if the supplied {@link Annotation} is defined in the core JDK + * {@code java.lang.annotation} package. + * @param annotation the annotation to check (never {@code null}) + * @return {@code true} if the annotation is in the {@code java.lang.annotation} package + */ + public static boolean isInJavaLangAnnotationPackage(Annotation annotation) { + Assert.notNull(annotation, "Annotation must not be null"); + return annotation.annotationType().getName().startsWith("java.lang.annotation"); + } + + private static void logIntrospectionFailure(AnnotatedElement annotatedElement, Exception ex) { + Logger loggerToUse = logger; + if (loggerToUse == null) { + loggerToUse = LoggerFactory.getLogger(AnnotationUtils.class); + logger = loggerToUse; + } + if (loggerToUse.isInfoEnabled()) { + loggerToUse.info("Failed to introspect annotations on [" + annotatedElement + "]: " + ex); + } + } +} + diff --git a/rop-core/src/main/java/com/rop/utils/Assert.java b/rop-core/src/main/java/com/rop/utils/Assert.java new file mode 100644 index 0000000..f79a893 --- /dev/null +++ b/rop-core/src/main/java/com/rop/utils/Assert.java @@ -0,0 +1,145 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.utils; + +import java.util.Collection; + +public abstract class Assert { + + /** + * Assert a boolean expression, throwing {@code IllegalArgumentException} + * if the test result is {@code false}. + *

Assert.isTrue(i > 0, "The value must be greater than zero");
+ * @param expression a boolean expression + * @param message the exception message to use if the assertion fails + * @throws IllegalArgumentException if expression is {@code false} + */ + public static void isTrue(boolean expression, String message) { + if (!expression) { + throw new IllegalArgumentException(message); + } + } + + /** + * Assert a boolean expression, throwing {@code IllegalArgumentException} + * if the test result is {@code false}. + *
Assert.isTrue(i > 0);
+ * @param expression a boolean expression + * @throws IllegalArgumentException if expression is {@code false} + */ + public static void isTrue(boolean expression) { + isTrue(expression, "[Assertion failed] - this expression must be true"); + } + + /** + * Assert that an object is {@code null} . + *
Assert.isNull(value, "The value must be null");
+ * @param object the object to check + * @param message the exception message to use if the assertion fails + * @throws IllegalArgumentException if the object is not {@code null} + */ + public static void isNull(Object object, String message) { + if (object != null) { + throw new IllegalArgumentException(message); + } + } + + /** + * Assert that an object is {@code null} . + *
Assert.isNull(value);
+ * @param object the object to check + * @throws IllegalArgumentException if the object is not {@code null} + */ + public static void isNull(Object object) { + isNull(object, "[Assertion failed] - the object argument must be null"); + } + + /** + * Assert that an object is not {@code null} . + *
Assert.notNull(clazz, "The class must not be null");
+ * @param object the object to check + * @param message the exception message to use if the assertion fails + * @throws IllegalArgumentException if the object is {@code null} + */ + public static void notNull(Object object, String message) { + if (object == null) { + throw new IllegalArgumentException(message); + } + } + + /** + * Assert that an object is not {@code null} . + *
Assert.notNull(clazz);
+ * @param object the object to check + * @throws IllegalArgumentException if the object is {@code null} + */ + public static void notNull(Object object) { + notNull(object, "[Assertion failed] - this argument is required; it must not be null"); + } + + + /** + * Assert that an array has elements; that is, it must not be + * {@code null} and must have at least one element. + *
Assert.notEmpty(array, "The array must have elements");
+ * @param array the array to check + * @param message the exception message to use if the assertion fails + * @throws IllegalArgumentException if the object array is {@code null} or has no elements + */ + public static void notEmpty(Object[] array, String message) { + if (array == null || array.length <= 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * Assert that an array has elements; that is, it must not be + * {@code null} and must have at least one element. + *
Assert.notEmpty(array);
+ * @param array the array to check + * @throws IllegalArgumentException if the object array is {@code null} or has no elements + */ + public static void notEmpty(Object[] array) { + notEmpty(array, "[Assertion failed] - this array must not be empty: it must contain at least 1 element"); + } + + /** + * Assert that a collection has elements; that is, it must not be + * {@code null} and must have at least one element. + *
Assert.notEmpty(collection, "Collection must have elements");
+ * @param collection the collection to check + * @param message the exception message to use if the assertion fails + * @throws IllegalArgumentException if the collection is {@code null} or has no elements + */ + public static void notEmpty(Collection collection, String message) { + if (collection == null || collection.size() <= 0) { + throw new IllegalArgumentException(message); + } + } + + /** + * Assert that a collection has elements; that is, it must not be + * {@code null} and must have at least one element. + *
Assert.notEmpty(collection, "Collection must have elements");
+ * @param collection the collection to check + * @throws IllegalArgumentException if the collection is {@code null} or has no elements + */ + public static void notEmpty(Collection collection) { + notEmpty(collection, + "[Assertion failed] - this collection must not be empty: it must contain at least 1 element"); + } + +} diff --git a/rop-core/src/main/java/com/rop/utils/ObjectMapperUtils.java b/rop-core/src/main/java/com/rop/utils/ObjectMapperUtils.java new file mode 100644 index 0000000..725e011 --- /dev/null +++ b/rop-core/src/main/java/com/rop/utils/ObjectMapperUtils.java @@ -0,0 +1,84 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.utils; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.TimeZone; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.type.TypeFactory; +import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector; + +public class ObjectMapperUtils { + + private static ObjectMapper objectMapper; + + public static ObjectMapper getObjectMapper(){ + if(objectMapper == null){ + synchronized (ObjectMapperUtils.class) { + if(objectMapper == null){ + objectMapper = createObjectMapper(); + } + } + } + return objectMapper; + } + + private static ObjectMapper createObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance(), true)); + objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss")); + objectMapper.setSerializationInclusion(Include.NON_EMPTY); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + // 空值处理为空串 + objectMapper.getSerializerProvider().setNullValueSerializer( + new JsonSerializer() { + @Override + public void serialize(Object value, JsonGenerator jgen, + SerializerProvider provider) throws IOException, + JsonProcessingException { + jgen.writeString(""); + } + }); + // 进行HTML解码。 + objectMapper.registerModule(new SimpleModule().addSerializer( + String.class, new JsonSerializer() { + @Override + public void serialize(String value, JsonGenerator jgen, + SerializerProvider provider) throws IOException, + JsonProcessingException { + jgen.writeString(StringEscapeUtils.unescapeHtml(value)); + } + })); + // 设置时区 + objectMapper.setTimeZone(TimeZone.getDefault()); + return objectMapper; + } + + public void setObjectMapper(ObjectMapper objectMapper) { + ObjectMapperUtils.objectMapper = objectMapper; + } +} diff --git a/rop-core/src/main/java/com/rop/utils/ReflectionUtils.java b/rop-core/src/main/java/com/rop/utils/ReflectionUtils.java new file mode 100644 index 0000000..b50d2d9 --- /dev/null +++ b/rop-core/src/main/java/com/rop/utils/ReflectionUtils.java @@ -0,0 +1,135 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.utils; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +import com.rop.annotation.IgnoreSign; +import com.rop.annotation.Temporary; +import com.rop.config.SystemParameterNames; + +public abstract class ReflectionUtils { + + public static Object getField(Field field, Object target) { + makeAccessible(field); + try { + return field.get(target); + } catch (IllegalArgumentException e) { + throw e; + } catch (IllegalAccessException e) { + throw new IllegalArgumentException(e); + } + } + + /** + * Make the given field accessible, explicitly setting it accessible if necessary. + * The setAccessible(true) method is only called when actually necessary, + * to avoid unnecessary conflicts with a JVM SecurityManager (if active). + * @param field the field to make accessible + * @see java.lang.reflect.Field#setAccessible + */ + public static void makeAccessible(Field field) { + if (!Modifier.isPublic(field.getModifiers()) || + !Modifier.isPublic(field.getDeclaringClass().getModifiers())) { + field.setAccessible(true); + } + } + + public static List getIgnoreSignFieldNames(Class type){ + final List list = new ArrayList(); + list.add(SystemParameterNames.getSign()); + list.add(SystemParameterNames.getJsonp()); + if(type == null){ + return list; + } + doWithFields(type, new FieldCallback() { + public void doWith(Field field) { + list.add(field.getName()); + } + }, + new FieldFilter() { + public boolean matches(Field field) { + //属性类标注了@IgnoreSign + IgnoreSign typeIgnore = AnnotationUtils.findAnnotation(field.getType(), IgnoreSign.class); + //属性定义处标注了@IgnoreSign + IgnoreSign ignoreSign = field.getAnnotation(IgnoreSign.class); + //属性定义处标注了@Temporary + Temporary temporary = field.getAnnotation(Temporary.class); + return typeIgnore != null || ignoreSign != null || temporary != null; + } + }); + return list; + } + + public static List getFields(Class type){ + final List list = new ArrayList(); + if(type == null){ + return list; + } + doWithFields(type, new FieldCallback() { + public void doWith(Field field) { + makeAccessible(field); + list.add(field); + } + }, + new FieldFilter() { + public boolean matches(Field field) { + //属性定义处标注了@Temporary + Temporary temporary = field.getAnnotation(Temporary.class); + return temporary != null; + } + }); + return list; + } + + public static void doWithFields(Class searchType, FieldCallback callback, FieldFilter filter){ + doWithFields(searchType, null, callback, filter); + } + + public static void doWithFields(Class searchType, Class stopType, FieldCallback callback, FieldFilter filter){ + Assert.notNull(searchType, "the searchType argument must be null"); + Assert.notNull(callback, "the callback argument must be null"); + if(stopType == null){ + stopType = Object.class; + } + while(!stopType.equals(searchType)){ + Field[] fields = searchType.getDeclaredFields(); + if(fields != null && fields.length > 0){ + for(Field field : fields){ + if(filter != null){ + if(filter.matches(field)){ + callback.doWith(field); + } + }else{ + callback.doWith(field); + } + } + } + searchType = searchType.getSuperclass(); + } + } + + static interface FieldFilter { + boolean matches(Field field); + } + + static interface FieldCallback { + void doWith(Field field); + } +} diff --git a/rop-core/src/main/java/com/rop/utils/RopUtils.java b/rop-core/src/main/java/com/rop/utils/RopUtils.java new file mode 100644 index 0000000..fef0c9c --- /dev/null +++ b/rop-core/src/main/java/com/rop/utils/RopUtils.java @@ -0,0 +1,138 @@ +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.utils; + +import com.rop.RopException; + +import java.io.IOException; + +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopUtils { + + /** + * 使用secret对paramValues按以下算法进行签名:
+ * uppercase(hex(sha1(secretkey1value1key2value2...secret)) + * @deprecated + * @param paramValues 参数列表 + * @param secret + * @return + */ + public static String sign(Map paramValues, String secret) { + return sign(paramValues,null,secret); + } + + /** + * 对paramValues进行签名,其中ignoreParamNames这些参数不参与签名 + * @deprecated + * @param paramValues + * @param ignoreParamNames + * @param secret + * @return + */ + public static String sign(Map paramValues, List ignoreParamNames,String secret) { + try { + StringBuilder sb = new StringBuilder(); + sb.append(secret); + sb.append(RopUtils.getSignContent(paramValues, ignoreParamNames)); + sb.append(secret); + byte[] sha1Digest = getSHA1Digest(sb.toString()); + return byte2hex(sha1Digest); + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 根据参数集合获取需要签名的字符串内容 + * @param paramValues + * @return 需要签名的字符串内容 + */ + public static String getSignContent(Map paramValues){ + return getSignContent(paramValues, null); + } + + /** + * 根据参数集合和不需要签名的参数名称列表获取需要签名的字符串内容 + * @param paramValues + * @param ignoreParamNames + * @return 需要签名的字符串内容 + */ + public static String getSignContent(Map paramValues, Collection ignoreParamNames){ + StringBuilder sb = new StringBuilder(); + List paramNames = new ArrayList(paramValues.size()); + paramNames.addAll(paramValues.keySet()); + if(ignoreParamNames != null && ignoreParamNames.size() > 0){ + for (String ignoreParamName : ignoreParamNames) { + paramNames.remove(ignoreParamName); + } + } + Collections.sort(paramNames); + for (String paramName : paramNames) { + sb.append(paramName).append(paramValues.get(paramName)); + } + return sb.toString(); + } + + private static byte[] getSHA1Digest(String data) throws IOException { + byte[] bytes = null; + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + bytes = md.digest(data.getBytes()); + } catch (GeneralSecurityException gse) { + throw new IOException(gse.getMessage()); + } + return bytes; + } + + /** + * 二进制转十六进制字符串 + * + * @param bytes + * @return 十六进制字符串 + */ + public static String byte2hex(byte[] bytes) { + StringBuilder sign = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(bytes[i] & 0xFF); + if (hex.length() == 1) { + sign.append("0"); + } + sign.append(hex.toUpperCase()); + } + return sign.toString(); + } + + /** + * 产生一个uuid + * @return uuid + */ + public static String getUUID() { + UUID uuid = UUID.randomUUID(); + return uuid.toString().toUpperCase(); + } +} + diff --git a/rop-core/src/test/java/com/rop/marshaller/Bar.java b/rop-core/src/test/java/com/rop/marshaller/Bar.java new file mode 100644 index 0000000..372d2da --- /dev/null +++ b/rop-core/src/test/java/com/rop/marshaller/Bar.java @@ -0,0 +1,90 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-4-21 + */ +public class Bar { + + private String fld1 = "a"; + + private String fld2 = "b"; + + private Foo foo; + + public String getFld1() { + return fld1; + } + + public void setFld1(String fld1) { + this.fld1 = fld1; + } + + public String getFld2() { + return fld2; + } + + public void setFld2(String fld2) { + this.fld2 = fld2; + } + + public Foo getFoo() { + return foo; + } + + public void setFoo(Foo foo) { + this.foo = foo; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((fld1 == null) ? 0 : fld1.hashCode()); + result = prime * result + ((fld2 == null) ? 0 : fld2.hashCode()); + result = prime * result + ((foo == null) ? 0 : foo.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Bar other = (Bar) obj; + if (fld1 == null) { + if (other.fld1 != null) + return false; + } else if (!fld1.equals(other.fld1)) + return false; + if (fld2 == null) { + if (other.fld2 != null) + return false; + } else if (!fld2.equals(other.fld2)) + return false; + if (foo == null) { + if (other.foo != null) + return false; + } else if (!foo.equals(other.foo)) + return false; + return true; + } +} diff --git a/rop-core/src/test/java/com/rop/marshaller/FastjsonRopMarshallerTest.java b/rop-core/src/test/java/com/rop/marshaller/FastjsonRopMarshallerTest.java new file mode 100644 index 0000000..6e55bfd --- /dev/null +++ b/rop-core/src/test/java/com/rop/marshaller/FastjsonRopMarshallerTest.java @@ -0,0 +1,42 @@ +package com.rop.marshaller; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +public class FastjsonRopMarshallerTest { + + private FastjsonRopMarshaller marshaller = new FastjsonRopMarshaller(); + + @Test + public void testMarshaller() throws IOException { + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + Bar bar = new Bar(); + bar.setFoo(foo); + marshaller.marshaller(bar, System.out); + List lists = new ArrayList(2); + Foo f1 = new Foo(); + f1.setI2(2); + lists.add(f1); + Foo f2 = new Foo(); + f2.setI2(1); + lists.add(f2); + System.out.println(); + marshaller.marshaller(lists, System.out); + System.out.println(); + + Map maps = new LinkedHashMap(2); + maps.put("1", f2); + maps.put("2", f1); + marshaller.marshaller(maps, System.out); + } + +} diff --git a/rop-core/src/test/java/com/rop/marshaller/Foo.java b/rop-core/src/test/java/com/rop/marshaller/Foo.java new file mode 100644 index 0000000..c3152fe --- /dev/null +++ b/rop-core/src/test/java/com/rop/marshaller/Foo.java @@ -0,0 +1,119 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import javax.xml.bind.annotation.XmlRootElement; + +/** +* @author : chenxh(quickselect@163.com) +* @date: 14-4-21 +*/ +@XmlRootElement +public class Foo implements IFoo{ + private Boolean b1; + + private boolean b2; + + private Integer i1; + + private int i2; + + private String ok; + + public Boolean getB1() { + return b1; + } + + public void setB1(Boolean b1) { + this.b1 = b1; + } + + public boolean isB2() { + return b2; + } + + public void setB2(boolean b2) { + this.b2 = b2; + } + + public Integer getI1() { + return i1; + } + + + public void setI1(Integer i1) { + this.i1 = i1; + } + + public int getI2() { + return i2; + } + + public void setI2(int i2) { + this.i2 = i2; + } + + public String getOk() { + return ok; + } + + public void setOk(String ok) { + this.ok = ok; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((b1 == null) ? 0 : b1.hashCode()); + result = prime * result + (b2 ? 1231 : 1237); + result = prime * result + ((i1 == null) ? 0 : i1.hashCode()); + result = prime * result + i2; + result = prime * result + ((ok == null) ? 0 : ok.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Foo other = (Foo) obj; + if (b1 == null) { + if (other.b1 != null) + return false; + } else if (!b1.equals(other.b1)) + return false; + if (b2 != other.b2) + return false; + if (i1 == null) { + if (other.i1 != null) + return false; + } else if (!i1.equals(other.i1)) + return false; + if (i2 != other.i2) + return false; + if (ok == null) { + if (other.ok != null) + return false; + } else if (!ok.equals(other.ok)) + return false; + return true; + } +} diff --git a/rop-core/src/test/java/com/rop/marshaller/IFoo.java b/rop-core/src/test/java/com/rop/marshaller/IFoo.java new file mode 100644 index 0000000..13a2fbf --- /dev/null +++ b/rop-core/src/test/java/com/rop/marshaller/IFoo.java @@ -0,0 +1,28 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import javax.xml.bind.annotation.XmlTransient; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-4-21 + */ +public interface IFoo { + + @XmlTransient + Integer getI1(); +} diff --git a/rop-core/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java b/rop-core/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java new file mode 100644 index 0000000..77417c3 --- /dev/null +++ b/rop-core/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java @@ -0,0 +1,64 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-3-27 + */ +public class JacksonJsonRopMarshallerTest { + + private JacksonJsonRopMarshaller marshaller = new JacksonJsonRopMarshaller(); + + @Test + public void test1() throws IOException{ + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + Bar bar = new Bar(); + bar.setFoo(foo); + marshaller.marshaller(bar,System.out); + } + + @Test + public void test2() throws IOException{ + List lists = new ArrayList(2); + Foo f1 = new Foo(); + f1.setI2(2); + lists.add(f1); + Foo f2 = new Foo(); + f2.setI2(1); + lists.add(f2); + System.out.println(); + marshaller.marshaller(lists,System.out); + System.out.println(); + + Map maps= new LinkedHashMap(2); + maps.put("1",f2); + maps.put("2",f1); + marshaller.marshaller(maps,System.out); + } +} diff --git a/rop/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java b/rop-core/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java similarity index 62% rename from rop/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java rename to rop-core/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java index 443fc20..289a134 100644 --- a/rop/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java +++ b/rop-core/src/test/java/com/rop/marshaller/JaxbXmlRopResponseMarshallerTest.java @@ -1,51 +1,61 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-18 - */ -package com.rop.marshaller; - -import org.testng.annotations.Test; - -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class JaxbXmlRopResponseMarshallerTest { - - private JaxbXmlRopMarshaller marshaller = new JaxbXmlRopMarshaller(); - - @Test - public void buildMarshaller() throws Throwable { - //marshaller.marshaller(new SampleResponse(), new ByteArrayOutputStream(1024)); - SampleResponse sampleResponse = new SampleResponse(); - List> table = new ArrayList>(); - HashMap row = new HashMap(); - row.put("c1", "c1"); - row.put("c2", "c2"); - row.put("c3", "c3"); - table.add(row); - sampleResponse.setUserId("json"); - sampleResponse.setTable(table); - marshaller.marshaller(sampleResponse, System.out); - } - - @Test - public void test1(){ - Foo foo = new Foo(); - foo.setB1(true); - foo.setB2(true); - foo.setI1(1); - foo.setI2(1); - marshaller.marshaller(foo,System.out); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.Test; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class JaxbXmlRopResponseMarshallerTest { + + private JaxbXmlRopMarshaller marshaller = new JaxbXmlRopMarshaller(); + + @Test + public void buildMarshaller() throws Throwable { + //marshaller.marshaller(new SampleResponse(), new ByteArrayOutputStream(1024)); + SampleResponse sampleResponse = new SampleResponse(); + List> table = new ArrayList>(); + HashMap row = new HashMap(); + row.put("c1", "c1"); + row.put("c2", "c2"); + row.put("c3", "c3"); + table.add(row); + sampleResponse.setUserId("json"); + sampleResponse.setTable(table); + marshaller.marshaller(sampleResponse, System.out); + } + + @Test + public void test1(){ + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + marshaller.marshaller(foo,System.out); + } +} + diff --git a/rop/src/test/java/com/rop/marshaller/SampleResponse.java b/rop-core/src/test/java/com/rop/marshaller/SampleResponse.java similarity index 63% rename from rop/src/test/java/com/rop/marshaller/SampleResponse.java rename to rop-core/src/test/java/com/rop/marshaller/SampleResponse.java index ed8ea18..5588e4c 100644 --- a/rop/src/test/java/com/rop/marshaller/SampleResponse.java +++ b/rop-core/src/test/java/com/rop/marshaller/SampleResponse.java @@ -1,71 +1,80 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.marshaller; - - -import javax.xml.bind.annotation.*; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "sampleResponse") -public class SampleResponse{ - - @XmlAttribute - private String userId; - - @XmlAttribute - private String createTime; - - private HashMap attaches; - - private List> table; - - public SampleResponse() { - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public List> getTable() { - return table; - } - - public void setTable(List> table) { - this.table = table; - } - - public HashMap getAttaches() { - return attaches; - } - - public void setAttaches(HashMap attaches) { - this.attaches = attaches; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.marshaller; + + +import javax.xml.bind.annotation.*; +import java.util.HashMap; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "sampleResponse") +public class SampleResponse{ + + @XmlAttribute + private String userId; + + @XmlAttribute + private String createTime; + + private HashMap attaches; + + private List> table; + + public SampleResponse() { + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public List> getTable() { + return table; + } + + public void setTable(List> table) { + this.table = table; + } + + public HashMap getAttaches() { + return attaches; + } + + public void setAttaches(HashMap attaches) { + this.attaches = attaches; + } +} + diff --git a/rop-core/src/test/java/com/rop/unmarshaller/FastjsonRopUnmarshallerTest.java b/rop-core/src/test/java/com/rop/unmarshaller/FastjsonRopUnmarshallerTest.java new file mode 100644 index 0000000..f6e0ee5 --- /dev/null +++ b/rop-core/src/test/java/com/rop/unmarshaller/FastjsonRopUnmarshallerTest.java @@ -0,0 +1,80 @@ +package com.rop.unmarshaller; + +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.rop.marshaller.Bar; +import com.rop.marshaller.FastjsonRopMarshaller; +import com.rop.marshaller.Foo; +import com.rop.marshaller.JacksonJsonRopMarshaller; + +public class FastjsonRopUnmarshallerTest { + + private FastjsonRopMarshaller fastjsonMarshaller = new FastjsonRopMarshaller(); + + private JacksonJsonRopMarshaller jacksonJsonMarshaller = new JacksonJsonRopMarshaller(); + + private FastjsonRopUnmarshaller unmarshaller = new FastjsonRopUnmarshaller(); + + @SuppressWarnings("unchecked") + @Test + public void testUnmarshaller() throws IOException { + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + Bar bar = new Bar(); + bar.setFoo(foo); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + fastjsonMarshaller.marshaller(bar, baos); + String json = baos.toString(); + Bar bar2 = unmarshaller.unmarshaller(json, Bar.class); + assertTrue(bar.equals(bar2)); + baos.reset(); + jacksonJsonMarshaller.marshaller(bar, baos); + json = baos.toString(); + bar2 = unmarshaller.unmarshaller(json, Bar.class); + assertNotNull(bar2); + List lists = new ArrayList(2); + Foo f1 = new Foo(); + f1.setI2(2); + lists.add(f1); + Foo f2 = new Foo(); + f2.setI2(1); + lists.add(f2); + baos.reset(); + fastjsonMarshaller.marshaller(lists, baos); + json = baos.toString(); + List list = unmarshaller.unmarshaller(json, lists.getClass()); + assertNotNull(list); + baos.reset(); + jacksonJsonMarshaller.marshaller(lists, baos); + json = baos.toString(); + list = unmarshaller.unmarshaller(json, lists.getClass()); + assertNotNull(list); + + Map maps = new LinkedHashMap(2); + maps.put("1", f2); + maps.put("2", f1); + baos.reset(); + fastjsonMarshaller.marshaller(maps, baos); + json = baos.toString(); + Map map = unmarshaller.unmarshaller(json, maps.getClass()); + assertNotNull(map); + baos.reset(); + jacksonJsonMarshaller.marshaller(maps, baos); + json = baos.toString(); + map = unmarshaller.unmarshaller(json, maps.getClass()); + assertNotNull(map); + } + +} diff --git a/rop-core/src/test/java/com/rop/unmarshaller/JacksonJsonRopUnmarshallerTest.java b/rop-core/src/test/java/com/rop/unmarshaller/JacksonJsonRopUnmarshallerTest.java new file mode 100644 index 0000000..5ffb810 --- /dev/null +++ b/rop-core/src/test/java/com/rop/unmarshaller/JacksonJsonRopUnmarshallerTest.java @@ -0,0 +1,79 @@ +package com.rop.unmarshaller; + +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.rop.marshaller.Bar; +import com.rop.marshaller.FastjsonRopMarshaller; +import com.rop.marshaller.Foo; +import com.rop.marshaller.JacksonJsonRopMarshaller; + +public class JacksonJsonRopUnmarshallerTest { + + private FastjsonRopMarshaller fastjsonMarshaller = new FastjsonRopMarshaller(); + + private JacksonJsonRopMarshaller jacksonJsonMarshaller = new JacksonJsonRopMarshaller(); + + private JacksonJsonRopUnmarshaller unmarshaller = new JacksonJsonRopUnmarshaller(); + + @SuppressWarnings("unchecked") + @Test + public void testUnmarshaller() throws IOException { + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + Bar bar = new Bar(); + bar.setFoo(foo); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + fastjsonMarshaller.marshaller(bar, baos); + String json = baos.toString(); + Bar bar2 = unmarshaller.unmarshaller(json, Bar.class); + assertNotNull(bar2); + baos.reset(); + jacksonJsonMarshaller.marshaller(bar, baos); + json = baos.toString(); + bar2 = unmarshaller.unmarshaller(json, Bar.class); + assertNotNull(bar2); + List lists = new ArrayList(2); + Foo f1 = new Foo(); + f1.setI2(2); + lists.add(f1); + Foo f2 = new Foo(); + f2.setI2(1); + lists.add(f2); + baos.reset(); + fastjsonMarshaller.marshaller(lists, baos); + json = baos.toString(); + List list = unmarshaller.unmarshaller(json, lists.getClass()); + assertNotNull(list); + baos.reset(); + jacksonJsonMarshaller.marshaller(lists, baos); + json = baos.toString(); + list = unmarshaller.unmarshaller(json, lists.getClass()); + assertNotNull(list); + + Map maps = new LinkedHashMap(2); + maps.put("1", f2); + maps.put("2", f1); + baos.reset(); + fastjsonMarshaller.marshaller(maps, baos); + json = baos.toString(); + Map map = unmarshaller.unmarshaller(json, maps.getClass()); + assertNotNull(map); + baos.reset(); + jacksonJsonMarshaller.marshaller(maps, baos); + json = baos.toString(); + map = unmarshaller.unmarshaller(json, maps.getClass()); + assertNotNull(map); + } +} diff --git a/rop-core/src/test/java/com/rop/unmarshaller/JaxbXmlRopUnmarshallerTest.java b/rop-core/src/test/java/com/rop/unmarshaller/JaxbXmlRopUnmarshallerTest.java new file mode 100644 index 0000000..f99233b --- /dev/null +++ b/rop-core/src/test/java/com/rop/unmarshaller/JaxbXmlRopUnmarshallerTest.java @@ -0,0 +1,50 @@ +package com.rop.unmarshaller; + +import static org.junit.Assert.*; + +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.Test; + +import com.rop.marshaller.Foo; +import com.rop.marshaller.JaxbXmlRopMarshaller; +import com.rop.marshaller.SampleResponse; + +public class JaxbXmlRopUnmarshallerTest { + + private JaxbXmlRopMarshaller marshaller = new JaxbXmlRopMarshaller(); + + private JaxbXmlRopUnmarshaller unmarshaller = new JaxbXmlRopUnmarshaller(); + + @Test + public void testUnmarshaller() { + Foo foo = new Foo(); + foo.setB1(true); + foo.setB2(true); + foo.setI1(1); + foo.setI2(1); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + marshaller.marshaller(foo, baos); + String xml = baos.toString(); + Foo foo2 = unmarshaller.unmarshaller(xml, Foo.class); + assertEquals(foo, foo2); + SampleResponse sampleResponse = new SampleResponse(); + List> table = new ArrayList>(); + HashMap row = new HashMap(); + row.put("c1", "c1"); + row.put("c2", "c2"); + row.put("c3", "c3"); + table.add(row); + sampleResponse.setUserId("json"); + sampleResponse.setTable(table); + baos.reset(); + marshaller.marshaller(sampleResponse, baos); + xml = baos.toString(); + SampleResponse response = unmarshaller.unmarshaller(xml, SampleResponse.class); + assertNotNull(response); + } + +} diff --git a/rop-sample/.gitignore b/rop-sample/.gitignore new file mode 100644 index 0000000..b77461b --- /dev/null +++ b/rop-sample/.gitignore @@ -0,0 +1,3 @@ +/target/ +/.settings/ +.classpath \ No newline at end of file diff --git a/rop-sample/pom.xml b/rop-sample/pom.xml index d7766af..3450e84 100644 --- a/rop-sample/pom.xml +++ b/rop-sample/pom.xml @@ -1,136 +1,196 @@ - - - 4.0.0 - - - org.sonatype.oss - oss-parent - 7 - - - com.rop - rop-sample - ropSample - 1.0.7-SNAPSHOT - war - rest open platform - - http://www.github.com - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - scm:git:git@github.com:itstamen/rop.git - scm:git:git@github.com:itstamen/rop.git - git@github.com:itstamen/rop.git - - - - - stamen - stamen - itstamen@qq.com - - - - - - - javax.servlet - servlet-api - ${servlet.version} - provided - - - - com.rop - rop - ${project.version} - - - - - org.springframework - spring-context - ${spring.version} - - - - org.unitils - unitils-core - ${unitils.version} - test - - - - org.unitils - unitils-testng - ${unitils.version} - test - - - - org.unitils - unitils-spring - ${unitils.version} - test - - - - org.testng - testng - ${testng.version} - test - - - - org.mockito - mockito-all - ${mockito.version} - test - - - - - - rop-sample - - - - org.mortbay.jetty - maven-jetty-plugin - 6.1.5 - - src/main/resources/jetty/webdefault.xml - src/main/webapp - 3 - / - - - 8088 - - - - - - - - - UTF-8 - 1.5 - 2.5 - 3.2.3.RELEASE - 1.9.5 - 6.3 - 1.8.5 - 3.3 - + + + 4.0.0 + + + com.rop + rop-parent + 2.0-SNAPSHOT + + + rop-sample + ropSample + war + rest open platform + + http://www.github.com + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git@github.com:itstamen/rop.git + scm:git:git@github.com:itstamen/rop.git + git@github.com:itstamen/rop.git + + + + + stamen + stamen + itstamen@qq.com + + + + + + + javax.servlet + servlet-api + ${servlet.version} + provided + + + + com.rop + rop + ${project.version} + + + + com.rop + rop-client + ${project.version} + + + + org.springframework + spring-context + ${spring.version} + + + + org.unitils + unitils-core + ${unitils.version} + test + + + + org.unitils + unitils-testng + ${unitils.version} + test + + + + org.unitils + unitils-spring + ${unitils.version} + test + + + + org.testng + testng + ${testng.version} + test + + + + org.mockito + mockito-all + ${mockito.version} + test + + + com.alibaba + fastjson + ${fastjson.version} + + + + + rop-sample + + + + org.mortbay.jetty + maven-jetty-plugin + 6.1.5 + + src/main/resources/jetty/webdefault.xml + src/main/webapp + 3 + / + + + 8088 + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + ${file.encoding} + ${file.encoding} + ${file.encoding} + + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${file.encoding} + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${file.encoding} + + + + + + + UTF-8 + 1.6 + 2.5 + 3.2.3.RELEASE + 1.9.5 + 6.3 + 1.8.5 + 3.3 + 1.2.4 + \ No newline at end of file diff --git a/rop-sample/src/main/java/com/rop/sample/AbstractUserService.java b/rop-sample/src/main/java/com/rop/sample/AbstractUserService.java index 2778316..52099d9 100644 --- a/rop-sample/src/main/java/com/rop/sample/AbstractUserService.java +++ b/rop-sample/src/main/java/com/rop/sample/AbstractUserService.java @@ -1,11 +1,23 @@ -/** - * Copyright:中软海晟信息科技有限公司 版权所有 违者必究 2014 - */ -package com.rop.sample; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-3-6 - */ -public abstract class AbstractUserService implements UserServiceInterface { -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-3-6 + */ +public abstract class AbstractUserService implements UserServiceInterface { +} diff --git a/rop-sample/src/main/java/com/rop/sample/LogoutService.java b/rop-sample/src/main/java/com/rop/sample/LogoutService.java index 7cce682..f160450 100644 --- a/rop-sample/src/main/java/com/rop/sample/LogoutService.java +++ b/rop-sample/src/main/java/com/rop/sample/LogoutService.java @@ -1,27 +1,38 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-27 - */ -package com.rop.sample; - -import com.rop.RopRequest; -import com.rop.annotation.ServiceMethod; -import com.rop.annotation.ServiceMethodBean; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@ServiceMethodBean(version = "1.0") -public class LogoutService { - - @ServiceMethod(method = "user.logout") - public Object logout(RopRequest request){ - return null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.RopRequest; +import com.rop.annotation.ServiceMethod; +import com.rop.annotation.ServiceMethodBean; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@ServiceMethodBean(version = "1.0") +public class LogoutService { + + @ServiceMethod(method = "user.logout") + public Object logout(RopRequest request){ + return null; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/ReservedUserNameInterceptor.java b/rop-sample/src/main/java/com/rop/sample/ReservedUserNameInterceptor.java index 0d4c524..8aaa971 100644 --- a/rop-sample/src/main/java/com/rop/sample/ReservedUserNameInterceptor.java +++ b/rop-sample/src/main/java/com/rop/sample/ReservedUserNameInterceptor.java @@ -1,63 +1,74 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-26 - */ -package com.rop.sample; - -import com.rop.AbstractInterceptor; -import com.rop.RopRequestContext; -import com.rop.sample.response.InterceptorResponse; -import org.springframework.stereotype.Component; - -/** - *
- *    该拦截器仅对method为“user.add”进行拦截,你可以在{@link #isMatch(com.rop.RopRequestContext)}方法中定义拦截器的匹配规则。
- *  你可以通过{@link com.rop.RopRequestContext#getServiceMethodDefinition()}获取服务方法的注解信息,通过这些信息进行拦截匹配规则
- *  定义。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ - -@Component -public class ReservedUserNameInterceptor extends AbstractInterceptor { - - /** - * 在数据绑定后,服务方法调用前执行该拦截方法 - * - * @param ropRequestContext - */ - public void beforeService(RopRequestContext ropRequestContext) { - System.out.println("beforeService ..."); - - if ("jhonson".equals(ropRequestContext.getParamValue("userName"))) { - InterceptorResponse response = new InterceptorResponse(); - response.setTestField("the userName can't be jhonson!"); - //设置了RopResponse后,后续的服务将不执行,直接返回这个RopResponse响应 - ropRequestContext.setRopResponse(response); - } - } - - /** - * 在服务执行完成后,响应返回前执行该拦截方法 - * - * @param ropRequestContext - */ - - public void beforeResponse(RopRequestContext ropRequestContext) { - System.out.println("beforeResponse ..."); - } - - /** - * 对method为user.add的方法进行拦截,你可以通过methodContext中的信息制定拦截方案 - * - * @param ropRequestContext - * @return - */ - - public boolean isMatch(RopRequestContext ropRequestContext) { - return "user.add".equals(ropRequestContext.getMethod()); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.AbstractInterceptor; +import com.rop.RopRequestContext; +import com.rop.sample.response.InterceptorResponse; +import org.springframework.stereotype.Component; + +/** + *
+ *    该拦截器仅对method为“user.add”进行拦截,你可以在{@link #isMatch(com.rop.RopRequestContext)}方法中定义拦截器的匹配规则。
+ *  你可以通过{@link com.rop.RopRequestContext#getServiceMethodDefinition()}获取服务方法的注解信息,通过这些信息进行拦截匹配规则
+ *  定义。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ + +@Component +public class ReservedUserNameInterceptor extends AbstractInterceptor { + + /** + * 在数据绑定后,服务方法调用前执行该拦截方法 + * + * @param ropRequestContext + */ + public void beforeService(RopRequestContext ropRequestContext) { + System.out.println("beforeService ..."); + + if ("jhonson".equals(ropRequestContext.getParamValue("userName"))) { + InterceptorResponse response = new InterceptorResponse(); + response.setTestField("the userName can't be jhonson!"); + //设置了RopResponse后,后续的服务将不执行,直接返回这个RopResponse响应 + ropRequestContext.setRopResponse(response); + } + } + + /** + * 在服务执行完成后,响应返回前执行该拦截方法 + * + * @param ropRequestContext + */ + + public void beforeResponse(RopRequestContext ropRequestContext) { + System.out.println("beforeResponse ..."); + } + + /** + * 对method为user.add的方法进行拦截,你可以通过methodContext中的信息制定拦截方案 + * + * @param ropRequestContext + * @return + */ + + public boolean isMatch(RopRequestContext ropRequestContext) { + return "user.add".equals(ropRequestContext.getMethod()); + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleAfterDoServiceEventListener.java b/rop-sample/src/main/java/com/rop/sample/SampleAfterDoServiceEventListener.java index b031341..056d564 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleAfterDoServiceEventListener.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleAfterDoServiceEventListener.java @@ -1,40 +1,48 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.sample; - -import com.rop.RopRequest; -import com.rop.RopRequestContext; -import com.rop.event.AfterDoServiceEvent; -import com.rop.event.RopEventListener; -import com.rop.marshaller.MessageMarshallerUtils; - -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleAfterDoServiceEventListener implements RopEventListener { - - - public void onRopEvent(AfterDoServiceEvent ropEvent) { - RopRequestContext ropRequestContext = ropEvent.getRopRequestContext(); - if(ropRequestContext != null){ - Map allParams = ropRequestContext.getAllParams(); - String message = MessageMarshallerUtils.asUrlString(allParams); - System.out.println("message("+ropEvent.getServiceEndTime()+")"+message); - } - } - - - public int getOrder() { - return 0; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.RopRequestContext; +import com.rop.event.AfterDoServiceEvent; +import com.rop.event.RopEventListener; +import com.rop.sample.utils.UrlUtils; + +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleAfterDoServiceEventListener implements RopEventListener { + + public void onRopEvent(AfterDoServiceEvent ropEvent) { + RopRequestContext ropRequestContext = ropEvent.getRopRequestContext(); + if(ropRequestContext != null){ + Map allParams = ropRequestContext.getAllParams(); + String message = UrlUtils.asUrlString(allParams); + System.out.println("message("+ropEvent.getServiceEndTime()+")"+message); + } + } + + public int getOrder() { + return 0; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleAppSecretManager.java b/rop-sample/src/main/java/com/rop/sample/SampleAppSecretManager.java index 2b8931d..e586c92 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleAppSecretManager.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleAppSecretManager.java @@ -1,40 +1,52 @@ -package com.rop.sample; /** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-25 - */ - -import com.rop.security.AppSecretManager; - -import java.util.HashMap; -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleAppSecretManager implements AppSecretManager { - - private static Map appKeySecretMap = new HashMap(); - - static { - appKeySecretMap.put("00001", "abcdeabcdeabcdeabcdeabcde"); - appKeySecretMap.put("00002","abcdeabcdeabcdeabcdeaaaaa"); - appKeySecretMap.put("00003","abcdeabcdeabcdeabcdeaaaaa"); - } - - - public String getSecret(String appKey) { - System.out.println("use SampleAppSecretManager!"); - return appKeySecretMap.get(appKey); - } - - - public boolean isValidAppKey(String appKey) { - return getSecret(appKey) != null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.security.AppSecretManager; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleAppSecretManager implements AppSecretManager { + + private static Map appKeySecretMap = new HashMap(); + + static { + appKeySecretMap.put("00001", "abcdeabcdeabcdeabcdeabcde"); + appKeySecretMap.put("00002","abcdeabcdeabcdeabcdeaaaaa"); + appKeySecretMap.put("00003","abcdeabcdeabcdeabcdeaaaaa"); + } + + + public String getSecret(String appKey) { + System.out.println("use SampleAppSecretManager!"); + return appKeySecretMap.get(appKey); + } + + + public boolean isValidAppKey(String appKey) { + return getSecret(appKey) != null; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleInvokeTimesController.java b/rop-sample/src/main/java/com/rop/sample/SampleInvokeTimesController.java index 0731b20..6277571 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleInvokeTimesController.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleInvokeTimesController.java @@ -1,58 +1,69 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-30 - */ -package com.rop.sample; - -import com.rop.security.InvokeTimesController; -import com.rop.session.Session; - -import java.util.HashMap; -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleInvokeTimesController implements InvokeTimesController { - - private static Map appCallLimits = new HashMap(); - private static Map appCallCounter = new HashMap(); - static { - appCallLimits.put("00002",10); - } - - - public void caculateInvokeTimes(String appKey, Session session) { - if(!appCallCounter.containsKey(appKey)){ - appCallCounter.put(appKey,0); - } - appCallCounter.put(appKey,appCallCounter.get(appKey)+1); - } - - - public boolean isUserInvokeLimitExceed(String appKey, Session session) { - return false; - } - - - public boolean isSessionInvokeLimitExceed(String appKey, String sessionId) { - return false; - } - - - public boolean isAppInvokeLimitExceed(String appKey) { - return appCallLimits.containsKey(appKey) && - appCallCounter.get(appKey) > appCallLimits.get(appKey) ; - } - - - public boolean isAppInvokeFrequencyExceed(String appKey) { - return false; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.security.InvokeTimesController; +import com.rop.session.Session; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleInvokeTimesController implements InvokeTimesController { + + private static Map appCallLimits = new HashMap(); + private static Map appCallCounter = new HashMap(); + static { + appCallLimits.put("00002",10); + } + + + public void caculateInvokeTimes(String appKey, Session session) { + if(!appCallCounter.containsKey(appKey)){ + appCallCounter.put(appKey,0); + } + appCallCounter.put(appKey,appCallCounter.get(appKey)+1); + } + + + public boolean isUserInvokeLimitExceed(String appKey, Session session) { + return false; + } + + + public boolean isSessionInvokeLimitExceed(String appKey, String sessionId) { + return false; + } + + + public boolean isAppInvokeLimitExceed(String appKey) { + return appCallLimits.containsKey(appKey) && + appCallCounter.get(appKey) > appCallLimits.get(appKey) ; + } + + + public boolean isAppInvokeFrequencyExceed(String appKey) { + return false; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SamplePostInitializeEventListener.java b/rop-sample/src/main/java/com/rop/sample/SamplePostInitializeEventListener.java index c219803..3e0c831 100644 --- a/rop-sample/src/main/java/com/rop/sample/SamplePostInitializeEventListener.java +++ b/rop-sample/src/main/java/com/rop/sample/SamplePostInitializeEventListener.java @@ -1,30 +1,41 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.sample; - -import com.rop.event.AfterStartedRopEvent; -import com.rop.event.RopEventListener; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SamplePostInitializeEventListener implements RopEventListener { - - - public void onRopEvent(AfterStartedRopEvent ropRopEvent) { - System.out.println("execute SamplePostInitializeEventListener!"); - } - - - public int getOrder() { - return 0; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.event.AfterStartedRopEvent; +import com.rop.event.RopEventListener; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SamplePostInitializeEventListener implements RopEventListener { + + + public void onRopEvent(AfterStartedRopEvent ropRopEvent) { + System.out.println("execute SamplePostInitializeEventListener!"); + } + + + public int getOrder() { + return 0; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SamplePreDoServiceEventListener.java b/rop-sample/src/main/java/com/rop/sample/SamplePreDoServiceEventListener.java index 0e8250b..fe2d7c3 100644 --- a/rop-sample/src/main/java/com/rop/sample/SamplePreDoServiceEventListener.java +++ b/rop-sample/src/main/java/com/rop/sample/SamplePreDoServiceEventListener.java @@ -1,40 +1,48 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-17 - */ -package com.rop.sample; - -import com.rop.RopRequest; -import com.rop.RopRequestContext; -import com.rop.event.PreDoServiceEvent; -import com.rop.event.RopEventListener; -import com.rop.marshaller.MessageMarshallerUtils; - -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SamplePreDoServiceEventListener implements RopEventListener { - - - public void onRopEvent(PreDoServiceEvent ropEvent) { - RopRequestContext ropRequestContext = ropEvent.getRopRequestContext(); - if(ropRequestContext != null){ - Map allParams = ropRequestContext.getAllParams(); - String message = MessageMarshallerUtils.asUrlString(allParams); - System.out.println("message("+ropEvent.getServiceBeginTime()+")"+message); - } - } - - - public int getOrder() { - return 1; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.RopRequestContext; +import com.rop.event.PreDoServiceEvent; +import com.rop.event.RopEventListener; +import com.rop.sample.utils.UrlUtils; + +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SamplePreDoServiceEventListener implements RopEventListener { + + public void onRopEvent(PreDoServiceEvent ropEvent) { + RopRequestContext ropRequestContext = ropEvent.getRopRequestContext(); + if(ropRequestContext != null){ + Map allParams = ropRequestContext.getAllParams(); + String message = UrlUtils.asUrlString(allParams); + System.out.println("message("+ropEvent.getServiceBeginTime()+")"+message); + } + } + + public int getOrder() { + return 1; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleServiceAccessController.java b/rop-sample/src/main/java/com/rop/sample/SampleServiceAccessController.java index ec1f608..d92737f 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleServiceAccessController.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleServiceAccessController.java @@ -1,50 +1,61 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-25 - */ -package com.rop.sample; - -import com.rop.security.ServiceAccessController; -import com.rop.session.Session; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleServiceAccessController implements ServiceAccessController { - - private static final Map> aclMap = new HashMap>(); - - static { - ArrayList serviceMethods = new ArrayList(); - serviceMethods.add("user.logon"); - serviceMethods.add("user.logout"); - serviceMethods.add("user.getSession"); - aclMap.put("00003", serviceMethods); - } - - - public boolean isAppGranted(String appKey, String method, String version) { - if(aclMap.containsKey(appKey)){ - List serviceMethods = aclMap.get(appKey); - return serviceMethods.contains(method); - }else{ - return true; - } - } - - - public boolean isUserGranted(Session session, String method, String version) { - return true; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.security.ServiceAccessController; +import com.rop.session.Session; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleServiceAccessController implements ServiceAccessController { + + private static final Map> aclMap = new HashMap>(); + + static { + ArrayList serviceMethods = new ArrayList(); + serviceMethods.add("user.logon"); + serviceMethods.add("user.logout"); + serviceMethods.add("user.getSession"); + aclMap.put("00003", serviceMethods); + } + + + public boolean isAppGranted(String appKey, String method, String version) { + if(aclMap.containsKey(appKey)){ + List serviceMethods = aclMap.get(appKey); + return serviceMethods.contains(method); + }else{ + return true; + } + } + + + public boolean isUserGranted(Session session, String method, String version) { + return true; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleSessionManager.java b/rop-sample/src/main/java/com/rop/sample/SampleSessionManager.java index a2a43a1..b1ef6c5 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleSessionManager.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleSessionManager.java @@ -1,43 +1,54 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-17 - */ -package com.rop.sample; - -import com.rop.session.Session; -import com.rop.session.SessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleSessionManager implements SessionManager{ - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private final Map sessionCache = new ConcurrentHashMap(128, 0.75f, 32); - - - public void addSession(String sessionId, Session session) { - sessionCache.put(sessionId, session); - } - - - public Session getSession(String sessionId) { - return sessionCache.get(sessionId); - } - - - public void removeSession(String sessionId) { - sessionCache.remove(sessionId); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.session.Session; +import com.rop.session.SessionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleSessionManager implements SessionManager{ + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private final Map sessionCache = new ConcurrentHashMap(128, 0.75f, 32); + + + public void addSession(String sessionId, Session session) { + sessionCache.put(sessionId, session); + } + + + public Session getSession(String sessionId) { + return sessionCache.get(sessionId); + } + + + public void removeSession(String sessionId) { + sessionCache.remove(sessionId); + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/SampleThreadFerry.java b/rop-sample/src/main/java/com/rop/sample/SampleThreadFerry.java index 149f548..f6297f3 100644 --- a/rop-sample/src/main/java/com/rop/sample/SampleThreadFerry.java +++ b/rop-sample/src/main/java/com/rop/sample/SampleThreadFerry.java @@ -1,29 +1,40 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-20 - */ -package com.rop.sample; - -import com.rop.ThreadFerry; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SampleThreadFerry implements ThreadFerry{ - - - public void doInSrcThread() { - System.out.println("doInSrcThread:"+Thread.currentThread().getId()); - } - - - public void doInDestThread() { - System.out.println("doInSrcThread:"+Thread.currentThread().getId()); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.ThreadFerry; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SampleThreadFerry implements ThreadFerry{ + + + public void doInSrcThread() { + System.out.println("doInSrcThread:"+Thread.currentThread().getId()); + } + + + public void doInDestThread() { + System.out.println("doInSrcThread:"+Thread.currentThread().getId()); + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/UserService.java b/rop-sample/src/main/java/com/rop/sample/UserService.java index 810c971..e6277ac 100644 --- a/rop-sample/src/main/java/com/rop/sample/UserService.java +++ b/rop-sample/src/main/java/com/rop/sample/UserService.java @@ -1,256 +1,264 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.sample; - -import com.rop.Constants; -import com.rop.RopRequest; -import com.rop.annotation.*; -import com.rop.response.BusinessServiceErrorResponse; -import com.rop.response.NotExistErrorResponse; -import com.rop.sample.request.CreateUserRequest; -import com.rop.sample.request.LogonRequest; -import com.rop.sample.request.UploadUserPhotoRequest; -import com.rop.sample.response.*; -import com.rop.session.Session; -import com.rop.session.SimpleSession; -import org.springframework.core.io.ClassPathResource; -import org.springframework.util.FileCopyUtils; - -import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@ServiceMethodBean(version = "1.0") -public class UserService extends AbstractUserService{ - - private static final String USER_NAME_RESERVED = "USER_NAME_RESERVED"; - private List reservesUserNames = Arrays.asList(new String[]{"toms", "jhon"}); - - - public Object getSession(LogonRequest request) { - - //创建一个会话 - SimpleSession session = new SimpleSession(); - session.setAttribute("userName", request.getUserName()); - request.getRopRequestContext().addSession("mockSessionId1", session); - - //返回响应 - LogonResponse logonResponse = new LogonResponse(); - logonResponse.setSessionId("mockSessionId1"); - return logonResponse; - } - - @ServiceMethod(method = "user.logon",version = "1.0",needInSession = NeedInSessionType.NO) - public Object logon(LogonRequest request) { - //创建一个会话 - SimpleSession session = new SimpleSession(); - session.setAttribute("userName",request.getUserName()); - request.getRopRequestContext().addSession("mockSessionId1", session); - - //返回响应 - LogonResponse logonResponse = new LogonResponse(); - logonResponse.setSessionId("mockSessionId1"); - return logonResponse; - } - - @ServiceMethod(method = "user.logout",version = "1.0") - public Object logout(RopRequest request) { - request.getRopRequestContext().removeSession(); - LogoutResponse response = new LogoutResponse(); - response.setSuccessful(true); - return response; - } - - /** - * 过期版本的服务方法 - * @param request - * @return - */ - @ServiceMethod(method = "user.add", version = "0.9",obsoleted = ObsoletedType.YES) - public Object addUserOfV0_9(CreateUserRequest request) { - request.getRopRequestContext().getLocale(); - if (reservesUserNames.contains(request.getUserName())) { - return new BusinessServiceErrorResponse( - request.getRopRequestContext(),USER_NAME_RESERVED,request.getUserName()); - } else { - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010101"); - response.setUserId("1"); - return response; - } - } - - @ServiceMethod(method = "user.add", version = "1.0")//② Let this method service the sample.user.add method - public Object addUser(CreateUserRequest request) { - if (reservesUserNames.contains(request.getUserName())) { //如果注册的用户是预留的帐号,则返回错误的报文 - //这个业务错误将引用扩展国际化错误资源中的消息(i18n/rop/sampleRopError) - return new BusinessServiceErrorResponse( - request.getRopRequestContext(), USER_NAME_RESERVED,request.getUserName()); - } else { - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010101"); - response.setUserId("1"); - response.setFeedback("hello"); - response.setDate(new Date()); - response.setFooList(Arrays.asList(new Foo("1","1"),new Foo("2","2"))); - - Session session = request.getRopRequestContext().getSession(); - session.setAttribute("aa","bb"); - - return response; - } - } - - //版本为2.0的user.add - @ServiceMethod(method = "user.add", version = "2.0") - public Object addUser2(CreateUserRequest request) { - if (reservesUserNames.contains(request.getUserName())) { //如果注册的用户是预留的帐号,则返回错误的报文 - return new BusinessServiceErrorResponse( - request.getRopRequestContext(), USER_NAME_RESERVED, request.getUserName()); - } else { - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId("2"); - return response; - } - } - - //版本为4.0的user.add:不需要会话 - @ServiceMethod(method = "user.add", version = "4.0", needInSession = NeedInSessionType.NO) - public Object addUser4(CreateUserRequest request) { - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId("4"); - return response; - } - - //版本为5.0的user.add:不需要进行签名验证 - @ServiceMethod(method = "user.add", version = "5.0", ignoreSign = IgnoreSignType.YES) - public Object addUser5(CreateUserRequest request) { - CreateUserResponse response = new CreateUserResponse(); - response.setCreateTime("20120101010102"); - response.setUserId("4"); - return response; - } - - //模拟一个会过期的服务(过期时间为1秒) - @ServiceMethod(method = "user.timeout", version = "1.0", timeout = 1) - public Object timeoutService(CreateUserRequest request) throws Throwable { - Thread.sleep(2000); - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId("2"); - return response; - } - - @ServiceMethod(method = "user.rawRopRequest", version = "1.0") - public Object useRawRopRequest(RopRequest request) throws Throwable { - String userId = request.getRopRequestContext().getParamValue("userId"); - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId(userId); - return response; - } - - @ServiceMethod(method = "user.customConverter", version = "1.0") - public Object customConverter(CreateUserRequest request) throws Throwable { - String userId = request.getRopRequestContext().getParamValue("userId"); - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId(userId); - response.setFeedback(request.getTelephone().getZoneCode() + "#" + request.getTelephone().getTelephoneCode()); - return response; - } - - //直接使用RopRequest对象作为入参 - @ServiceMethod(method = "user.query", version = "1.0", httpAction = HttpAction.GET) - public Object queryUsers(RopRequest request) throws Throwable { - //直接从参数列表中获取参数值 - String userId = request.getRopRequestContext().getParamValue("userId"); - CreateUserResponse response = new CreateUserResponse(); - response.setCreateTime("20120101010102"); - response.setUserId(userId); - response.setFeedback("user.query"); - return response; - } - - /** - * 当userId为9999时,模拟一个NotExistErrorResponse的响应 - * @param request - * @return - * @throws Throwable - */ - @ServiceMethod(method = "user.get", version = "1.0", httpAction = HttpAction.GET) - public Object getUser(RopRequest request) throws Throwable { - String userId = request.getRopRequestContext().getParamValue("userId"); - if("9999".equals(userId)){ - return new NotExistErrorResponse("user","userId","9999",request.getRopRequestContext().getLocale()); - }else{ - CreateUserResponse response = new CreateUserResponse(); - //add creaet new user here... - response.setCreateTime("20120101010102"); - response.setUserId(userId); - response.setFeedback("user.get"); - return response; - } - } - - /** - * 上传用户头像的图片 - * @param request - * @return - * @throws Throwable - */ - @ServiceMethod(method = "user.upload.photo", version = "1.0", httpAction = HttpAction.POST) - public Object uploadPhoto(UploadUserPhotoRequest request) throws Throwable { - String fileType = request.getPhoto().getFileType(); - int length = request.getPhoto().getContent().length; - ClassPathResource outFile = new ClassPathResource("/"); - FileCopyUtils.copy(request.getPhoto().getContent(),new File(outFile.getFile().getParent()+"/1." + fileType)); - UploadUserPhotoResponse response = new UploadUserPhotoResponse(); - response.setFileType(fileType); - response.setLength(length); - return response; - } - - - @ServiceMethod(method = "user.list", version = "1.0", httpAction = HttpAction.GET) - public Object userList(RopRequest ropRequest) throws Throwable { - return new UserListResponse(); - } - - @ServiceMethod(method = "img.get", version = "1.0", - httpAction = HttpAction.GET, - ignoreSign = IgnoreSignType.YES, - needInSession = NeedInSessionType.NO) - public void getImg(RopRequest ropRequest) throws Throwable { - HttpServletResponse response = (HttpServletResponse) - ropRequest.getRopRequestContext().getRawResponseObject(); - response.setCharacterEncoding(Constants.UTF8); - response.setContentType("image/jpeg;charset=UTF-8"); - ClassPathResource resource = new ClassPathResource("img/img1.jpg"); - FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream()); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.RopRequest; +import com.rop.annotation.*; +import com.rop.response.BusinessServiceErrorResponse; +import com.rop.response.NotExistErrorResponse; +import com.rop.sample.request.CreateUserRequest; +import com.rop.sample.request.LogonRequest; +import com.rop.sample.request.UploadUserPhotoRequest; +import com.rop.sample.response.*; +import com.rop.session.Session; +import com.rop.session.SimpleSession; +import org.springframework.core.io.ClassPathResource; +import org.springframework.util.FileCopyUtils; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@ServiceMethodBean(version = "1.0") +public class UserService extends AbstractUserService{ + + private static final String USER_NAME_RESERVED = "USER_NAME_RESERVED"; + private List reservesUserNames = Arrays.asList(new String[]{"toms", "jhon"}); + + + public Object getSession(LogonRequest request) { + + //创建一个会话 + SimpleSession session = new SimpleSession(); + session.setAttribute("userName", request.getUserName()); + request.getRopRequestContext().addSession("mockSessionId1", session); + + //返回响应 + LogonResponse logonResponse = new LogonResponse(); + logonResponse.setSessionId("mockSessionId1"); + return logonResponse; + } + + @ServiceMethod(method = "user.logon",version = "1.0",needInSession = NeedInSessionType.NO) + public Object logon(LogonRequest request) { + //创建一个会话 + SimpleSession session = new SimpleSession(); + session.setAttribute("userName",request.getUserName()); + request.getRopRequestContext().addSession("mockSessionId1", session); + + //返回响应 + LogonResponse logonResponse = new LogonResponse(); + logonResponse.setSessionId("mockSessionId1"); + return logonResponse; + } + + @ServiceMethod(method = "user.logout",version = "1.0") + public Object logout(RopRequest request) { + request.getRopRequestContext().removeSession(); + LogoutResponse response = new LogoutResponse(); + response.setSuccessful(true); + return response; + } + + /** + * 过期版本的服务方法 + * @param request + * @return + */ + @ServiceMethod(method = "user.add", version = "0.9",obsoleted = ObsoletedType.YES) + public Object addUserOfV0_9(CreateUserRequest request) { + request.getRopRequestContext().getLocale(); + if (reservesUserNames.contains(request.getUserName())) { + return new BusinessServiceErrorResponse( + request.getRopRequestContext(),USER_NAME_RESERVED,request.getUserName()); + } else { + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010101"); + response.setUserId("1"); + return response; + } + } + + @ServiceMethod(method = "user.add", version = "1.0")//② Let this method service the sample.user.add method + public Object addUser(CreateUserRequest request) { + if (reservesUserNames.contains(request.getUserName())) { //如果注册的用户是预留的帐号,则返回错误的报文 + //这个业务错误将引用扩展国际化错误资源中的消息(i18n/rop/sampleRopError) + return new BusinessServiceErrorResponse( + request.getRopRequestContext(), USER_NAME_RESERVED,request.getUserName()); + } else { + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010101"); + response.setUserId("1"); + response.setFeedback("hello"); + response.setDate(new Date()); + response.setFooList(Arrays.asList(new Foo("1","1"),new Foo("2","2"))); + + Session session = request.getRopRequestContext().getSession(); + session.setAttribute("aa","bb"); + + return response; + } + } + + //版本为2.0的user.add + @ServiceMethod(method = "user.add", version = "2.0") + public Object addUser2(CreateUserRequest request) { + if (reservesUserNames.contains(request.getUserName())) { //如果注册的用户是预留的帐号,则返回错误的报文 + return new BusinessServiceErrorResponse( + request.getRopRequestContext(), USER_NAME_RESERVED, request.getUserName()); + } else { + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId("2"); + return response; + } + } + + //版本为4.0的user.add:不需要会话 + @ServiceMethod(method = "user.add", version = "4.0", needInSession = NeedInSessionType.NO) + public Object addUser4(CreateUserRequest request) { + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId("4"); + return response; + } + + //版本为5.0的user.add:不需要进行签名验证 + @ServiceMethod(method = "user.add", version = "5.0", ignoreSign = IgnoreSignType.YES) + public Object addUser5(CreateUserRequest request) { + CreateUserResponse response = new CreateUserResponse(); + response.setCreateTime("20120101010102"); + response.setUserId("4"); + return response; + } + + //模拟一个会过期的服务(过期时间为1秒) + @ServiceMethod(method = "user.timeout", version = "1.0", timeout = 1) + public Object timeoutService(CreateUserRequest request) throws Throwable { + Thread.sleep(2000); + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId("2"); + return response; + } + + @ServiceMethod(method = "user.rawRopRequest", version = "1.0") + public Object useRawRopRequest(RopRequest request) throws Throwable { + String userId = request.getRopRequestContext().getParamValue("userId"); + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId(userId); + return response; + } + + @ServiceMethod(method = "user.customConverter", version = "1.0") + public Object customConverter(CreateUserRequest request) throws Throwable { + String userId = request.getRopRequestContext().getParamValue("userId"); + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId(userId); + response.setFeedback(request.getTelephone().getZoneCode() + "#" + request.getTelephone().getTelephoneCode()); + return response; + } + + //直接使用RopRequest对象作为入参 + @ServiceMethod(method = "user.query", version = "1.0", httpAction = HttpAction.GET) + public Object queryUsers(RopRequest request) throws Throwable { + //直接从参数列表中获取参数值 + String userId = request.getRopRequestContext().getParamValue("userId"); + CreateUserResponse response = new CreateUserResponse(); + response.setCreateTime("20120101010102"); + response.setUserId(userId); + response.setFeedback("user.query"); + return response; + } + + /** + * 当userId为9999时,模拟一个NotExistErrorResponse的响应 + * @param request + * @return + * @throws Throwable + */ + @ServiceMethod(method = "user.get", version = "1.0", httpAction = HttpAction.GET) + public Object getUser(RopRequest request) throws Throwable { + String userId = request.getRopRequestContext().getParamValue("userId"); + if("9999".equals(userId)){ + return new NotExistErrorResponse("user","userId","9999",request.getRopRequestContext().getLocale()); + }else{ + CreateUserResponse response = new CreateUserResponse(); + //add creaet new user here... + response.setCreateTime("20120101010102"); + response.setUserId(userId); + response.setFeedback("user.get"); + return response; + } + } + + /** + * 上传用户头像的图片 + * @param request + * @return + * @throws Throwable + */ + @ServiceMethod(method = "user.upload.photo", version = "1.0", httpAction = HttpAction.POST) + public Object uploadPhoto(UploadUserPhotoRequest request) throws Throwable { + String fileType = request.getPhoto().getFileType(); + int length = request.getPhoto().getContent().length; + ClassPathResource outFile = new ClassPathResource("/"); + FileCopyUtils.copy(request.getPhoto().getContent(),new File(outFile.getFile().getParent()+"/1." + fileType)); + UploadUserPhotoResponse response = new UploadUserPhotoResponse(); + response.setFileType(fileType); + response.setLength(length); + return response; + } + + + @ServiceMethod(method = "user.list", version = "1.0", httpAction = HttpAction.GET) + public Object userList(RopRequest ropRequest) throws Throwable { + return new UserListResponse(); + } + + @ServiceMethod(method = "img.get", version = "1.0", + httpAction = HttpAction.GET, + ignoreSign = IgnoreSignType.YES, + needInSession = NeedInSessionType.NO) + public void getImg(RopRequest ropRequest) throws Throwable { + HttpServletResponse response = (HttpServletResponse) + ropRequest.getRopRequestContext().getRawResponseObject(); + response.setContentType("image/jpeg;charset=UTF-8"); + ClassPathResource resource = new ClassPathResource("img/img1.jpg"); + FileCopyUtils.copy(resource.getInputStream(), response.getOutputStream()); + } + +} + diff --git a/rop-sample/src/main/java/com/rop/sample/UserServiceInterface.java b/rop-sample/src/main/java/com/rop/sample/UserServiceInterface.java index f30090d..16382d2 100644 --- a/rop-sample/src/main/java/com/rop/sample/UserServiceInterface.java +++ b/rop-sample/src/main/java/com/rop/sample/UserServiceInterface.java @@ -1,19 +1,30 @@ -/** - * Copyright:中软海晟信息科技有限公司 版权所有 违者必究 2014 - */ -package com.rop.sample; - -import com.rop.annotation.NeedInSessionType; -import com.rop.annotation.ServiceMethod; -import com.rop.annotation.ServiceMethodBean; -import com.rop.sample.request.LogonRequest; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-3-6 - */ -public interface UserServiceInterface { - - @ServiceMethod(method = "user.getSession",version = "1.0",needInSession = NeedInSessionType.NO) - Object getSession(LogonRequest request); -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.annotation.NeedInSessionType; +import com.rop.annotation.ServiceMethod; +import com.rop.sample.request.LogonRequest; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-3-6 + */ +public interface UserServiceInterface { + + @ServiceMethod(method = "user.getSession",version = "1.0",needInSession = NeedInSessionType.NO) + Object getSession(LogonRequest request); +} diff --git a/rop-sample/src/main/java/com/rop/sample/client/RopSampleClient.java b/rop-sample/src/main/java/com/rop/sample/client/RopSampleClient.java index 21e187f..83fde0e 100644 --- a/rop-sample/src/main/java/com/rop/sample/client/RopSampleClient.java +++ b/rop-sample/src/main/java/com/rop/sample/client/RopSampleClient.java @@ -1,62 +1,78 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-4 - */ -package com.rop.sample.client; - -import com.rop.client.ClientRequest; -import com.rop.client.CompositeResponse; -import com.rop.client.DefaultRopClient; -import com.rop.sample.request.LogonRequest; -import com.rop.sample.converter.TelephoneConverter; -import com.rop.sample.response.LogonResponse; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopSampleClient { - - public static final String SERVER_URL = "http://localhost:8088/router"; - - private DefaultRopClient ropClient ; - - /** - * 创建客户端对象 - * @param appKey - * @param secret - */ - public RopSampleClient(String appKey,String secret) { - ropClient = new DefaultRopClient(SERVER_URL, appKey, secret); - ropClient.setFormatParamName("messageFormat"); - ropClient.addRopConvertor(new TelephoneConverter()); - } - - /** - * 登录系统 - * - * @return - */ - public String logon(String userName, String password) { - LogonRequest ropRequest = new LogonRequest(); - ropRequest.setUserName("tomson"); - ropRequest.setPassword("123456"); - CompositeResponse response = ropClient.buildClientRequest().get(ropRequest, LogonResponse.class, "user.logon", "1.0"); - String sessionId = ((LogonResponse) response.getSuccessResponse()).getSessionId(); - ropClient.setSessionId(sessionId); - return sessionId; - } - - public void logout() { - ropClient.buildClientRequest().get(LogonResponse.class, "user.logout", "1.0"); - } - - public ClientRequest buildClientRequest(){ - return ropClient.buildClientRequest(); - } -} - +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.client; + +import java.io.IOException; + +import com.rop.client.ClientRequest; +import com.rop.client.CompositeResponse; +import com.rop.client.DefaultRopClient; +import com.rop.sample.request.LogonRequest; +import com.rop.sample.converter.TelephoneConverter; +import com.rop.sample.response.LogonResponse; +import com.rop.client.sign.DigestSignHandler; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopSampleClient { + + public static final String SERVER_URL = "http://localhost:8088/router"; + + private DefaultRopClient ropClient ; + + /** + * 创建客户端对象 + * @param appKey + * @param secret + */ + public RopSampleClient(String appKey,String secret) { + ropClient = new DefaultRopClient(SERVER_URL, appKey); + ropClient.setSignHandler(new DigestSignHandler("SHA-1", secret)); + ropClient.setFormatParamName("messageFormat"); + ropClient.addRopConvertor(new TelephoneConverter()); + } + + /** + * 登录系统 + * + * @return + * @throws IOException + */ + public String logon(String userName, String password) throws IOException { + LogonRequest ropRequest = new LogonRequest(); + ropRequest.setUserName("tomson"); + ropRequest.setPassword("123456"); + CompositeResponse response = ropClient.buildClientRequest().get(ropRequest, LogonResponse.class, "user.logon", "1.0"); + String sessionId = response.getSuccessResponse().getSessionId(); + ropClient.setSessionId(sessionId); + return sessionId; + } + + public void logout() throws IOException { + ropClient.buildClientRequest().get(LogonResponse.class, "user.logout", "1.0"); + } + + public ClientRequest buildClientRequest(){ + return ropClient.buildClientRequest(); + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/converter/CollectionsConverter.java b/rop-sample/src/main/java/com/rop/sample/converter/CollectionsConverter.java index e2616df..53aa93a 100644 --- a/rop-sample/src/main/java/com/rop/sample/converter/CollectionsConverter.java +++ b/rop-sample/src/main/java/com/rop/sample/converter/CollectionsConverter.java @@ -1,40 +1,50 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-8 - */ -package com.rop.sample.converter; - -import com.rop.request.RopConverter; - -import java.util.Collection; -import java.util.List; - -/** - * Created with IntelliJ IDEA. - * User: stamen - * Date: 13-10-25 - * Time: 上午11:54 - * To change this template use File | Settings | File Templates. - */ -public class CollectionsConverter implements RopConverter { - - - public String unconvert(Collection target) { - return null; - } - - - public Class getSourceClass() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - - public Class getTargetClass() { - return null; //To change body of implemented methods use File | Settings | File Templates. - } - - - public Collection convert(String s) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.converter; + +import com.rop.converter.RopConverter; + +import java.util.Collection; + +/** + * Created with IntelliJ IDEA. + * User: stamen + * Date: 13-10-25 + * Time: 上午11:54 + * To change this template use File | Settings | File Templates. + */ +public class CollectionsConverter implements RopConverter> { + + + public String unconvert(Collection target) { + return null; + } + + + public Class getSourceClass() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + + public Class> getTargetClass() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + + public Collection convert(String s) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } +} diff --git a/rop-sample/src/main/java/com/rop/sample/converter/DateConverter.java b/rop-sample/src/main/java/com/rop/sample/converter/DateConverter.java index 367c3ba..8c8ccb4 100644 --- a/rop-sample/src/main/java/com/rop/sample/converter/DateConverter.java +++ b/rop-sample/src/main/java/com/rop/sample/converter/DateConverter.java @@ -1,36 +1,47 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-8 - */ -package com.rop.sample.converter; - -import com.rop.request.RopConverter; - -import java.util.Date; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-3-18 - */ -public class DateConverter implements RopConverter { - - - public Date convert(String s) { - return DateUtils.parseDate(s); - } - - - public String unconvert(Date date) { - return DateUtils.format(date,DateUtils.DATETIME_FORMAT); - } - - - public Class getSourceClass() { - return String.class; - } - - - public Class getTargetClass() { - return Date.class; - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.converter; + +import com.rop.converter.RopConverter; + +import java.util.Date; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-3-18 + */ +public class DateConverter implements RopConverter { + + + public Date convert(String s) { + return DateUtils.parseDate(s); + } + + + public String unconvert(Date date) { + return DateUtils.format(date,DateUtils.DATETIME_FORMAT); + } + + + public Class getSourceClass() { + return String.class; + } + + + public Class getTargetClass() { + return Date.class; + } +} diff --git a/rop-sample/src/main/java/com/rop/sample/converter/DateUtils.java b/rop-sample/src/main/java/com/rop/sample/converter/DateUtils.java index e3e8e22..8580af7 100644 --- a/rop-sample/src/main/java/com/rop/sample/converter/DateUtils.java +++ b/rop-sample/src/main/java/com/rop/sample/converter/DateUtils.java @@ -1,175 +1,186 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-27 - */ -package com.rop.sample.converter; - -import org.apache.commons.lang.StringUtils; -import org.springframework.util.Assert; - -import java.text.DateFormat; -import java.text.MessageFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 时间日期的工具类 - * - * @author : chenxh(quickselect@163.com) - * @date: 13-7-1 - */ -public class DateUtils { - - public static final String DATETIME_FORMAT = "yyyyMMddHHmmss"; - public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(DATETIME_FORMAT); - public static final String DATE_FORMAT = "yyyyMMdd"; - public static final String SHOW_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; - public static final String SHOW_DATE_FORMAT = "yyyy-MM-dd"; - - /** - * 获取当前时间串,格式为:yyyymmddHHMiSS - * - * @return - */ - public static final String getCurrDatetime() { - return format(new Date(), DATETIME_FORMAT); - } - - /** - * 获取当前日期串,格式为yyyymmdd - * - * @return - */ - public static final String getCurrDate() { - return format(new Date(), DATE_FORMAT); - } - - - /** - * @param date 时间 - * @param formatStr 格式化串 - * @return - */ - public static String format(Date date, String formatStr) { - SimpleDateFormat sdf = new SimpleDateFormat(formatStr); - return sdf.format(date); - } - - /** - * 对{@code date}字符串,采用0右补齐到{@code length}的长度 - * - * @param date - * @param length - * @return - */ - public static String pad0(String date, int length) { - return padChar(date, length, '0'); - } - - /** - * 对{@code date}字符串,采用9右补齐到{@code length}的长度 - * - * @param date - * @param length - * @return - */ - public static String pad9(String date, int length) { - return padChar(date, length, '9'); - } - - private static String padChar(String date, int length, char theChar) { - if (StringUtils.isEmpty(date)) { - date = ""; - } - return StringUtils.rightPad(date, length, theChar); - } - - /** - * {@code time1}是否小于{@code time2},即类似于
time1 < time2
。 如果{@code time2}为null, - * 则视为最小。 - * - * @param time1 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补0 - * @param time2 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补0 - * @return - */ - public static boolean lessThan(String time1, String time2) { - if (StringUtils.isEmpty(time1)) { - if (StringUtils.isEmpty(time2)) { - return false; - } else { - return true; - } - } else { - return time1.compareTo(time2) < 0; - } - } - - - /** - * {@code time1}是否大于{@code time2},即类似于
time1 > time2
。如果{@code time2}为null, - * 则视为最大。 - * - * @param time1 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补9 - * @param time2 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补9 - * @return - */ - public static boolean greaterThan(String time1, String time2) { - if (StringUtils.isEmpty(time1)) { - if (StringUtils.isEmpty(time2)) { - return false; - } else { - return true; - } - } else { - return time1.compareTo(time2) > 0; - } - } - - /** - * 将datetime字符串时间转换为毫秒数 - * @param datetime 长度必须大于等于8而小于等于14,格式为 yyyyMMddHHmmss,不足14位后补0 - * @return - */ - public static long toMilliseconds(String datetime){ - return parseDate(datetime).getTime(); - } - - /** - * 将格式为{@link #DATETIME_FORMAT}的时间格式解析为Date对象,{@code datetime}的长度必须大于8小于14. - * @param datetime - * @return - */ - public static Date parseDate(String datetime){ - Assert.notNull(datetime); - Assert.isTrue(datetime.length() >= 4 && datetime.length() <= 14,"长度必须大于等于8而小于等于14"); - DateFormat dateFormat = SIMPLE_DATE_FORMAT; - try { - if(datetime.length() < 14){ - dateFormat = new SimpleDateFormat(DATETIME_FORMAT.substring(0, datetime.length())); - } - return dateFormat.parse(datetime); - } catch (ParseException e) { - throw new IllegalArgumentException("入参datetime:"+datetime+"解析异常,请检查格式必须为:"+DATETIME_FORMAT); - } - } - - /** - * 将字符串时间解析为对象 - * @param datetime - * @param format - * @return - */ - public static Date parseDate(String datetime,String format){ - Assert.notNull(datetime); - Assert.notNull(format); - Assert.isTrue(datetime.length() == format.length(),"值和格式串的长度不一致"); - DateFormat dateFormat = new SimpleDateFormat(format); - try { - return dateFormat.parse(datetime); - } catch (ParseException e) { - throw new IllegalArgumentException( - MessageFormat.format("入参datetime:{1}解析异常,请检查格式必须为:{2}",datetime,format)); - } - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.converter; + +import org.apache.commons.lang.StringUtils; +import org.springframework.util.Assert; + +import java.text.DateFormat; +import java.text.MessageFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 时间日期的工具类 + * + * @author : chenxh(quickselect@163.com) + * @date: 13-7-1 + */ +public class DateUtils { + + public static final String DATETIME_FORMAT = "yyyyMMddHHmmss"; + public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat(DATETIME_FORMAT); + public static final String DATE_FORMAT = "yyyyMMdd"; + public static final String SHOW_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String SHOW_DATE_FORMAT = "yyyy-MM-dd"; + + /** + * 获取当前时间串,格式为:yyyymmddHHMiSS + * + * @return + */ + public static final String getCurrDatetime() { + return format(new Date(), DATETIME_FORMAT); + } + + /** + * 获取当前日期串,格式为yyyymmdd + * + * @return + */ + public static final String getCurrDate() { + return format(new Date(), DATE_FORMAT); + } + + + /** + * @param date 时间 + * @param formatStr 格式化串 + * @return + */ + public static String format(Date date, String formatStr) { + SimpleDateFormat sdf = new SimpleDateFormat(formatStr); + return sdf.format(date); + } + + /** + * 对{@code date}字符串,采用0右补齐到{@code length}的长度 + * + * @param date + * @param length + * @return + */ + public static String pad0(String date, int length) { + return padChar(date, length, '0'); + } + + /** + * 对{@code date}字符串,采用9右补齐到{@code length}的长度 + * + * @param date + * @param length + * @return + */ + public static String pad9(String date, int length) { + return padChar(date, length, '9'); + } + + private static String padChar(String date, int length, char theChar) { + if (StringUtils.isEmpty(date)) { + date = ""; + } + return StringUtils.rightPad(date, length, theChar); + } + + /** + * {@code time1}是否小于{@code time2},即类似于
time1 < time2
。 如果{@code time2}为null, + * 则视为最小。 + * + * @param time1 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补0 + * @param time2 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补0 + * @return + */ + public static boolean lessThan(String time1, String time2) { + if (StringUtils.isEmpty(time1)) { + if (StringUtils.isEmpty(time2)) { + return false; + } else { + return true; + } + } else { + return time1.compareTo(time2) < 0; + } + } + + + /** + * {@code time1}是否大于{@code time2},即类似于
time1 > time2
。如果{@code time2}为null, + * 则视为最大。 + * + * @param time1 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补9 + * @param time2 时间字符串,格式为 yyyyMMddHHmmss,不足14位后补9 + * @return + */ + public static boolean greaterThan(String time1, String time2) { + if (StringUtils.isEmpty(time1)) { + if (StringUtils.isEmpty(time2)) { + return false; + } else { + return true; + } + } else { + return time1.compareTo(time2) > 0; + } + } + + /** + * 将datetime字符串时间转换为毫秒数 + * @param datetime 长度必须大于等于8而小于等于14,格式为 yyyyMMddHHmmss,不足14位后补0 + * @return + */ + public static long toMilliseconds(String datetime){ + return parseDate(datetime).getTime(); + } + + /** + * 将格式为{@link #DATETIME_FORMAT}的时间格式解析为Date对象,{@code datetime}的长度必须大于8小于14. + * @param datetime + * @return + */ + public static Date parseDate(String datetime){ + Assert.notNull(datetime); + Assert.isTrue(datetime.length() >= 4 && datetime.length() <= 14,"长度必须大于等于8而小于等于14"); + DateFormat dateFormat = SIMPLE_DATE_FORMAT; + try { + if(datetime.length() < 14){ + dateFormat = new SimpleDateFormat(DATETIME_FORMAT.substring(0, datetime.length())); + } + return dateFormat.parse(datetime); + } catch (ParseException e) { + throw new IllegalArgumentException("入参datetime:"+datetime+"解析异常,请检查格式必须为:"+DATETIME_FORMAT); + } + } + + /** + * 将字符串时间解析为对象 + * @param datetime + * @param format + * @return + */ + public static Date parseDate(String datetime,String format){ + Assert.notNull(datetime); + Assert.notNull(format); + Assert.isTrue(datetime.length() == format.length(),"值和格式串的长度不一致"); + DateFormat dateFormat = new SimpleDateFormat(format); + try { + return dateFormat.parse(datetime); + } catch (ParseException e) { + throw new IllegalArgumentException( + MessageFormat.format("入参datetime:{1}解析异常,请检查格式必须为:{2}",datetime,format)); + } + } +} diff --git a/rop-sample/src/main/java/com/rop/sample/converter/TelephoneConverter.java b/rop-sample/src/main/java/com/rop/sample/converter/TelephoneConverter.java index 93db76b..7c76657 100644 --- a/rop-sample/src/main/java/com/rop/sample/converter/TelephoneConverter.java +++ b/rop-sample/src/main/java/com/rop/sample/converter/TelephoneConverter.java @@ -1,55 +1,62 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-8 - */ -package com.rop.sample.converter; - -import com.rop.request.RopConverter; -import com.rop.sample.request.Telephone; -import org.springframework.core.convert.converter.Converter; -import org.springframework.util.StringUtils; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class TelephoneConverter implements RopConverter { - - - public Telephone convert(String source) { - if (StringUtils.hasText(source)) { - String zoneCode = source.substring(0, source.indexOf("-")); - String telephoneCode = source.substring(source.indexOf("-") + 1); - Telephone telephone = new Telephone(); - telephone.setZoneCode(zoneCode); - telephone.setTelephoneCode(telephoneCode); - return telephone; - } else { - return null; - } - } - - - public String unconvert(Telephone target) { - StringBuilder sb = new StringBuilder(); - sb.append(target.getZoneCode()); - sb.append("-"); - sb.append(target.getTelephoneCode()); - return sb.toString(); - } - - - public Class getSourceClass() { - return String.class; - } - - - public Class getTargetClass() { - return Telephone.class; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.converter; + +import com.rop.converter.RopConverter; +import com.rop.sample.request.Telephone; + +import org.springframework.util.StringUtils; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class TelephoneConverter implements RopConverter { + + public Telephone convert(String source) { + if (StringUtils.hasText(source)) { + String zoneCode = source.substring(0, source.indexOf("-")); + String telephoneCode = source.substring(source.indexOf("-") + 1); + Telephone telephone = new Telephone(); + telephone.setZoneCode(zoneCode); + telephone.setTelephoneCode(telephoneCode); + return telephone; + } else { + return null; + } + } + + public String unconvert(Telephone target) { + StringBuilder sb = new StringBuilder(); + sb.append(target.getZoneCode()); + sb.append("-"); + sb.append(target.getTelephoneCode()); + return sb.toString(); + } + + public Class getSourceClass() { + return String.class; + } + + public Class getTargetClass() { + return Telephone.class; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/Address.java b/rop-sample/src/main/java/com/rop/sample/request/Address.java index 730a662..40d3d0d 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/Address.java +++ b/rop-sample/src/main/java/com/rop/sample/request/Address.java @@ -1,72 +1,83 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.sample.request; - -import javax.validation.constraints.Pattern; -import javax.xml.bind.annotation.*; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "address") -public class Address { - - @XmlAttribute - @Pattern(regexp = "\\w{4,30}") - private String zoneCode; - - @XmlAttribute - private String doorCode; - - /** - * 在请求属性的属性类中,你可以使用接口的集合 - */ - @XmlElementWrapper(name = "streets") - @XmlElement(name = "street") - private List streets; - - @XmlElementWrapper(name = "codes") - private String[] codes; - - public String getZoneCode() { - return zoneCode; - } - - public void setZoneCode(String zoneCode) { - this.zoneCode = zoneCode; - } - - public String getDoorCode() { - return doorCode; - } - - public void setDoorCode(String doorCode) { - this.doorCode = doorCode; - } - - public List getStreets() { - return streets; - } - - public void setStreets(List streets) { - this.streets = streets; - } - - public String[] getCodes() { - return codes; - } - - public void setCodes(String[] codes) { - this.codes = codes; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +import javax.validation.constraints.Pattern; +import javax.xml.bind.annotation.*; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "address") +public class Address { + + @XmlAttribute + @Pattern(regexp = "\\w{4,30}") + private String zoneCode; + + @XmlAttribute + private String doorCode; + + /** + * 在请求属性的属性类中,你可以使用接口的集合 + */ + @XmlElementWrapper(name = "streets") + @XmlElement(name = "street") + private List streets; + + @XmlElementWrapper(name = "codes") + private String[] codes; + + public String getZoneCode() { + return zoneCode; + } + + public void setZoneCode(String zoneCode) { + this.zoneCode = zoneCode; + } + + public String getDoorCode() { + return doorCode; + } + + public void setDoorCode(String doorCode) { + this.doorCode = doorCode; + } + + public List getStreets() { + return streets; + } + + public void setStreets(List streets) { + this.streets = streets; + } + + public String[] getCodes() { + return codes; + } + + public void setCodes(String[] codes) { + this.codes = codes; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/CreateUserRequest.java b/rop-sample/src/main/java/com/rop/sample/request/CreateUserRequest.java index b4377aa..fe5b2ff 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/CreateUserRequest.java +++ b/rop-sample/src/main/java/com/rop/sample/request/CreateUserRequest.java @@ -1,143 +1,152 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.sample.request; - -import com.rop.AbstractRopRequest; -import com.rop.annotation.IgnoreSign; -import org.springframework.format.annotation.NumberFormat; - -import javax.validation.Valid; -import javax.validation.constraints.*; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import java.util.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class CreateUserRequest extends AbstractRopRequest { - - @NotNull - @Pattern(regexp = "\\w{4,30}") - private String userName; - - @IgnoreSign - @Pattern(regexp = "\\w{6,30}") - private String password; - - @DecimalMin("1000.00") - @DecimalMax("100000.00") - @NumberFormat(pattern = "#,###.##") - private long salary; - - @Valid - private Address address; - -// @Valid -// private List
addresses; -// -// private Map attachMap; - - private String format; - - private Telephone telephone; - - private boolean locked; - - private Date date; - - private String favorites[]; - - @Null - @Pattern(regexp = "^((EXCEL)|(WORD))$") - private String fileType; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public long getSalary() { - return salary; - } - - public void setSalary(long salary) { - this.salary = salary; - } - - public Address getAddress() { - return address; - } - - public void setAddress(Address address) { - this.address = address; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public Telephone getTelephone() { - return telephone; - } - - public void setTelephone(Telephone telephone) { - this.telephone = telephone; - } - - public boolean isLocked() { - return locked; - } - - public void setLocked(boolean locked) { - this.locked = locked; - } - - public String[] getFavorites() { - return favorites; - } - - public void setFavorites(String[] favorites) { - this.favorites = favorites; - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +import com.rop.AbstractRopRequest; +import com.rop.annotation.IgnoreSign; +import org.springframework.format.annotation.NumberFormat; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class CreateUserRequest extends AbstractRopRequest { + + @NotNull + @Pattern(regexp = "\\w{4,30}") + private String userName; + + @IgnoreSign + @Pattern(regexp = "\\w{6,30}") + private String password; + + @DecimalMin("1000.00") + @DecimalMax("100000.00") + @NumberFormat(pattern = "#,###.##") + private long salary; + + @Valid + private Address address; + +// @Valid +// private List
addresses; +// +// private Map attachMap; + + private String format; + + private Telephone telephone; + + private boolean locked; + + private Date date; + + private String favorites[]; + + @Null + @Pattern(regexp = "^((EXCEL)|(WORD))$") + private String fileType; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getFileType() { + return fileType; + } + + public void setFileType(String fileType) { + this.fileType = fileType; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public long getSalary() { + return salary; + } + + public void setSalary(long salary) { + this.salary = salary; + } + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public String getFormat() { + return format; + } + + public void setFormat(String format) { + this.format = format; + } + + public Telephone getTelephone() { + return telephone; + } + + public void setTelephone(Telephone telephone) { + this.telephone = telephone; + } + + public boolean isLocked() { + return locked; + } + + public void setLocked(boolean locked) { + this.locked = locked; + } + + public String[] getFavorites() { + return favorites; + } + + public void setFavorites(String[] favorites) { + this.favorites = favorites; + } + +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/LogonRequest.java b/rop-sample/src/main/java/com/rop/sample/request/LogonRequest.java index 13cbffa..d60d94e 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/LogonRequest.java +++ b/rop-sample/src/main/java/com/rop/sample/request/LogonRequest.java @@ -1,47 +1,56 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-14 - */ -package com.rop.sample.request; - -import com.rop.AbstractRopRequest; -import com.rop.annotation.IgnoreSign; - -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class LogonRequest extends AbstractRopRequest{ - - @NotNull - @Pattern(regexp = "\\w{4,30}") - private String userName; - - @IgnoreSign - @Pattern(regexp = "\\w{6,30}") - private String password; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +import com.rop.AbstractRopRequest; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class LogonRequest extends AbstractRopRequest{ + + @NotNull + @Pattern(regexp = "\\w{4,30}") + private String userName; + + @Pattern(regexp = "\\w{6,30}") + private String password; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/ReservedNames.java b/rop-sample/src/main/java/com/rop/sample/request/ReservedNames.java index a883641..ec89f65 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/ReservedNames.java +++ b/rop-sample/src/main/java/com/rop/sample/request/ReservedNames.java @@ -1,19 +1,30 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-18 - */ -package com.rop.sample.request; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ReservedNames { - - public static String TOM = "Tom"; -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ReservedNames { + + public static String TOM = "Tom"; +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/Street.java b/rop-sample/src/main/java/com/rop/sample/request/Street.java index 2cc16a2..e1a5afc 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/Street.java +++ b/rop-sample/src/main/java/com/rop/sample/request/Street.java @@ -1,46 +1,57 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.sample.request; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "street") -public class Street { - - @XmlAttribute - private String no; - - @XmlAttribute - private String name; - - public String getNo() { - return no; - } - - public void setNo(String no) { - this.no = no; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "street") +public class Street { + + @XmlAttribute + private String no; + + @XmlAttribute + private String name; + + public String getNo() { + return no; + } + + public void setNo(String no) { + this.no = no; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/Telephone.java b/rop-sample/src/main/java/com/rop/sample/request/Telephone.java index ffce8bb..5327c23 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/Telephone.java +++ b/rop-sample/src/main/java/com/rop/sample/request/Telephone.java @@ -1,37 +1,48 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-7 - */ -package com.rop.sample.request; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class Telephone { - - private String zoneCode; - - private String telephoneCode; - - public String getZoneCode() { - return zoneCode; - } - - public void setZoneCode(String zoneCode) { - this.zoneCode = zoneCode; - } - - public String getTelephoneCode() { - return telephoneCode; - } - - public void setTelephoneCode(String telephoneCode) { - this.telephoneCode = telephoneCode; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class Telephone { + + private String zoneCode; + + private String telephoneCode; + + public String getZoneCode() { + return zoneCode; + } + + public void setZoneCode(String zoneCode) { + this.zoneCode = zoneCode; + } + + public String getTelephoneCode() { + return telephoneCode; + } + + public void setTelephoneCode(String telephoneCode) { + this.telephoneCode = telephoneCode; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/request/UploadUserPhotoRequest.java b/rop-sample/src/main/java/com/rop/sample/request/UploadUserPhotoRequest.java index 6dcbb73..9bae029 100644 --- a/rop-sample/src/main/java/com/rop/sample/request/UploadUserPhotoRequest.java +++ b/rop-sample/src/main/java/com/rop/sample/request/UploadUserPhotoRequest.java @@ -1,40 +1,51 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.sample.request; - -import com.rop.AbstractRopRequest; -import com.rop.request.UploadFile; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class UploadUserPhotoRequest extends AbstractRopRequest { - - private String userId; - - private UploadFile photo; - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public UploadFile getPhoto() { - return photo; - } - - public void setPhoto(UploadFile photo) { - this.photo = photo; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.request; + +import com.rop.AbstractRopRequest; +import com.rop.converter.UploadFile; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UploadUserPhotoRequest extends AbstractRopRequest { + + private String userId; + + private UploadFile photo; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public UploadFile getPhoto() { + return photo; + } + + public void setPhoto(UploadFile photo) { + this.photo = photo; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/CreateUserResponse.java b/rop-sample/src/main/java/com/rop/sample/response/CreateUserResponse.java index 1d5a940..b617436 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/CreateUserResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/CreateUserResponse.java @@ -1,155 +1,165 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.sample.response; - - -import com.rop.sample.sys.DateXmlAdapter; - -import javax.xml.bind.annotation.*; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "createUserResponse") -public class CreateUserResponse{ - - @XmlAttribute - private String userId; - - @XmlAttribute - private String createTime; - - @XmlElement - private Foo foo = new Foo("0","0"); - - @XmlElement - private String feedback; - - @XmlAttribute - private Boolean status = true; - - @XmlAttribute - private Integer age = 10; - - @XmlAttribute - private Float height = 170.01f; - - @XmlElement - private List fooList; - - @XmlElement - private LinkedHashMap maps = new LinkedHashMap(); - { - maps.put("a","a"); - maps.put("b","b"); - maps.put("c","c"); - } - - @XmlElement - @XmlJavaTypeAdapter(DateXmlAdapter.class) - private Date date; - - private boolean ok = true; - - public List getFooList() { - return fooList; - } - - public void setFooList(List fooList) { - this.fooList = fooList; - } - - public Boolean getStatus() { - return status; - } - - public void setStatus(Boolean status) { - this.status = status; - } - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - - public Float getHeight() { - return height; - } - - public void setHeight(Float height) { - this.height = height; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getCreateTime() { - return createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public String getFeedback() { - return feedback; - } - - public LinkedHashMap getMaps() { - return maps; - } - - public void setMaps(LinkedHashMap maps) { - this.maps = maps; - } - - public void setFeedback(String feedback) { - this.feedback = feedback; - } - - public Foo getFoo() { - return foo; - } - - public void setFoo(Foo foo) { - this.foo = foo; - } - - public boolean isOk() { - return ok; - } - - public void setOk(boolean ok) { - this.ok = ok; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + + +import com.rop.sample.sys.DateXmlAdapter; + +import javax.xml.bind.annotation.*; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "createUserResponse") +public class CreateUserResponse{ + + @XmlAttribute + private String userId; + + @XmlAttribute + private String createTime; + + @XmlElement + private Foo foo = new Foo("0","0"); + + @XmlElement + private String feedback; + + @XmlAttribute + private Boolean status = true; + + @XmlAttribute + private Integer age = 10; + + @XmlAttribute + private Float height = 170.01f; + + @XmlElement + private List fooList; + + @XmlElement + private LinkedHashMap maps = new LinkedHashMap(); + { + maps.put("a","a"); + maps.put("b","b"); + maps.put("c","c"); + } + + @XmlElement + @XmlJavaTypeAdapter(DateXmlAdapter.class) + private Date date; + + private boolean ok = true; + + public List getFooList() { + return fooList; + } + + public void setFooList(List fooList) { + this.fooList = fooList; + } + + public Boolean getStatus() { + return status; + } + + public void setStatus(Boolean status) { + this.status = status; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Float getHeight() { + return height; + } + + public void setHeight(Float height) { + this.height = height; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getCreateTime() { + return createTime; + } + + public void setCreateTime(String createTime) { + this.createTime = createTime; + } + + public String getFeedback() { + return feedback; + } + + public LinkedHashMap getMaps() { + return maps; + } + + public void setMaps(LinkedHashMap maps) { + this.maps = maps; + } + + public void setFeedback(String feedback) { + this.feedback = feedback; + } + + public Foo getFoo() { + return foo; + } + + public void setFoo(Foo foo) { + this.foo = foo; + } + + public boolean isOk() { + return ok; + } + + public void setOk(boolean ok) { + this.ok = ok; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/Foo.java b/rop-sample/src/main/java/com/rop/sample/response/Foo.java index 1467760..fedc77b 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/Foo.java +++ b/rop-sample/src/main/java/com/rop/sample/response/Foo.java @@ -1,50 +1,61 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-14 - */ -package com.rop.sample.response; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "foo1") -public class Foo { - - @XmlAttribute - private String field1 = "1"; - - @XmlAttribute - private String field2 = "2"; - - public Foo() { - } - - public Foo(String field1, String field2) { - this.field1 = field1; - this.field2 = field2; - } - - public String getField1() { - return field1; - } - - public void setField1(String field1) { - this.field1 = field1; - } - - public String getField2() { - return field2; - } - - public void setField2(String field2) { - this.field2 = field2; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "foo1") +public class Foo { + + @XmlAttribute + private String field1 = "1"; + + @XmlAttribute + private String field2 = "2"; + + public Foo() { + } + + public Foo(String field1, String field2) { + this.field1 = field1; + this.field2 = field2; + } + + public String getField1() { + return field1; + } + + public void setField1(String field1) { + this.field1 = field1; + } + + public String getField2() { + return field2; + } + + public void setField2(String field2) { + this.field2 = field2; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/InterceptorResponse.java b/rop-sample/src/main/java/com/rop/sample/response/InterceptorResponse.java index c5e79c0..ce23138 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/InterceptorResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/InterceptorResponse.java @@ -1,36 +1,47 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-26 - */ -package com.rop.sample.response; - - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "createUserResponse") -public class InterceptorResponse { - - @XmlAttribute - private String testField; - - public String getTestField() { - return testField; - } - - public void setTestField(String testField) { - this.testField = testField; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "createUserResponse") +public class InterceptorResponse { + + @XmlAttribute + private String testField; + + public String getTestField() { + return testField; + } + + public void setTestField(String testField) { + this.testField = testField; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/LogonResponse.java b/rop-sample/src/main/java/com/rop/sample/response/LogonResponse.java index 4aa37c8..10a97a5 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/LogonResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/LogonResponse.java @@ -1,36 +1,47 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-21 - */ -package com.rop.sample.response; - - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "logonResponse") -public class LogonResponse{ - - @XmlAttribute - private String sessionId; - - public String getSessionId() { - return sessionId; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "logonResponse") +public class LogonResponse{ + + @XmlAttribute + private String sessionId; + + public String getSessionId() { + return sessionId; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/LogoutResponse.java b/rop-sample/src/main/java/com/rop/sample/response/LogoutResponse.java index 51c9d90..210b389 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/LogoutResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/LogoutResponse.java @@ -1,36 +1,47 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-7-29 - */ -package com.rop.sample.response; - - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "logonResponse") -public class LogoutResponse{ - - @XmlAttribute - private boolean successful; - - public boolean isSuccessful() { - return successful; - } - - public void setSuccessful(boolean successful) { - this.successful = successful; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "logonResponse") +public class LogoutResponse{ + + @XmlAttribute + private boolean successful; + + public boolean isSuccessful() { + return successful; + } + + public void setSuccessful(boolean successful) { + this.successful = successful; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/UploadUserPhotoResponse.java b/rop-sample/src/main/java/com/rop/sample/response/UploadUserPhotoResponse.java index 38c01f3..fdfe554 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/UploadUserPhotoResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/UploadUserPhotoResponse.java @@ -1,46 +1,57 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.sample.response; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "uploadUserPhotoResponse") -public class UploadUserPhotoResponse{ - - @XmlAttribute - private String fileType; - - @XmlAttribute - private int length; - - public String getFileType() { - return fileType; - } - - public void setFileType(String fileType) { - this.fileType = fileType; - } - - public int getLength() { - return length; - } - - public void setLength(int length) { - this.length = length; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "uploadUserPhotoResponse") +public class UploadUserPhotoResponse{ + + @XmlAttribute + private String fileType; + + @XmlAttribute + private int length; + + public String getFileType() { + return fileType; + } + + public void setFileType(String fileType) { + this.fileType = fileType; + } + + public int getLength() { + return length; + } + + public void setLength(int length) { + this.length = length; + } +} + diff --git a/rop-sample/src/main/java/com/rop/sample/response/UserListResponse.java b/rop-sample/src/main/java/com/rop/sample/response/UserListResponse.java index ffae98d..347d3c9 100644 --- a/rop-sample/src/main/java/com/rop/sample/response/UserListResponse.java +++ b/rop-sample/src/main/java/com/rop/sample/response/UserListResponse.java @@ -1,24 +1,39 @@ -package com.rop.sample.response; - -import javax.xml.bind.annotation.*; -import java.util.Arrays; -import java.util.List; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "userList") -public class UserListResponse { - - @XmlAttribute - private List userIds = Arrays.asList("1","2","2"); - - @XmlElement - private List userNames = Arrays.asList("a","b","c"); - - public List getUserIds() { - return userIds; - } - - public List getUserNames() { - return userNames; - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.response; + +import javax.xml.bind.annotation.*; +import java.util.Arrays; +import java.util.List; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "userList") +public class UserListResponse { + + @XmlAttribute + private List userIds = Arrays.asList("1","2","2"); + + @XmlElement + private List userNames = Arrays.asList("a","b","c"); + + public List getUserIds() { + return userIds; + } + + public List getUserNames() { + return userNames; + } +} diff --git a/rop-sample/src/main/java/com/rop/sample/sys/DateXmlAdapter.java b/rop-sample/src/main/java/com/rop/sample/sys/DateXmlAdapter.java index f6c9a74..ac750de 100644 --- a/rop-sample/src/main/java/com/rop/sample/sys/DateXmlAdapter.java +++ b/rop-sample/src/main/java/com/rop/sample/sys/DateXmlAdapter.java @@ -1,24 +1,38 @@ - -package com.rop.sample.sys; - -import com.rop.sample.converter.DateUtils; - -import javax.xml.bind.annotation.adapters.XmlAdapter; -import java.util.Date; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-3-18 - */ -public class DateXmlAdapter extends XmlAdapter { - - - public Date unmarshal(String v) throws Exception { - return DateUtils.parseDate(v); - } - - - public String marshal(Date date) throws Exception { - return DateUtils.format(date,DateUtils.DATETIME_FORMAT); - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.sys; + +import com.rop.sample.converter.DateUtils; + +import javax.xml.bind.annotation.adapters.XmlAdapter; +import java.util.Date; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 14-3-18 + */ +public class DateXmlAdapter extends XmlAdapter { + + + public Date unmarshal(String v) throws Exception { + return DateUtils.parseDate(v); + } + + + public String marshal(Date date) throws Exception { + return DateUtils.format(date,DateUtils.DATETIME_FORMAT); + } +} diff --git a/rop-sample/src/main/java/com/rop/sample/utils/UrlUtils.java b/rop-sample/src/main/java/com/rop/sample/utils/UrlUtils.java new file mode 100644 index 0000000..f0a0c04 --- /dev/null +++ b/rop-sample/src/main/java/com/rop/sample/utils/UrlUtils.java @@ -0,0 +1,42 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.utils; + +import java.util.Map; + +public class UrlUtils { + + /** + * 将请求对象转换为String + * + * @param allParams + * @return + */ + public static String asUrlString(Map allParams) { + StringBuilder sb = new StringBuilder(256); + boolean first = true; + for (Map.Entry entry : allParams.entrySet()) { + if (!first) { + sb.append("&"); + } + first = false; + sb.append(entry.getKey()); + sb.append("="); + sb.append(entry.getValue()); + } + return sb.toString(); + } +} diff --git a/rop-sample/src/main/resources/sampleRopApplicationContext.xml b/rop-sample/src/main/resources/sampleRopApplicationContext.xml index 84c4539..0d082d1 100644 --- a/rop-sample/src/main/resources/sampleRopApplicationContext.xml +++ b/rop-sample/src/main/resources/sampleRopApplicationContext.xml @@ -1,70 +1,70 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + _ + + + + \ No newline at end of file diff --git a/rop-sample/src/test/java/com/rop/config/RopNamespaceHandlerIT.java b/rop-sample/src/test/java/com/rop/config/RopNamespaceHandlerIT.java index 85592c4..dea0b99 100644 --- a/rop-sample/src/test/java/com/rop/config/RopNamespaceHandlerIT.java +++ b/rop-sample/src/test/java/com/rop/config/RopNamespaceHandlerIT.java @@ -1,115 +1,120 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-7 - */ -package com.rop.config; - -import com.rop.RopContext; -import com.rop.impl.AnnotationServletServiceRouter; -import com.rop.sample.SampleAppSecretManager; -import com.rop.sample.SampleServiceAccessController; -import com.rop.sample.request.Telephone; -import com.rop.security.DefaultSecurityManager; -import org.springframework.context.ApplicationContext; -import org.testng.annotations.Test; -import org.unitils.UnitilsTestNG; -import org.unitils.database.annotations.Transactional; -import org.unitils.database.util.TransactionMode; -import org.unitils.spring.annotation.SpringApplicationContext; -import org.unitils.spring.annotation.SpringBean; -import org.unitils.spring.annotation.SpringBeanByName; -import org.unitils.spring.annotation.SpringBeanByType; - -import java.util.concurrent.TimeUnit; - -import static org.testng.Assert.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ - -@Transactional(TransactionMode.DISABLED) -@SpringApplicationContext("com/rop/config/simplestRopConfig.xml") -public class RopNamespaceHandlerIT extends UnitilsTestNG { - - @SpringBean("router") - AnnotationServletServiceRouter serviceRouter; - - /** - * 最简单的配置 - * - * @param serviceRouter - */ - @Test - public void testSimplestConfig() { - assertNotNull(serviceRouter); - RopContext ropContext = serviceRouter.getRopContext(); - assertNotNull(ropContext); - assertTrue(ropContext.isSignEnable()); - assertNotNull(serviceRouter.getApplicationContext()); - assertEquals(serviceRouter.getExtErrorBasename(), "i18n/rop/ropError"); - assertEquals(serviceRouter.getListeners().size(), 0); - assertEquals(serviceRouter.getInterceptors().size(), 0); - assertNotNull(serviceRouter.getFormattingConversionService()); - assertFalse(serviceRouter.getFormattingConversionService().canConvert(String.class, Telephone.class)); - assertTrue(serviceRouter.isSignEnable()); - assertNotNull(serviceRouter.getSecurityManager()); - assertNotNull(serviceRouter.getRopEventMulticaster()); - assertNotNull(serviceRouter.getThreadPoolExecutor()); - assertEquals(serviceRouter.getThreadPoolExecutor().getCorePoolSize(), 200); - assertEquals(serviceRouter.getThreadPoolExecutor().getMaximumPoolSize(),500); - assertEquals(serviceRouter.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS),5 * 60); - } - -// -// AnnotationServletServiceRouter serviceRouter; - - /** - * 最简单的配置 - * - * @param serviceRouter - */ -// @Test -// @SpringBeanByType -// @SpringApplicationContext("com/rop/config/fullRopConfig.xml") -// public void testFullConfig(AnnotationServletServiceRouter serviceRouter) { -// assertNotNull(serviceRouter); -// RopContext ropContext = serviceRouter.getRopContext(); -// assertNotNull(ropContext); -// assertTrue(!ropContext.isSignEnable()); -// assertNotNull(serviceRouter.getApplicationContext()); -// assertEquals(serviceRouter.getExtErrorBasename(), "i18n/rop/sampleRopError"); -// assertEquals(serviceRouter.getInterceptors().size(), 1); -// assertEquals(serviceRouter.getListeners().size(), 2); -// assertNotNull(serviceRouter.getFormattingConversionService()); -// assertTrue(serviceRouter.getFormattingConversionService().canConvert(String.class, Telephone.class)); -// -// assertFalse(serviceRouter.isSignEnable()); -// DefaultSecurityManager validator = (DefaultSecurityManager) serviceRouter.getSecurityManager(); -// assertNotNull(validator); -// assertTrue(validator.getAppSecretManager() instanceof SampleAppSecretManager); -// assertTrue(validator.getServiceAccessController() instanceof SampleServiceAccessController); -// -// assertNotNull(serviceRouter.getRopEventMulticaster()); -// assertNotNull(serviceRouter.getThreadPoolExecutor()); -// assertEquals(serviceRouter.getThreadPoolExecutor().getCorePoolSize(), 2); -// assertEquals(serviceRouter.getThreadPoolExecutor().getMaximumPoolSize(), 100); -// assertEquals(serviceRouter.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS), 200); -// assertEquals(serviceRouter.getThreadPoolExecutor().getQueue().remainingCapacity(), 120); -// assertEquals(serviceRouter.getServiceTimeoutSeconds(), 10); -// -// assertEquals(SystemParameterNames.getAppKey(), "a1"); -// assertEquals(SystemParameterNames.getFormat(), "f1"); -// assertEquals(SystemParameterNames.getSessionId(), "s1"); -// assertEquals(SystemParameterNames.getSign(), "s2"); -// assertEquals(SystemParameterNames.getLocale(), "l1"); -// assertEquals(SystemParameterNames.getMethod(), "m1"); -// assertEquals(SystemParameterNames.getVersion(), "v1"); -// } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import com.rop.RopContext; +import com.rop.impl.AnnotationServletServiceRouter; +import com.rop.sample.request.Telephone; +import org.testng.annotations.Test; +import org.unitils.UnitilsTestNG; +import org.unitils.database.annotations.Transactional; +import org.unitils.database.util.TransactionMode; +import org.unitils.spring.annotation.SpringApplicationContext; +import org.unitils.spring.annotation.SpringBean; + +import java.util.concurrent.TimeUnit; + +import static org.testng.Assert.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ + +@Transactional(TransactionMode.DISABLED) +@SpringApplicationContext("com/rop/config/simplestRopConfig.xml") +public class RopNamespaceHandlerIT extends UnitilsTestNG { + + @SpringBean("router") + AnnotationServletServiceRouter serviceRouter; + + /** + * 最简单的配置 + * + * @param serviceRouter + */ + @Test + public void testSimplestConfig() { + assertNotNull(serviceRouter); + RopContext ropContext = serviceRouter.getRopContext(); + assertNotNull(ropContext); + assertTrue(ropContext.isSignEnable()); + assertNotNull(serviceRouter.getApplicationContext()); + assertEquals(serviceRouter.getExtErrorBasename(), "i18n/rop/ropError"); + assertEquals(serviceRouter.getListeners().size(), 0); + assertEquals(serviceRouter.getInterceptors().size(), 0); + assertNotNull(serviceRouter.getFormattingConversionService()); + assertFalse(serviceRouter.getFormattingConversionService().canConvert(String.class, Telephone.class)); + assertTrue(serviceRouter.isSignEnable()); + assertNotNull(serviceRouter.getSecurityManager()); + assertNotNull(serviceRouter.getRopEventMulticaster()); + assertNotNull(serviceRouter.getThreadPoolExecutor()); + assertEquals(serviceRouter.getThreadPoolExecutor().getCorePoolSize(), 200); + assertEquals(serviceRouter.getThreadPoolExecutor().getMaximumPoolSize(),500); + assertEquals(serviceRouter.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS),5 * 60); + } + +// +// AnnotationServletServiceRouter serviceRouter; + + /** + * 最简单的配置 + * + * @param serviceRouter + */ +// @Test +// @SpringBeanByType +// @SpringApplicationContext("com/rop/config/fullRopConfig.xml") +// public void testFullConfig(AnnotationServletServiceRouter serviceRouter) { +// assertNotNull(serviceRouter); +// RopContext ropContext = serviceRouter.getRopContext(); +// assertNotNull(ropContext); +// assertTrue(!ropContext.isSignEnable()); +// assertNotNull(serviceRouter.getApplicationContext()); +// assertEquals(serviceRouter.getExtErrorBasename(), "i18n/rop/sampleRopError"); +// assertEquals(serviceRouter.getInterceptors().size(), 1); +// assertEquals(serviceRouter.getListeners().size(), 2); +// assertNotNull(serviceRouter.getFormattingConversionService()); +// assertTrue(serviceRouter.getFormattingConversionService().canConvert(String.class, Telephone.class)); +// +// assertFalse(serviceRouter.isSignEnable()); +// DefaultSecurityManager validator = (DefaultSecurityManager) serviceRouter.getSecurityManager(); +// assertNotNull(validator); +// assertTrue(validator.getAppSecretManager() instanceof SampleAppSecretManager); +// assertTrue(validator.getServiceAccessController() instanceof SampleServiceAccessController); +// +// assertNotNull(serviceRouter.getRopEventMulticaster()); +// assertNotNull(serviceRouter.getThreadPoolExecutor()); +// assertEquals(serviceRouter.getThreadPoolExecutor().getCorePoolSize(), 2); +// assertEquals(serviceRouter.getThreadPoolExecutor().getMaximumPoolSize(), 100); +// assertEquals(serviceRouter.getThreadPoolExecutor().getKeepAliveTime(TimeUnit.SECONDS), 200); +// assertEquals(serviceRouter.getThreadPoolExecutor().getQueue().remainingCapacity(), 120); +// assertEquals(serviceRouter.getServiceTimeoutSeconds(), 10); +// +// assertEquals(SystemParameterNames.getAppKey(), "a1"); +// assertEquals(SystemParameterNames.getFormat(), "f1"); +// assertEquals(SystemParameterNames.getSessionId(), "s1"); +// assertEquals(SystemParameterNames.getSign(), "s2"); +// assertEquals(SystemParameterNames.getLocale(), "l1"); +// assertEquals(SystemParameterNames.getMethod(), "m1"); +// assertEquals(SystemParameterNames.getVersion(), "v1"); +// } +} + diff --git a/rop-sample/src/test/java/com/rop/sample/UserServiceClient.java b/rop-sample/src/test/java/com/rop/sample/UserServiceClient.java index 0141e24..0a98363 100644 --- a/rop-sample/src/test/java/com/rop/sample/UserServiceClient.java +++ b/rop-sample/src/test/java/com/rop/sample/UserServiceClient.java @@ -1,255 +1,267 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.sample; - -import com.rop.MessageFormat; -import com.rop.client.ClientRequest; -import com.rop.client.CompositeResponse; -import com.rop.client.DefaultRopClient; -import com.rop.request.UploadFile; -import com.rop.response.ErrorResponse; -import com.rop.sample.converter.TelephoneConverter; -import com.rop.sample.request.*; -import com.rop.sample.response.CreateUserResponse; -import com.rop.sample.response.LogonResponse; -import com.rop.sample.response.UploadUserPhotoResponse; -import com.rop.sample.response.UserListResponse; -import com.rop.security.MainErrorType; -import org.springframework.core.io.ClassPathResource; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.util.*; - -import static org.testng.Assert.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class UserServiceClient { - - public static final String SERVER_URL = "http://localhost:8088/router"; - public static final String APP_KEY = "00001"; - public static final String APP_SECRET = "abcdeabcdeabcdeabcdeabcde"; - private DefaultRopClient ropClient = new DefaultRopClient(SERVER_URL, APP_KEY, APP_SECRET); - - { - ropClient.setFormatParamName("messageFormat"); - ropClient.addRopConvertor(new TelephoneConverter()); - } - - - @BeforeClass - public void createSession() { - LogonRequest ropRequest = new LogonRequest(); - ropRequest.setUserName("tomson"); - ropRequest.setPassword("123456"); - CompositeResponse response = ropClient.buildClientRequest() - .get(ropRequest, LogonResponse.class, "user.getSession", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertNotNull(response.getSuccessResponse()); - assertTrue(response.getSuccessResponse() instanceof LogonResponse); - assertEquals(((LogonResponse) response.getSuccessResponse()).getSessionId(), "mockSessionId1"); - ropClient.setSessionId(((LogonResponse) response.getSuccessResponse()).getSessionId()); - } - - @Test - public void createSessionWithParamMap() { - CompositeResponse response = ropClient.buildClientRequest() - .addParam("userName", "tomson") - .addParam("password", "123456", true) - .get(LogonResponse.class, "user.getSession", "1.0"); - - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertNotNull(response.getSuccessResponse()); - assertTrue(response.getSuccessResponse() instanceof LogonResponse); - assertEquals(((LogonResponse) response.getSuccessResponse()).getSessionId(), "mockSessionId1"); - } - - @Test - public void addUser() { - CompositeResponse response = ropClient.buildClientRequest() - .addParam("userName", "tomson") - .addParam("password", "123456", true) - .get(LogonResponse.class, "user.getSession", "1.0"); - String sessionId = ((LogonResponse) response.getSuccessResponse()).getSessionId(); - ropClient.setSessionId(sessionId); - - - CreateUserRequest createUserRequest = new CreateUserRequest(); - createUserRequest.setUserName("katty"); - createUserRequest.setSalary(2500L); - - Telephone telephone = new Telephone(); - telephone.setZoneCode("010"); - telephone.setTelephoneCode("12345678"); - createUserRequest.setTelephone(telephone); - - //add1 - response = ropClient.buildClientRequest() - .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - - //add2 - response = ropClient.buildClientRequest() - .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); - } - - @Test - public void addUserUseParamMap() { - CompositeResponse response = ropClient.buildClientRequest() - .addParam("userName", "tomson") - .addParam("password", "123456", true) - .get(LogonResponse.class, "user.getSession", "1.0"); - String sessionId = ((LogonResponse) response.getSuccessResponse()).getSessionId(); - ropClient.setSessionId(sessionId); - - - ClientRequest cr2 = ropClient.buildClientRequest(); - cr2.addParam("userName", "katty"); - cr2.addParam("salary", 2500L); - Telephone telephone = new Telephone(); - telephone.setZoneCode("010"); - telephone.setTelephoneCode("12345678"); - cr2.addParam("telephone", telephone); - - response = cr2.post(CreateUserResponse.class, "user.add", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - } - - - @Test - public void testAddUserByVersion3() { - CreateUserRequest ropRequest = new CreateUserRequest(); - ropRequest.setUserName("tomson"); - ropRequest.setSalary(2500L); - ropClient.setMessageFormat(MessageFormat.xml); - - CompositeResponse response = ropClient.buildClientRequest() - .post(ropRequest, CreateUserResponse.class, "user.add", "3.0"); - assertNotNull(response); - assertFalse(response.isSuccessful()); - assertNull(response.getSuccessResponse()); - assertNotNull(response.getErrorResponse()); - assertTrue(response.getErrorResponse() instanceof ErrorResponse); - assertEquals(response.getErrorResponse().getCode(), MainErrorType.UNSUPPORTED_VERSION.value()); - } - - @Test - public void testFileUpload() throws Throwable { - ClientRequest cr = ropClient.buildClientRequest(); - - UploadUserPhotoRequest request = new UploadUserPhotoRequest(); - ClassPathResource resource = new ClassPathResource("photo.png"); - UploadFile uploadFile = new UploadFile(resource.getFile()); - request.setPhoto(uploadFile); - request.setUserId("1"); - ropClient.setMessageFormat(MessageFormat.xml); - - CompositeResponse response = ropClient.buildClientRequest() - .post(request, UploadUserPhotoResponse.class, "user.upload.photo", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof UploadUserPhotoResponse); - assertEquals(((UploadUserPhotoResponse) response.getSuccessResponse()).getFileType(), "png"); - assertEquals(((UploadUserPhotoResponse) response.getSuccessResponse()).getLength(), uploadFile.getContent().length); - } - - @Test - public void testServiceXmlRequestAttr() throws Throwable { - CreateUserRequest request = new CreateUserRequest(); - request.setUserName("tomson"); - request.setLocked(true); - request.setSalary(2500L); - Address address = new Address(); - address.setZoneCode("0001"); - address.setDoorCode("002"); - Street street1 = new Street(); - street1.setName("street1"); - street1.setNo("001"); - Street street2 = new Street(); - street2.setName("street2"); - street2.setNo("002"); - ArrayList streets = new ArrayList(); - streets.add(street1); - streets.add(street2); - address.setStreets(streets); - request.setAddress(address); - - ropClient.setMessageFormat(MessageFormat.xml); - CompositeResponse response = ropClient.buildClientRequest() - .post(request, CreateUserResponse.class, "user.add", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - } - - @Test - public void testServiceJsonRequestAttr() throws Throwable { - ropClient.setMessageFormat(MessageFormat.json); - CreateUserRequest request = new CreateUserRequest(); - request.setUserName("tomson"); - request.setSalary(2500L); - Address address = new Address(); - address.setZoneCode("0001"); - address.setDoorCode("002"); - Street street1 = new Street(); - street1.setName("street1"); - street1.setNo("001"); - Street street2 = new Street(); - street2.setName("street2"); - street2.setNo("002"); - ArrayList streets = new ArrayList(); - streets.add(street1); - streets.add(street2); - address.setStreets(streets); - request.setAddress(address); - - CompositeResponse response = ropClient.buildClientRequest() - .post(request, CreateUserResponse.class, "user.add", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - } - - @Test - public void testUserList() throws Throwable { - ropClient.setMessageFormat(MessageFormat.json); - CompositeResponse response = ropClient.buildClientRequest().get(UserListResponse.class,"user.list", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof UserListResponse); - } - - - @Test - public void testCustomConverter() { - ropClient.addRopConvertor(new TelephoneConverter()); - CreateUserRequest request = new CreateUserRequest(); - request.setUserName("tomson"); - request.setSalary(2500L); - Telephone telephone = new Telephone(); - telephone.setZoneCode("0592"); - telephone.setTelephoneCode("12345678"); - - CompositeResponse response = ropClient.buildClientRequest().post(request, CreateUserResponse.class, "user.add", "1.0"); - - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - } -} - +/* + * Copyright 2012-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.MessageFormat; +import com.rop.client.ClientRequest; +import com.rop.client.CompositeResponse; +import com.rop.client.DefaultRopClient; +import com.rop.client.sign.DigestSignHandler; +import com.rop.converter.UploadFile; +import com.rop.response.ErrorResponse; +import com.rop.response.MainErrorType; +import com.rop.sample.converter.TelephoneConverter; +import com.rop.sample.request.*; +import com.rop.sample.response.CreateUserResponse; +import com.rop.sample.response.LogonResponse; +import com.rop.sample.response.UploadUserPhotoResponse; +import com.rop.sample.response.UserListResponse; + +import org.springframework.core.io.ClassPathResource; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.*; + +import static org.testng.Assert.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UserServiceClient { + + public static final String SERVER_URL = "http://localhost:8088/router"; + public static final String APP_KEY = "00001"; + public static final String APP_SECRET = "abcdeabcdeabcdeabcdeabcde"; + private DefaultRopClient ropClient = new DefaultRopClient(SERVER_URL, APP_KEY); + + { + ropClient.setSignHandler(new DigestSignHandler("SHA-1", APP_SECRET)); + ropClient.setFormatParamName("messageFormat"); + ropClient.addRopConvertor(new TelephoneConverter()); + } + + + @BeforeClass + public void createSession() throws IOException { + LogonRequest ropRequest = new LogonRequest(); + ropRequest.setUserName("tomson"); + ropRequest.setPassword("123456"); + CompositeResponse response = ropClient.buildClientRequest() + .get(ropRequest, LogonResponse.class, "user.getSession", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertNotNull(response.getSuccessResponse()); + assertTrue(response.getSuccessResponse() instanceof LogonResponse); + assertEquals(((LogonResponse) response.getSuccessResponse()).getSessionId(), "mockSessionId1"); + ropClient.setSessionId(((LogonResponse) response.getSuccessResponse()).getSessionId()); + } + + @Test + public void createSessionWithParamMap() throws IOException { + CompositeResponse response = ropClient.buildClientRequest() + .addParam("userName", "tomson") + .addParam("password", "123456", true) + .get(LogonResponse.class, "user.getSession", "1.0"); + + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertNotNull(response.getSuccessResponse()); + assertTrue(response.getSuccessResponse() instanceof LogonResponse); + assertEquals(((LogonResponse) response.getSuccessResponse()).getSessionId(), "mockSessionId1"); + } + + @Test + public void addUser() throws IOException { + CompositeResponse response = ropClient.buildClientRequest() + .addParam("userName", "tomson") + .addParam("password", "123456", true) + .get(LogonResponse.class, "user.getSession", "1.0"); + String sessionId = response.getSuccessResponse().getSessionId(); + ropClient.setSessionId(sessionId); + + + CreateUserRequest createUserRequest = new CreateUserRequest(); + createUserRequest.setUserName("katty"); + createUserRequest.setSalary(2500L); + + Telephone telephone = new Telephone(); + telephone.setZoneCode("010"); + telephone.setTelephoneCode("12345678"); + createUserRequest.setTelephone(telephone); + + //add1 + CompositeResponse createUserResponse = ropClient.buildClientRequest() + .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); + assertNotNull(createUserResponse); + assertTrue(createUserResponse.isSuccessful()); + assertTrue(createUserResponse.getSuccessResponse() instanceof CreateUserResponse); + + //add2 + createUserResponse = ropClient.buildClientRequest() + .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); + } + + @Test + public void addUserUseParamMap() throws IOException { + CompositeResponse response = ropClient.buildClientRequest() + .addParam("userName", "tomson") + .addParam("password", "123456", true) + .get(LogonResponse.class, "user.getSession", "1.0"); + String sessionId = response.getSuccessResponse().getSessionId(); + ropClient.setSessionId(sessionId); + + ClientRequest cr2 = ropClient.buildClientRequest(); + cr2.addParam("userName", "katty"); + cr2.addParam("salary", 2500L); + Telephone telephone = new Telephone(); + telephone.setZoneCode("010"); + telephone.setTelephoneCode("12345678"); + cr2.addParam("telephone", telephone); + + CompositeResponse createUserResponse = cr2.post(CreateUserResponse.class, "user.add", "1.0"); + assertNotNull(createUserResponse); + assertTrue(createUserResponse.isSuccessful()); + assertTrue(createUserResponse.getSuccessResponse() instanceof CreateUserResponse); + } + + + @Test + public void testAddUserByVersion3() throws IOException { + CreateUserRequest ropRequest = new CreateUserRequest(); + ropRequest.setUserName("tomson"); + ropRequest.setSalary(2500L); + ropClient.setMessageFormat(MessageFormat.XML); + + CompositeResponse response = ropClient.buildClientRequest() + .post(ropRequest, CreateUserResponse.class, "user.add", "3.0"); + assertNotNull(response); + assertFalse(response.isSuccessful()); + assertNull(response.getSuccessResponse()); + assertNotNull(response.getErrorResponse()); + assertTrue(response.getErrorResponse() instanceof ErrorResponse); + assertEquals(response.getErrorResponse().getCode(), MainErrorType.UNSUPPORTED_VERSION.value()); + } + + @Test + public void testFileUpload() throws Throwable { + UploadUserPhotoRequest request = new UploadUserPhotoRequest(); + ClassPathResource resource = new ClassPathResource("photo.png"); + UploadFile uploadFile = new UploadFile(resource.getFile()); + request.setPhoto(uploadFile); + request.setUserId("1"); + ropClient.setMessageFormat(MessageFormat.XML); + + CompositeResponse response = ropClient.buildClientRequest() + .post(request, UploadUserPhotoResponse.class, "user.upload.photo", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof UploadUserPhotoResponse); + assertEquals(response.getSuccessResponse().getFileType(), "png"); + assertEquals(response.getSuccessResponse().getLength(), uploadFile.getContent().length); + } + + @Test + public void testServiceXmlRequestAttr() throws Throwable { + CreateUserRequest request = new CreateUserRequest(); + request.setUserName("tomson"); + request.setLocked(true); + request.setSalary(2500L); + Address address = new Address(); + address.setZoneCode("0001"); + address.setDoorCode("002"); + Street street1 = new Street(); + street1.setName("street1"); + street1.setNo("001"); + Street street2 = new Street(); + street2.setName("street2"); + street2.setNo("002"); + ArrayList streets = new ArrayList(); + streets.add(street1); + streets.add(street2); + address.setStreets(streets); + request.setAddress(address); + + ropClient.setMessageFormat(MessageFormat.XML); + CompositeResponse response = ropClient.buildClientRequest() + .post(request, CreateUserResponse.class, "user.add", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); + } + + @Test + public void testServiceJsonRequestAttr() throws Throwable { + ropClient.setMessageFormat(MessageFormat.JSON); + CreateUserRequest request = new CreateUserRequest(); + request.setUserName("tomson"); + request.setSalary(2500L); + Address address = new Address(); + address.setZoneCode("0001"); + address.setDoorCode("002"); + Street street1 = new Street(); + street1.setName("street1"); + street1.setNo("001"); + Street street2 = new Street(); + street2.setName("street2"); + street2.setNo("002"); + ArrayList streets = new ArrayList(); + streets.add(street1); + streets.add(street2); + address.setStreets(streets); + request.setAddress(address); + + CompositeResponse response = ropClient.buildClientRequest() + .post(request, CreateUserResponse.class, "user.add", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); + } + + @Test + public void testUserList() throws Throwable { + ropClient.setMessageFormat(MessageFormat.JSON); + CompositeResponse response = ropClient.buildClientRequest().get(UserListResponse.class,"user.list", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof UserListResponse); + } + + + @Test + public void testCustomConverter() throws IOException { + ropClient.addRopConvertor(new TelephoneConverter()); + CreateUserRequest request = new CreateUserRequest(); + request.setUserName("tomson"); + request.setSalary(2500L); + Telephone telephone = new Telephone(); + telephone.setZoneCode("0592"); + telephone.setTelephoneCode("12345678"); + + CompositeResponse response = ropClient.buildClientRequest().post(request, CreateUserResponse.class, "user.add", "1.0"); + + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); + } +} + diff --git a/rop-sample/src/test/java/com/rop/sample/UserServiceRawClient.java b/rop-sample/src/test/java/com/rop/sample/UserServiceRawClient.java index 259151f..01f7b86 100644 --- a/rop-sample/src/test/java/com/rop/sample/UserServiceRawClient.java +++ b/rop-sample/src/test/java/com/rop/sample/UserServiceRawClient.java @@ -1,888 +1,896 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.sample; - -import com.rop.request.UploadFile; -import com.rop.security.MainErrorType; -import com.rop.utils.RopUtils; -import org.apache.commons.codec.binary.Base64; -import org.springframework.core.io.ClassPathResource; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.client.RestTemplate; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.HashMap; -import java.util.Map; - -import static org.testng.Assert.assertTrue; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class UserServiceRawClient { - - public static final String SERVER_URL = "http://localhost:8088/router"; - - private String sessionId; - - /** - * 创建一个服务端的会话 - */ -// @Test - @BeforeClass - public void createSession() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.getSession"); - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("userName", "tomson"); - form.add("locale", "en"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); -// assertTrue(response.indexOf("") > -1); - } - - /** - * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) - */ - @Test - public void testAddUserByVersion1() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); -// form.add("messageFormat", "json"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - form.add("date", "20140101010101"); -// form.add("fileType", "EXCEL"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf(" -1); - } - - /** - * 测试过期版本的服务 - */ - @Test - public void testAddUserByVersion0_9() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "0.9"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("code=\"" + MainErrorType.METHOD_OBSOLETED.value() + "\"") > -1); - } - - - /** - * 显式指定返回的报文类型,在配置文件中已经显式指定了 报文格式参数的名称为format - */ - @Test - public void testAddUserWithJsonFormat() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("messageFormat", "json"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("{\"userId\":\"1\",") > -1); - } - - /** - * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) - */ - @Test - public void testAddUserByVersion2() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "2.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf(" -1); - } - - /** - * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) - */ - @Test - public void testQueryUserByUserId() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - - form.put("method", "user.query");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "en"); - form.put("userId", "userId1"); - - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); - form.put("sign", sign); - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + - "&userId={userId}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - assertTrue(response.indexOf("user.query") > -1 && response.indexOf("userId1") > -1); - } - - /** - * 测试自定义的类型转换器{@link com.rop.sample.converter.TelephoneConverter} - */ - @Test - public void testCustomConverter() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.customConverter");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - form.add("telephone", "0592-12345678"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("0592#12345678") > -1); - } - - /** - * 验证内部格式为XML的请求参数会正确绑定到RopRequest的内部属性对象中,参见{@link com.rop.sample.request.CreateUserRequest#address} - * - * @see com.rop.sample.request.Address - */ - @Test - public void testServiceXmlRequestAttr() { - - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - - //address会正确绑定 - form.add("address", - "
\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "
"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); -// System.out.println("response:\n" + response); -// assertTrue(response.indexOf("") > -1); - } - - - - - @Test - public void testServiceJsonRequestAttr() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - form.add("messageFormat", "json"); - - //address会正确绑定 - form.add("address", - "{\"zoneCode\":\"0001\",\n" + - " \"doorCode\":\"002\",\n" + - " \"codes\":[\"aa\",\"bb\",\"cc\"],\n"+ - " \"streets\":[{\"no\":\"001\",\"name\":\"street1\"},\n" + - " {\"no\":\"002\",\"name\":\"street2\"}]}"); -// form.add("favorites", "\"aa\",\"bb\",\"cc\""); - - form.add("addresses", - "[{\"zoneCode\":\"0001\",\n" + - " \"doorCode\":\"002\",\n" + - " \"codes\":[\"aa\",\"bb\",\"cc\"],\n"+ - " \"streets\":[{\"no\":\"001\",\"name\":\"street1\"},\n" + - " {\"no\":\"002\",\"name\":\"street2\"}]}]"); - form.add("addresses", - "[{\"zoneCode\":\"0001\"},{\"zoneCode\":\"0001\"}]"); - form.add("favorites", "\"aa\",\"bb\",\"cc\""); - form.add("attachMap", "{\"key1\":\"value1\",\"key2\":\"value2\"}"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("\"userId\":\"1\"") > -1); - } - - /** - * 由于{@link com.rop.sample.request.CreateUserRequest#password}标注了{@link com.rop.annotation.IgnoreSign},所以Rop - * 会忽略对password请求参数进行签名验证。 - */ - @Test - public void testIngoreSignParamOfPassword() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "tomsony"); - form.add("salary", "2,500.00"); - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - - form.add("sign", sign); - form.add("password", "123456"); //password无需签名,所以放在最后 - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf(" -1); - } - - /** - * 忽略对 user.add#4.0服务的会话验证功能 - */ - @Test - public void testIngoreSession() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("appKey", "00001"); - form.add("method", "user.add");//<--指定方法名称 - form.add("v", "4.0"); - form.add("userName", "tomsony"); - form.add("salary", "2,500.00"); - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - - form.add("sign", sign); - - String response = restTemplate.postForObject(SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("userId=\"4\"") > -1); - } - - /** - * 忽略对user.add#5.0服务的签名验证功能 - */ - @Test - public void testIngoreSign() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("appKey", "00001"); - form.add("method", "user.add");//<--指定方法名称 - form.add("v", "5.0"); - form.add("userName", "tomsony"); - form.add("sessionId", "mockSessionId1"); - form.add("salary", "2,500.00"); -// String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); -// form.add("sign", sign); - - String response = restTemplate.postForObject(SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("userId=\"4\"") > -1); - } - - /** - * 请求参数违反合法性校验限制时,返回相应的错误报文 - * 服务端限制salary的格式必须是“#,###.##”,且必须在1000.00和100000.00之间, - * 参见{@link com.rop.sample.request.CreateUserRequest#salary} - */ - @Test - public void testParamConstrainViolation() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "tom"); - form.add("salary", "aaa"); - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("isv.parameters-mismatch:salary") > -1); - } - - /** - * 在类路径的rop.appSecret.properties中我们定义了两个合法的appKey,分别是: - * 00001=abcdeabcdeabcdeabcdeabcde - * 00002=abcdeabcdeabcdeabcdeaaaaa - * 我们使用一个错误的appKey以验证是否会返回正确的错误报文。 - */ - @Test - public void testInvalidSysParams() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - form.put("method", "user.get");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "en"); - form.put("userName", "tomson"); - form.put("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); - form.put("sign", sign); - - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + - "&userName={userName}&v={v}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - } - - - @Test - public void testI18nErrorMessage() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - form.put("method", "user.add");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "en"); - form.put("userName", "tomson"); - form.put("salary", "aaa"); - - //对请求参数列表进行签名 - form.put("sign", RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde")); - - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + - "&userName={userName}&v={v}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - - form.clear(); - form.put("method", "user.add");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "zh_CN"); - form.put("userName", "tomson"); - form.put("salary", "aaa"); - - //对请求参数列表进行签名 - form.put("sign", RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde")); - - - //使用GET获取:正确返回 - response = restTemplate.getForObject( - SERVER_URL + - "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + - "&userName={userName}&v={v}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - } - - /** - * 请求参数违反合法性校验限制时,返回相应的错误报文 - * 服务端限制salary的格式必须是“#,###.##”,且必须在1000.00和100000.00之间, - * 参见{@link com.rop.sample.request.CreateUserRequest#salary} - */ - @Test - public void testInvalidSign() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //设置一个错误的签名 - String sign = "xxx"; - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - - System.out.println("response:\n" + response); - assertTrue(response.indexOf("code=\"" + MainErrorType.INVALID_SIGNATURE.value() + "\"") > -1); - } - - /** - * 在{@link SampleAppSecretManager}中,我们模拟让sessionId为mockSessionId1拥有访问 - * {@link UserService#addUser(com.rop.sample.request.CreateUserRequest)}的权限,而sessionId为mockSessionId2时则没有这个权限。 - * 将返回会话错误的响应报文。 - */ - @Test - public void testInvalidSessionId() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add"); - form.add("appKey", "00001"); - form.add("v", "1.0"); - - form.add("sessionId", "mockSessionId2"); //<--模拟一个错误的sessionId - - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //设置一个错误的签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - - System.out.println("response:\n" + response); - assertTrue(response.indexOf("code=\"" + MainErrorType.INVALID_SESSION.value() + "\"") > -1); - } - - /** - * 在{@link SampleSessionChecker}中,我们模拟了一个合法的sessionId,即 mockSessionId1,使用其它的sessionId, - * 将返回会话错误的响应报文。 - */ - @Test - public void testViolationServiceAccessController() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add"); - form.add("appKey", "00003"); - form.add("v", "1.0"); - - form.add("sessionId", "mockSessionId1"); - - form.add("userName", "tomsony"); - form.add("salary", "2,500.00"); - - //设置一个错误的签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeaaaaa"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - - System.out.println("response:\n" + response); - assertTrue(response.indexOf("code=\"" + MainErrorType.INSUFFICIENT_ISV_PERMISSIONS.value() + "\"") > -1); - } - - /** - * 违反应用最大服务调用次数的限制 - */ - @Test - public void testViolationInvokeTimesController() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add"); - form.add("appKey", "00002"); - form.add("v", "1.0"); - - form.add("sessionId", "mockSessionId1"); - - form.add("userName", "tomsony"); - form.add("salary", "2,500.00"); - - //设置一个错误的签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeaaaaa"); - form.add("sign", sign); - - for (int i = 0; i < 11; i++) { - restTemplate.postForObject(SERVER_URL, form, String.class); - } - - String response = restTemplate.postForObject(SERVER_URL, form, String.class); - System.out.println("response1:" + response); - assertTrue(response.indexOf("code=\"" + MainErrorType.EXCEED_APP_INVOKE_LIMITED.value() + "\"") > -1); - } - - /** - * “jhon”是{@link UserService#addUser(com.rop.sample.request.CreateUserRequest)} 服务方法预留的用户名, - * 验证其会返回正确的业务错误码。 - */ - @Test - public void testBusinessServiceError() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("userName", "jhon"); - form.add("salary", "2,500.00"); - - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - - form.add("sign", sign); - form.add("password", "123456"); //password无需签名,所以放在最后 - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - - //返回业务的错误报文 - assertTrue(response.indexOf("isv.user-add-service-error:USER_NAME_RESERVED") > 0); - } - - /** - * 测试被拦截器阻截服务的情况 (user.add + 1.0) - */ - @Test - public void testAddUserWithInterceptorViolidateReservedUserName() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "2.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userName", "jhonson");//这个用户名会被ReservedUserNameInterceptor拦截器驳回 - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("the userName can't be jhonson!") > -1); - } - - /** - * user.timeout 服务方法必须在1秒内执行完成,我们在服务端故意让user.timeout过期,看是否会返回正确的错误报文 - */ - @Test - public void testServiceWhenExceedTimeout() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.timeout");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "zh_CN"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:" + response); - assertTrue(response.indexOf("isp.user-timeout-service-timeout") > -1); - } - - /** - * user.get 获取用户的信息 - */ - @Test - public void testGetUserWithGET() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - - form.put("method", "user.get");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "en"); - form.put("userId", "1"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); - form.put("sign", sign); - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + - "&userId={userId}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - assertTrue(response.indexOf("user.get") > -1); - } - - /** - * user.get 获取用户的信息 - */ - @Test - public void testGetUserWithPOST() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.get");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userId", "2"); - - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("code=\"5\"") > -1); - } - - @Test - public void testGetUserOf9999() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - - form.put("method", "user.get");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("sessionId", "mockSessionId1"); - form.put("locale", "en"); - form.put("userId", "9999"); - form.put("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); - form.put("sign", sign); - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + - "&userId={userId}&salary={salary}&sign={sign}", - String.class, form); - System.out.println("response:" + response); - assertTrue(response.indexOf("isv.user-not-exist") > -1); - } - - - /** - * 测试多次执行的服务性能: 100次调用,在1秒内完成! - */ - @Test(timeOut = 2000) - public void testMultiTimeRun() { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.add");//<--指定方法名称 - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userName", "tomson"); - form.add("salary", "2,500.00"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - long begin = System.currentTimeMillis(); - for (int i = 0; i < 100; i++) { - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - assertTrue(response.indexOf(" -1); - } - System.out.println("time elapsed:" + (System.currentTimeMillis() - begin)); - } - - - /** - * 测试文件上传 - */ - @Test - public void testUploadUserPhoto() throws Throwable { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.upload.photo"); - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userId", "1"); - ClassPathResource resource = new ClassPathResource("photo.png"); - UploadFile uploadFile = new UploadFile(resource.getFile()); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - form.add("photo", "png@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf("png") > -1); - } - - /** - * 上传文件类型不允许 - */ - @Test - public void testUploadErrorFileType() throws Throwable { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.upload.photo"); - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userId", "1"); - ClassPathResource resource = new ClassPathResource("photo.png"); - UploadFile uploadFile = new UploadFile(resource.getFile()); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - form.add("photo", "exe@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 - - String response = restTemplate.postForObject( - SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf(MainErrorType.UPLOAD_FAIL.value()) > -1); - } - - /** - * 测试文件大小超限 - * - * @throws Throwable - */ - @Test - public void testUploadExceedMaxSizeError() throws Throwable { - RestTemplate restTemplate = new RestTemplate(); - MultiValueMap form = new LinkedMultiValueMap(); - form.add("method", "user.upload.photo"); - form.add("appKey", "00001"); - form.add("v", "1.0"); - form.add("sessionId", "mockSessionId1"); - form.add("locale", "en"); - form.add("userId", "1"); - ClassPathResource resource = new ClassPathResource("exceedMaxSize.png"); - UploadFile uploadFile = new UploadFile(resource.getFile()); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); - form.add("sign", sign); - - form.add("photo", "png@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 - - String response = restTemplate.postForObject(SERVER_URL, form, String.class); - System.out.println("response:\n" + response); - assertTrue(response.indexOf(MainErrorType.UPLOAD_FAIL.value()) > -1); - } - - @Test - public void testStreamOutput() { - RestTemplate restTemplate = new RestTemplate(); - Map form = new HashMap(); - form.put("method", "img.get");//<--指定方法名称 - form.put("appKey", "00001"); - form.put("v", "1.0"); - form.put("locale", "en"); - form.put("sessionId", "mockSessionId1"); - form.put("messageFormat", "stream"); - - //对请求参数列表进行签名 - String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); - form.put("sign", sign); - - //使用GET获取:正确返回 - String response = restTemplate.getForObject( - SERVER_URL + - "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + - "&messageFormat={messageFormat}&sign={sign}", - String.class, form); -// System.out.println("response:" + response); -// assertTrue(response.indexOf("Is StreamOutput!") > -1); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample; + +import com.rop.converter.UploadFile; +import com.rop.response.MainErrorType; +import com.rop.utils.RopUtils; + +import org.apache.commons.codec.binary.Base64; +import org.springframework.core.io.ClassPathResource; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.testng.Assert.assertTrue; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UserServiceRawClient { + + public static final String SERVER_URL = "http://localhost:8088/router"; + + /** + * 创建一个服务端的会话 + */ +// @Test + @BeforeClass + public void createSession() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.getSession"); + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("userName", "tomson"); + form.add("locale", "en"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); +// assertTrue(response.indexOf("") > -1); + } + + /** + * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) + */ + @Test + public void testAddUserByVersion1() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); +// form.add("messageFormat", "json"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + form.add("date", "20140101010101"); +// form.add("fileType", "EXCEL"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf(" -1); + } + + /** + * 测试过期版本的服务 + */ + @Test + public void testAddUserByVersion0_9() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "0.9"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("code=\"" + MainErrorType.METHOD_OBSOLETED.value() + "\"") > -1); + } + + + /** + * 显式指定返回的报文类型,在配置文件中已经显式指定了 报文格式参数的名称为format + */ + @Test + public void testAddUserWithJsonFormat() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("messageFormat", "json"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("{\"userId\":\"1\",") > -1); + } + + /** + * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) + */ + @Test + public void testAddUserByVersion2() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "2.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf(" -1); + } + + /** + * 在一切正确的情况下,返回正确的服务报文 (user.add + 1.0) + */ + @Test + public void testQueryUserByUserId() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + + form.put("method", "user.query");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "en"); + form.put("userId", "userId1"); + + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); + form.put("sign", sign); + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + + "&userId={userId}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + assertTrue(response.indexOf("user.query") > -1 && response.indexOf("userId1") > -1); + } + + /** + * 测试自定义的类型转换器{@link com.rop.sample.converter.TelephoneConverter} + */ + @Test + public void testCustomConverter() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.customConverter");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + form.add("telephone", "0592-12345678"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("0592#12345678") > -1); + } + + /** + * 验证内部格式为XML的请求参数会正确绑定到RopRequest的内部属性对象中,参见{@link com.rop.sample.request.CreateUserRequest#address} + * + * @see com.rop.sample.request.Address + */ + @Test + public void testServiceXmlRequestAttr() { + + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + + //address会正确绑定 + form.add("address", + "
\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject(SERVER_URL, form, String.class); + System.out.println("response:\n" + response); +// assertTrue(response.indexOf("") > -1); + } + + + + + @Test + public void testServiceJsonRequestAttr() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + form.add("messageFormat", "json"); + + //address会正确绑定 + form.add("address", + "{\"zoneCode\":\"0001\",\n" + + " \"doorCode\":\"002\",\n" + + " \"codes\":[\"aa\",\"bb\",\"cc\"],\n"+ + " \"streets\":[{\"no\":\"001\",\"name\":\"street1\"},\n" + + " {\"no\":\"002\",\"name\":\"street2\"}]}"); +// form.add("favorites", "\"aa\",\"bb\",\"cc\""); + + form.add("addresses", + "[{\"zoneCode\":\"0001\",\n" + + " \"doorCode\":\"002\",\n" + + " \"codes\":[\"aa\",\"bb\",\"cc\"],\n"+ + " \"streets\":[{\"no\":\"001\",\"name\":\"street1\"},\n" + + " {\"no\":\"002\",\"name\":\"street2\"}]}]"); + form.add("addresses", + "[{\"zoneCode\":\"0001\"},{\"zoneCode\":\"0001\"}]"); + form.add("favorites", "\"aa\",\"bb\",\"cc\""); + form.add("attachMap", "{\"key1\":\"value1\",\"key2\":\"value2\"}"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("\"userId\":\"1\"") > -1); + } + + /** + * 由于{@link com.rop.sample.request.CreateUserRequest#password}标注了{@link com.rop.annotation.IgnoreSign},所以Rop + * 会忽略对password请求参数进行签名验证。 + */ + @Test + public void testIngoreSignParamOfPassword() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "tomsony"); + form.add("salary", "2,500.00"); + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + + form.add("sign", sign); + form.add("password", "123456"); //password无需签名,所以放在最后 + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf(" -1); + } + + /** + * 忽略对 user.add#4.0服务的会话验证功能 + */ + @Test + public void testIngoreSession() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("appKey", "00001"); + form.add("method", "user.add");//<--指定方法名称 + form.add("v", "4.0"); + form.add("userName", "tomsony"); + form.add("salary", "2,500.00"); + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + + form.add("sign", sign); + + String response = restTemplate.postForObject(SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("userId=\"4\"") > -1); + } + + /** + * 忽略对user.add#5.0服务的签名验证功能 + */ + @Test + public void testIngoreSign() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("appKey", "00001"); + form.add("method", "user.add");//<--指定方法名称 + form.add("v", "5.0"); + form.add("userName", "tomsony"); + form.add("sessionId", "mockSessionId1"); + form.add("salary", "2,500.00"); +// String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); +// form.add("sign", sign); + + String response = restTemplate.postForObject(SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("userId=\"4\"") > -1); + } + + /** + * 请求参数违反合法性校验限制时,返回相应的错误报文 + * 服务端限制salary的格式必须是“#,###.##”,且必须在1000.00和100000.00之间, + * 参见{@link com.rop.sample.request.CreateUserRequest#salary} + */ + @Test + public void testParamConstrainViolation() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "tom"); + form.add("salary", "aaa"); + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("isv.parameters-mismatch:salary") > -1); + } + + /** + * 在类路径的rop.appSecret.properties中我们定义了两个合法的appKey,分别是: + * 00001=abcdeabcdeabcdeabcdeabcde + * 00002=abcdeabcdeabcdeabcdeaaaaa + * 我们使用一个错误的appKey以验证是否会返回正确的错误报文。 + */ + @Test + public void testInvalidSysParams() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + form.put("method", "user.get");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "en"); + form.put("userName", "tomson"); + form.put("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); + form.put("sign", sign); + + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + + "&userName={userName}&v={v}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + } + + + @Test + public void testI18nErrorMessage() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + form.put("method", "user.add");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "en"); + form.put("userName", "tomson"); + form.put("salary", "aaa"); + + //对请求参数列表进行签名 + form.put("sign", RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde")); + + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + + "&userName={userName}&v={v}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + + form.clear(); + form.put("method", "user.add");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "zh_CN"); + form.put("userName", "tomson"); + form.put("salary", "aaa"); + + //对请求参数列表进行签名 + form.put("sign", RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde")); + + + //使用GET获取:正确返回 + response = restTemplate.getForObject( + SERVER_URL + + "?appKey={appKey}&locale={locale}&method={method}&salary={salary}&sessionId={sessionId}" + + "&userName={userName}&v={v}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + } + + /** + * 请求参数违反合法性校验限制时,返回相应的错误报文 + * 服务端限制salary的格式必须是“#,###.##”,且必须在1000.00和100000.00之间, + * 参见{@link com.rop.sample.request.CreateUserRequest#salary} + */ + @Test + public void testInvalidSign() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //设置一个错误的签名 + String sign = "xxx"; + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + + System.out.println("response:\n" + response); + assertTrue(response.indexOf("code=\"" + MainErrorType.INVALID_SIGNATURE.value() + "\"") > -1); + } + + /** + * 在{@link SampleAppSecretManager}中,我们模拟让sessionId为mockSessionId1拥有访问 + * {@link UserService#addUser(com.rop.sample.request.CreateUserRequest)}的权限,而sessionId为mockSessionId2时则没有这个权限。 + * 将返回会话错误的响应报文。 + */ + @Test + public void testInvalidSessionId() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add"); + form.add("appKey", "00001"); + form.add("v", "1.0"); + + form.add("sessionId", "mockSessionId2"); //<--模拟一个错误的sessionId + + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //设置一个错误的签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + + System.out.println("response:\n" + response); + assertTrue(response.indexOf("code=\"" + MainErrorType.INVALID_SESSION.value() + "\"") > -1); + } + + /** + * 在{@link SampleSessionChecker}中,我们模拟了一个合法的sessionId,即 mockSessionId1,使用其它的sessionId, + * 将返回会话错误的响应报文。 + */ + @Test + public void testViolationServiceAccessController() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add"); + form.add("appKey", "00003"); + form.add("v", "1.0"); + + form.add("sessionId", "mockSessionId1"); + + form.add("userName", "tomsony"); + form.add("salary", "2,500.00"); + + //设置一个错误的签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeaaaaa"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + + System.out.println("response:\n" + response); + assertTrue(response.indexOf("code=\"" + MainErrorType.INSUFFICIENT_ISV_PERMISSIONS.value() + "\"") > -1); + } + + /** + * 违反应用最大服务调用次数的限制 + */ + @Test + public void testViolationInvokeTimesController() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add"); + form.add("appKey", "00002"); + form.add("v", "1.0"); + + form.add("sessionId", "mockSessionId1"); + + form.add("userName", "tomsony"); + form.add("salary", "2,500.00"); + + //设置一个错误的签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeaaaaa"); + form.add("sign", sign); + + for (int i = 0; i < 11; i++) { + restTemplate.postForObject(SERVER_URL, form, String.class); + } + + String response = restTemplate.postForObject(SERVER_URL, form, String.class); + System.out.println("response1:" + response); + assertTrue(response.indexOf("code=\"" + MainErrorType.EXCEED_APP_INVOKE_LIMITED.value() + "\"") > -1); + } + + /** + * “jhon”是{@link UserService#addUser(com.rop.sample.request.CreateUserRequest)} 服务方法预留的用户名, + * 验证其会返回正确的业务错误码。 + */ + @Test + public void testBusinessServiceError() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("userName", "jhon"); + form.add("salary", "2,500.00"); + + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + + form.add("sign", sign); + form.add("password", "123456"); //password无需签名,所以放在最后 + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + + //返回业务的错误报文 + assertTrue(response.indexOf("isv.user-add-service-error:USER_NAME_RESERVED") > 0); + } + + /** + * 测试被拦截器阻截服务的情况 (user.add + 1.0) + */ + @Test + public void testAddUserWithInterceptorViolidateReservedUserName() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "2.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userName", "jhonson");//这个用户名会被ReservedUserNameInterceptor拦截器驳回 + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("the userName can't be jhonson!") > -1); + } + + /** + * user.timeout 服务方法必须在1秒内执行完成,我们在服务端故意让user.timeout过期,看是否会返回正确的错误报文 + */ + @Test + public void testServiceWhenExceedTimeout() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.timeout");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "zh_CN"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:" + response); + assertTrue(response.indexOf("isp.user-timeout-service-timeout") > -1); + } + + /** + * user.get 获取用户的信息 + */ + @Test + public void testGetUserWithGET() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + + form.put("method", "user.get");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "en"); + form.put("userId", "1"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); + form.put("sign", sign); + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + + "&userId={userId}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + assertTrue(response.indexOf("user.get") > -1); + } + + /** + * user.get 获取用户的信息 + */ + @Test + public void testGetUserWithPOST() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.get");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userId", "2"); + + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("code=\"5\"") > -1); + } + + @Test + public void testGetUserOf9999() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + + form.put("method", "user.get");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("sessionId", "mockSessionId1"); + form.put("locale", "en"); + form.put("userId", "9999"); + form.put("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); + form.put("sign", sign); + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + + "&userId={userId}&salary={salary}&sign={sign}", + String.class, form); + System.out.println("response:" + response); + assertTrue(response.indexOf("isv.user-not-exist") > -1); + } + + + /** + * 测试多次执行的服务性能: 100次调用,在1秒内完成! + */ + @Test(timeOut = 2000) + public void testMultiTimeRun() { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.add");//<--指定方法名称 + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userName", "tomson"); + form.add("salary", "2,500.00"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + long begin = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + assertTrue(response.indexOf(" -1); + } + System.out.println("time elapsed:" + (System.currentTimeMillis() - begin)); + } + + + /** + * 测试文件上传 + */ + @Test + public void testUploadUserPhoto() throws Throwable { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.upload.photo"); + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userId", "1"); + ClassPathResource resource = new ClassPathResource("photo.png"); + UploadFile uploadFile = new UploadFile(resource.getFile()); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + form.add("photo", "png@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf("png") > -1); + } + + /** + * 上传文件类型不允许 + */ + @Test + public void testUploadErrorFileType() throws Throwable { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.upload.photo"); + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userId", "1"); + ClassPathResource resource = new ClassPathResource("photo.png"); + UploadFile uploadFile = new UploadFile(resource.getFile()); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + form.add("photo", "exe@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 + + String response = restTemplate.postForObject( + SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf(MainErrorType.UPLOAD_FAIL.value()) > -1); + } + + /** + * 测试文件大小超限 + * + * @throws Throwable + */ + @Test + public void testUploadExceedMaxSizeError() throws Throwable { + RestTemplate restTemplate = new RestTemplate(); + MultiValueMap form = new LinkedMultiValueMap(); + form.add("method", "user.upload.photo"); + form.add("appKey", "00001"); + form.add("v", "1.0"); + form.add("sessionId", "mockSessionId1"); + form.add("locale", "en"); + form.add("userId", "1"); + ClassPathResource resource = new ClassPathResource("exceedMaxSize.png"); + UploadFile uploadFile = new UploadFile(resource.getFile()); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form.toSingleValueMap(), "abcdeabcdeabcdeabcdeabcde"); + form.add("sign", sign); + + form.add("photo", "png@" + Base64.encodeBase64String(uploadFile.getContent())); //文件不进行签名 + + String response = restTemplate.postForObject(SERVER_URL, form, String.class); + System.out.println("response:\n" + response); + assertTrue(response.indexOf(MainErrorType.UPLOAD_FAIL.value()) > -1); + } + + @Test + public void testStreamOutput() { + RestTemplate restTemplate = new RestTemplate(); + Map form = new HashMap(); + form.put("method", "img.get");//<--指定方法名称 + form.put("appKey", "00001"); + form.put("v", "1.0"); + form.put("locale", "en"); + form.put("sessionId", "mockSessionId1"); + form.put("messageFormat", "stream"); + + //对请求参数列表进行签名 + String sign = RopUtils.sign(form, "abcdeabcdeabcdeabcdeabcde"); + form.put("sign", sign); + + //使用GET获取:正确返回 + String response = restTemplate.getForObject( + SERVER_URL + + "?method={method}&appKey={appKey}&v={v}&sessionId={sessionId}&locale={locale}" + + "&messageFormat={messageFormat}&sign={sign}", + String.class, form); + System.out.println("response:" + response); +// assertTrue(response.indexOf("Is StreamOutput!") > -1); + } + +} + diff --git a/rop-sample/src/test/java/com/rop/sample/client/RopSampleClientIT.java b/rop-sample/src/test/java/com/rop/sample/client/RopSampleClientIT.java index 2c042a3..1cf6ac3 100644 --- a/rop-sample/src/test/java/com/rop/sample/client/RopSampleClientIT.java +++ b/rop-sample/src/test/java/com/rop/sample/client/RopSampleClientIT.java @@ -1,62 +1,76 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-4 - */ -package com.rop.sample.client; - -import com.rop.client.CompositeResponse; -import com.rop.sample.request.CreateUserRequest; -import com.rop.sample.request.Telephone; -import com.rop.sample.response.CreateUserResponse; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopSampleClientIT { - public static final String APP_KEY = "00001"; - public static final String APP_SECRET = "abcdeabcdeabcdeabcdeabcde"; - - RopSampleClient ropSampleClient = new RopSampleClient(APP_KEY,APP_SECRET); - - @Test - public void testLogon() throws Exception { - String sessionId = ropSampleClient.logon("tomson", "123456"); - assertNotNull(sessionId); - } - - @Test - public void testLogout() throws Exception { - ropSampleClient.logout(); - } - - @Test - public void addUser() { - - ropSampleClient.logon("tomson", "123456"); - - CreateUserRequest createUserRequest = new CreateUserRequest(); - createUserRequest.setUserName("katty"); - createUserRequest.setSalary(2500L); - - Telephone telephone = new Telephone(); - telephone.setZoneCode("010"); - telephone.setTelephoneCode("12345678"); - createUserRequest.setTelephone(telephone); - - CompositeResponse response = ropSampleClient.buildClientRequest() - .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); - assertNotNull(response); - assertTrue(response.isSuccessful()); - assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.sample.client; + +import java.io.IOException; + +import com.rop.client.CompositeResponse; +import com.rop.sample.request.CreateUserRequest; +import com.rop.sample.request.Telephone; +import com.rop.sample.response.CreateUserResponse; + +import org.testng.annotations.Test; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopSampleClientIT { + public static final String APP_KEY = "00001"; + public static final String APP_SECRET = "abcdeabcdeabcdeabcdeabcde"; + + RopSampleClient ropSampleClient = new RopSampleClient(APP_KEY,APP_SECRET); + + @Test + public void testLogon() throws Exception { + String sessionId = ropSampleClient.logon("tomson", "123456"); + assertNotNull(sessionId); + } + + @Test + public void testLogout() throws Exception { + ropSampleClient.logout(); + } + + @Test + public void addUser() throws IOException { + + ropSampleClient.logon("tomson", "123456"); + + CreateUserRequest createUserRequest = new CreateUserRequest(); + createUserRequest.setUserName("katty"); + createUserRequest.setSalary(2500L); + + Telephone telephone = new Telephone(); + telephone.setZoneCode("010"); + telephone.setTelephoneCode("12345678"); + createUserRequest.setTelephone(telephone); + + CompositeResponse response = ropSampleClient.buildClientRequest() + .post(createUserRequest, CreateUserResponse.class, "user.add", "1.0"); + assertNotNull(response); + assertTrue(response.isSuccessful()); + assertTrue(response.getSuccessResponse() instanceof CreateUserResponse); + } +} + diff --git a/rop-sample/src/test/resources/com/rop/config/fullRopConfig.xml b/rop-sample/src/test/resources/com/rop/config/fullRopConfig.xml index 963af88..c8ce310 100644 --- a/rop-sample/src/test/resources/com/rop/config/fullRopConfig.xml +++ b/rop-sample/src/test/resources/com/rop/config/fullRopConfig.xml @@ -1,47 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/rop/.gitignore b/rop/.gitignore new file mode 100644 index 0000000..f675857 --- /dev/null +++ b/rop/.gitignore @@ -0,0 +1,2 @@ +/target/ +/.settings/ \ No newline at end of file diff --git a/rop/changelog.txt b/rop/changelog.txt index 5abc6a3..073d359 100644 --- a/rop/changelog.txt +++ b/rop/changelog.txt @@ -1,176 +1,183 @@ -1.0.7-SNAPSHOT -1.com.rop.response.ErrorResponse添加addSubError(SubError subError)方法; - -addSubError(SubError subError) -1.0.6 (2014-07-16) -1.Fix BUG: not support ${xxx}; -2.remove conf debug message of AnnotationDrivenBeanDefinitionParser,move to - AnnotationServletServiceRouter; - - -1.0.5 (2014-07-10) -1.the JDK version down grade to JDK 5.0,the before version need the JDK 6.0; -2.BusinessServiceErrorResponse#BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params) - Deprecated.Please use BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) - -1.0.4 (2014-07-06) -1.change i18n/rop/error resource ,add method and version to the Main Error message, -just like: - ERROR_3 = service method ({0}, {1}) user permissions - ERROR_4 = service method ({0}, {1}) image upload failed, reason is: {2} - ERROR_5 = service method ({0}, {1}) HTTP method {2} be banned - the {0} and {1} is the holderplace of method name and method version. -2.Fix Bug of AbstractAuthRequest,getDetail() return null but not detail; - -1.0.3-SNAPSHOT (2014-07-04) - -1.ROP系统级错误信息添加了绑定参数的支持,大部分错误消息都添加了当前的服务方法及版本的信息; -2.解决了com.rop.session.AbstractAuthRequest#getDetail()返回空的BUG; -3.解决了的upload-file-max-size属性无法设置的问题; -4.解决了若干个rop-sample的测试BUG; -5.BusinessServiceErrorResponse的构造函数从 - - 改为: - BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) - -1.0.2-SNAPSHOT (2014-05-27) -1.com.rop.response.RejectedServiceResponse的构造函数改为RejectedServiceResponse(RopRequestContext context); -2.com.rop.response.BusinessServiceErrorResponse的构造函数从BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params)改为 -BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params); - - -1.0.2-SNAPSHOT (2014-03-24) -1.ServiceMethodAdapter的方法 :Object invokeServiceMethod(RopRequestContext ropRequestContext)变更为: -Object invokeServiceMethod(RopRequest ropRequest); -2.ReopRequestContext删除getRopRequest及setRopRequest的方法; -3.SimpleRopRequestContext添加session属性,在创建RopRequestContext时获取设置session; -4.解决会话更新后不能自动同步到会话管理器的BUG. - -1.0.2-SNAPSHOT (2014-03-21) -1.com.rop.MessageFormat添加stream的输出类型,这种类型支持直接输出流,如文件下载 - 图片获取等; -2.重构了pom.xml的结构. - -1.0-SNAPSHOP-9 (2014-02-27) -1.com.rop.session.Session接口添加3个方法: - 1)isChanged():在会话内容变动后,该方法返回为true,以便ROP在处理完服务后通过SessionBindInterceptor将Session - 同步到外部的会话管理器中; - 2)removeAttribute(String name):删除会话中属性列表的条目; - 3)getAllAttributes():获取所有条目的方法; -2.com.rop.session.SessionBindInterceptor复写了beforeResponse(RopRequestContext ropRequestContext) - 方法,以便在服务处理后,如果会话内容有变化,则将其重写到外部缓存管理器,完成会话的同步。 - -1.0-SNAPSHOP-8 (2014-02-17) -1.添加JSONP及XCOR的支持,JSONP,默认使用callback函数,可以通过 -callback系统参数指定JSONP回调函数,只要系统参数中有callback参数, -即会以JSONP的格式返回。如 -http://yourhost?method=rop.user.add&v=1.0&callback=myfun,则响应报文的 -内容以会以JSONP格式包含中myfun函数中返回。 - -1.0-SNAPSHOP-7 (2013-11-01) -1.com.rop.response.ErrorResponse添加一个特殊标识:errorToken, -同时修改了com.rop.client.DefaultRopClient#isSuccessful()方法。 - -1.0-SNAPSHOP-6 (2013-10-31) -1.添加 ext-error-base-names,允许通过逗号分隔的方式设置多个国际化资源文件。 - -1.0-SNAPSHOP-5 (2013-10-18) -1.新增com.rop.session.AuthRequest 认证请求; -2.新增com.rop.session.AbstractAuthRequest,即AuthRequest的抽象类; -2.新增com.rop.session.AuthResponse 认证响应,即认证的结果,如果认证成功,AuthResponse将包括一个Session对象,代表认证成功对应的会话; -3.新增com.rop.session.AuthenticationManager认证管理器,即完成对AuthRequest进行认证,返回认证结果AuthResponse; -4.新增com.rop.session.AuthenticationService 认证服务类,具体的项目可以通过扩展该抽象类提供认证服务,具体可以参见rop-sample的 -SampleAuthenticationService例子; -5.新增com.rop.session.RopSessionHolder认证成功后,会产生Session,项目可以配置一个 -com.rop.session.SessionBindInterceptor拦截器,SessionBindInterceptor会将Session从SessionManager中 -绑定到本地线程中,这样当次请求的所有调用堆栈都可以通过RopSessionHolder访问到Session了。 -6.新增com.rop.session.SessionBindInterceptor参见com.rop.session.RopSessionHolder的说明,和rop-sample的配置。 -7.新增com.rop.session.UserNamePasswordAuthRequest基于用户名和密码的认证请求。 -8.解决了com.rop.impl.DefaultRopContext中的几个BUG: - BUG1:Rop启动时会扫描所有的Bean,性能较低,现改成只扫描标注 -@ServiceMethodBean的Bean!!所以ROP的服务类必须标注@ServiceMethodBean,否则会扫描不到!! - BUG2:原ROP会扫描所有的服务类方法,包括桥接方法和合成方法,这会引起服务方法注册的问题, - 现已改成只扫描非合成方法(即手工写方法); -9.com.rop.impl.AnnotationServletServiceRouter在启动时自动注册com.rop.session.SessionBindInterceptor。 - -1.0-SNAPSHOP-4 (2013-09-18) -1.支持JSONP调用,默认指定回调方法的参数名为callback,也可以通过 -标签指定一个自定义的jsonp参数名,如下所示: - -调用很简单,只要请求参数中有callback(或指定的)参数,即以jsonp形式返回。 -2.支持CORS报文头的跨域功能。 - -1.0-SNAPSHOP-3 (2012-07-31) -1.com.rop.response.ServiceErrorResponse 易名为BusinessServiceErrorResponse,其对应的主错误代码调整为9; -2.新增com.rop.CallLimitManager,用以限定应用、会话、用户的访问效率及频率,在中添加call-limit-manager的配置属性; -3.删除大部分ISP的子错误,仅留下isp.xxx-service-unavailable和isp.xxx-service-timeout错误; -4.请求参数数据校验精细化处理,首先如何发现必须的参数未提供,则返回isv.missing-parameter:xxx错误, - 然后再看是否存在数据类型转换的错误,如果存在则返回isv.parameters-mismatch:xxx-and-yyy错误, - 最后查看是否存在其它类型的校验错误,如果存在则返回isv.invalid-paramete:xxx错误; -5.添加了34~37的主错误,分别对应应用、会话及用户的访问超限; -6.文件上传主错误码从34调用为4; -7.错误报文的message,solution从属性调整为元素(因为其内容比较长,放在元素中好看些); -8.com.rop.SecurityManager的接口调用,新的接口方法一个用于检查应用的权限,另一个用户检查用户的权限, - 当应用或用户的权限不满足要求时,返回的主错误码分别对应2和3; -9.当服务内部抛出异常时,子错误对应isp.xxx-service-unavailable,其message会包含异常名字及异常的堆栈信息,方便问题定位和排查; -10.新增FileItem对象及其转换器FileItemConverter; -11.RopUtils新增若干个静态方法; -12.如果RopRequest中的属性类型标注了@IgnoreSign,则也不纳入签名,FileItem类就打了@IgnoreSign -13.新增com.rop.UploadFileSecurityManager类,用于管理上传文件的安全,同时中添加 -upload-file-max-size和upload-file-types属性。 -14.com.rop.validation包易名为com.rop.security,同时RopValidator易名为RopSecurityManager; -15.com.rop.SecurityManager易名为com.rop.security.ServiceInvokeSecurityManager; -16.CallLimitManager易名为InvokeTimesLimitSecurityManager -17.删除RopResponse,服务方法的返回值可以是任何类型。 - -1.0-SNAPSHOP-2 (2012-06-21) -1.新增com.rop.session包,管理会话,感谢iteye的melin的贡献; -2.删除com.rop.validation.SessionChecker,采用com.rop.session新的会话管理体系,相应调整RopValidator的接口; - -1.0-SNAPSHOP-1 (2012-05-29) -1.com.rop.ApiMethod及IgoreSign注解类迁移到com.rop.annotation包下,同时易名为com.rop.ServiceMethod, - 新增group,tags,title,timeout,version,ignoreSign,ioLogLevel等属性。 -2.在com.rop.annotation包下,新增com.rop.ServiceMethodGroup,ServiceMethodGroup 用于标注在服务类中,由于其 - 已经标注了Spring的Component注解,因此服务类标注ServiceMethodGroup后,即成为Spring的Bean,无需额外标注 - @Component或@Service等。 -3.新增com.rop.ServiceMethodDefinition,用于描述Rop的服务方法定义; -4.com.rop.RopServiceContext易名为ServiceMethodContext,在ServiceMethodContext中新增获取ServiceMethodDefinition的方法。 -5.com.rop.RopServiceHandler添加serviceMethodDefinition()的方法; -6.com.rop.Interceptor添加boolean isMatch(ServiceMethodContext methodContext)方法,以便指定拦截器的拦截范围。 - com.rop.AbstractInterceptor添加isMatch()的默认实现,返回true。 -7.com.rop.ResponseFormat易名为com.rop.MessageFormat. -8.com.rop.RopResponseMarshaller接口类名易名为RopMarshaller,接口方法: - void marshaller(RopResponse response, OutputStream outputStream) 调整为 - void marshaller(Object obj, OutputStream outputStream) -9.新增com.rop.marshaller.MessageMarshallerUtils,可以对RopRequest和RopResponse对象进行序列化输出。 -10.对RopValidator及其实现类进行重构,使代码更加清晰。 -11.新增SignUtils工具类,它负责对参数列表进行签名. -12.新增com.rop.RopContext它代表Rop框架的上下文,服务处理器(ServiceMethodHandler)在RopContext中通过 method+version的方式 - 注册。 - -1.0-SNAPSHOP-1 (2012-05-18) -1.解决JaxbXmlRopResponseMarshaller 存在的多线程安全问题; -2.RopRequest添加一个rawRequestObject的属性,可以获取原始Request的对象(即HttpServletRequest) -3.RopSample的UserRestServiceClient改为测试用例。 -4.可通过RopServlet的needCheckSign Servlet参数指定是否要进行签名校验。 -5.Rop框架的配置原来使用RopServlet的初始化参数,现在改为使用一个配置文件,默认的配置文件为:/WEB-INF/.properties,参见RopSample的实例; -6.解决JaxbXmlRopResponseMarshallerTest一个BUG,原来有依赖JUnit,现已经移除。 - - - - - - - - - - - - - - - - - - - +2.0-SNAPSHOT +1.将client代码独立开来,client的代码移除spring依赖,将client和平台服务公共用到的代码独立放到rop-core目录下 +2.将RopConverter移除spring依赖,并移到com.rop.converter包下 +3.将AnnotationServletServiceRouter中的xmlMarshaller对象、serviceMethodAdapter对象、jsonMarshaller对象变为可通过set方法设置 +4.将服务方法的参数类型必需继承AbstractRopRequest类型移除,变成可使用普通的pojo对象,服务方法的参数可接收RopRequestContext、HttpServletRequest、HttpServletResponse、RopContext对象,类似spring的Conttroller类的方法可变参数列表 +5.添加FastjsonRopMarshaller和FastjsonRopUnmarshaller,给使用者更多的选择,当然你也可以自定义数据格式转换器 + +1.0.7-SNAPSHOT +1.com.rop.response.ErrorResponse添加addSubError(SubError subError)方法; + +addSubError(SubError subError) +1.0.6 (2014-07-16) +1.Fix BUG: not support ${xxx}; +2.remove conf debug message of AnnotationDrivenBeanDefinitionParser,move to + AnnotationServletServiceRouter; + + +1.0.5 (2014-07-10) +1.the JDK version down grade to JDK 5.0,the before version need the JDK 6.0; +2.BusinessServiceErrorResponse#BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params) + Deprecated.Please use BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) + +1.0.4 (2014-07-06) +1.change i18n/rop/error resource ,add method and version to the Main Error message, +just like: + ERROR_3 = service method ({0}, {1}) user permissions + ERROR_4 = service method ({0}, {1}) image upload failed, reason is: {2} + ERROR_5 = service method ({0}, {1}) HTTP method {2} be banned + the {0} and {1} is the holderplace of method name and method version. +2.Fix Bug of AbstractAuthRequest,getDetail() return null but not detail; + +1.0.3-SNAPSHOT (2014-07-04) + +1.ROP系统级错误信息添加了绑定参数的支持,大部分错误消息都添加了当前的服务方法及版本的信息; +2.解决了com.rop.session.AbstractAuthRequest#getDetail()返回空的BUG; +3.解决了的upload-file-max-size属性无法设置的问题; +4.解决了若干个rop-sample的测试BUG; +5.BusinessServiceErrorResponse的构造函数从 + + 改为: + BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) + +1.0.2-SNAPSHOT (2014-05-27) +1.com.rop.response.RejectedServiceResponse的构造函数改为RejectedServiceResponse(RopRequestContext context); +2.com.rop.response.BusinessServiceErrorResponse的构造函数从BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params)改为 +BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params); + + +1.0.2-SNAPSHOT (2014-03-24) +1.ServiceMethodAdapter的方法 :Object invokeServiceMethod(RopRequestContext ropRequestContext)变更为: +Object invokeServiceMethod(RopRequest ropRequest); +2.ReopRequestContext删除getRopRequest及setRopRequest的方法; +3.SimpleRopRequestContext添加session属性,在创建RopRequestContext时获取设置session; +4.解决会话更新后不能自动同步到会话管理器的BUG. + +1.0.2-SNAPSHOT (2014-03-21) +1.com.rop.MessageFormat添加stream的输出类型,这种类型支持直接输出流,如文件下载 + 图片获取等; +2.重构了pom.xml的结构. + +1.0-SNAPSHOP-9 (2014-02-27) +1.com.rop.session.Session接口添加3个方法: + 1)isChanged():在会话内容变动后,该方法返回为true,以便ROP在处理完服务后通过SessionBindInterceptor将Session + 同步到外部的会话管理器中; + 2)removeAttribute(String name):删除会话中属性列表的条目; + 3)getAllAttributes():获取所有条目的方法; +2.com.rop.session.SessionBindInterceptor复写了beforeResponse(RopRequestContext ropRequestContext) + 方法,以便在服务处理后,如果会话内容有变化,则将其重写到外部缓存管理器,完成会话的同步。 + +1.0-SNAPSHOP-8 (2014-02-17) +1.添加JSONP及XCOR的支持,JSONP,默认使用callback函数,可以通过 +callback系统参数指定JSONP回调函数,只要系统参数中有callback参数, +即会以JSONP的格式返回。如 +http://yourhost?method=rop.user.add&v=1.0&callback=myfun,则响应报文的 +内容以会以JSONP格式包含中myfun函数中返回。 + +1.0-SNAPSHOP-7 (2013-11-01) +1.com.rop.response.ErrorResponse添加一个特殊标识:errorToken, +同时修改了com.rop.client.DefaultRopClient#isSuccessful()方法。 + +1.0-SNAPSHOP-6 (2013-10-31) +1.添加 ext-error-base-names,允许通过逗号分隔的方式设置多个国际化资源文件。 + +1.0-SNAPSHOP-5 (2013-10-18) +1.新增com.rop.session.AuthRequest 认证请求; +2.新增com.rop.session.AbstractAuthRequest,即AuthRequest的抽象类; +2.新增com.rop.session.AuthResponse 认证响应,即认证的结果,如果认证成功,AuthResponse将包括一个Session对象,代表认证成功对应的会话; +3.新增com.rop.session.AuthenticationManager认证管理器,即完成对AuthRequest进行认证,返回认证结果AuthResponse; +4.新增com.rop.session.AuthenticationService 认证服务类,具体的项目可以通过扩展该抽象类提供认证服务,具体可以参见rop-sample的 +SampleAuthenticationService例子; +5.新增com.rop.session.RopSessionHolder认证成功后,会产生Session,项目可以配置一个 +com.rop.session.SessionBindInterceptor拦截器,SessionBindInterceptor会将Session从SessionManager中 +绑定到本地线程中,这样当次请求的所有调用堆栈都可以通过RopSessionHolder访问到Session了。 +6.新增com.rop.session.SessionBindInterceptor参见com.rop.session.RopSessionHolder的说明,和rop-sample的配置。 +7.新增com.rop.session.UserNamePasswordAuthRequest基于用户名和密码的认证请求。 +8.解决了com.rop.impl.DefaultRopContext中的几个BUG: + BUG1:Rop启动时会扫描所有的Bean,性能较低,现改成只扫描标注 +@ServiceMethodBean的Bean!!所以ROP的服务类必须标注@ServiceMethodBean,否则会扫描不到!! + BUG2:原ROP会扫描所有的服务类方法,包括桥接方法和合成方法,这会引起服务方法注册的问题, + 现已改成只扫描非合成方法(即手工写方法); +9.com.rop.impl.AnnotationServletServiceRouter在启动时自动注册com.rop.session.SessionBindInterceptor。 + +1.0-SNAPSHOP-4 (2013-09-18) +1.支持JSONP调用,默认指定回调方法的参数名为callback,也可以通过 +标签指定一个自定义的jsonp参数名,如下所示: + +调用很简单,只要请求参数中有callback(或指定的)参数,即以jsonp形式返回。 +2.支持CORS报文头的跨域功能。 + +1.0-SNAPSHOP-3 (2012-07-31) +1.com.rop.response.ServiceErrorResponse 易名为BusinessServiceErrorResponse,其对应的主错误代码调整为9; +2.新增com.rop.CallLimitManager,用以限定应用、会话、用户的访问效率及频率,在中添加call-limit-manager的配置属性; +3.删除大部分ISP的子错误,仅留下isp.xxx-service-unavailable和isp.xxx-service-timeout错误; +4.请求参数数据校验精细化处理,首先如何发现必须的参数未提供,则返回isv.missing-parameter:xxx错误, + 然后再看是否存在数据类型转换的错误,如果存在则返回isv.parameters-mismatch:xxx-and-yyy错误, + 最后查看是否存在其它类型的校验错误,如果存在则返回isv.invalid-paramete:xxx错误; +5.添加了34~37的主错误,分别对应应用、会话及用户的访问超限; +6.文件上传主错误码从34调用为4; +7.错误报文的message,solution从属性调整为元素(因为其内容比较长,放在元素中好看些); +8.com.rop.SecurityManager的接口调用,新的接口方法一个用于检查应用的权限,另一个用户检查用户的权限, + 当应用或用户的权限不满足要求时,返回的主错误码分别对应2和3; +9.当服务内部抛出异常时,子错误对应isp.xxx-service-unavailable,其message会包含异常名字及异常的堆栈信息,方便问题定位和排查; +10.新增FileItem对象及其转换器FileItemConverter; +11.RopUtils新增若干个静态方法; +12.如果RopRequest中的属性类型标注了@IgnoreSign,则也不纳入签名,FileItem类就打了@IgnoreSign +13.新增com.rop.UploadFileSecurityManager类,用于管理上传文件的安全,同时中添加 +upload-file-max-size和upload-file-types属性。 +14.com.rop.validation包易名为com.rop.security,同时RopValidator易名为RopSecurityManager; +15.com.rop.SecurityManager易名为com.rop.security.ServiceInvokeSecurityManager; +16.CallLimitManager易名为InvokeTimesLimitSecurityManager +17.删除RopResponse,服务方法的返回值可以是任何类型。 + +1.0-SNAPSHOP-2 (2012-06-21) +1.新增com.rop.session包,管理会话,感谢iteye的melin的贡献; +2.删除com.rop.validation.SessionChecker,采用com.rop.session新的会话管理体系,相应调整RopValidator的接口; + +1.0-SNAPSHOP-1 (2012-05-29) +1.com.rop.ApiMethod及IgoreSign注解类迁移到com.rop.annotation包下,同时易名为com.rop.ServiceMethod, + 新增group,tags,title,timeout,version,ignoreSign,ioLogLevel等属性。 +2.在com.rop.annotation包下,新增com.rop.ServiceMethodGroup,ServiceMethodGroup 用于标注在服务类中,由于其 + 已经标注了Spring的Component注解,因此服务类标注ServiceMethodGroup后,即成为Spring的Bean,无需额外标注 + @Component或@Service等。 +3.新增com.rop.ServiceMethodDefinition,用于描述Rop的服务方法定义; +4.com.rop.RopServiceContext易名为ServiceMethodContext,在ServiceMethodContext中新增获取ServiceMethodDefinition的方法。 +5.com.rop.RopServiceHandler添加serviceMethodDefinition()的方法; +6.com.rop.Interceptor添加boolean isMatch(ServiceMethodContext methodContext)方法,以便指定拦截器的拦截范围。 + com.rop.AbstractInterceptor添加isMatch()的默认实现,返回true。 +7.com.rop.ResponseFormat易名为com.rop.MessageFormat. +8.com.rop.RopResponseMarshaller接口类名易名为RopMarshaller,接口方法: + void marshaller(RopResponse response, OutputStream outputStream) 调整为 + void marshaller(Object obj, OutputStream outputStream) +9.新增com.rop.marshaller.MessageMarshallerUtils,可以对RopRequest和RopResponse对象进行序列化输出。 +10.对RopValidator及其实现类进行重构,使代码更加清晰。 +11.新增SignUtils工具类,它负责对参数列表进行签名. +12.新增com.rop.RopContext它代表Rop框架的上下文,服务处理器(ServiceMethodHandler)在RopContext中通过 method+version的方式 + 注册。 + +1.0-SNAPSHOP-1 (2012-05-18) +1.解决JaxbXmlRopResponseMarshaller 存在的多线程安全问题; +2.RopRequest添加一个rawRequestObject的属性,可以获取原始Request的对象(即HttpServletRequest) +3.RopSample的UserRestServiceClient改为测试用例。 +4.可通过RopServlet的needCheckSign Servlet参数指定是否要进行签名校验。 +5.Rop框架的配置原来使用RopServlet的初始化参数,现在改为使用一个配置文件,默认的配置文件为:/WEB-INF/.properties,参见RopSample的实例; +6.解决JaxbXmlRopResponseMarshallerTest一个BUG,原来有依赖JUnit,现已经移除。 + + + + + + + + + + + + + + + + + + + diff --git a/rop/pom.xml b/rop/pom.xml index 09fcea2..9e51070 100644 --- a/rop/pom.xml +++ b/rop/pom.xml @@ -1,313 +1,190 @@ - - - 4.0.0 - - org.sonatype.oss - oss-parent - 7 - - com.rop - rop - 1.0.7-SNAPSHOT - jar - rop core - rest open platform - https://github.com/itstamen/rop - - - - The Apache Software License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - scm:git:git://github.com/itstamen/rop.git - scm:git:git://github.com/itstamen/rop.git - git://github.com/itstamen/rop.git - - - - - stamen - stamen - itstamen@qq.com - - - - - - - javax.servlet - servlet-api - ${servlet.version} - provided - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - - org.slf4j - slf4j-log4j12 - ${slf4j.version} - - - - log4j - log4j - ${log4j.version} - - - - commons-lang - commons-lang - ${commonslang.version} - - - - commons-codec - commons-codec - ${codec.version} - - - - org.springframework - spring-context-support - ${spring.version} - - - - org.springframework - spring-webmvc - ${spring.version} - - - - org.hibernate - hibernate-validator - ${hibernate.version} - - - - org.codehaus.jackson - jackson-core-asl - ${jackson.version} - - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson.version} - - - org.codehaus.jackson - jackson-jaxrs - ${jackson.version} - - - org.codehaus.jackson - jackson-xc - ${jackson.version} - - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.xml.version} - - - - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - - - javax.xml - jaxb-impl - ${jaxb-impl.version} - - - org.codehaus.woodstox - woodstox-core-asl - ${woodstox.version} - - - javax.activation - activation - ${activation.version} - - - - - org.springframework - spring-test - ${spring.version} - test - - - - org.testng - testng - ${testng.version} - test - - - - org.mockito - mockito-all - ${mockito.version} - test - - - - org.unitils - unitils-core - ${unitils.version} - test - - - - org.unitils - unitils-testng - ${unitils.version} - test - - - - org.unitils - unitils-spring - ${unitils.version} - test - - - - com.google.code.gson - gson - 2.2.4 - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - - - - - - - - - - - - - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - ${java.version} - ${java.version} - ${file.encoding} - - - - - org.apache.maven.plugins - maven-resources-plugin - 2.6 - - ${file.encoding} - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.7.2 - - once - -Dfile.encoding=${file.encoding} - - - net.sourceforge.cobertura.datafile - target/cobertura/cobertura.ser - - - - - - - - - - localDM - - true - - - - internal.repo.release - http://10.188.182.140:8081/nexus/content/repositories/releases/ - - - internal.repo.snapshot - http://10.188.182.140:8081/nexus/content/repositories/snapshots/ - - - - - - - UTF-8 - 1.5 - 2.5 - 3.2.3.RELEASE - - 1.9.5 - 1.6.1 - 1.2.16 - 4.2.0.Final - 1.6 - 2.3.2-jdk1.5 - 2.2.6 - 2.1 - 4.1.5 - 1.1.1 - 2.4 - 6.3 - 3.3 - 1.8.5 - 2.8 - 2.5.1 - - + + + 4.0.0 + + + com.rop + rop-parent + 2.0-SNAPSHOT + + + rop + jar + rop core + rest open platform + https://github.com/itstamen/rop + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + scm:git:git://github.com/itstamen/rop.git + scm:git:git://github.com/itstamen/rop.git + git://github.com/itstamen/rop.git + + + + + stamen + stamen + itstamen@qq.com + + + + + + + javax.servlet + servlet-api + ${servlet.version} + provided + + + + org.slf4j + slf4j-api + ${slf4j.version} + + + + org.springframework + spring-context-support + ${spring.version} + + + + org.springframework + spring-webmvc + ${spring.version} + + + + org.hibernate + hibernate-validator + ${hibernate.version} + + + + org.springframework + spring-test + ${spring.version} + test + + + + org.testng + testng + ${testng.version} + test + + + + org.mockito + mockito-all + ${mockito.version} + test + + + + org.unitils + unitils-core + ${unitils.version} + test + + + + org.unitils + unitils-testng + ${unitils.version} + test + + + + org.unitils + unitils-spring + ${unitils.version} + test + + + + com.rop + rop-core + ${project.version} + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + ${file.encoding} + ${file.encoding} + ${file.encoding} + + + + attach-javadocs + + jar + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${file.encoding} + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + ${file.encoding} + + + + + + + UTF-8 + 1.6 + 2.5 + 3.2.3.RELEASE + 1.6.1 + 4.2.0.Final + 6.3 + 3.3 + 1.8.5 + + \ No newline at end of file diff --git a/rop/src/main/java/com/rop/AbstractInterceptor.java b/rop/src/main/java/com/rop/AbstractInterceptor.java index 56ccac3..84f2fda 100644 --- a/rop/src/main/java/com/rop/AbstractInterceptor.java +++ b/rop/src/main/java/com/rop/AbstractInterceptor.java @@ -1,38 +1,49 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-4-26 - */ -package com.rop; - -/** - *
- *    抽象拦截器,实现类仅需覆盖特定的方法即可。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public abstract class AbstractInterceptor implements Interceptor { - - public void beforeService(RopRequestContext ropRequestContext) { - } - - - public void beforeResponse(RopRequestContext ropRequestContext) { - } - - - public boolean isMatch(RopRequestContext ropRequestContext) { - return true; - } - - /** - * 放在拦截器链的最后 - * - * @return - */ - public int getOrder() { - return Integer.MAX_VALUE; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *    抽象拦截器,实现类仅需覆盖特定的方法即可。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public abstract class AbstractInterceptor implements Interceptor { + + public void beforeService(RopRequestContext ropRequestContext) { + } + + + public void beforeResponse(RopRequestContext ropRequestContext) { + } + + + public boolean isMatch(RopRequestContext ropRequestContext) { + return true; + } + + /** + * 放在拦截器链的最后 + * + * @return + */ + public int getOrder() { + return Integer.MAX_VALUE; + } +} + diff --git a/rop/src/main/java/com/rop/AbstractRopRequest.java b/rop/src/main/java/com/rop/AbstractRopRequest.java index 6e4fa69..c3aac36 100644 --- a/rop/src/main/java/com/rop/AbstractRopRequest.java +++ b/rop/src/main/java/com/rop/AbstractRopRequest.java @@ -1,31 +1,42 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop; - -import com.rop.annotation.Temporary; - -/** - *
- *   所有请求对象应该通过扩展此抽象类实现
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public abstract class AbstractRopRequest implements RopRequest { - - @Temporary - private RopRequestContext ropRequestContext; - - - public RopRequestContext getRopRequestContext() { - return ropRequestContext; - } - - public final void setRopRequestContext(RopRequestContext ropRequestContext) { - this.ropRequestContext = ropRequestContext; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import com.rop.annotation.Temporary; + +/** + *
+ *   所有请求对象应该通过扩展此抽象类实现
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public abstract class AbstractRopRequest implements RopRequest { + + @Temporary + private RopRequestContext ropRequestContext; + + + public RopRequestContext getRopRequestContext() { + return ropRequestContext; + } + + public final void setRopRequestContext(RopRequestContext ropRequestContext) { + this.ropRequestContext = ropRequestContext; + } +} + diff --git a/rop/src/main/java/com/rop/CommonConstant.java b/rop/src/main/java/com/rop/CommonConstant.java deleted file mode 100644 index 0452b53..0000000 --- a/rop/src/main/java/com/rop/CommonConstant.java +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 13-11-1 - */ -public class CommonConstant { - - public static final String ERROR_TOKEN = "@@$-ERROR_TOKEN$-@@"; - - public static final String SESSION_CHANGED = "@@SESSION_CHANGED__"; -} diff --git a/rop/src/main/java/com/rop/Constants.java b/rop/src/main/java/com/rop/Constants.java deleted file mode 100644 index 0870dcd..0000000 --- a/rop/src/main/java/com/rop/Constants.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-11 - */ -package com.rop; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class Constants { - - public static final String UTF8 = "UTF-8"; -} - diff --git a/rop/src/main/java/com/rop/Interceptor.java b/rop/src/main/java/com/rop/Interceptor.java index d61d35c..555cb17 100644 --- a/rop/src/main/java/com/rop/Interceptor.java +++ b/rop/src/main/java/com/rop/Interceptor.java @@ -1,47 +1,58 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-4-25 - */ -package com.rop; - -/** - *
- *   拦截器,将在服务之前,服务之后响应之前调用
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface Interceptor { - - /** - * 在进行服务之前调用,如果在方法中往{@link RopRequestContext}设置了{@link RopResponse}(相当于已经产生了响应了), - * 所以服务将直接返回,不往下继续执行,反之服务会继续往下执行直到返回响应 - * - * @param ropRequestContext - */ - void beforeService(RopRequestContext ropRequestContext); - - /** - * 在服务之后,响应之前调用 - * - * @param ropRequestContext - */ - void beforeResponse(RopRequestContext ropRequestContext); - - /** - * 该方法返回true时才实施拦截,否则不拦截。可以通过{@link RopRequestContext} - * - * @param ropRequestContext - * @return - */ - boolean isMatch(RopRequestContext ropRequestContext); - - /** - * 执行的顺序,整数值越小的越早执行 - * - * @return - */ - int getOrder(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *   拦截器,将在服务之前,服务之后响应之前调用
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface Interceptor { + + /** + * 在进行服务之前调用,如果在方法中往{@link RopRequestContext}设置了{@link RopResponse}(相当于已经产生了响应了), + * 所以服务将直接返回,不往下继续执行,反之服务会继续往下执行直到返回响应 + * + * @param ropRequestContext + */ + void beforeService(RopRequestContext ropRequestContext); + + /** + * 在服务之后,响应之前调用 + * + * @param ropRequestContext + */ + void beforeResponse(RopRequestContext ropRequestContext); + + /** + * 该方法返回true时才实施拦截,否则不拦截。可以通过{@link RopRequestContext} + * + * @param ropRequestContext + * @return + */ + boolean isMatch(RopRequestContext ropRequestContext); + + /** + * 执行的顺序,整数值越小的越早执行 + * + * @return + */ + int getOrder(); +} + diff --git a/rop/src/main/java/com/rop/MessageFormat.java b/rop/src/main/java/com/rop/MessageFormat.java deleted file mode 100644 index 5b8a29d..0000000 --- a/rop/src/main/java/com/rop/MessageFormat.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 日期:12-2-10 - */ -package com.rop; - -import org.springframework.util.StringUtils; - -/** - * 支持的响应的格式类型 - */ -public enum MessageFormat { - - xml, json, stream; - - public static MessageFormat getFormat(String value) { - if (!StringUtils.hasText(value)) { - return xml; - } else { - try { - return MessageFormat.valueOf(value.toLowerCase()); - } catch (IllegalArgumentException e) { - return xml; - } - } - } - - public static boolean isValidFormat(String value) { - if (!StringUtils.hasText(value)) { - return true; - }else{ - try { - MessageFormat.valueOf(value.toLowerCase()); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } - } - -} diff --git a/rop/src/main/java/com/rop/RequestContextBuilder.java b/rop/src/main/java/com/rop/RequestContextBuilder.java index a249402..78c729d 100644 --- a/rop/src/main/java/com/rop/RequestContextBuilder.java +++ b/rop/src/main/java/com/rop/RequestContextBuilder.java @@ -1,32 +1,46 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-1 - */ -package com.rop; - -/** - *
- *    更改请求对象创建{@link RopRequestContext}实例,子类可以根据多种传输协议定义自己的创建器。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RequestContextBuilder { - /** - * 根据reqeuest及response请求响应对象,创建{@link RopRequestContext}实例。绑定系统参数,请求对象 - * @param ropContext - * @param request - * @param response - * @return - */ - RopRequestContext buildBySysParams(RopContext ropContext, Object request,Object response); - - /** - * 绑定业务参数 - * - * @param ropRequestContext - */ - RopRequest buildRopRequest(RopRequestContext ropRequestContext); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + *
+ *    更改请求对象创建{@link RopRequestContext}实例,子类可以根据多种传输协议定义自己的创建器。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RequestContextBuilder { + /** + * 根据reqeuest及response请求响应对象,创建{@link RopRequestContext}实例。绑定系统参数,请求对象 + * @param ropContext + * @param request + * @param response + * @return + */ + RopRequestContext buildBySysParams(RopContext ropContext, HttpServletRequest request, HttpServletResponse response); + + /** + * 绑定业务参数 + * + * @param ropRequestContext + */ + Object buildRopRequest(RopRequestContext ropRequestContext); +} + diff --git a/rop/src/main/java/com/rop/RopContext.java b/rop/src/main/java/com/rop/RopContext.java index 199a069..35339d2 100644 --- a/rop/src/main/java/com/rop/RopContext.java +++ b/rop/src/main/java/com/rop/RopContext.java @@ -1,86 +1,97 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop; - -import com.rop.session.SessionManager; - -import java.util.Map; - -/** - *
- *    ROP服务方法的处理者的注册表
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopContext { - - /** - * 注册一个服务处理器 - * - * @param methodName - * @param version - * @param serviceMethodHandler - */ - void addServiceMethod(String methodName, String version, ServiceMethodHandler serviceMethodHandler); - - /** - * 获取服务处理器 - * - * @param methodName - * @return - */ - ServiceMethodHandler getServiceMethodHandler(String methodName, String version); - - /** - * 是否是合法的服务方法 - * - * @param methodName - * @return - */ - boolean isValidMethod(String methodName); - - /** - * 是否存在对应的服务方法的版本号 - * - * @param methodName - * @param version - * @return - */ - boolean isValidVersion(String methodName, String version); - - - /** - * 服务方法的版本是否已经弃用 - * - * @param methodName - * @param version - * @return - */ - boolean isVersionObsoleted(String methodName, String version); - - /** - * 获取所有的处理器列表 - * - * @return - */ - Map getAllServiceMethodHandlers(); - - /** - * 是开启签名功能 - * - * @return - */ - boolean isSignEnable(); - - /** - * 获取会话管理器 - * @return - */ - SessionManager getSessionManager(); - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import com.rop.session.SessionManager; + +import java.util.Map; + +/** + *
+ *    ROP服务方法的处理者的注册表
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopContext { + + /** + * 注册一个服务处理器 + * + * @param methodName + * @param version + * @param serviceMethodHandler + */ + void addServiceMethod(String methodName, String version, ServiceMethodHandler serviceMethodHandler); + + /** + * 获取服务处理器 + * + * @param methodName + * @return + */ + ServiceMethodHandler getServiceMethodHandler(String methodName, String version); + + /** + * 是否是合法的服务方法 + * + * @param methodName + * @return + */ + boolean isValidMethod(String methodName); + + /** + * 是否存在对应的服务方法的版本号 + * + * @param methodName + * @param version + * @return + */ + boolean isValidVersion(String methodName, String version); + + + /** + * 服务方法的版本是否已经弃用 + * + * @param methodName + * @param version + * @return + */ + boolean isVersionObsoleted(String methodName, String version); + + /** + * 获取所有的处理器列表 + * + * @return + */ + Map getAllServiceMethodHandlers(); + + /** + * 是开启签名功能 + * + * @return + */ + boolean isSignEnable(); + + /** + * 获取会话管理器 + * @return + */ + SessionManager getSessionManager(); + +} + diff --git a/rop/src/main/java/com/rop/RopException.java b/rop/src/main/java/com/rop/RopException.java deleted file mode 100644 index d1c45fa..0000000 --- a/rop/src/main/java/com/rop/RopException.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop; - -/** - *
- *   ROP的异常。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopException extends RuntimeException { - public RopException() { - } - - public RopException(String message) { - super(message); - } - - public RopException(String message, Throwable cause) { - super(message, cause); - } - - public RopException(Throwable cause) { - super(cause); - } -} - diff --git a/rop/src/main/java/com/rop/RopMarshaller.java b/rop/src/main/java/com/rop/RopMarshaller.java deleted file mode 100644 index 1b88714..0000000 --- a/rop/src/main/java/com/rop/RopMarshaller.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * - * 日 期:12-2-27 - */ -package com.rop; - -import java.io.OutputStream; - -/** - *
- *   负责将请求方法返回的响应对应流化为相应格式的内容。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopMarshaller { - void marshaller(Object object, OutputStream outputStream); -} - diff --git a/rop/src/main/java/com/rop/RopRequest.java b/rop/src/main/java/com/rop/RopRequest.java index df83956..8d22298 100644 --- a/rop/src/main/java/com/rop/RopRequest.java +++ b/rop/src/main/java/com/rop/RopRequest.java @@ -1,25 +1,37 @@ -/** - * - * 日 期:12-2-10 - */ -package com.rop; - -/** - *
- *    ROP服务的请求对象,请求方法的入参必须是继承于该类。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopRequest { - - /** - * 获取服务方法的上下文 - * - * @return - */ - RopRequestContext getRopRequestContext(); - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *    ROP服务的请求对象,请求方法的入参必须是继承于该类。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopRequest { + + /** + * 获取服务方法的上下文 + * + * @return + */ + RopRequestContext getRopRequestContext(); + + void setRopRequestContext(RopRequestContext ropRequestContext); +} + diff --git a/rop/src/main/java/com/rop/RopRequestContext.java b/rop/src/main/java/com/rop/RopRequestContext.java index e897d89..a5d029a 100644 --- a/rop/src/main/java/com/rop/RopRequestContext.java +++ b/rop/src/main/java/com/rop/RopRequestContext.java @@ -1,230 +1,242 @@ -/** - * - * 日 期:12-2-27 - */ -package com.rop; - -import com.rop.annotation.HttpAction; -import com.rop.session.Session; - -import java.util.Locale; -import java.util.Map; - -/** - *
- *    接到服务请求后,将产生一个{@link RopRequestContext}上下文对象,它被本次请求直到返回响应的这个线程共享。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopRequestContext { - - /** - * 获取Rop的上下文 - * - * @return - */ - RopContext getRopContext(); - - /** - * 获取服务的方法 - * - * @return - */ - String getMethod(); - - /** - * 获取服务的版本号 - * - * @return - */ - String getVersion(); - - /** - * 获取应用的appKey - * - * @return - */ - String getAppKey(); - - /** - * 获取会话的ID - * - * @return - */ - String getSessionId(); - - /** - * 获取请求所对应的会话 - * - * @return - */ - Session getSession(); - - /** - * 绑定一个会话 - * - * @param session - */ - void addSession(String sessionId, Session session); - - /** - * 删除会话,删除{@link #getSessionId()}对应的Session - */ - void removeSession(); - - /** - * 获取报文格式化参数 - * - * @return - */ - String getFormat(); - - /** - * 获取响应的格式 - * - * @return - */ - MessageFormat getMessageFormat(); - - /** - * 获取本地化对象 - * - * @return - */ - Locale getLocale(); - - /** - * 获取签名 - * - * @return - */ - String getSign(); - - /** - * 获取客户端的IP - * - * @return - */ - String getIp(); - - /** - * 获取请求的方法 如POST - */ - HttpAction getHttpAction(); - - /** - * 获取请求的原对象(如HttpServletRequest) - * - * @return - */ - Object getRawRequestObject(); - - /** - * 获取请求的原响应对象(如HttpServletResponse) - * @return - */ - Object getRawResponseObject(); - - /** - * 设置服务开始时间 - * - * @param serviceBeginTime - */ - void setServiceBeginTime(long serviceBeginTime); - - /** - * 获取服务开始时间,单位为毫秒,为-1表示无意义 - * - * @return - */ - long getServiceBeginTime(); - - /** - * 设置服务开始时间 - * - * @param serviceEndTime - */ - void setServiceEndTime(long serviceEndTime); - - /** - * 获取服务结束时间,单位为毫秒,为-1表示无意义 - * - * @return - */ - long getServiceEndTime(); - - /** - * 获取服务方法对应的ApiMethod对象信息 - * - * @return - */ - ServiceMethodDefinition getServiceMethodDefinition(); - - /** - * 获取服务的处理者 - * - * @return - */ - ServiceMethodHandler getServiceMethodHandler(); - - - /** - * @param ropResponse - */ - void setRopResponse(Object ropResponse); - - /** - * 返回响应对象 - * - * @return - */ - Object getRopResponse(); - - - /** - * 获取特定属性 - * - * @param name - * @return - */ - Object getAttribute(String name); - - /** - * 设置属性的值 - * - * @param name - * @param value - */ - void setAttribute(String name, Object value); - - /** - * 该方法是否开启签名的功能 - * - * @return - */ - boolean isSignEnable(); - - /** - * 获取请求参数列表 - * - * @return - */ - Map getAllParams(); - - /** - * 获取请求参数值 - * - * @param paramName - * @return - */ - String getParamValue(String paramName); - - /** - * 获取请求ID,是一个唯一的UUID,每次请求对应一个唯一的ID - * @return - */ - String getRequestId(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import com.rop.annotation.HttpAction; +import com.rop.session.Session; + +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + *
+ *    接到服务请求后,将产生一个{@link RopRequestContext}上下文对象,它被本次请求直到返回响应的这个线程共享。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopRequestContext { + + /** + * 获取Rop的上下文 + * + * @return + */ + RopContext getRopContext(); + + /** + * 获取服务的方法 + * + * @return + */ + String getMethod(); + + /** + * 获取服务的版本号 + * + * @return + */ + String getVersion(); + + /** + * 获取应用的appKey + * + * @return + */ + String getAppKey(); + + /** + * 获取会话的ID + * + * @return + */ + String getSessionId(); + + /** + * 获取请求所对应的会话 + * + * @return + */ + Session getSession(); + + /** + * 绑定一个会话 + * + * @param session + */ + void addSession(String sessionId, Session session); + + /** + * 删除会话,删除{@link #getSessionId()}对应的Session + */ + void removeSession(); + + /** + * 获取报文格式化参数 + * + * @return + */ + String getFormat(); + + /** + * 获取响应的格式 + * + * @return + */ + MessageFormat getMessageFormat(); + + /** + * 获取本地化对象 + * + * @return + */ + Locale getLocale(); + + /** + * 获取签名 + * + * @return + */ + String getSign(); + + /** + * 获取客户端的IP + * + * @return + */ + String getIp(); + + /** + * 获取请求的方法 如POST + */ + HttpAction getHttpAction(); + + /** + * 获取请求的原对象(如HttpServletRequest) + * + * @return + */ + HttpServletRequest getRawRequestObject(); + + /** + * 获取请求的原响应对象(如HttpServletResponse) + * @return + */ + HttpServletResponse getRawResponseObject(); + + /** + * 设置服务开始时间 + * + * @param serviceBeginTime + */ + void setServiceBeginTime(long serviceBeginTime); + + /** + * 获取服务开始时间,单位为毫秒,为-1表示无意义 + * + * @return + */ + long getServiceBeginTime(); + + /** + * 设置服务开始时间 + * + * @param serviceEndTime + */ + void setServiceEndTime(long serviceEndTime); + + /** + * 获取服务结束时间,单位为毫秒,为-1表示无意义 + * + * @return + */ + long getServiceEndTime(); + + /** + * 获取服务方法对应的ApiMethod对象信息 + * + * @return + */ + ServiceMethodDefinition getServiceMethodDefinition(); + + /** + * 获取服务的处理者 + * + * @return + */ + ServiceMethodHandler getServiceMethodHandler(); + + /** + * @param ropResponse + */ + void setRopResponse(Object ropResponse); + + /** + * 返回响应对象 + * + * @return + */ + Object getRopResponse(); + + /** + * 获取特定属性 + * + * @param name + * @return + */ + Object getAttribute(String name); + + /** + * 设置属性的值 + * + * @param name + * @param value + */ + void setAttribute(String name, Object value); + + /** + * 该方法是否开启签名的功能 + * + * @return + */ + boolean isSignEnable(); + + /** + * 获取请求参数列表 + * + * @return + */ + Map getAllParams(); + + /** + * 获取请求参数值 + * + * @param paramName + * @return + */ + String getParamValue(String paramName); + + /** + * 获取请求ID,是一个唯一的UUID,每次请求对应一个唯一的ID + * @return + */ + String getRequestId(); +} + diff --git a/rop/src/main/java/com/rop/RopRequestParseException.java b/rop/src/main/java/com/rop/RopRequestParseException.java index 0c9cec0..0638d7e 100644 --- a/rop/src/main/java/com/rop/RopRequestParseException.java +++ b/rop/src/main/java/com/rop/RopRequestParseException.java @@ -1,35 +1,44 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-5-29 - */ -package com.rop; - -/** - *
- *   对请求数据进行解析时发生异常
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopRequestParseException extends RopException { - private String requestMessage; - - public RopRequestParseException(String requestMessage) { - this(requestMessage, ""); - } - - public RopRequestParseException(String requestMessage, String message) { - this(requestMessage, message, null); - } - - public RopRequestParseException(String requestMessage, String message, Throwable cause) { - super(message, cause); - this.requestMessage = requestMessage; - } - - public RopRequestParseException(String requestMessage, Throwable cause) { - this(requestMessage, null, cause); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *   对请求数据进行解析时发生异常
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@SuppressWarnings("serial") +public class RopRequestParseException extends RopException { + public RopRequestParseException(String requestMessage) { + this(requestMessage, ""); + } + + public RopRequestParseException(String requestMessage, String message) { + this(requestMessage, message, null); + } + + public RopRequestParseException(String requestMessage, String message, Throwable cause) { + super(message, cause); + } + + public RopRequestParseException(String requestMessage, Throwable cause) { + this(requestMessage, null, cause); + } +} + diff --git a/rop/src/main/java/com/rop/RopServlet.java b/rop/src/main/java/com/rop/RopServlet.java index 7673b06..90800c4 100644 --- a/rop/src/main/java/com/rop/RopServlet.java +++ b/rop/src/main/java/com/rop/RopServlet.java @@ -1,72 +1,92 @@ -/** - * 日 期:12-3-21 - */ -package com.rop; - -import com.rop.security.AppSecretManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - *
- *
- * HttpServlet是Rop框架的总入口,提供了多个定制ROP框架的配置参数:
- * 1.Rop会自己扫描Spring容器并加载之{@link SessionChecker}、{@link AppSecretManager}及{@link Interceptor}的Bean。也可以通过
- * "sessionCheckerClassName"、"appSecretManagerClassName"、"interceptorClassNames"的Servlet参数指定实现类的类名。如果显式指定了Servlet
- * 参数,则Rop就不会扫描Spring容器中的Bean了。
- *
- *   如果既没有使用Servlet参数指定,也没有在Spring容器中配置,则Rop使用{@link DefaultSessionChecker}和{@link FileBaseAppSecretManager}
- * 作为{@link SessionChecker}和{@link AppSecretManager}的实现类。
- *
- * 2.可通过"errorResourceBaseName"指定错误资源文件的基名,默认为“i18n/rop/ropError”.
- *
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopServlet extends HttpServlet { - - protected Logger logger = LoggerFactory.getLogger(getClass()); - - private ServiceRouter serviceRouter; - - - /** - * 将请求导向到Rop的框架中。 - * - * @param req - * @param resp - * @throws ServletException - * @throws IOException - */ - - protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - serviceRouter.service(req, resp); - } - - - public void init(ServletConfig servletConfig) throws ServletException { - ApplicationContext ctx = getApplicationContext(servletConfig); - this.serviceRouter = ctx.getBean(ServiceRouter.class); - if (this.serviceRouter == null) { - logger.error("在Spring容器中未找到" + ServiceRouter.class.getName() + - "的Bean,请在Spring配置文件中通过安装rop框架。"); - } - } - - private ApplicationContext getApplicationContext(ServletConfig servletConfig) { - return (ApplicationContext) servletConfig.getServletContext().getAttribute( - WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import com.rop.security.AppSecretManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.web.context.WebApplicationContext; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + *
+ *
+ * HttpServlet是Rop框架的总入口,提供了多个定制ROP框架的配置参数:
+ * 1.Rop会自己扫描Spring容器并加载之{@link SessionChecker}、{@link AppSecretManager}及{@link Interceptor}的Bean。也可以通过
+ * "sessionCheckerClassName"、"appSecretManagerClassName"、"interceptorClassNames"的Servlet参数指定实现类的类名。如果显式指定了Servlet
+ * 参数,则Rop就不会扫描Spring容器中的Bean了。
+ *
+ *   如果既没有使用Servlet参数指定,也没有在Spring容器中配置,则Rop使用{@link DefaultSessionChecker}和{@link FileBaseAppSecretManager}
+ * 作为{@link SessionChecker}和{@link AppSecretManager}的实现类。
+ *
+ * 2.可通过"errorResourceBaseName"指定错误资源文件的基名,默认为“i18n/rop/ropError”.
+ *
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopServlet extends HttpServlet { + private static final long serialVersionUID = 8092313047926951512L; + + protected Logger logger = LoggerFactory.getLogger(getClass()); + + private ServiceRouter serviceRouter; + + /** + * 将请求导向到Rop的框架中。 + * + * @param req + * @param resp + * @throws ServletException + * @throws IOException + */ + + protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + serviceRouter.service(req, resp); + } + + + public void init(ServletConfig servletConfig) throws ServletException { + ApplicationContext ctx = getApplicationContext(servletConfig); + this.serviceRouter = ctx.getBean(ServiceRouter.class); + if (this.serviceRouter == null) { + logger.error("在Spring容器中未找到" + ServiceRouter.class.getName() + + "的Bean,请在Spring配置文件中通过安装rop框架。"); + } + } + + private ApplicationContext getApplicationContext(ServletConfig servletConfig) { + return (ApplicationContext) servletConfig.getServletContext().getAttribute( + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); + } + + @Override + public void destroy() { + super.destroy(); + if(serviceRouter != null){ + serviceRouter.shutdown(); + } + } +} + diff --git a/rop/src/main/java/com/rop/ServiceMethodAdapter.java b/rop/src/main/java/com/rop/ServiceMethodAdapter.java index 674aa05..17dd48c 100644 --- a/rop/src/main/java/com/rop/ServiceMethodAdapter.java +++ b/rop/src/main/java/com/rop/ServiceMethodAdapter.java @@ -1,25 +1,36 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop; - -/** - *
- *    通过该适配器以统一的方式调用ROP方法
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface ServiceMethodAdapter { - /** - * 调用服务方法 - * - * @param ropRequest - * @return - */ - Object invokeServiceMethod(RopRequest ropRequest); - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ *    通过该适配器以统一的方式调用ROP方法
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface ServiceMethodAdapter { + /** + * 调用服务方法 + * + * @param ropRequest + * @return + */ + Object invokeServiceMethod(Object ropRequest, RopRequestContext context); + +} + diff --git a/rop/src/main/java/com/rop/ServiceMethodDefinition.java b/rop/src/main/java/com/rop/ServiceMethodDefinition.java index 3c6837d..bd8afd1 100644 --- a/rop/src/main/java/com/rop/ServiceMethodDefinition.java +++ b/rop/src/main/java/com/rop/ServiceMethodDefinition.java @@ -1,173 +1,184 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-5-31 - */ -package com.rop; - - -import com.rop.annotation.HttpAction; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ServiceMethodDefinition { - - /** - * 默认的组 - */ - public static final String DEFAULT_GROUP = "DEFAULT"; - - /** - * 默认分组标识 - */ - public static final String DEFAULT_GROUP_TITLE = "DEFAULT GROUP"; - - /** - * API的方法 - */ - private String method; - - /** - * API的方法的标识 - */ - private String methodTitle; - - /** - * HTTP请求的方法 - */ - private HttpAction[] httpAction; - - /** - * API方法所属组名 - */ - private String methodGroup = DEFAULT_GROUP; - - /** - * API方法组名的标识 - */ - private String methodGroupTitle; - - /** - * API所属的标签 - */ - private String[] tags = {}; - - /** - * 过期时间,单位为秒,0或负数表示不过期 - */ - private int timeout = -9999; - - /** - * 对应的版本号,如果为null或""表示不区分版本 - */ - private String version = null; - - /** - * 是否需要进行会话校验 - */ - private boolean needInSession; - - /** - * 是否忽略服务请求签名的校验,默认为false - */ - private boolean ignoreSign = false; - - /** - * 服务方法是否已经过期 - */ - private boolean obsoleted = false; - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public String getMethodTitle() { - return methodTitle; - } - - public void setMethodTitle(String methodTitle) { - this.methodTitle = methodTitle; - } - - public String getMethodGroup() { - return methodGroup; - } - - public void setMethodGroup(String methodGroup) { - this.methodGroup = methodGroup; - } - - public String getMethodGroupTitle() { - return methodGroupTitle; - } - - public void setMethodGroupTitle(String methodGroupTitle) { - this.methodGroupTitle = methodGroupTitle; - } - - public String[] getTags() { - return tags; - } - - public void setTags(String[] tags) { - this.tags = tags; - } - - public int getTimeout() { - return this.timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public boolean isNeedInSession() { - return needInSession; - } - - public void setNeedInSession(boolean needInSession) { - this.needInSession = needInSession; - } - - public boolean isIgnoreSign() { - return ignoreSign; - } - - public void setIgnoreSign(boolean ignoreSign) { - this.ignoreSign = ignoreSign; - } - - public HttpAction[] getHttpAction() { - return httpAction; - } - - public void setHttpAction(HttpAction[] httpAction) { - this.httpAction = httpAction; - } - - public boolean isObsoleted() { - return obsoleted; - } - - public void setObsoleted(boolean obsoleted) { - this.obsoleted = obsoleted; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + + +import com.rop.annotation.HttpAction; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ServiceMethodDefinition { + + /** + * 默认的组 + */ + public static final String DEFAULT_GROUP = "DEFAULT"; + + /** + * 默认分组标识 + */ + public static final String DEFAULT_GROUP_TITLE = "DEFAULT GROUP"; + + /** + * API的方法 + */ + private String method; + + /** + * API的方法的标识 + */ + private String methodTitle; + + /** + * HTTP请求的方法 + */ + private HttpAction[] httpAction; + + /** + * API方法所属组名 + */ + private String methodGroup = DEFAULT_GROUP; + + /** + * API方法组名的标识 + */ + private String methodGroupTitle; + + /** + * API所属的标签 + */ + private String[] tags = {}; + + /** + * 过期时间,单位为秒,0或负数表示不过期 + */ + private int timeout = -9999; + + /** + * 对应的版本号,如果为null或""表示不区分版本 + */ + private String version = null; + + /** + * 是否需要进行会话校验 + */ + private boolean needInSession; + + /** + * 是否忽略服务请求签名的校验,默认为false + */ + private boolean ignoreSign = false; + + /** + * 服务方法是否已经过期 + */ + private boolean obsoleted = false; + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getMethodTitle() { + return methodTitle; + } + + public void setMethodTitle(String methodTitle) { + this.methodTitle = methodTitle; + } + + public String getMethodGroup() { + return methodGroup; + } + + public void setMethodGroup(String methodGroup) { + this.methodGroup = methodGroup; + } + + public String getMethodGroupTitle() { + return methodGroupTitle; + } + + public void setMethodGroupTitle(String methodGroupTitle) { + this.methodGroupTitle = methodGroupTitle; + } + + public String[] getTags() { + return tags; + } + + public void setTags(String[] tags) { + this.tags = tags; + } + + public int getTimeout() { + return this.timeout; + } + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public boolean isNeedInSession() { + return needInSession; + } + + public void setNeedInSession(boolean needInSession) { + this.needInSession = needInSession; + } + + public boolean isIgnoreSign() { + return ignoreSign; + } + + public void setIgnoreSign(boolean ignoreSign) { + this.ignoreSign = ignoreSign; + } + + public HttpAction[] getHttpAction() { + return httpAction; + } + + public void setHttpAction(HttpAction[] httpAction) { + this.httpAction = httpAction; + } + + public boolean isObsoleted() { + return obsoleted; + } + + public void setObsoleted(boolean obsoleted) { + this.obsoleted = obsoleted; + } +} + diff --git a/rop/src/main/java/com/rop/ServiceMethodHandler.java b/rop/src/main/java/com/rop/ServiceMethodHandler.java index 36eadcf..a9bc5c8 100644 --- a/rop/src/main/java/com/rop/ServiceMethodHandler.java +++ b/rop/src/main/java/com/rop/ServiceMethodHandler.java @@ -1,112 +1,97 @@ -/** - * - * 日 期:12-2-10 - */ -package com.rop; - -import java.lang.reflect.Method; -import java.util.List; - -/** - *
- *     服务处理器的相关信息
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ServiceMethodHandler { - - //处理器对象 - private Object handler; - - //处理器的处理方法 - private Method handlerMethod; - - private ServiceMethodDefinition serviceMethodDefinition; - - //处理方法的请求对象类 - private Class requestType = RopRequest.class; - - //无需签名的字段列表 - private List ignoreSignFieldNames; - - //属性类型为FileItem的字段列表 - private List uploadFileFieldNames; - - //是否是实现类 - private boolean ropRequestImplType; - - public ServiceMethodHandler() { - } - - public Object getHandler() { - return handler; - } - - public void setHandler(Object handler) { - this.handler = handler; - } - - public Method getHandlerMethod() { - return handlerMethod; - } - - public void setHandlerMethod(Method handlerMethod) { - this.handlerMethod = handlerMethod; - } - - public Class getRequestType() { - return requestType; - } - - public void setRequestType(Class requestType) { - this.requestType = requestType; - } - - - public boolean isHandlerMethodWithParameter() { - return this.requestType != null; - } - - public void setIgnoreSignFieldNames(List ignoreSignFieldNames) { - this.ignoreSignFieldNames = ignoreSignFieldNames; - } - - public List getIgnoreSignFieldNames() { - return ignoreSignFieldNames; - } - - public ServiceMethodDefinition getServiceMethodDefinition() { - return serviceMethodDefinition; - } - - public void setServiceMethodDefinition(ServiceMethodDefinition serviceMethodDefinition) { - this.serviceMethodDefinition = serviceMethodDefinition; - } - - public static String methodWithVersion(String methodName, String version) { - return methodName + "#" + version; - } - - public boolean isRopRequestImplType() { - return ropRequestImplType; - } - - public void setRopRequestImplType(boolean ropRequestImplType) { - this.ropRequestImplType = ropRequestImplType; - } - - public List getUploadFileFieldNames() { - return uploadFileFieldNames; - } - - public void setUploadFileFieldNames(List uploadFileFieldNames) { - this.uploadFileFieldNames = uploadFileFieldNames; - } - - public boolean hasUploadFiles(){ - return uploadFileFieldNames != null && uploadFileFieldNames.size() > 0; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import java.lang.reflect.Method; +import java.util.List; + +/** + *
+ *     服务处理器的相关信息
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ServiceMethodHandler { + + //处理器对象 + private Object handler; + + //处理器的处理方法 + private Method handlerMethod; + + private ServiceMethodDefinition serviceMethodDefinition; + + //无需签名的字段列表 + private List ignoreSignFieldNames; + + //属性类型为FileItem的字段列表 + private List uploadFileFieldNames; + + + public ServiceMethodHandler() { + } + + public Object getHandler() { + return handler; + } + + public void setHandler(Object handler) { + this.handler = handler; + } + + public Method getHandlerMethod() { + return handlerMethod; + } + + public void setHandlerMethod(Method handlerMethod) { + this.handlerMethod = handlerMethod; + } + + public void setIgnoreSignFieldNames(List ignoreSignFieldNames) { + this.ignoreSignFieldNames = ignoreSignFieldNames; + } + + public List getIgnoreSignFieldNames() { + return ignoreSignFieldNames; + } + + public ServiceMethodDefinition getServiceMethodDefinition() { + return serviceMethodDefinition; + } + + public void setServiceMethodDefinition(ServiceMethodDefinition serviceMethodDefinition) { + this.serviceMethodDefinition = serviceMethodDefinition; + } + + public static String methodWithVersion(String methodName, String version) { + return methodName + "#" + version; + } + + public List getUploadFileFieldNames() { + return uploadFileFieldNames; + } + + public void setUploadFileFieldNames(List uploadFileFieldNames) { + this.uploadFileFieldNames = uploadFileFieldNames; + } + + public boolean hasUploadFiles(){ + return uploadFileFieldNames != null && uploadFileFieldNames.size() > 0; + } +} + diff --git a/rop/src/main/java/com/rop/ServiceRouter.java b/rop/src/main/java/com/rop/ServiceRouter.java index 9f9bf3f..1617e78 100644 --- a/rop/src/main/java/com/rop/ServiceRouter.java +++ b/rop/src/main/java/com/rop/ServiceRouter.java @@ -1,153 +1,173 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop; - -import com.rop.event.RopEventListener; -import com.rop.security.InvokeTimesController; -import com.rop.session.SessionManager; -import org.springframework.context.ApplicationContext; -import org.springframework.format.support.FormattingConversionService; - -import java.util.concurrent.ThreadPoolExecutor; - -/** - *
- *      ROP的服务路由器,服务方法必须位于@Controller的类中,服务方法使用{@link com.rop.annotation.ServiceMethod}注解,有两个合法的方法签名方式:
- * 签名方式1:有入参,且参数必须实现{@link RopRequest}接口,返回参数为{@link RopResponse}
- *   
- *    @ServiceMethod("method1")
- *    RopResponse handleMethod1(RopRequest ropRequest){
- *        ...
- *    }
- *   
- * 签名方式2:无入参,返回参数为{@link RopResponse}
- *   
- *    @ServiceMethod("method1")
- *    RopResponse handleMethod1(){
- *        ...
- *    }
- *   
- *   ROP框架会自动将请求参数的值绑定到入参请求对象中。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface ServiceRouter { - - /** - * ROP框架的总入口,一般框架实现,开发者无需关注。 - * - * @param request - * @param response - */ - void service(Object request, Object response); - - /** - * 启动服务路由器 - */ - void startup(); - - /** - * 关闭服务路由器 - */ - void shutdown(); - - /** - * 获取{@link RopContext} - * - * @return - */ - RopContext getRopContext(); - - /** - * 设置Spring的上下文 - * - * @param applicationContext - */ - void setApplicationContext(ApplicationContext applicationContext); - - /** - * 注册拦截器 - * - * @param interceptor - */ - void addInterceptor(Interceptor interceptor); - - /** - * 注册监听器 - * - * @param listener - */ - void addListener(RopEventListener listener); - - /** - * 设置{@link com.rop.security.SecurityManager} - * - * @param securityManager - */ - void setSecurityManager(com.rop.security.SecurityManager securityManager); - - /** - * 注册 - * - * @param threadPoolExecutor - */ - void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor); - - /** - * 设置是否需要进行签名校验 - * - * @param signEnable - */ - void setSignEnable(boolean signEnable); - - /** - * 设置所有服务的通用过期时间,单位为秒 - * - * @param serviceTimeoutSeconds - */ - void setServiceTimeoutSeconds(int serviceTimeoutSeconds); - - /** - * 设置扩展错误资源基名 - * - * @param extErrorBasename - */ - void setExtErrorBasename(String extErrorBasename); - - /** - * 允许设置多个资源文件 - * @param extErrorBasenames - */ - void setExtErrorBasenames(String[] extErrorBasenames); - - /** - * 设置格式化类型转换器 - * - * @param conversionService - */ - void setFormattingConversionService(FormattingConversionService conversionService); - - /** - * 添加会话管理器 - * - * @param sessionManager - */ - void setSessionManager(SessionManager sessionManager); - - /** - * 设置服务调用限制管理器 - * @param invokeTimesController - */ - void setInvokeTimesController(InvokeTimesController invokeTimesController); - - /** - * 设置线程信息摆渡器 - * @param threadFerryClass - */ - void setThreadFerryClass(Class threadFerryClass); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +import com.rop.event.RopEvent; +import com.rop.event.RopEventListener; +import com.rop.security.InvokeTimesController; +import com.rop.session.SessionManager; + +import org.springframework.context.ApplicationContext; +import org.springframework.format.support.FormattingConversionService; + +import java.util.concurrent.ThreadPoolExecutor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + *
+ *      ROP的服务路由器,服务方法必须位于@Controller的类中,服务方法使用{@link com.rop.annotation.ServiceMethod}注解,有两个合法的方法签名方式:
+ * 签名方式1:有入参,且参数必须实现{@link RopRequest}接口,返回参数为{@link RopResponse}
+ *   
+ *    @ServiceMethod("method1")
+ *    RopResponse handleMethod1(RopRequest ropRequest){
+ *        ...
+ *    }
+ *   
+ * 签名方式2:无入参,返回参数为{@link RopResponse}
+ *   
+ *    @ServiceMethod("method1")
+ *    RopResponse handleMethod1(){
+ *        ...
+ *    }
+ *   
+ *   ROP框架会自动将请求参数的值绑定到入参请求对象中。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface ServiceRouter { + + /** + * ROP框架的总入口,一般框架实现,开发者无需关注。 + * + * @param request + * @param response + */ + void service(HttpServletRequest request, HttpServletResponse response); + + /** + * 启动服务路由器 + */ + void startup(); + + /** + * 关闭服务路由器 + */ + void shutdown(); + + /** + * 获取{@link RopContext} + * + * @return + */ + RopContext getRopContext(); + + /** + * 设置Spring的上下文 + * + * @param applicationContext + */ + void setApplicationContext(ApplicationContext applicationContext); + + /** + * 注册拦截器 + * + * @param interceptor + */ + void addInterceptor(Interceptor interceptor); + + /** + * 注册监听器 + * + * @param listener + */ + void addListener(RopEventListener listener); + + /** + * 设置{@link com.rop.security.SecurityManager} + * + * @param securityManager + */ + void setSecurityManager(com.rop.security.SecurityManager securityManager); + + /** + * 注册 + * + * @param threadPoolExecutor + */ + void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor); + + /** + * 设置是否需要进行签名校验 + * + * @param signEnable + */ + void setSignEnable(boolean signEnable); + + /** + * 设置所有服务的通用过期时间,单位为秒 + * + * @param serviceTimeoutSeconds + */ + void setServiceTimeoutSeconds(int serviceTimeoutSeconds); + + /** + * 设置扩展错误资源基名 + * + * @param extErrorBasename + */ + void setExtErrorBasename(String extErrorBasename); + + /** + * 允许设置多个资源文件 + * @param extErrorBasenames + */ + void setExtErrorBasenames(String[] extErrorBasenames); + + /** + * 设置格式化类型转换器 + * + * @param conversionService + */ + void setFormattingConversionService(FormattingConversionService conversionService); + + /** + * 添加会话管理器 + * + * @param sessionManager + */ + void setSessionManager(SessionManager sessionManager); + + /** + * 设置服务调用限制管理器 + * @param invokeTimesController + */ + void setInvokeTimesController(InvokeTimesController invokeTimesController); + + /** + * 设置线程信息摆渡器 + * @param threadFerryClass + */ + void setThreadFerryClass(Class threadFerryClass); + + void setJsonMarshaller(RopMarshaller jsonMarshaller); + + void setXmlMarshaller(RopMarshaller xmlMarshaller); +} + diff --git a/rop/src/main/java/com/rop/ThreadFerry.java b/rop/src/main/java/com/rop/ThreadFerry.java index 5565396..baf24e0 100644 --- a/rop/src/main/java/com/rop/ThreadFerry.java +++ b/rop/src/main/java/com/rop/ThreadFerry.java @@ -1,34 +1,45 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-7-19 - */ -package com.rop; - -/** - *
- * 由于ROP采用异步方式工作,也即接收HTTP请求的线程和执行ROP方法的线程是不一样的,如果你在请求线程中通过
- * {@link ThreadLocal}绑定了一个本地线程变量,在ROP服务方法中将访问不到!因此必须进行在两线程之间进行
- * 变量的传递(也即线程摆渡),即在{@link #doInSrcThread()}方法中获取请求线程中的变量,放到
- * 实例变量中缓存起来,然后在{@link #doInDestThread()}方法中将实例变量的值手工设置到ROP方法执行线程的
- * 本地线程变量中。
- *
- * {@link ThreadFerry}每次都会创建一个实例,因此是线程安全的。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface ThreadFerry { - - /** - * 在源线程中执行 - * @param - */ - void doInSrcThread(); - - /** - * 在目标线程中执行 - */ - void doInDestThread(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop; + +/** + *
+ * 由于ROP采用异步方式工作,也即接收HTTP请求的线程和执行ROP方法的线程是不一样的,如果你在请求线程中通过
+ * {@link ThreadLocal}绑定了一个本地线程变量,在ROP服务方法中将访问不到!因此必须进行在两线程之间进行
+ * 变量的传递(也即线程摆渡),即在{@link #doInSrcThread()}方法中获取请求线程中的变量,放到
+ * 实例变量中缓存起来,然后在{@link #doInDestThread()}方法中将实例变量的值手工设置到ROP方法执行线程的
+ * 本地线程变量中。
+ *
+ * {@link ThreadFerry}每次都会创建一个实例,因此是线程安全的。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface ThreadFerry { + + /** + * 在源线程中执行 + * @param + */ + void doInSrcThread(); + + /** + * 在目标线程中执行 + */ + void doInDestThread(); +} + diff --git a/rop/src/main/java/com/rop/annotation/HttpAction.java b/rop/src/main/java/com/rop/annotation/HttpAction.java index f6e92ae..2c52651 100644 --- a/rop/src/main/java/com/rop/annotation/HttpAction.java +++ b/rop/src/main/java/com/rop/annotation/HttpAction.java @@ -1,29 +1,40 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-8 - */ -package com.rop.annotation; - -/** - *
- *   请求类型的方法
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum HttpAction { - - GET, POST; - - public static HttpAction fromValue(String value) { - if (GET.name().equalsIgnoreCase(value)) { - return GET; - } else if (POST.name().equalsIgnoreCase(value)) { - return POST; - } else { - return POST; - } - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +/** + *
+ *   请求类型的方法
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum HttpAction { + + GET, POST; + + public static HttpAction fromValue(String value) { + if (GET.name().equalsIgnoreCase(value)) { + return GET; + } else if (POST.name().equalsIgnoreCase(value)) { + return POST; + } else { + return POST; + } + } +} + diff --git a/rop/src/main/java/com/rop/annotation/IgnoreSign.java b/rop/src/main/java/com/rop/annotation/IgnoreSign.java deleted file mode 100644 index 4e1af37..0000000 --- a/rop/src/main/java/com/rop/annotation/IgnoreSign.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - * 日 期:12-2-10 - */ -package com.rop.annotation; - - -import java.lang.annotation.*; - -/** - *
- *     如果标注在请求类的属性上,则表示该属性无需进行签名,如下所示:
- * 请求对象({@link com.rop.RopRequest})中不需要签名校验的属性(默认都要签名)。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@Target({ElementType.FIELD,ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface IgnoreSign { -} diff --git a/rop/src/main/java/com/rop/annotation/IgnoreSignType.java b/rop/src/main/java/com/rop/annotation/IgnoreSignType.java deleted file mode 100644 index b3fb530..0000000 --- a/rop/src/main/java/com/rop/annotation/IgnoreSignType.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-5-31 - */ -package com.rop.annotation; - -/** - *
- *    是否需求进行签名校验.{@link #DEFAULT}是系统预留的,请不要在实际中使用
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum IgnoreSignType { - - YES, NO, DEFAULT; - - public static boolean isIgnoreSign(IgnoreSignType type) { - if (NO == type || DEFAULT == type) { - return false; - } else { - return true; - } - } -} - diff --git a/rop/src/main/java/com/rop/annotation/NeedInSessionType.java b/rop/src/main/java/com/rop/annotation/NeedInSessionType.java index 98d234c..3960e24 100644 --- a/rop/src/main/java/com/rop/annotation/NeedInSessionType.java +++ b/rop/src/main/java/com/rop/annotation/NeedInSessionType.java @@ -1,26 +1,37 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-5-31 - */ -package com.rop.annotation; - -/** - *
- * 功能说明:是否需求会话检查
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum NeedInSessionType { - YES, NO, DEFAULT; - - public static boolean isNeedInSession(NeedInSessionType type) { - if (YES == type || DEFAULT == type) { - return true; - } else { - return false; - } - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +/** + *
+ * 功能说明:是否需求会话检查
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum NeedInSessionType { + YES, NO, DEFAULT; + + public static boolean isNeedInSession(NeedInSessionType type) { + if (YES == type || DEFAULT == type) { + return true; + } else { + return false; + } + } +} + diff --git a/rop/src/main/java/com/rop/annotation/ObsoletedType.java b/rop/src/main/java/com/rop/annotation/ObsoletedType.java index 5603c8e..7be40a5 100644 --- a/rop/src/main/java/com/rop/annotation/ObsoletedType.java +++ b/rop/src/main/java/com/rop/annotation/ObsoletedType.java @@ -1,26 +1,37 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-7-30 - */ -package com.rop.annotation; - -/** - *
- *   服务方法是否已经过期,过期的服务方法不能再访问
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public enum ObsoletedType { - YES, NO, DEFAULT; - - public static boolean isObsoleted(ObsoletedType type) { - if (YES == type ) { - return true; - } else { - return false; - } - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +/** + *
+ *   服务方法是否已经过期,过期的服务方法不能再访问
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public enum ObsoletedType { + YES, NO, DEFAULT; + + public static boolean isObsoleted(ObsoletedType type) { + if (YES == type ) { + return true; + } else { + return false; + } + } +} + diff --git a/rop/src/main/java/com/rop/annotation/ServiceMethod.java b/rop/src/main/java/com/rop/annotation/ServiceMethod.java index 590339e..d5b0020 100644 --- a/rop/src/main/java/com/rop/annotation/ServiceMethod.java +++ b/rop/src/main/java/com/rop/annotation/ServiceMethod.java @@ -1,102 +1,113 @@ -/** - * - * 日 期:12-2-10 - */ -package com.rop.annotation; - - -import com.rop.ServiceMethodDefinition; - -import java.lang.annotation.*; - -/** - *
- *     使用该注解对服务方法进行标注,这些方法必须是Spring的Service:既打了@Service的注解。
- *
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@Target({ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface ServiceMethod { - - /** - * 服务的方法名,即由method参数指定的服务方法名 - * - * @return - */ - String method() default ""; - - /** - * 所属的服务分组 - * - * @return - */ - String group() default ServiceMethodDefinition.DEFAULT_GROUP; - - /** - * 所属的服务分组的标识 - * - * @return - */ - String groupTitle() default ServiceMethodDefinition.DEFAULT_GROUP_TITLE; - - /** - * 标签,可以打上多个标签 - * - * @return - */ - String[] tags() default {}; - - /** - * 服务的中文名称 - * - * @return - */ - String title() default ""; - - /** - * 访问过期时间,单位为毫秒,即大于这个过期时间的链接会结束并返回错误报文,如果 - * 为0或负数则表示不进行过期限制 - * - * @return - */ - int timeout() default -1; - - /** - * 请求方法,默认不限制 - * - * @return - */ - HttpAction[] httpAction() default {}; - - /** - * 该方法所对应的版本号,对应version请求参数的值,版本为空,表示不进行版本限定 - * - * @return - */ - String version() default ""; - - /** - * 服务方法需要需求会话检查,默认要检查 - * - * @return - */ - NeedInSessionType needInSession() default NeedInSessionType.DEFAULT; - - /** - * 是否忽略签名检查,默认不忽略 - * - * @return - */ - IgnoreSignType ignoreSign() default IgnoreSignType.DEFAULT; - - /** - * 服务方法是否已经过期,默认不过期 - * @return - */ - ObsoletedType obsoleted() default ObsoletedType.DEFAULT; -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + + +import com.rop.ServiceMethodDefinition; + +import java.lang.annotation.*; + +/** + *
+ *     使用该注解对服务方法进行标注,这些方法必须是Spring的Service:既打了@Service的注解。
+ *
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface ServiceMethod { + + /** + * 服务的方法名,即由method参数指定的服务方法名 + * + * @return + */ + String method() default ""; + + /** + * 所属的服务分组 + * + * @return + */ + String group() default ServiceMethodDefinition.DEFAULT_GROUP; + + /** + * 所属的服务分组的标识 + * + * @return + */ + String groupTitle() default ServiceMethodDefinition.DEFAULT_GROUP_TITLE; + + /** + * 标签,可以打上多个标签 + * + * @return + */ + String[] tags() default {}; + + /** + * 服务的中文名称 + * + * @return + */ + String title() default ""; + + /** + * 访问过期时间,单位为毫秒,即大于这个过期时间的链接会结束并返回错误报文,如果 + * 为0或负数则表示不进行过期限制 + * + * @return + */ + int timeout() default -1; + + /** + * 请求方法,默认不限制 + * + * @return + */ + HttpAction[] httpAction() default {}; + + /** + * 该方法所对应的版本号,对应version请求参数的值,版本为空,表示不进行版本限定 + * + * @return + */ + String version() default ""; + + /** + * 服务方法需要需求会话检查,默认要检查 + * + * @return + */ + NeedInSessionType needInSession() default NeedInSessionType.DEFAULT; + + /** + * 是否忽略签名检查,默认不忽略 + * + * @return + */ + IgnoreSignType ignoreSign() default IgnoreSignType.DEFAULT; + + /** + * 服务方法是否已经过期,默认不过期 + * @return + */ + ObsoletedType obsoleted() default ObsoletedType.DEFAULT; +} diff --git a/rop/src/main/java/com/rop/annotation/ServiceMethodBean.java b/rop/src/main/java/com/rop/annotation/ServiceMethodBean.java index b07049d..b9e1713 100644 --- a/rop/src/main/java/com/rop/annotation/ServiceMethodBean.java +++ b/rop/src/main/java/com/rop/annotation/ServiceMethodBean.java @@ -1,92 +1,103 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-5-31 - */ -package com.rop.annotation; - -import com.rop.ServiceMethodDefinition; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -import java.lang.annotation.*; - -/** - *
- *    在服务类中标该类,以便确定服务方法所属的组及相关信息。由于ApiMethodGroup已经标注了
- * Spring的{@link Component}注解,因此标注了{@link ServiceMethodBean}的类自动成为Spring的Bean.
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@Target({ElementType.TYPE}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Service -public @interface ServiceMethodBean { - - String value() default ""; - /** - * 所属的服务分组,默认为"DEFAULT" - * - * @return - */ - String group() default ServiceMethodDefinition.DEFAULT_GROUP; - - /** - * 组中文名 - * - * @return - */ - String groupTitle() default ServiceMethodDefinition.DEFAULT_GROUP_TITLE; - - /** - * 标签,可以打上多个标签 - * - * @return - */ - String[] tags() default {}; - - /** - * 访问过期时间,单位为毫秒,即大于这个过期时间的链接会结束并返回错误报文,如果 - * 为0或负数则表示不进行过期限制 - * - * @return - */ - int timeout() default -1; - - /** - * 该方法所对应的版本号,对应version请求参数的值,版本为空,表示不进行版本限定 - * - * @return - */ - String version() default ""; - - /** - * 请求方法,默认不限制 - * - * @return - */ - HttpAction[] httpAction() default {}; - - /** - * 服务方法需要需求会话检查,默认要检查 - * - * @return - */ - NeedInSessionType needInSession() default NeedInSessionType.DEFAULT; - - /** - * 是否忽略签名检查,默认不忽略 - * - * @return - */ - IgnoreSignType ignoreSign() default IgnoreSignType.DEFAULT; - - /** - * 服务方法是否已经过期,默认不过期 - * @return - */ - ObsoletedType obsoleted() default ObsoletedType.DEFAULT; -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +import com.rop.ServiceMethodDefinition; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + +import java.lang.annotation.*; + +/** + *
+ *    在服务类中标该类,以便确定服务方法所属的组及相关信息。由于ApiMethodGroup已经标注了
+ * Spring的{@link Component}注解,因此标注了{@link ServiceMethodBean}的类自动成为Spring的Bean.
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Service +public @interface ServiceMethodBean { + + String value() default ""; + /** + * 所属的服务分组,默认为"DEFAULT" + * + * @return + */ + String group() default ServiceMethodDefinition.DEFAULT_GROUP; + + /** + * 组中文名 + * + * @return + */ + String groupTitle() default ServiceMethodDefinition.DEFAULT_GROUP_TITLE; + + /** + * 标签,可以打上多个标签 + * + * @return + */ + String[] tags() default {}; + + /** + * 访问过期时间,单位为毫秒,即大于这个过期时间的链接会结束并返回错误报文,如果 + * 为0或负数则表示不进行过期限制 + * + * @return + */ + int timeout() default -1; + + /** + * 该方法所对应的版本号,对应version请求参数的值,版本为空,表示不进行版本限定 + * + * @return + */ + String version() default ""; + + /** + * 请求方法,默认不限制 + * + * @return + */ + HttpAction[] httpAction() default {}; + + /** + * 服务方法需要需求会话检查,默认要检查 + * + * @return + */ + NeedInSessionType needInSession() default NeedInSessionType.DEFAULT; + + /** + * 是否忽略签名检查,默认不忽略 + * + * @return + */ + IgnoreSignType ignoreSign() default IgnoreSignType.DEFAULT; + + /** + * 服务方法是否已经过期,默认不过期 + * @return + */ + ObsoletedType obsoleted() default ObsoletedType.DEFAULT; +} + diff --git a/rop/src/main/java/com/rop/client/ClientRequest.java b/rop/src/main/java/com/rop/client/ClientRequest.java deleted file mode 100644 index c22bf38..0000000 --- a/rop/src/main/java/com/rop/client/ClientRequest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-7 - */ -package com.rop.client; - -import com.rop.RopRequest; - -/** - *
- *   每个请求对应一个ClientRequest对象
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface ClientRequest { - - /** - * 添加请求参数,默认需要签名,如果类已经标注了{@link com.rop.annotation.IgnoreSign}则始终不加入签名 - * @param paramName - * @param paramValue - * @return - */ - ClientRequest addParam(String paramName,Object paramValue); - - /** - * 添加请求参数,如果needSign=false表示不参于签名 - * @param paramName - * @param paramValue - * @param needSign - * @return - */ - ClientRequest addParam(String paramName,Object paramValue,boolean needSign); - - /** - * 清除参数列表 - * @return - */ - ClientRequest clearParam(); - - /** - * 使用POST发起请求 - * @param ropResponseClass - * @param methodName - * @param version - * @param - * @return - */ - CompositeResponse post(Class ropResponseClass, String methodName, String version); - - /** - * 直接使用 ropRequest发送请求 - * @param ropRequest - * @param ropResponseClass - * @param methodName - * @param version - * @param - * @return - */ - CompositeResponse post(RopRequest ropRequest, Class ropResponseClass, String methodName, String version); - - /** - * 使用GET发送服务请求 - * @param ropResponseClass - * @param methodName - * @param version - * @param - * @return - */ - CompositeResponse get(Class ropResponseClass, String methodName, String version); - - /** - * 使用GET发送ropRequest的请求 - * @param ropRequest - * @param ropResponseClass - * @param methodName - * @param version - * @param - * @return - */ - CompositeResponse get(RopRequest ropRequest, Class ropResponseClass, String methodName, String version); -} - diff --git a/rop/src/main/java/com/rop/client/DefaultRopClient.java b/rop/src/main/java/com/rop/client/DefaultRopClient.java deleted file mode 100644 index 66a7ddd..0000000 --- a/rop/src/main/java/com/rop/client/DefaultRopClient.java +++ /dev/null @@ -1,493 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client; - -import com.rop.CommonConstant; -import com.rop.MessageFormat; -import com.rop.RopRequest; -import com.rop.annotation.IgnoreSign; -import com.rop.annotation.Temporary; -import com.rop.client.unmarshaller.JacksonJsonRopUnmarshaller; -import com.rop.client.unmarshaller.JaxbXmlRopUnmarshaller; -import com.rop.config.SystemParameterNames; -import com.rop.impl.DefaultRopContext; -import com.rop.marshaller.MessageMarshallerUtils; -import com.rop.request.RopConverter; -import com.rop.request.UploadFile; -import com.rop.request.UploadFileConverter; -import com.rop.response.ErrorResponse; -import com.rop.utils.RopUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.util.*; -import org.springframework.web.client.RestTemplate; - -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.util.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultRopClient implements RopClient { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - //服务地址 - private String serverUrl; - - //应用键 - private String appKey; - - //应用密钥 - private String appSecret; - - private String sessionId; - - //报文格式 - private MessageFormat messageFormat = MessageFormat.xml; - - private Locale locale = Locale.SIMPLIFIED_CHINESE; - - private RestTemplate restTemplate = new RestTemplate(); - - private RopUnmarshaller xmlUnmarshaller = new JaxbXmlRopUnmarshaller(); - - private RopUnmarshaller jsonUnmarshaller = new JacksonJsonRopUnmarshaller(); - - //请求类所有请求参数 - private Map, List> requestAllFields = new HashMap, List>(); - - //请求类所有不需要进行签名的参数 - private Map, List> requestIgnoreSignFieldNames = new HashMap, List>(); - - - //键为转换的目标类型 - private static Map, RopConverter> ropConverterMap = - new HashMap, RopConverter>(); - { - ropConverterMap.put(UploadFile.class, new UploadFileConverter()); - } - - public DefaultRopClient(String serverUrl, String appKey, String appSecret) { - this.serverUrl = serverUrl; - this.appKey = appKey; - this.appSecret = appSecret; - } - - public DefaultRopClient(String serverUrl, String appKey, String appSecret, MessageFormat messageFormat) { - this.serverUrl = serverUrl; - this.appKey = appKey; - this.appSecret = appSecret; - this.messageFormat = messageFormat; - } - - public DefaultRopClient(String serverUrl, String appKey, String appSecret, MessageFormat messageFormat, Locale locale) { - this.serverUrl = serverUrl; - this.appKey = appKey; - this.appSecret = appSecret; - this.messageFormat = messageFormat; - this.locale = locale; - } - - - public MessageFormat getMessageFormat() { - return messageFormat; - } - - public void setMessageFormat(MessageFormat messageFormat) { - this.messageFormat = messageFormat; - } - - public Locale getLocale() { - return locale; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - - public RopClient setAppKeyParamName(String paramName) { - SystemParameterNames.setAppKey(paramName); - return this; - } - - - public RopClient setSessionIdParamName(String paramName) { - SystemParameterNames.setSessionId(paramName); - return this; - } - - - public RopClient setMethodParamName(String paramName) { - SystemParameterNames.setMethod(paramName); - return this; - } - - - public RopClient setVersionParamName(String paramName) { - SystemParameterNames.setVersion(paramName); - return this; - } - - - public RopClient setFormatParamName(String paramName) { - SystemParameterNames.setFormat(paramName); - return this; - } - - - public RopClient setLocaleParamName(String paramName) { - SystemParameterNames.setLocale(paramName); - return this; - } - - - public RopClient setSignParamName(String paramName) { - SystemParameterNames.setSign(paramName); - return this; - } - - - public void addRopConvertor(RopConverter ropConverter) { - this.ropConverterMap.put(ropConverter.getTargetClass(), ropConverter); - } - - - public ClientRequest buildClientRequest() { - return new DefaultClientRequest(this); - } - - private class DefaultClientRequest implements ClientRequest { - - private RopClient ropClient; - - private Map paramMap = new HashMap(20); - - private List ignoreSignParams = new ArrayList(); - - private DefaultClientRequest(RopClient ropClient) { - this.ropClient = ropClient; - paramMap.put(SystemParameterNames.getAppKey(), appKey); - paramMap.put(SystemParameterNames.getFormat(), messageFormat.name()); - paramMap.put(SystemParameterNames.getLocale(), locale.toString()); - if (sessionId != null) { - paramMap.put(SystemParameterNames.getSessionId(), sessionId); - } - } - - - public ClientRequest addParam(String paramName, Object paramValue) { - addParam(paramName,paramValue,false); - return this; - } - - - public ClientRequest clearParam() { - paramMap.clear(); - return this; - } - - - public ClientRequest addParam(String paramName, Object paramValue, boolean ignoreSign) { - Assert.isTrue(paramName != null && paramName.length() > 0, "参数名不能为空"); - Assert.notNull(paramValue, "参数值不能为null"); - - //将参数添加到参数列表中 - String valueAsStr = paramValue.toString(); - if (ropConverterMap.containsKey(paramValue.getClass())) { - RopConverter ropConverter = ropConverterMap.get(paramValue.getClass()); - valueAsStr = (String) ropConverter.unconvert(paramValue); - } - paramMap.put(paramName, valueAsStr); - - IgnoreSign typeIgnore = AnnotationUtils.findAnnotation(paramValue.getClass(), IgnoreSign.class); - if (ignoreSign || typeIgnore != null) { - ignoreSignParams.add(paramName); - } - return this; - } - - - public CompositeResponse post(Class ropResponseClass, String methodName, String version) { - Map requestParams = addOtherParamMap(methodName, version); - return post(ropResponseClass, requestParams); - } - - - public CompositeResponse post(RopRequest ropRequest, Class ropResponseClass, String methodName, String version) { - Map requestParams = getRequestForm(ropRequest, methodName, version); - return post(ropResponseClass, requestParams); - } - - private CompositeResponse post(Class ropResponseClass, Map requestParams) { - String responseContent = restTemplate.postForObject(serverUrl, toMultiValueMap(requestParams), String.class); - if (logger.isDebugEnabled()) { - logger.debug("response:\n" + responseContent); - } - return toCompositeResponse(responseContent, ropResponseClass); - } - - - public CompositeResponse get(Class ropResponseClass, String methodName, String version) { - Map requestParams = addOtherParamMap(methodName, version); - return get(ropResponseClass, requestParams); - } - - - public CompositeResponse get(RopRequest ropRequest, Class ropResponseClass, String methodName, String version) { - Map requestParams = getRequestForm(ropRequest, methodName, version); - return get(ropResponseClass, requestParams); - } - - private CompositeResponse get(Class ropResponseClass, Map requestParams) { - String responseContent = restTemplate.getForObject(buildGetUrl(requestParams), String.class, requestParams); - if (logger.isDebugEnabled()) { - logger.debug("response:\n" + responseContent); - } - return toCompositeResponse(responseContent, ropResponseClass); - } - - private Map addOtherParamMap(String methodName, String version) { - paramMap.put(SystemParameterNames.getMethod(), methodName); - paramMap.put(SystemParameterNames.getVersion(), version); - String signValue = RopUtils.sign(paramMap, ignoreSignParams, appSecret); - paramMap.put(SystemParameterNames.getSign(), signValue); - return paramMap; - } - - private CompositeResponse toCompositeResponse(String content, Class ropResponseClass) { - if(logger.isDebugEnabled()){ - logger.debug(content); - } - boolean successful = isSuccessful(content); - DefaultCompositeResponse compositeResponse = new DefaultCompositeResponse(successful); - - if (MessageFormat.json == messageFormat) { - if (successful) { - T ropResponse = jsonUnmarshaller.unmarshaller(content, ropResponseClass); - compositeResponse.setSuccessRopResponse(ropResponse); - } else { - ErrorResponse errorResponse = jsonUnmarshaller.unmarshaller(content, ErrorResponse.class); - compositeResponse.setErrorResponse(errorResponse); - } - } else { - if (successful) { - T ropResponse = xmlUnmarshaller.unmarshaller(content, ropResponseClass); - compositeResponse.setSuccessRopResponse(ropResponse); - } else { - ErrorResponse errorResponse = xmlUnmarshaller.unmarshaller(content, ErrorResponse.class); - compositeResponse.setErrorResponse(errorResponse); - } - } - return compositeResponse; - } - - private boolean isSuccessful(String content) { - return !(content.contains(CommonConstant.ERROR_TOKEN)); - } - - private String buildGetUrl(Map form) { - StringBuilder requestUrl = new StringBuilder(); - requestUrl.append(serverUrl); - requestUrl.append("?"); - String joinChar = ""; - for (Map.Entry entry : form.entrySet()) { - requestUrl.append(joinChar); - requestUrl.append(entry.getKey()); - requestUrl.append("="); - requestUrl.append(entry.getValue()); - joinChar = "&"; - } - return requestUrl.toString(); - } - - private Map getRequestForm(RopRequest ropRequest, String methodName, String version) { - - Map form = new LinkedHashMap(16); - - //系统级参数 - form.put(SystemParameterNames.getAppKey(), appKey); - form.put(SystemParameterNames.getMethod(), methodName); - form.put(SystemParameterNames.getVersion(), version); - form.put(SystemParameterNames.getFormat(), messageFormat.name()); - form.put(SystemParameterNames.getLocale(), locale.toString()); - if (sessionId != null) { - form.put(SystemParameterNames.getSessionId(), sessionId); - } - - //业务级参数 - form.putAll(getParamFields(ropRequest, messageFormat)); - - //对请求进行签名 - String signValue = sign(ropRequest.getClass(), appSecret, form); - form.put("sign", signValue); - return form; - } - - private MultiValueMap toMultiValueMap(Map form) { - MultiValueMap mvm = new LinkedMultiValueMap(); - for (Map.Entry entry : form.entrySet()) { - mvm.add(entry.getKey(), entry.getValue()); - } - return mvm; - } - - /** - * 对请求参数进行签名 - * - * @param ropRequestClass - * @param appSecret - * @param form - * @return - */ - private String sign(Class ropRequestClass, String appSecret, Map form) { - List ignoreFieldNames = requestIgnoreSignFieldNames.get(ropRequestClass); - return RopUtils.sign(form, ignoreFieldNames, appSecret); - } - - /** - * 获取ropRequest对应的参数名列表 - * - * @param ropRequest - * @param mf - * @return - */ - private Map getParamFields(RopRequest ropRequest, MessageFormat mf) { - if (!requestAllFields.containsKey(ropRequest.getClass())) { - parseRopRequestClass(ropRequest); - } - return toParamValueMap(ropRequest, mf); - } - - /** - * 获取ropRequest对象的对应的参数列表 - * - * @param ropRequest - * @param mf - * @return - */ - private Map toParamValueMap(RopRequest ropRequest, MessageFormat mf) { - List fields = requestAllFields.get(ropRequest.getClass()); - Map params = new HashMap(); - for (Field field : fields) { - RopConverter convertor = getConvertor(field.getType()); - Object fieldValue = ReflectionUtils.getField(field, ropRequest); - if (fieldValue != null) { - if (convertor != null) {//有对应转换器 - String strParamValue = (String) convertor.unconvert(fieldValue); - params.put(field.getName(), strParamValue); - } else if (field.getType().isAnnotationPresent(XmlRootElement.class) || - field.getType().isAnnotationPresent(XmlType.class)) { - String message = MessageMarshallerUtils.getMessage(fieldValue, mf); - params.put(field.getName(), message); - } else { - params.put(field.getName(), fieldValue.toString()); - } - } - } - return params; - } - } - - private RopConverter getConvertor(Class fieldType) { - for (Class aClass : ropConverterMap.keySet()) { - if (ClassUtils.isAssignable(aClass, fieldType)) { - return ropConverterMap.get(aClass); - } - } - return null; - } - - private void parseRopRequestClass(RopRequest ropRequest) { - final ArrayList allFields = new ArrayList(); - final List ignoreSignFieldNames = DefaultRopContext.getIgnoreSignFieldNames(ropRequest.getClass()); - ReflectionUtils.doWithFields(ropRequest.getClass(), new ReflectionUtils.FieldCallback() { - - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - ReflectionUtils.makeAccessible(field); - if (!isTemporaryField(field)) { - allFields.add(field); - } - } - - private boolean isTemporaryField(Field field) { - Annotation[] declaredAnnotations = field.getDeclaredAnnotations(); - if (declaredAnnotations != null) { - for (Annotation declaredAnnotation : declaredAnnotations) { - Temporary varTemporary = field.getAnnotation(Temporary.class); - if (varTemporary != null) { - return true; - } - } - } - return false; - } - }); - - requestAllFields.put(ropRequest.getClass(), allFields); - requestIgnoreSignFieldNames.put(ropRequest.getClass(), ignoreSignFieldNames); - } - - /** - * 获取ropRequest对应的参数名列表 - * - * @param ropRequest - * @param mf - * @return - */ - private Map getParamFields(RopRequest ropRequest, MessageFormat mf) { - if (!requestAllFields.containsKey(ropRequest.getClass())) { - parseRopRequestClass(ropRequest); - } - return toParamValueMap(ropRequest, mf); - } - - /** - * 获取ropRequest对象的对应的参数列表 - * - * @param ropRequest - * @param mf - * @return - */ - private Map toParamValueMap(RopRequest ropRequest, MessageFormat mf) { - List fields = requestAllFields.get(ropRequest.getClass()); - Map params = new HashMap(); - for (Field field : fields) { - RopConverter convertor = getConvertor(field.getType()); - Object fieldValue = ReflectionUtils.getField(field, ropRequest); - if (fieldValue != null) { - if (convertor != null) {//有对应转换器 - String strParamValue = (String) convertor.unconvert(fieldValue); - params.put(field.getName(), strParamValue); - } else if (field.getType().isAnnotationPresent(XmlRootElement.class) || - field.getType().isAnnotationPresent(XmlType.class)) { - String message = MessageMarshallerUtils.getMessage(fieldValue, mf); - params.put(field.getName(), message); - } else { - params.put(field.getName(), fieldValue.toString()); - } - } - } - return params; - } - - -} - diff --git a/rop/src/main/java/com/rop/client/RopUnmarshaller.java b/rop/src/main/java/com/rop/client/RopUnmarshaller.java deleted file mode 100644 index b3d86f1..0000000 --- a/rop/src/main/java/com/rop/client/RopUnmarshaller.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client; - -/** - *
- *   对响应进行反流化
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopUnmarshaller { - - /** - * 将字符串反序列化为相应的对象 - * - * @param inputStream - * @param objectType - * @param - * @return - */ - T unmarshaller(String content, Class objectType); -} - diff --git a/rop/src/main/java/com/rop/client/unmarshaller/JacksonJsonRopUnmarshaller.java b/rop/src/main/java/com/rop/client/unmarshaller/JacksonJsonRopUnmarshaller.java deleted file mode 100644 index bf47bae..0000000 --- a/rop/src/main/java/com/rop/client/unmarshaller/JacksonJsonRopUnmarshaller.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client.unmarshaller; - -import com.rop.RopException; -import com.rop.client.RopUnmarshaller; -import org.codehaus.jackson.map.AnnotationIntrospector; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; - -import java.io.IOException; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class JacksonJsonRopUnmarshaller implements RopUnmarshaller { - - private static ObjectMapper objectMapper; - - - public T unmarshaller(String content, Class objectType) { - try { - return getObjectMapper().readValue(content, objectType); - } catch (IOException e) { - throw new RopException(e); - } - } - - private ObjectMapper getObjectMapper() throws IOException { - if (this.objectMapper == null) { - ObjectMapper objectMapper = new ObjectMapper(); - AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); - SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); - serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE) - .withAnnotationIntrospector(introspector); - objectMapper.setSerializationConfig(serializationConfig); - this.objectMapper = objectMapper; - } - return this.objectMapper; - } -} - diff --git a/rop/src/main/java/com/rop/config/AnnotationDrivenBeanDefinitionParser.java b/rop/src/main/java/com/rop/config/AnnotationDrivenBeanDefinitionParser.java index 0395bf4..0e34834 100644 --- a/rop/src/main/java/com/rop/config/AnnotationDrivenBeanDefinitionParser.java +++ b/rop/src/main/java/com/rop/config/AnnotationDrivenBeanDefinitionParser.java @@ -1,266 +1,259 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-4 - */ -package com.rop.config; - -import com.rop.impl.AnnotationServletServiceRouterFactoryBean; -import com.rop.impl.DefaultServiceAccessController; -import com.rop.security.DefaultInvokeTimesController; -import com.rop.security.FileBaseAppSecretManager; -import com.rop.session.DefaultSessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CompositeComponentDefinition; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.format.support.FormattingConversionServiceFactoryBean; -import org.springframework.util.StringUtils; -import org.w3c.dom.Element; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser { - - public static final int DEFAULT_CORE_POOL_SIZE = 30; - - public static final int DEFAULT_MAX_POOL_SIZE = 120; - - public static final int DEFAULT_KEEP_ALIVE_SECONDS = 3 * 60; - - public static final int DEFAULT_QUENE_CAPACITY = 10; - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - - public BeanDefinition parse(Element element, ParserContext parserContext) { - Object source = parserContext.extractSource(element); - CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); - parserContext.pushContainingComponent(compDefinition); - - //注册ServiceRouter Bean - RootBeanDefinition serviceRouterDef = new RootBeanDefinition(AnnotationServletServiceRouterFactoryBean.class); - String serviceRouterName = element.getAttribute("id"); - if (StringUtils.hasText(serviceRouterName)) { - parserContext.getRegistry().registerBeanDefinition(serviceRouterName, serviceRouterDef); - } else { - serviceRouterName = parserContext.getReaderContext().registerWithGeneratedName(serviceRouterDef); - } - parserContext.registerComponent(new BeanComponentDefinition(serviceRouterDef, serviceRouterName)); - - //设置formattingConversionService - RuntimeBeanReference conversionServiceRbf = getConversionService(element, source, parserContext); - serviceRouterDef.getPropertyValues().add("formattingConversionService", conversionServiceRbf); - - //会话管理器 - RuntimeBeanReference sessionManager = getSessionManager(element, source, parserContext); - serviceRouterDef.getPropertyValues().add("sessionManager", sessionManager); - - //密钥管理器 - RuntimeBeanReference appSecretManager = getAppSecretManager(element, source, parserContext); - serviceRouterDef.getPropertyValues().add("appSecretManager", appSecretManager); - - //服务访问控制器 - RuntimeBeanReference serviceAccessController = getServiceAccessController(element, source, parserContext); - serviceRouterDef.getPropertyValues().add("serviceAccessController", serviceAccessController); - - //访问次数/频度控制器 - RuntimeBeanReference invokeTimesController = getInvokeTimesController(element, source, parserContext); - serviceRouterDef.getPropertyValues().add("invokeTimesController", invokeTimesController); - - //设置TaskExecutor - setTaskExecutor(element, parserContext, source, serviceRouterDef); - - //设置signEnable - setSignEnable(element, serviceRouterDef); - - //设置threadFerryClass - setThreadFerry(element, serviceRouterDef); - - - //设置国际化错误文件 - setExtErrorBaseNames(element, serviceRouterDef); - - //设置服务过期时间 - setServiceTimeout(element, serviceRouterDef); - - //设置文件上传配置信息 - setUploadFileSetting(element, serviceRouterDef); - - parserContext.popAndRegisterContainingComponent(); - return null; - } - - private void setUploadFileSetting(Element element, RootBeanDefinition serviceRouterDef) { - String uploadFileMaxSize = element.getAttribute("upload-file-max-size"); - if (StringUtils.hasText(uploadFileMaxSize)) { - serviceRouterDef.getPropertyValues().addPropertyValue("uploadFileMaxSize",uploadFileMaxSize); - } - - String uploadFileTypes = element.getAttribute("upload-file-types"); - if (StringUtils.hasText(uploadFileTypes)) { - serviceRouterDef.getPropertyValues().addPropertyValue("uploadFileTypes", uploadFileTypes); - } - } - - private void setTaskExecutor(Element element, ParserContext parserContext, Object source, RootBeanDefinition serviceRouterDef) { - RootBeanDefinition taskExecutorDef = - new RootBeanDefinition(org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean.class); - String taskExecutorName = parserContext.getReaderContext().registerWithGeneratedName(taskExecutorDef); - - String corePoolSize = element.getAttribute("core-pool-size"); - if (StringUtils.hasText(corePoolSize)) { - taskExecutorDef.getPropertyValues().addPropertyValue("corePoolSize", corePoolSize); - } else { - taskExecutorDef.getPropertyValues().addPropertyValue("corePoolSize", DEFAULT_CORE_POOL_SIZE); - } - - String maxPoolSize = element.getAttribute("max-pool-size"); - if (StringUtils.hasText(maxPoolSize)) { - taskExecutorDef.getPropertyValues().addPropertyValue("maxPoolSize", maxPoolSize); - } else { - taskExecutorDef.getPropertyValues().addPropertyValue("maxPoolSize", DEFAULT_MAX_POOL_SIZE); - } - - String keepAliveSeconds = element.getAttribute("keep-alive-seconds"); - if (StringUtils.hasText(keepAliveSeconds)) { - taskExecutorDef.getPropertyValues().addPropertyValue("keepAliveSeconds", keepAliveSeconds); - } else { - taskExecutorDef.getPropertyValues().addPropertyValue("keepAliveSeconds", DEFAULT_KEEP_ALIVE_SECONDS); - } - - String queueCapacity = element.getAttribute("queue-capacity"); - if (StringUtils.hasText(queueCapacity)) { - taskExecutorDef.getPropertyValues().addPropertyValue("queueCapacity", queueCapacity); - } else { - taskExecutorDef.getPropertyValues().addPropertyValue("queueCapacity", DEFAULT_QUENE_CAPACITY); - } - - parserContext.registerComponent(new BeanComponentDefinition(taskExecutorDef, taskExecutorName)); - RuntimeBeanReference taskExecutorBeanReference = new RuntimeBeanReference(taskExecutorName); - serviceRouterDef.getPropertyValues().add("threadPoolExecutor", taskExecutorBeanReference); - } - - private void setSignEnable(Element element, RootBeanDefinition serviceRouterDef) { - String signEnable = element.getAttribute("sign-enable"); - if (StringUtils.hasText(signEnable)) { - serviceRouterDef.getPropertyValues().addPropertyValue("signEnable", signEnable); - } - } - - private void setServiceTimeout(Element element, RootBeanDefinition serviceRouterDef) { - String serviceTimeoutSeconds = element.getAttribute("service-timeout-seconds"); - if (StringUtils.hasText(serviceTimeoutSeconds)) { - serviceRouterDef.getPropertyValues().addPropertyValue("serviceTimeoutSeconds", serviceTimeoutSeconds); - } - } - - private void setExtErrorBaseNames(Element element, RootBeanDefinition serviceRouterDef) { - String extErrorBasename = element.getAttribute("ext-error-base-name"); - String extErrorBasenames = element.getAttribute("ext-error-base-names"); - if (StringUtils.hasText(extErrorBasenames)) { - serviceRouterDef.getPropertyValues().addPropertyValue("extErrorBasenames", extErrorBasenames); - } - if (StringUtils.hasText(extErrorBasename)) { - serviceRouterDef.getPropertyValues().addPropertyValue("extErrorBasename", extErrorBasename); - } - if (logger.isDebugEnabled()) { - logger.debug("Please use {}/{} of schema to set error resources", - extErrorBasename,extErrorBasenames); - } - - } - - private void setThreadFerry(Element element, RootBeanDefinition serviceRouterDef) { - String threadFerryClassName = element.getAttribute("thread-ferry-class"); - if (StringUtils.hasText(threadFerryClassName)) { - serviceRouterDef.getPropertyValues().addPropertyValue("threadFerryClassName", threadFerryClassName); - } - } - - private RuntimeBeanReference getInvokeTimesController(Element element, Object source, ParserContext parserContext) { - RuntimeBeanReference invokeTimesControllerRef; - if (element.hasAttribute("invoke-times-controller")) { - invokeTimesControllerRef = new RuntimeBeanReference(element.getAttribute("invoke-times-controller")); - } else { - RootBeanDefinition invokeTimesControllerDef = new RootBeanDefinition(DefaultInvokeTimesController.class); - invokeTimesControllerDef.setSource(source); - invokeTimesControllerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - String invokeTimesControllerName = parserContext.getReaderContext().registerWithGeneratedName(invokeTimesControllerDef); - parserContext.registerComponent(new BeanComponentDefinition(invokeTimesControllerDef, invokeTimesControllerName)); - invokeTimesControllerRef = new RuntimeBeanReference(invokeTimesControllerName); - } - return invokeTimesControllerRef; - } - - private RuntimeBeanReference getServiceAccessController(Element element, Object source, ParserContext parserContext) { - RuntimeBeanReference serviceAccessControllerRef; - if (element.hasAttribute("service-access-controller")) { - serviceAccessControllerRef = new RuntimeBeanReference(element.getAttribute("service-access-controller")); - } else { - RootBeanDefinition serviceAccessControllerDef = new RootBeanDefinition(DefaultServiceAccessController.class); - serviceAccessControllerDef.setSource(source); - serviceAccessControllerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - String serviceAccessControllerName = parserContext.getReaderContext().registerWithGeneratedName(serviceAccessControllerDef); - parserContext.registerComponent(new BeanComponentDefinition(serviceAccessControllerDef, serviceAccessControllerName)); - serviceAccessControllerRef = new RuntimeBeanReference(serviceAccessControllerName); - } - return serviceAccessControllerRef; - } - - private RuntimeBeanReference getAppSecretManager(Element element, Object source, ParserContext parserContext) { - RuntimeBeanReference appSecretManagerRef; - if (element.hasAttribute("app-secret-manager")) { - appSecretManagerRef = new RuntimeBeanReference(element.getAttribute("app-secret-manager")); - } else { - RootBeanDefinition appSecretManagerDef = new RootBeanDefinition(FileBaseAppSecretManager.class); - appSecretManagerDef.setSource(source); - appSecretManagerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - String appSecretManagerName = parserContext.getReaderContext().registerWithGeneratedName(appSecretManagerDef); - parserContext.registerComponent(new BeanComponentDefinition(appSecretManagerDef, appSecretManagerName)); - appSecretManagerRef = new RuntimeBeanReference(appSecretManagerName); - } - return appSecretManagerRef; - } - - private RuntimeBeanReference getSessionManager(Element element, Object source, ParserContext parserContext) { - RuntimeBeanReference sessionManagerRef; - if (element.hasAttribute("session-manager")) { - sessionManagerRef = new RuntimeBeanReference(element.getAttribute("session-manager")); - } else { - RootBeanDefinition sessionManagerDef = new RootBeanDefinition(DefaultSessionManager.class); - sessionManagerDef.setSource(source); - sessionManagerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - String sessionManagerName = parserContext.getReaderContext().registerWithGeneratedName(sessionManagerDef); - parserContext.registerComponent(new BeanComponentDefinition(sessionManagerDef, sessionManagerName)); - sessionManagerRef = new RuntimeBeanReference(sessionManagerName); - } - return sessionManagerRef; - } - - private RuntimeBeanReference getConversionService(Element element, Object source, ParserContext parserContext) { - RuntimeBeanReference conversionServiceRbf; - if (element.hasAttribute("formatting-conversion-service")) { - conversionServiceRbf = new RuntimeBeanReference(element.getAttribute("formatting-conversion-service")); - } else { - RootBeanDefinition conversionDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); - conversionDef.setSource(source); - conversionDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - String conversionName = parserContext.getReaderContext().registerWithGeneratedName(conversionDef); - parserContext.registerComponent(new BeanComponentDefinition(conversionDef, conversionName)); - conversionServiceRbf = new RuntimeBeanReference(conversionName); - } - return conversionServiceRbf; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import com.rop.impl.AnnotationServletServiceRouterFactoryBean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.StringUtils; +import org.w3c.dom.Element; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser { + + public static final int DEFAULT_CORE_POOL_SIZE = 30; + + public static final int DEFAULT_MAX_POOL_SIZE = 120; + + public static final int DEFAULT_KEEP_ALIVE_SECONDS = 3 * 60; + + public static final int DEFAULT_QUENE_CAPACITY = 10; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + + public BeanDefinition parse(Element element, ParserContext parserContext) { + Object source = parserContext.extractSource(element); + CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); + parserContext.pushContainingComponent(compDefinition); + + //注册ServiceRouter Bean + RootBeanDefinition serviceRouterDef = new RootBeanDefinition(AnnotationServletServiceRouterFactoryBean.class); + String serviceRouterName = element.getAttribute("id"); + if (StringUtils.hasText(serviceRouterName)) { + parserContext.getRegistry().registerBeanDefinition(serviceRouterName, serviceRouterDef); + } else { + serviceRouterName = parserContext.getReaderContext().registerWithGeneratedName(serviceRouterDef); + } + parserContext.registerComponent(new BeanComponentDefinition(serviceRouterDef, serviceRouterName)); + + //设置formattingConversionService + RuntimeBeanReference conversionServiceRbf = getConversionService(element, source, parserContext); + if(conversionServiceRbf != null){ + serviceRouterDef.getPropertyValues().add("formattingConversionService", conversionServiceRbf); + } + //会话管理器 + RuntimeBeanReference sessionManager = getSessionManager(element, source, parserContext); + if(sessionManager != null){ + serviceRouterDef.getPropertyValues().add("sessionManager", sessionManager); + } + //密钥管理器 + RuntimeBeanReference appSecretManager = getAppSecretManager(element, source, parserContext); + if(appSecretManager != null){ + serviceRouterDef.getPropertyValues().add("appSecretManager", appSecretManager); + } + //服务访问控制器 + RuntimeBeanReference serviceAccessController = getServiceAccessController(element, source, parserContext); + if(serviceAccessController != null){ + serviceRouterDef.getPropertyValues().add("serviceAccessController", serviceAccessController); + } + //访问次数/频度控制器 + RuntimeBeanReference invokeTimesController = getInvokeTimesController(element, source, parserContext); + if(invokeTimesController != null){ + serviceRouterDef.getPropertyValues().add("invokeTimesController", invokeTimesController); + } + //Xml格式转换器 + RuntimeBeanReference xmlMarshaller = getXmlMarshaller(element, source, parserContext); + if(xmlMarshaller != null){ + serviceRouterDef.getPropertyValues().add("xmlMarshaller", xmlMarshaller); + } + //JSON格式转换器 + RuntimeBeanReference jsonMarshaller = getJsonMarshaller(element, source, parserContext); + if(jsonMarshaller != null){ + serviceRouterDef.getPropertyValues().add("jsonMarshaller", jsonMarshaller); + } + //设置TaskExecutor + setTaskExecutor(element, parserContext, source, serviceRouterDef); + + //设置signEnable + setSignEnable(element, serviceRouterDef); + + //设置threadFerryClass + setThreadFerry(element, serviceRouterDef); + + //设置国际化错误文件 + setExtErrorBaseNames(element, serviceRouterDef); + + //设置服务过期时间 + setServiceTimeout(element, serviceRouterDef); + + //设置文件上传配置信息 + setUploadFileSetting(element, serviceRouterDef); + + parserContext.popAndRegisterContainingComponent(); + return null; + } + + private void setUploadFileSetting(Element element, RootBeanDefinition serviceRouterDef) { + String uploadFileMaxSize = element.getAttribute("upload-file-max-size"); + if (StringUtils.hasText(uploadFileMaxSize)) { + serviceRouterDef.getPropertyValues().addPropertyValue("uploadFileMaxSize",uploadFileMaxSize); + } + + String uploadFileTypes = element.getAttribute("upload-file-types"); + if (StringUtils.hasText(uploadFileTypes)) { + serviceRouterDef.getPropertyValues().addPropertyValue("uploadFileTypes", uploadFileTypes); + } + } + + private void setTaskExecutor(Element element, ParserContext parserContext, Object source, RootBeanDefinition serviceRouterDef) { + RootBeanDefinition taskExecutorDef = + new RootBeanDefinition(org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean.class); + String taskExecutorName = parserContext.getReaderContext().registerWithGeneratedName(taskExecutorDef); + + String corePoolSize = element.getAttribute("core-pool-size"); + if (StringUtils.hasText(corePoolSize)) { + taskExecutorDef.getPropertyValues().addPropertyValue("corePoolSize", corePoolSize); + } else { + taskExecutorDef.getPropertyValues().addPropertyValue("corePoolSize", DEFAULT_CORE_POOL_SIZE); + } + + String maxPoolSize = element.getAttribute("max-pool-size"); + if (StringUtils.hasText(maxPoolSize)) { + taskExecutorDef.getPropertyValues().addPropertyValue("maxPoolSize", maxPoolSize); + } else { + taskExecutorDef.getPropertyValues().addPropertyValue("maxPoolSize", DEFAULT_MAX_POOL_SIZE); + } + + String keepAliveSeconds = element.getAttribute("keep-alive-seconds"); + if (StringUtils.hasText(keepAliveSeconds)) { + taskExecutorDef.getPropertyValues().addPropertyValue("keepAliveSeconds", keepAliveSeconds); + } else { + taskExecutorDef.getPropertyValues().addPropertyValue("keepAliveSeconds", DEFAULT_KEEP_ALIVE_SECONDS); + } + + String queueCapacity = element.getAttribute("queue-capacity"); + if (StringUtils.hasText(queueCapacity)) { + taskExecutorDef.getPropertyValues().addPropertyValue("queueCapacity", queueCapacity); + } else { + taskExecutorDef.getPropertyValues().addPropertyValue("queueCapacity", DEFAULT_QUENE_CAPACITY); + } + + parserContext.registerComponent(new BeanComponentDefinition(taskExecutorDef, taskExecutorName)); + RuntimeBeanReference taskExecutorBeanReference = new RuntimeBeanReference(taskExecutorName); + serviceRouterDef.getPropertyValues().add("threadPoolExecutor", taskExecutorBeanReference); + } + + private void setSignEnable(Element element, RootBeanDefinition serviceRouterDef) { + String signEnable = element.getAttribute("sign-enable"); + if (StringUtils.hasText(signEnable)) { + serviceRouterDef.getPropertyValues().addPropertyValue("signEnable", signEnable); + } + } + + private void setServiceTimeout(Element element, RootBeanDefinition serviceRouterDef) { + String serviceTimeoutSeconds = element.getAttribute("service-timeout-seconds"); + if (StringUtils.hasText(serviceTimeoutSeconds)) { + serviceRouterDef.getPropertyValues().addPropertyValue("serviceTimeoutSeconds", serviceTimeoutSeconds); + } + } + + private void setExtErrorBaseNames(Element element, RootBeanDefinition serviceRouterDef) { + String extErrorBasename = element.getAttribute("ext-error-base-name"); + String extErrorBasenames = element.getAttribute("ext-error-base-names"); + if (StringUtils.hasText(extErrorBasenames)) { + serviceRouterDef.getPropertyValues().addPropertyValue("extErrorBasenames", extErrorBasenames); + } + if (StringUtils.hasText(extErrorBasename)) { + serviceRouterDef.getPropertyValues().addPropertyValue("extErrorBasename", extErrorBasename); + } + if (logger.isDebugEnabled()) { + logger.debug("Please use {}/{} of schema to set error resources", extErrorBasename,extErrorBasenames); + } + } + + private void setThreadFerry(Element element, RootBeanDefinition serviceRouterDef) { + String threadFerryClassName = element.getAttribute("thread-ferry-class"); + if (StringUtils.hasText(threadFerryClassName)) { + serviceRouterDef.getPropertyValues().addPropertyValue("threadFerryClassName", threadFerryClassName); + } + } + + private RuntimeBeanReference getInvokeTimesController(Element element, Object source, ParserContext parserContext) { + if (element.hasAttribute("invoke-times-controller")) { + return new RuntimeBeanReference(element.getAttribute("invoke-times-controller")); + } + return null; + } + + private RuntimeBeanReference getServiceAccessController(Element element, Object source, ParserContext parserContext) { + if (element.hasAttribute("service-access-controller")) { + return new RuntimeBeanReference(element.getAttribute("service-access-controller")); + } + return null; + } + + private RuntimeBeanReference getAppSecretManager(Element element, Object source, ParserContext parserContext) { + if (element.hasAttribute("app-secret-manager")) { + return new RuntimeBeanReference(element.getAttribute("app-secret-manager")); + } + return null; + } + + private RuntimeBeanReference getSessionManager(Element element, Object source, ParserContext parserContext) { + if (element.hasAttribute("session-manager")) { + return new RuntimeBeanReference(element.getAttribute("session-manager")); + } + return null; + } + + private RuntimeBeanReference getConversionService(Element element, Object source, ParserContext parserContext) { + if (element.hasAttribute("formatting-conversion-service")) { + return new RuntimeBeanReference(element.getAttribute("formatting-conversion-service")); + } + return null; + } + + private RuntimeBeanReference getXmlMarshaller(Element element, Object source, ParserContext parserContext){ + if(element.hasAttribute("xml-marshaller")){ + return new RuntimeBeanReference(element.getAttribute("xml-marshaller")); + } + return null; + } + + private RuntimeBeanReference getJsonMarshaller(Element element, Object source, ParserContext parserContext){ + if(element.hasAttribute("json-marshaller")){ + return new RuntimeBeanReference(element.getAttribute("json-marshaller")); + } + return null; + } +} + diff --git a/rop/src/main/java/com/rop/config/InterceptorHolder.java b/rop/src/main/java/com/rop/config/InterceptorHolder.java index e66eaee..9ae51e3 100644 --- a/rop/src/main/java/com/rop/config/InterceptorHolder.java +++ b/rop/src/main/java/com/rop/config/InterceptorHolder.java @@ -1,29 +1,40 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.config; - -import com.rop.Interceptor; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class InterceptorHolder { - - private Interceptor interceptor; - - public InterceptorHolder(Interceptor interceptor) { - this.interceptor = interceptor; - } - - public Interceptor getInterceptor() { - return interceptor; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import com.rop.Interceptor; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class InterceptorHolder { + + private Interceptor interceptor; + + public InterceptorHolder(Interceptor interceptor) { + this.interceptor = interceptor; + } + + public Interceptor getInterceptor() { + return interceptor; + } +} + diff --git a/rop/src/main/java/com/rop/config/InterceptorsBeanDefinitionParser.java b/rop/src/main/java/com/rop/config/InterceptorsBeanDefinitionParser.java index 1231c72..0bffefb 100644 --- a/rop/src/main/java/com/rop/config/InterceptorsBeanDefinitionParser.java +++ b/rop/src/main/java/com/rop/config/InterceptorsBeanDefinitionParser.java @@ -1,51 +1,56 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-4 - */ -package com.rop.config; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CompositeComponentDefinition; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.util.xml.DomUtils; -import org.w3c.dom.Element; - -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class InterceptorsBeanDefinitionParser implements BeanDefinitionParser { - - - public BeanDefinition parse(Element element, ParserContext parserContext) { - CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); - parserContext.pushContainingComponent(compDefinition); - List interceptors = DomUtils.getChildElementsByTagName(element, new String[]{"bean", "ref"}); - - for (Element interceptor : interceptors) { - RootBeanDefinition interceptorHolderDef = new RootBeanDefinition(InterceptorHolder.class); - interceptorHolderDef.setSource(parserContext.extractSource(interceptor)); - interceptorHolderDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - - Object interceptorBean = parserContext.getDelegate().parsePropertySubElement(interceptor, null); - interceptorHolderDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorBean); - - - String beanName = parserContext.getReaderContext().registerWithGeneratedName(interceptorHolderDef); - parserContext.registerComponent(new BeanComponentDefinition(interceptorHolderDef, beanName)); - } - - parserContext.popAndRegisterContainingComponent(); - return null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.xml.DomUtils; +import org.w3c.dom.Element; + +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class InterceptorsBeanDefinitionParser implements BeanDefinitionParser { + + public BeanDefinition parse(Element element, ParserContext parserContext) { + CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); + parserContext.pushContainingComponent(compDefinition); + List interceptors = DomUtils.getChildElementsByTagName(element, new String[]{"bean", "ref"}); + for (Element interceptor : interceptors) { + RootBeanDefinition interceptorHolderDef = new RootBeanDefinition(InterceptorHolder.class); + interceptorHolderDef.setSource(parserContext.extractSource(interceptor)); + interceptorHolderDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + Object interceptorBean = parserContext.getDelegate().parsePropertySubElement(interceptor, null); + interceptorHolderDef.getConstructorArgumentValues().addIndexedArgumentValue(0, interceptorBean); + String beanName = parserContext.getReaderContext().registerWithGeneratedName(interceptorHolderDef); + parserContext.registerComponent(new BeanComponentDefinition(interceptorHolderDef, beanName)); + } + parserContext.popAndRegisterContainingComponent(); + return null; + } +} + diff --git a/rop/src/main/java/com/rop/config/ListenersBeanDefinitionParser.java b/rop/src/main/java/com/rop/config/ListenersBeanDefinitionParser.java index d08e443..c4bd7d0 100644 --- a/rop/src/main/java/com/rop/config/ListenersBeanDefinitionParser.java +++ b/rop/src/main/java/com/rop/config/ListenersBeanDefinitionParser.java @@ -1,51 +1,62 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-4 - */ -package com.rop.config; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CompositeComponentDefinition; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.util.xml.DomUtils; -import org.w3c.dom.Element; - -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ListenersBeanDefinitionParser implements BeanDefinitionParser { - - public BeanDefinition parse(Element element, ParserContext parserContext) { - CompositeComponentDefinition compDefinition = - new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); - parserContext.pushContainingComponent(compDefinition); - - List listeners = DomUtils.getChildElementsByTagName(element, new String[]{"bean", "ref"}); - - for (Element interceptor : listeners) { - RootBeanDefinition listenerHolderDef = new RootBeanDefinition(RopEventListenerHodler.class); - listenerHolderDef.setSource(parserContext.extractSource(interceptor)); - listenerHolderDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - - Object listenerBean = parserContext.getDelegate().parsePropertySubElement(interceptor, null); - listenerHolderDef.getConstructorArgumentValues().addIndexedArgumentValue(0, listenerBean); - - String beanName = parserContext.getReaderContext().registerWithGeneratedName(listenerHolderDef); - parserContext.registerComponent(new BeanComponentDefinition(listenerHolderDef, beanName)); - } - - parserContext.popAndRegisterContainingComponent(); - return null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.xml.DomUtils; +import org.w3c.dom.Element; + +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ListenersBeanDefinitionParser implements BeanDefinitionParser { + + public BeanDefinition parse(Element element, ParserContext parserContext) { + CompositeComponentDefinition compDefinition = + new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); + parserContext.pushContainingComponent(compDefinition); + + List listeners = DomUtils.getChildElementsByTagName(element, new String[]{"bean", "ref"}); + + for (Element interceptor : listeners) { + RootBeanDefinition listenerHolderDef = new RootBeanDefinition(RopEventListenerHodler.class); + listenerHolderDef.setSource(parserContext.extractSource(interceptor)); + listenerHolderDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + + Object listenerBean = parserContext.getDelegate().parsePropertySubElement(interceptor, null); + listenerHolderDef.getConstructorArgumentValues().addIndexedArgumentValue(0, listenerBean); + + String beanName = parserContext.getReaderContext().registerWithGeneratedName(listenerHolderDef); + parserContext.registerComponent(new BeanComponentDefinition(listenerHolderDef, beanName)); + } + + parserContext.popAndRegisterContainingComponent(); + return null; + } +} + diff --git a/rop/src/main/java/com/rop/config/RopEventListenerHodler.java b/rop/src/main/java/com/rop/config/RopEventListenerHodler.java index d700a30..eea6ff9 100644 --- a/rop/src/main/java/com/rop/config/RopEventListenerHodler.java +++ b/rop/src/main/java/com/rop/config/RopEventListenerHodler.java @@ -1,29 +1,41 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.config; - -import com.rop.event.RopEventListener; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopEventListenerHodler { - - private RopEventListener ropEventListener; - - public RopEventListenerHodler(RopEventListener ropEventListener) { - this.ropEventListener = ropEventListener; - } - - public RopEventListener getRopEventListener() { - return ropEventListener; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import com.rop.event.RopEvent; +import com.rop.event.RopEventListener; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopEventListenerHodler { + + private RopEventListener ropEventListener; + + public RopEventListenerHodler(RopEventListener ropEventListener) { + this.ropEventListener = ropEventListener; + } + + public RopEventListener getRopEventListener() { + return ropEventListener; + } +} + diff --git a/rop/src/main/java/com/rop/config/RopNamespaceHandler.java b/rop/src/main/java/com/rop/config/RopNamespaceHandler.java index 343c9c1..60200ac 100644 --- a/rop/src/main/java/com/rop/config/RopNamespaceHandler.java +++ b/rop/src/main/java/com/rop/config/RopNamespaceHandler.java @@ -1,27 +1,38 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-4 - */ -package com.rop.config; - -import org.springframework.beans.factory.xml.NamespaceHandlerSupport; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopNamespaceHandler extends NamespaceHandlerSupport { - - - public void init() { - registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser()); - registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser()); - registerBeanDefinitionParser("listeners", new ListenersBeanDefinitionParser()); - registerBeanDefinitionParser("sysparams", new SystemParameterNamesBeanDefinitionParser()); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import org.springframework.beans.factory.xml.NamespaceHandlerSupport; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopNamespaceHandler extends NamespaceHandlerSupport { + + + public void init() { + registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser()); + registerBeanDefinitionParser("interceptors", new InterceptorsBeanDefinitionParser()); + registerBeanDefinitionParser("listeners", new ListenersBeanDefinitionParser()); + registerBeanDefinitionParser("sysparams", new SystemParameterNamesBeanDefinitionParser()); + } +} + diff --git a/rop/src/main/java/com/rop/config/SystemParameterNamesBeanDefinitionParser.java b/rop/src/main/java/com/rop/config/SystemParameterNamesBeanDefinitionParser.java index c3a6be9..fd9049b 100644 --- a/rop/src/main/java/com/rop/config/SystemParameterNamesBeanDefinitionParser.java +++ b/rop/src/main/java/com/rop/config/SystemParameterNamesBeanDefinitionParser.java @@ -1,60 +1,71 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.config; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.util.StringUtils; -import org.w3c.dom.Element; - -/** - *
- *    指定自定义的系统参数名
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SystemParameterNamesBeanDefinitionParser implements BeanDefinitionParser { - - public BeanDefinition parse(Element element, ParserContext parserContext) { - String appKey = element.getAttribute("appkey-param-name"); - String sessionId = element.getAttribute("sessionid-param-name"); - String method = element.getAttribute("method-param-name"); - String version = element.getAttribute("version-param-name"); - String format = element.getAttribute("format-param-name"); - String locale = element.getAttribute("locale-param-name"); - String sign = element.getAttribute("sign-param-name"); - String jsonp = element.getAttribute("jsonp-param-name"); - - if (StringUtils.hasText(appKey)) { - SystemParameterNames.setAppKey(appKey); - } - if (StringUtils.hasText(sessionId)) { - SystemParameterNames.setSessionId(sessionId); - } - if (StringUtils.hasText(method)) { - SystemParameterNames.setMethod(method); - } - if (StringUtils.hasText(version)) { - SystemParameterNames.setVersion(version); - } - if (StringUtils.hasText(format)) { - SystemParameterNames.setFormat(format); - } - if (StringUtils.hasText(locale)) { - SystemParameterNames.setLocale(locale); - } - if (StringUtils.hasText(sessionId)) { - SystemParameterNames.setSign(sign); - } - if (StringUtils.hasText(jsonp)) { - SystemParameterNames.setJsonp(jsonp); - } - return null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.util.StringUtils; +import org.w3c.dom.Element; + +/** + *
+ *    指定自定义的系统参数名
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SystemParameterNamesBeanDefinitionParser implements BeanDefinitionParser { + + public BeanDefinition parse(Element element, ParserContext parserContext) { + String appKey = element.getAttribute("appkey-param-name"); + String sessionId = element.getAttribute("sessionid-param-name"); + String method = element.getAttribute("method-param-name"); + String version = element.getAttribute("version-param-name"); + String format = element.getAttribute("format-param-name"); + String locale = element.getAttribute("locale-param-name"); + String sign = element.getAttribute("sign-param-name"); + String jsonp = element.getAttribute("jsonp-param-name"); + + if (StringUtils.hasText(appKey)) { + SystemParameterNames.setAppKey(appKey); + } + if (StringUtils.hasText(sessionId)) { + SystemParameterNames.setSessionId(sessionId); + } + if (StringUtils.hasText(method)) { + SystemParameterNames.setMethod(method); + } + if (StringUtils.hasText(version)) { + SystemParameterNames.setVersion(version); + } + if (StringUtils.hasText(format)) { + SystemParameterNames.setFormat(format); + } + if (StringUtils.hasText(locale)) { + SystemParameterNames.setLocale(locale); + } + if (StringUtils.hasText(sign)) { + SystemParameterNames.setSign(sign); + } + if (StringUtils.hasText(jsonp)) { + SystemParameterNames.setJsonp(jsonp); + } + return null; + } +} + diff --git a/rop/src/main/java/com/rop/converter/RopFormattingConversionServiceFactoryBean.java b/rop/src/main/java/com/rop/converter/RopFormattingConversionServiceFactoryBean.java new file mode 100644 index 0000000..8549f95 --- /dev/null +++ b/rop/src/main/java/com/rop/converter/RopFormattingConversionServiceFactoryBean.java @@ -0,0 +1,158 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +import java.util.HashSet; +import java.util.Set; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.EmbeddedValueResolverAware; +import org.springframework.core.convert.support.ConversionServiceFactory; +import org.springframework.format.AnnotationFormatterFactory; +import org.springframework.format.Formatter; +import org.springframework.format.FormatterRegistrar; +import org.springframework.format.FormatterRegistry; +import org.springframework.format.Parser; +import org.springframework.format.Printer; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.util.StringValueResolver; + +/** + * 该类解决spring将RopConverter转换成org.springframework.core.convert.converter.Converter + * 来解决设置的RopConverter对象没有实现org.springframework.core.convert.converter.Converter接口的问题 + */ +public class RopFormattingConversionServiceFactoryBean implements FactoryBean, EmbeddedValueResolverAware, InitializingBean{ + + private Set converters; + + private Set formatters; + + private Set formatterRegistrars; + + private boolean registerDefaultFormatters = true; + + private StringValueResolver embeddedValueResolver; + + private FormattingConversionService conversionService; + + /** + * Configure the set of custom converter objects that should be added. + * @param converters instances of any of the following: + * {@link org.springframework.core.convert.converter.Converter}, + * {@link org.springframework.core.convert.converter.ConverterFactory}, + * {@link org.springframework.core.convert.converter.GenericConverter} + */ + public void setConverters(Set converters) { + this.converters = converters; + } + + /** + * Configure the set of custom formatter objects that should be added. + * @param formatters instances of {@link Formatter} or {@link AnnotationFormatterFactory} + */ + public void setFormatters(Set formatters) { + this.formatters = formatters; + } + + /** + *

Configure the set of FormatterRegistrars to invoke to register + * Converters and Formatters in addition to those added declaratively + * via {@link #setConverters(Set)} and {@link #setFormatters(Set)}. + *

FormatterRegistrars are useful when registering multiple related + * converters and formatters for a formatting category, such as Date + * formatting. All types related needed to support the formatting + * category can be registered from one place. + *

FormatterRegistrars can also be used to register Formatters + * indexed under a specific field type different from its own <T>, + * or when registering a Formatter from a Printer/Parser pair. + * @see FormatterRegistry#addFormatterForFieldType(Class, Formatter) + * @see FormatterRegistry#addFormatterForFieldType(Class, Printer, Parser) + */ + public void setFormatterRegistrars(Set formatterRegistrars) { + this.formatterRegistrars = formatterRegistrars; + } + + /** + * Indicate whether default formatters should be registered or not. + *

By default, built-in formatters are registered. This flag can be used + * to turn that off and rely on explicitly registered formatters only. + * @see #setFormatters(Set) + * @see #setFormatterRegistrars(Set) + */ + public void setRegisterDefaultFormatters(boolean registerDefaultFormatters) { + this.registerDefaultFormatters = registerDefaultFormatters; + } + + public void setEmbeddedValueResolver(StringValueResolver embeddedValueResolver) { + this.embeddedValueResolver = embeddedValueResolver; + } + + public void afterPropertiesSet() { + this.conversionService = new DefaultFormattingConversionService(this.embeddedValueResolver, this.registerDefaultFormatters); + ConversionServiceFactory.registerConverters(parseConverters(this.converters), this.conversionService); + registerFormatters(); + } + + private Set parseConverters(Set converters){ + if(converters == null || converters.isEmpty()){ + return converters; + } + Set set = new HashSet(converters.size()); + for(Object converter : converters){ + if(converter instanceof RopConverter){ + converter = SpringConverter.toSpringConverter((RopConverter)converter); + } + set.add(converter); + } + return set; + } + + private void registerFormatters() { + if (this.formatters != null) { + for (Object formatter : this.formatters) { + if (formatter instanceof Formatter) { + this.conversionService.addFormatter((Formatter) formatter); + } + else if (formatter instanceof AnnotationFormatterFactory) { + this.conversionService.addFormatterForFieldAnnotation((AnnotationFormatterFactory) formatter); + } + else { + throw new IllegalArgumentException( + "Custom formatters must be implementations of Formatter or AnnotationFormatterFactory"); + } + } + } + if (this.formatterRegistrars != null) { + for (FormatterRegistrar registrar : this.formatterRegistrars) { + registrar.registerFormatters(this.conversionService); + } + } + } + + public FormattingConversionService getObject() { + return this.conversionService; + } + + public Class getObjectType() { + return FormattingConversionService.class; + } + + public boolean isSingleton() { + return true; + } +} diff --git a/rop/src/main/java/com/rop/converter/SpringConverter.java b/rop/src/main/java/com/rop/converter/SpringConverter.java new file mode 100644 index 0000000..ab36ca8 --- /dev/null +++ b/rop/src/main/java/com/rop/converter/SpringConverter.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.converter; + +import org.springframework.core.convert.converter.Converter; + +/** + * Converter不使用泛型是为了解决spring4.x版本验证Converter实现类没有设置泛型的具体类型的检查不通过的问题 + */ +@SuppressWarnings("rawtypes") +public class SpringConverter implements Converter { + + public static Converter toSpringConverter(RopConverter ropConverter){ + if(ropConverter instanceof Converter){ + return (Converter)ropConverter; + } + return new SpringConverter(ropConverter); + } + + private final RopConverter ropConverter; + + public SpringConverter(RopConverter ropConverter) { + super(); + this.ropConverter = ropConverter; + } + + @SuppressWarnings("unchecked") + public Object convert(Object source) { + return ropConverter.convert(source); + } +} diff --git a/rop/src/main/java/com/rop/event/AbstractRopEventMulticaster.java b/rop/src/main/java/com/rop/event/AbstractRopEventMulticaster.java index 5a3aa9e..451f21d 100644 --- a/rop/src/main/java/com/rop/event/AbstractRopEventMulticaster.java +++ b/rop/src/main/java/com/rop/event/AbstractRopEventMulticaster.java @@ -1,92 +1,103 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import java.util.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public abstract class AbstractRopEventMulticaster implements RopEventMulticaster { - - private Set ropEventListeners = new HashSet(); - - private static final Map, ListenerRegistry> cachedRopEventListeners = - new HashMap, ListenerRegistry>(); - - - public void removeAllRopListeners() { - ropEventListeners.clear(); - } - - - public void addRopListener(RopEventListener listener) { - ropEventListeners.add(listener); - } - - - public void removeRopListener(RopEventListener listener) { - ropEventListeners.remove(listener); - } - - protected List getRopEventListeners(RopEvent event) { - Class eventType = event.getClass(); - if (!cachedRopEventListeners.containsKey(eventType)) { - LinkedList allListeners = new LinkedList(); - if (ropEventListeners != null && ropEventListeners.size() > 0) { - for (RopEventListener ropEventListener : ropEventListeners) { - if (supportsEvent(ropEventListener, eventType)) { - allListeners.add(ropEventListener); - } - } - sortRopEventListener(allListeners); - } - ListenerRegistry listenerRegistry = new ListenerRegistry(allListeners); - cachedRopEventListeners.put(eventType, listenerRegistry); - } - return cachedRopEventListeners.get(eventType).getRopEventListeners(); - } - - protected boolean supportsEvent( - RopEventListener listener, Class eventType) { - SmartRopEventListener smartListener = (listener instanceof SmartRopEventListener ? - (SmartRopEventListener) listener : new GenericRopEventAdapter(listener)); - return (smartListener.supportsEventType(eventType)); - } - - - protected void sortRopEventListener(List ropEventListeners) { - Collections.sort(ropEventListeners, new Comparator() { - public int compare(RopEventListener o1, RopEventListener o2) { - if (o1.getOrder() > o2.getOrder()) { - return 1; - } else if (o1.getOrder() < o2.getOrder()) { - return -1; - } else { - return 0; - } - } - }); - } - - private class ListenerRegistry { - - public List ropEventListeners; - - private ListenerRegistry(List ropEventListeners) { - this.ropEventListeners = ropEventListeners; - } - - public List getRopEventListeners() { - return ropEventListeners; - } - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import java.util.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public abstract class AbstractRopEventMulticaster implements RopEventMulticaster { + + private Set> ropEventListeners = new HashSet>(); + + private static final Map, ListenerRegistry> cachedRopEventListeners = + new HashMap, ListenerRegistry>(); + + + public void removeAllRopListeners() { + ropEventListeners.clear(); + } + + + public void addRopListener(RopEventListener listener) { + ropEventListeners.add(listener); + } + + + public void removeRopListener(RopEventListener listener) { + ropEventListeners.remove(listener); + } + + protected List> getRopEventListeners(RopEvent event) { + Class eventType = event.getClass(); + if (!cachedRopEventListeners.containsKey(eventType)) { + LinkedList> allListeners = new LinkedList>(); + if (ropEventListeners != null && ropEventListeners.size() > 0) { + for (RopEventListener ropEventListener : ropEventListeners) { + if (supportsEvent(ropEventListener, eventType)) { + allListeners.add(ropEventListener); + } + } + sortRopEventListener(allListeners); + } + ListenerRegistry listenerRegistry = new ListenerRegistry(allListeners); + cachedRopEventListeners.put(eventType, listenerRegistry); + } + return cachedRopEventListeners.get(eventType).getRopEventListeners(); + } + + protected boolean supportsEvent( + RopEventListener listener, Class eventType) { + SmartRopEventListener smartListener = (listener instanceof SmartRopEventListener ? + (SmartRopEventListener) listener : new GenericRopEventAdapter(listener)); + return (smartListener.supportsEventType(eventType)); + } + + + protected void sortRopEventListener(List> ropEventListeners) { + Collections.sort(ropEventListeners, new Comparator>() { + public int compare(RopEventListener o1, RopEventListener o2) { + if (o1.getOrder() > o2.getOrder()) { + return 1; + } else if (o1.getOrder() < o2.getOrder()) { + return -1; + } else { + return 0; + } + } + }); + } + + private class ListenerRegistry { + + public List> ropEventListeners; + + private ListenerRegistry(List> ropEventListeners) { + this.ropEventListeners = ropEventListeners; + } + + public List> getRopEventListeners() { + return ropEventListeners; + } + } +} + diff --git a/rop/src/main/java/com/rop/event/AfterDoServiceEvent.java b/rop/src/main/java/com/rop/event/AfterDoServiceEvent.java index a3074fa..8080742 100644 --- a/rop/src/main/java/com/rop/event/AfterDoServiceEvent.java +++ b/rop/src/main/java/com/rop/event/AfterDoServiceEvent.java @@ -1,38 +1,50 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import com.rop.RopRequestContext; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class AfterDoServiceEvent extends RopEvent { - - private RopRequestContext ropRequestContext; - - public AfterDoServiceEvent(Object source, RopRequestContext ropRequestContext) { - super(source, ropRequestContext.getRopContext()); - this.ropRequestContext = ropRequestContext; - } - - public long getServiceBeginTime() { - return ropRequestContext.getServiceBeginTime(); - } - - public long getServiceEndTime() { - return ropRequestContext.getServiceEndTime(); - } - - public RopRequestContext getRopRequestContext() { - return ropRequestContext; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import com.rop.RopRequestContext; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class AfterDoServiceEvent extends RopEvent { + + private static final long serialVersionUID = -24176501518108425L; + private RopRequestContext ropRequestContext; + + public AfterDoServiceEvent(Object source, RopRequestContext ropRequestContext) { + super(source, ropRequestContext.getRopContext()); + this.ropRequestContext = ropRequestContext; + } + + public long getServiceBeginTime() { + return ropRequestContext.getServiceBeginTime(); + } + + public long getServiceEndTime() { + return ropRequestContext.getServiceEndTime(); + } + + public RopRequestContext getRopRequestContext() { + return ropRequestContext; + } +} + diff --git a/rop/src/main/java/com/rop/event/AfterStartedRopEvent.java b/rop/src/main/java/com/rop/event/AfterStartedRopEvent.java index 46f232d..32e71ba 100644 --- a/rop/src/main/java/com/rop/event/AfterStartedRopEvent.java +++ b/rop/src/main/java/com/rop/event/AfterStartedRopEvent.java @@ -1,24 +1,37 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-1 - */ -package com.rop.event; - -import com.rop.RopContext; - -/** - *
- *   在Rop框架初始化后产生的事件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class AfterStartedRopEvent extends RopEvent { - - public AfterStartedRopEvent(Object source, RopContext ropContext) { - super(source, ropContext); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import com.rop.RopContext; + +/** + *
+ *   在Rop框架初始化后产生的事件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class AfterStartedRopEvent extends RopEvent { + + private static final long serialVersionUID = 6562668009719141360L; + + public AfterStartedRopEvent(Object source, RopContext ropContext) { + super(source, ropContext); + } + +} + diff --git a/rop/src/main/java/com/rop/event/GenericRopEventAdapter.java b/rop/src/main/java/com/rop/event/GenericRopEventAdapter.java index 35f9984..eec34b8 100644 --- a/rop/src/main/java/com/rop/event/GenericRopEventAdapter.java +++ b/rop/src/main/java/com/rop/event/GenericRopEventAdapter.java @@ -1,48 +1,58 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import org.springframework.aop.support.AopUtils; -import org.springframework.core.GenericTypeResolver; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class GenericRopEventAdapter implements SmartRopEventListener { - - private final RopEventListener delegate; - - public GenericRopEventAdapter(RopEventListener delegate) { - this.delegate = delegate; - } - - - public boolean supportsEventType(Class eventType) { - Class typeArg = GenericTypeResolver.resolveTypeArgument(this.delegate.getClass(), RopEventListener.class); - if (typeArg == null || typeArg.equals(RopEvent.class)) { - Class targetClass = AopUtils.getTargetClass(this.delegate); - if (targetClass != this.delegate.getClass()) { - typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, RopEventListener.class); - } - } - return (typeArg == null || typeArg.isAssignableFrom(eventType)); - } - - - public void onRopEvent(RopEvent ropEvent) { - this.delegate.onRopEvent(ropEvent); - } - - - public int getOrder() { - return Integer.MAX_VALUE; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import org.springframework.aop.support.AopUtils; +import org.springframework.core.GenericTypeResolver; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class GenericRopEventAdapter implements SmartRopEventListener { + + private final RopEventListener delegate; + + public GenericRopEventAdapter(RopEventListener delegate) { + this.delegate = delegate; + } + + public boolean supportsEventType(Class eventType) { + Class typeArg = GenericTypeResolver.resolveTypeArgument(this.delegate.getClass(), RopEventListener.class); + if (typeArg == null || typeArg.equals(RopEvent.class)) { + Class targetClass = AopUtils.getTargetClass(this.delegate); + if (targetClass != this.delegate.getClass()) { + typeArg = GenericTypeResolver.resolveTypeArgument(targetClass, RopEventListener.class); + } + } + return (typeArg == null || typeArg.isAssignableFrom(eventType)); + } + + + public void onRopEvent(RopEvent ropEvent) { + this.delegate.onRopEvent(ropEvent); + } + + + public int getOrder() { + return Integer.MAX_VALUE; + } +} + diff --git a/rop/src/main/java/com/rop/event/PreCloseRopEvent.java b/rop/src/main/java/com/rop/event/PreCloseRopEvent.java index cc57ea9..26a9b68 100644 --- a/rop/src/main/java/com/rop/event/PreCloseRopEvent.java +++ b/rop/src/main/java/com/rop/event/PreCloseRopEvent.java @@ -1,22 +1,35 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.event; - -import com.rop.RopContext; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class PreCloseRopEvent extends RopEvent { - public PreCloseRopEvent(Object source, RopContext ropContext) { - super(source, ropContext); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import com.rop.RopContext; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class PreCloseRopEvent extends RopEvent { + private static final long serialVersionUID = 8140076188138851452L; + + public PreCloseRopEvent(Object source, RopContext ropContext) { + super(source, ropContext); + } +} + diff --git a/rop/src/main/java/com/rop/event/PreDoServiceEvent.java b/rop/src/main/java/com/rop/event/PreDoServiceEvent.java index 201a070..9aceab7 100644 --- a/rop/src/main/java/com/rop/event/PreDoServiceEvent.java +++ b/rop/src/main/java/com/rop/event/PreDoServiceEvent.java @@ -1,34 +1,46 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-1 - */ -package com.rop.event; - -import com.rop.RopRequestContext; - -/** - *
- *    在执行服务方法之前产生的事件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class PreDoServiceEvent extends RopEvent { - - private RopRequestContext ropRequestContext; - - public PreDoServiceEvent(Object source, RopRequestContext ropRequestContext) { - super(source, ropRequestContext.getRopContext()); - this.ropRequestContext = ropRequestContext; - } - - public RopRequestContext getRopRequestContext() { - return ropRequestContext; - } - - public long getServiceBeginTime() { - return ropRequestContext.getServiceBeginTime(); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import com.rop.RopRequestContext; + +/** + *
+ *    在执行服务方法之前产生的事件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class PreDoServiceEvent extends RopEvent { + + private static final long serialVersionUID = -3198265566192689456L; + private RopRequestContext ropRequestContext; + + public PreDoServiceEvent(Object source, RopRequestContext ropRequestContext) { + super(source, ropRequestContext.getRopContext()); + this.ropRequestContext = ropRequestContext; + } + + public RopRequestContext getRopRequestContext() { + return ropRequestContext; + } + + public long getServiceBeginTime() { + return ropRequestContext.getServiceBeginTime(); + } +} + diff --git a/rop/src/main/java/com/rop/event/RopEvent.java b/rop/src/main/java/com/rop/event/RopEvent.java index a704b8a..0d81896 100644 --- a/rop/src/main/java/com/rop/event/RopEvent.java +++ b/rop/src/main/java/com/rop/event/RopEvent.java @@ -1,32 +1,44 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import com.rop.RopContext; - -import java.util.EventObject; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public abstract class RopEvent extends EventObject { - - private RopContext ropContext; - - public RopEvent(Object source, RopContext ropContext) { - super(source); - this.ropContext = ropContext; - } - - public RopContext getRopContext() { - return ropContext; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import com.rop.RopContext; + +import java.util.EventObject; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@SuppressWarnings("serial") +public abstract class RopEvent extends EventObject { + + private RopContext ropContext; + + public RopEvent(Object source, RopContext ropContext) { + super(source); + this.ropContext = ropContext; + } + + public RopContext getRopContext() { + return ropContext; + } +} + diff --git a/rop/src/main/java/com/rop/event/RopEventListener.java b/rop/src/main/java/com/rop/event/RopEventListener.java index 9829250..ee2ee12 100644 --- a/rop/src/main/java/com/rop/event/RopEventListener.java +++ b/rop/src/main/java/com/rop/event/RopEventListener.java @@ -1,33 +1,44 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import java.util.EventListener; - -/** - *
- *    监听所有Rop框架的事件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopEventListener extends EventListener { - - /** - * 响应事件 - * - * @param ropEvent - */ - void onRopEvent(E ropEvent); - - /** - * 执行的顺序号 - * - * @return - */ - int getOrder(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import java.util.EventListener; + +/** + *
+ *    监听所有Rop框架的事件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopEventListener extends EventListener { + + /** + * 响应事件 + * + * @param ropEvent + */ + void onRopEvent(E ropEvent); + + /** + * 执行的顺序号 + * + * @return + */ + int getOrder(); +} + diff --git a/rop/src/main/java/com/rop/event/RopEventMulticaster.java b/rop/src/main/java/com/rop/event/RopEventMulticaster.java index 3661d0e..406c5cc 100644 --- a/rop/src/main/java/com/rop/event/RopEventMulticaster.java +++ b/rop/src/main/java/com/rop/event/RopEventMulticaster.java @@ -1,45 +1,56 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -/** - *
- *   注册事件监听器,发布事件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopEventMulticaster { - - /** - * Add a listener to be notified of all events. - * - * @param listener the listener to add - */ - void addRopListener(RopEventListener listener); - - /** - * Remove a listener from the notification list. - * - * @param listener the listener to remove - */ - void removeRopListener(RopEventListener listener); - - /** - * Remove all listeners registered with this multicaster. - *

After a remove call, the multicaster will perform no action - * on event notification until new listeners are being registered. - */ - void removeAllRopListeners(); - - /** - * Multicast the given application event to appropriate listeners. - * - * @param event the event to multicast - */ - void multicastEvent(RopEvent event); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +/** + *

+ *   注册事件监听器,发布事件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface RopEventMulticaster { + + /** + * Add a listener to be notified of all events. + * + * @param listener the listener to add + */ + void addRopListener(RopEventListener listener); + + /** + * Remove a listener from the notification list. + * + * @param listener the listener to remove + */ + void removeRopListener(RopEventListener listener); + + /** + * Remove all listeners registered with this multicaster. + *

After a remove call, the multicaster will perform no action + * on event notification until new listeners are being registered. + */ + void removeAllRopListeners(); + + /** + * Multicast the given application event to appropriate listeners. + * + * @param event the event to multicast + */ + void multicastEvent(RopEvent event); +} + diff --git a/rop/src/main/java/com/rop/event/SimpleRopEventMulticaster.java b/rop/src/main/java/com/rop/event/SimpleRopEventMulticaster.java index 3258a11..fb63d63 100644 --- a/rop/src/main/java/com/rop/event/SimpleRopEventMulticaster.java +++ b/rop/src/main/java/com/rop/event/SimpleRopEventMulticaster.java @@ -1,55 +1,66 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.Executor; - -/** - *

- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SimpleRopEventMulticaster extends AbstractRopEventMulticaster { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private Executor executor; - - - public void multicastEvent(final RopEvent event) { - try { - for (final RopEventListener listener : getRopEventListeners(event)) { - Executor executor = getExecutor(); - if (executor != null) { - executor.execute(new Runnable() { - - public void run() { - listener.onRopEvent(event); - } - }); - } else { - listener.onRopEvent(event); - } - } - } catch (Exception e) { - logger.error("处理"+event.getClass().getName()+"事件发生异常",e); - } - } - - public Executor getExecutor() { - return executor; - } - - public void setExecutor(Executor executor) { - this.executor = executor; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Executor; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SimpleRopEventMulticaster extends AbstractRopEventMulticaster { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private Executor executor; + + + public void multicastEvent(final RopEvent event) { + try { + for (final RopEventListener listener : getRopEventListeners(event)) { + Executor executor = getExecutor(); + if (executor != null) { + executor.execute(new Runnable() { + + public void run() { + listener.onRopEvent(event); + } + }); + } else { + listener.onRopEvent(event); + } + } + } catch (Exception e) { + logger.error("处理"+event.getClass().getName()+"事件发生异常",e); + } + } + + public Executor getExecutor() { + return executor; + } + + public void setExecutor(Executor executor) { + this.executor = executor; + } +} + diff --git a/rop/src/main/java/com/rop/event/SmartRopEventListener.java b/rop/src/main/java/com/rop/event/SmartRopEventListener.java index eaa5036..cb34575 100644 --- a/rop/src/main/java/com/rop/event/SmartRopEventListener.java +++ b/rop/src/main/java/com/rop/event/SmartRopEventListener.java @@ -1,25 +1,36 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.event; - -/** - *
- *   检查是否支持特定的事件
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface SmartRopEventListener extends RopEventListener { - - /** - * 是否支持此事件 - * - * @param eventType - * @return - */ - boolean supportsEventType(Class eventType); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.event; + +/** + *
+ *   检查是否支持特定的事件
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface SmartRopEventListener extends RopEventListener { + + /** + * 是否支持此事件 + * + * @param eventType + * @return + */ + boolean supportsEventType(Class eventType); +} + diff --git a/rop/src/main/java/com/rop/impl/AnnotationServiceMethodAdapter.java b/rop/src/main/java/com/rop/impl/AnnotationServiceMethodAdapter.java index 9d95494..773bfe7 100644 --- a/rop/src/main/java/com/rop/impl/AnnotationServiceMethodAdapter.java +++ b/rop/src/main/java/com/rop/impl/AnnotationServiceMethodAdapter.java @@ -1,64 +1,94 @@ -/** - * 日 期:12-2-11 - */ -package com.rop.impl; - -import com.rop.RopRequest; -import com.rop.RopRequestContext; -import com.rop.ServiceMethodAdapter; -import com.rop.ServiceMethodHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.LocalVariableTableParameterNameDiscoverer; -import org.springframework.core.ParameterNameDiscoverer; - -import java.lang.reflect.InvocationTargetException; - - -/** - *
- *    通过该服务方法适配器调用目标的服务方法
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class AnnotationServiceMethodAdapter implements ServiceMethodAdapter { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); - - /** - * 调用ROP服务方法 - * - * @param ropRequest - * @return - */ - public Object invokeServiceMethod(RopRequest ropRequest) { - try { - RopRequestContext ropRequestContext = ropRequest.getRopRequestContext(); - //分析上下文中的错误 - ServiceMethodHandler serviceMethodHandler = ropRequestContext.getServiceMethodHandler(); - if (logger.isDebugEnabled()) { - logger.debug("执行" + serviceMethodHandler.getHandler().getClass() + - "." + serviceMethodHandler.getHandlerMethod().getName()); - } - if (serviceMethodHandler.isHandlerMethodWithParameter()) { - return serviceMethodHandler.getHandlerMethod().invoke( - serviceMethodHandler.getHandler(),ropRequest); - } else { - return serviceMethodHandler.getHandlerMethod().invoke(serviceMethodHandler.getHandler()); - } - } catch (Throwable e) { - if (e instanceof InvocationTargetException) { - InvocationTargetException inve = (InvocationTargetException) e; - throw new RuntimeException(inve.getTargetException()); - } else { - throw new RuntimeException(e); - } - } - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.RopContext; +import com.rop.RopRequestContext; +import com.rop.ServiceMethodAdapter; +import com.rop.ServiceMethodHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + +/** + *
+ *    通过该服务方法适配器调用目标的服务方法
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class AnnotationServiceMethodAdapter implements ServiceMethodAdapter { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + /** + * 调用ROP服务方法 + * + * @param ropRequest + * @return + */ + public Object invokeServiceMethod(Object ropRequest, RopRequestContext context) { + try { + //分析上下文中的错误 + ServiceMethodHandler serviceMethodHandler = context.getServiceMethodHandler(); + if (logger.isDebugEnabled()) { + logger.debug("执行" + serviceMethodHandler.getHandler().getClass() + + "." + serviceMethodHandler.getHandlerMethod().getName()); + } + Method method = serviceMethodHandler.getHandlerMethod(); + Class[] classes = method.getParameterTypes(); + if(classes == null || classes.length <= 0){ + return method.invoke(serviceMethodHandler.getHandler()); + }else{ + Object[] objs = ropRequest.getClass().isArray() ? (Object[])ropRequest : null; + Object[] args = new Object[classes.length]; + for(int i = 0; i < args.length; i++){ + Class type = classes[i]; + Object obj = objs == null ? ropRequest : objs[i]; + if(obj != null && obj.getClass().isAssignableFrom(type)){ + args[i] = obj; + }else if(RopRequestContext.class.isAssignableFrom(type)){ + args[i] = context; + }else if(HttpServletRequest.class.isAssignableFrom(type)){ + args[i] = context.getRawRequestObject(); + }else if(HttpServletResponse.class.isAssignableFrom(type)){ + args[i] = context.getRawResponseObject(); + }else if(RopContext.class.isAssignableFrom(type)){ + args[i] = context.getRopContext(); + } + } + return method.invoke(serviceMethodHandler.getHandler(), args); + } + } catch (Throwable e) { + if (e instanceof InvocationTargetException) { + InvocationTargetException inve = (InvocationTargetException) e; + throw new RuntimeException(inve.getTargetException()); + } else { + throw new RuntimeException(e); + } + } + } + +} + diff --git a/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouter.java b/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouter.java index ae6b27c..e25a31d 100644 --- a/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouter.java +++ b/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouter.java @@ -1,733 +1,858 @@ -/** - * - * 日 期:12-2-8 - */ -package com.rop.impl; - -import com.rop.*; -import com.rop.MessageFormat; -import com.rop.config.SystemParameterNames; -import com.rop.event.*; -import com.rop.marshaller.JacksonJsonRopMarshaller; -import com.rop.marshaller.JaxbXmlRopMarshaller; -import com.rop.marshaller.MessageMarshallerUtils; -import com.rop.request.RopRequestMessageConverter; -import com.rop.request.UploadFileConverter; -import com.rop.response.ErrorResponse; -import com.rop.response.RejectedServiceResponse; -import com.rop.response.ServiceUnavailableErrorResponse; -import com.rop.response.TimeoutErrorResponse; -import com.rop.security.*; -import com.rop.security.SecurityManager; -import com.rop.session.DefaultSessionManager; -import com.rop.session.SessionBindInterceptor; -import com.rop.session.SessionManager; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.context.support.ResourceBundleMessageSource; -import org.springframework.format.support.FormattingConversionService; -import org.springframework.format.support.FormattingConversionServiceFactoryBean; -import org.springframework.util.Assert; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.text.*; -import java.util.*; -import java.util.concurrent.*; - -public class AnnotationServletServiceRouter implements ServiceRouter { - - public static final String APPLICATION_XML = "application/xml"; - - public static final String APPLICATION_JSON = "application/json"; - public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; - public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; - public static final String DEFAULT_EXT_ERROR_BASE_NAME = "i18n/rop/ropError"; - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private static final String I18N_ROP_ERROR = "i18n/rop/error"; - - private ServiceMethodAdapter serviceMethodAdapter = new AnnotationServiceMethodAdapter(); - - private RopMarshaller xmlMarshallerRop = new JaxbXmlRopMarshaller(); - - private RopMarshaller jsonMarshallerRop = new JacksonJsonRopMarshaller(); - - private RequestContextBuilder requestContextBuilder; - - private SecurityManager securityManager; - - private FormattingConversionService formattingConversionService; - - private ThreadPoolExecutor threadPoolExecutor; - - private RopContext ropContext; - - private RopEventMulticaster ropEventMulticaster; - - private List interceptors = new ArrayList(); - - private List listeners = new ArrayList(); - - private boolean signEnable = true; - - private ApplicationContext applicationContext; - - //所有服务方法的最大过期时间,单位为秒(0或负数代表不限制) - private int serviceTimeoutSeconds = Integer.MAX_VALUE; - - //会话管理器 - private SessionManager sessionManager = new DefaultSessionManager(); - - //服务调用频率管理器 - private InvokeTimesController invokeTimesController = new DefaultInvokeTimesController(); - - private Class threadFerryClass; - - private String extErrorBasename; - - private String[] extErrorBasenames; - - - public void service(Object request, Object response) { - HttpServletRequest servletRequest = (HttpServletRequest) request; - HttpServletResponse servletResponse = (HttpServletResponse) response; - - //获取服务方法最大过期时间 - String method = servletRequest.getParameter(SystemParameterNames.getMethod()); - String version = servletRequest.getParameter(SystemParameterNames.getVersion()); - if (logger.isDebugEnabled()) { - logger.debug("调用服务方法:" + method + "(" + version + ")"); - } - int serviceMethodTimeout = getServiceMethodTimeout(method, version); - long beginTime = System.currentTimeMillis(); - String jsonpCallback = getJsonpcallback(servletRequest); - - //使用异常方式调用服务方法 - try { - - //执行线程摆渡 - ThreadFerry threadFerry = buildThreadFerryInstance(); - if (threadFerry != null) { - threadFerry.doInSrcThread(); - } - - ServiceRunnable runnable = new ServiceRunnable(servletRequest, servletResponse, jsonpCallback, threadFerry); - Future future = this.threadPoolExecutor.submit(runnable); - while (!future.isDone()) { - future.get(serviceMethodTimeout, TimeUnit.SECONDS); - } - } catch (RejectedExecutionException ree) {//超过最大的服务平台的最大资源限制,无法提供服务 - if (logger.isInfoEnabled()) { - logger.info("调用服务方法:" + method + "(" + version + "),超过最大资源限制,无法提供服务。"); - } - RopRequestContext ropRequestContext = buildRequestContextWhenException(servletRequest, beginTime); - RejectedServiceResponse ropResponse = new RejectedServiceResponse(ropRequestContext); - writeResponse(ropResponse, servletResponse, ServletRequestContextBuilder.getResponseFormat(servletRequest), jsonpCallback); - fireAfterDoServiceEvent(ropRequestContext); - } catch (TimeoutException e) {//服务时间超限 - if (logger.isInfoEnabled()) { - logger.info("调用服务方法:" + method + "(" + version + "),服务调用超时。"); - } - RopRequestContext ropRequestContext = buildRequestContextWhenException(servletRequest, beginTime); - TimeoutErrorResponse ropResponse = - new TimeoutErrorResponse(ropRequestContext.getMethod(), - ropRequestContext.getLocale(), serviceMethodTimeout); - writeResponse(ropResponse, servletResponse, ServletRequestContextBuilder.getResponseFormat(servletRequest), jsonpCallback); - fireAfterDoServiceEvent(ropRequestContext); - } catch (Throwable throwable) {//产生未知的错误 - if (logger.isInfoEnabled()) { - logger.info("调用服务方法:" + method + "(" + version + "),产生异常", throwable); - } - ServiceUnavailableErrorResponse ropResponse = - new ServiceUnavailableErrorResponse(method, ServletRequestContextBuilder.getLocale(servletRequest), throwable); - writeResponse(ropResponse, servletResponse, ServletRequestContextBuilder.getResponseFormat(servletRequest), jsonpCallback); - RopRequestContext ropRequestContext = buildRequestContextWhenException(servletRequest, beginTime); - fireAfterDoServiceEvent(ropRequestContext); - } finally { - try { - servletResponse.getOutputStream().flush(); - servletResponse.getOutputStream().close(); - } catch (IOException e) { - logger.error("关闭响应出错", e); - } - } - } - - /** - * 获取JSONP的参数名,如果没有返回 - * - * @param servletRequest - * @return - */ - private String getJsonpcallback(HttpServletRequest servletRequest) { - if (servletRequest.getParameterMap().containsKey(SystemParameterNames.getJsonp())) { - String callback = servletRequest.getParameter(SystemParameterNames.getJsonp()); - if (StringUtils.isEmpty(callback)) { - callback = "callback"; - } - return callback; - } else { - return null; - } - } - - - public void startup() { - if (logger.isInfoEnabled()) { - logger.info("开始启动Rop框架..."); - } - Assert.notNull(this.applicationContext, "Spring上下文不能为空"); - - //初始化类型转换器 - if (this.formattingConversionService == null) { - this.formattingConversionService = getDefaultConversionService(); - } - registerConverters(formattingConversionService); - - //实例化ServletRequestContextBuilder - this.requestContextBuilder = new ServletRequestContextBuilder(this.formattingConversionService); - - //设置校验器 - if (this.securityManager == null) { - this.securityManager = new DefaultSecurityManager(); - } - - //设置异步执行器 - if (this.threadPoolExecutor == null) { - this.threadPoolExecutor = - new ThreadPoolExecutor(200, Integer.MAX_VALUE, 5 * 60, TimeUnit.SECONDS, new LinkedBlockingQueue()); - } - - //创建Rop上下文 - this.ropContext = buildRopContext(); - - //初始化事件发布器 - this.ropEventMulticaster = buildRopEventMulticaster(); - - //注册会话绑定拦截器 - this.addInterceptor(new SessionBindInterceptor()); - - //初始化信息源 - initMessageSource(); - - //产生Rop框架初始化事件 - fireAfterStartedRopEvent(); - - if (logger.isInfoEnabled()) { - logger.info("Rop框架启动成功!"); - } - } - - private void registerConverters(FormattingConversionService conversionService) { - conversionService.addConverter(new RopRequestMessageConverter()); - conversionService.addConverter(new UploadFileConverter()); - } - - private ThreadFerry buildThreadFerryInstance() { - if (threadFerryClass != null) { - return BeanUtils.instantiate(threadFerryClass); - } else { - return null; - } - } - - - public void shutdown() { - fireBeforeCloseRopEvent(); - threadPoolExecutor.shutdown(); - } - - - public void setSignEnable(boolean signEnable) { - if (!signEnable && logger.isWarnEnabled()) { - logger.warn("rop close request message sign"); - } - this.signEnable = signEnable; - } - - - public void setThreadFerryClass(Class threadFerryClass) { - if (logger.isDebugEnabled()) { - logger.debug("ThreadFerry set to {}",threadFerryClass.getName()); - } - this.threadFerryClass = threadFerryClass; - } - - - public void setInvokeTimesController(InvokeTimesController invokeTimesController) { - if (logger.isDebugEnabled()) { - logger.debug("InvokeTimesController set to {}",invokeTimesController.getClass().getName()); - } - this.invokeTimesController = invokeTimesController; - } - - - public void setServiceTimeoutSeconds(int serviceTimeoutSeconds) { - if (logger.isDebugEnabled()) { - logger.debug("serviceTimeoutSeconds set to {}",serviceTimeoutSeconds); - } - this.serviceTimeoutSeconds = serviceTimeoutSeconds; - } - - - public void setSecurityManager(SecurityManager securityManager) { - if (logger.isDebugEnabled()) { - logger.debug("securityManager set to {}",securityManager.getClass().getName()); - } - this.securityManager = securityManager; - } - - - public void setFormattingConversionService(FormattingConversionService formatConversionService) { - if (logger.isDebugEnabled()) { - logger.debug("formatConversionService set to {}",formatConversionService.getClass().getName()); - } - this.formattingConversionService = formatConversionService; - } - - - public void setSessionManager(SessionManager sessionManager) { - if (logger.isDebugEnabled()) { - logger.debug("sessionManager set to {}",sessionManager.getClass().getName()); - } - this.sessionManager = sessionManager; - } - - /** - * 获取默认的格式化转换器 - * - * @return - */ - private FormattingConversionService getDefaultConversionService() { - FormattingConversionServiceFactoryBean serviceFactoryBean = new FormattingConversionServiceFactoryBean(); - serviceFactoryBean.afterPropertiesSet(); - return serviceFactoryBean.getObject(); - } - - - public void setExtErrorBasename(String extErrorBasename) { - if (logger.isDebugEnabled()) { - logger.debug("extErrorBasename set to {}",extErrorBasename); - } - this.extErrorBasename = extErrorBasename; - } - - - public void setExtErrorBasenames(String[] extErrorBasenames) { - if (extErrorBasenames != null) { - List list = new ArrayList(); - for (String errorBasename : extErrorBasenames) { - if (StringUtils.isNotBlank(errorBasename)) { - list.add(errorBasename); - } - } - this.extErrorBasenames = list.toArray(new String[0]); - } - - if (logger.isDebugEnabled()) { - logger.debug("extErrorBasenames set to {}",extErrorBasenames); - } - } - - - public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { - this.threadPoolExecutor = threadPoolExecutor; - if (logger.isDebugEnabled()) { - logger.debug("threadPoolExecutor set to {}",threadPoolExecutor.getClass().getName()); - logger.debug("corePoolSize:{}",threadPoolExecutor.getCorePoolSize()); - logger.debug("maxPoolSize:{}",threadPoolExecutor.getMaximumPoolSize()); - logger.debug("keepAliveSeconds:{} seconds",threadPoolExecutor.getKeepAliveTime(TimeUnit.SECONDS)); - logger.debug("queueCapacity:{}",threadPoolExecutor.getQueue().remainingCapacity()); - } - } - - - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - - public RopContext getRopContext() { - return this.ropContext; - } - - - public void addInterceptor(Interceptor interceptor) { - this.interceptors.add(interceptor); - if (logger.isDebugEnabled()) { - logger.debug("add interceptor {}",interceptor.getClass().getName()); - } - } - - - public void addListener(RopEventListener listener) { - this.listeners.add(listener); - if (logger.isDebugEnabled()) { - logger.debug("add listener {}",listener.getClass().getName()); - } - } - - public int getServiceTimeoutSeconds() { - return serviceTimeoutSeconds > 0 ? serviceTimeoutSeconds : Integer.MAX_VALUE; - } - - /** - * 取最小的过期时间 - * - * @param method - * @param version - * @return - */ - private int getServiceMethodTimeout(String method, String version) { - ServiceMethodHandler serviceMethodHandler = ropContext.getServiceMethodHandler(method, version); - if (serviceMethodHandler == null) { - return getServiceTimeoutSeconds(); - } else { - int methodTimeout = serviceMethodHandler.getServiceMethodDefinition().getTimeout(); - if (methodTimeout <= 0) { - return getServiceTimeoutSeconds(); - } else { - return methodTimeout; - } - } - } - - private class ServiceRunnable implements Runnable { - - private HttpServletRequest servletRequest; - private HttpServletResponse servletResponse; - private ThreadFerry threadFerry; - private String jsonpCallback; - - private ServiceRunnable(HttpServletRequest servletRequest, - HttpServletResponse servletResponse, - String jsonpCallback, - ThreadFerry threadFerry) { - this.servletRequest = servletRequest; - this.servletResponse = servletResponse; - this.jsonpCallback = jsonpCallback; - this.threadFerry = threadFerry; - } - - - public void run() { - if (threadFerry != null) { - threadFerry.doInDestThread(); - } - - RopRequestContext ropRequestContext = null; - RopRequest ropRequest = null; - try { - //用系统级参数构造一个RequestContext实例(第一阶段绑定) - ropRequestContext = requestContextBuilder.buildBySysParams( - ropContext, servletRequest, servletResponse); - - //验证系统级参数的合法性 - MainError mainError = securityManager.validateSystemParameters(ropRequestContext); - if (mainError != null) { - ropRequestContext.setRopResponse(new ErrorResponse(mainError)); - } else { - - //绑定业务数据(第二阶段绑定) - ropRequest = requestContextBuilder.buildRopRequest(ropRequestContext); - - //进行其它检查业务数据合法性,业务安全等 - mainError = securityManager.validateOther(ropRequestContext); - if (mainError != null) { - ropRequestContext.setRopResponse(new ErrorResponse(mainError)); - } else { - firePreDoServiceEvent(ropRequestContext); - - //服务处理前拦截 - invokeBeforceServiceOfInterceptors(ropRequestContext); - - if (ropRequestContext.getRopResponse() == null) { //拦截器未生成response - //如果拦截器没有产生ropResponse时才调用服务方法 - ropRequestContext.setRopResponse(doService(ropRequest)); - - //输出响应前拦截 - invokeBeforceResponseOfInterceptors(ropRequest); - } - } - } - //输出响应 - writeResponse(ropRequestContext.getRopResponse(), servletResponse, ropRequestContext.getMessageFormat(), jsonpCallback); - } catch (Throwable e) { - if (ropRequestContext != null) { - String method = ropRequestContext.getMethod(); - Locale locale = ropRequestContext.getLocale(); - if (logger.isDebugEnabled()) { - String message = java.text.MessageFormat.format("service {0} call error", method); - logger.debug(message,e); - } - ServiceUnavailableErrorResponse ropResponse = new ServiceUnavailableErrorResponse(method, locale, e); - - //输出响应前拦截 - invokeBeforceResponseOfInterceptors(ropRequest); - writeResponse(ropResponse, servletResponse, ropRequestContext.getMessageFormat(), jsonpCallback); - } else { - throw new RopException("RopRequestContext is null.", e); - } - } finally { - if (ropRequestContext != null) { - - //发布服务完成事件 - ropRequestContext.setServiceEndTime(System.currentTimeMillis()); - - //完成一次服务请求,计算次数 - invokeTimesController.caculateInvokeTimes(ropRequestContext.getAppKey(), ropRequestContext.getSession()); - fireAfterDoServiceEvent(ropRequestContext); - } - } - } - } - - - /** - * 当发生异常时,创建一个请求上下文对象 - * - * @param request - * @param beginTime - * @return - */ - private RopRequestContext buildRequestContextWhenException(HttpServletRequest request, long beginTime) { - RopRequestContext ropRequestContext = requestContextBuilder.buildBySysParams(ropContext, request, null); - ropRequestContext.setServiceBeginTime(beginTime); - ropRequestContext.setServiceEndTime(System.currentTimeMillis()); - return ropRequestContext; - } - - private RopContext buildRopContext() { - DefaultRopContext defaultRopContext = new DefaultRopContext(this.applicationContext); - defaultRopContext.setSignEnable(this.signEnable); - defaultRopContext.setSessionManager(sessionManager); - return defaultRopContext; - } - - private RopEventMulticaster buildRopEventMulticaster() { - - SimpleRopEventMulticaster simpleRopEventMulticaster = new SimpleRopEventMulticaster(); - - //设置异步执行器 - if (this.threadPoolExecutor != null) { - simpleRopEventMulticaster.setExecutor(this.threadPoolExecutor); - } - - //添加事件监听器 - if (this.listeners != null && this.listeners.size() > 0) { - for (RopEventListener ropEventListener : this.listeners) { - simpleRopEventMulticaster.addRopListener(ropEventListener); - } - } - - return simpleRopEventMulticaster; - } - - /** - * 发布Rop启动后事件 - */ - private void fireAfterStartedRopEvent() { - AfterStartedRopEvent ropEvent = new AfterStartedRopEvent(this, this.ropContext); - this.ropEventMulticaster.multicastEvent(ropEvent); - } - - /** - * 发布Rop启动后事件 - */ - private void fireBeforeCloseRopEvent() { - PreCloseRopEvent ropEvent = new PreCloseRopEvent(this, this.ropContext); - this.ropEventMulticaster.multicastEvent(ropEvent); - } - - private void fireAfterDoServiceEvent(RopRequestContext ropRequestContext) { - this.ropEventMulticaster.multicastEvent(new AfterDoServiceEvent(this, ropRequestContext)); - } - - private void firePreDoServiceEvent(RopRequestContext ropRequestContext) { - this.ropEventMulticaster.multicastEvent(new PreDoServiceEvent(this, ropRequestContext)); - } - - /** - * 在服务调用之前拦截 - * - * @param ropRequestContext - */ - private void invokeBeforceServiceOfInterceptors(RopRequestContext ropRequestContext) { - Interceptor tempInterceptor = null; - try { - if (interceptors != null && interceptors.size() > 0) { - for (Interceptor interceptor : interceptors) { - - interceptor.beforeService(ropRequestContext); - - //如果有一个产生了响应,则阻止后续的调用 - if (ropRequestContext.getRopResponse() != null) { - if (logger.isDebugEnabled()) { - logger.debug("拦截器[" + interceptor.getClass().getName() + "]产生了一个RopResponse," + - " 阻止本次服务请求继续,服务将直接返回。"); - } - return; - } - } - } - } catch (Throwable e) { - ropRequestContext.setRopResponse(new ServiceUnavailableErrorResponse(ropRequestContext.getMethod(), ropRequestContext.getLocale(), e)); - logger.error("在执行拦截器[" + tempInterceptor.getClass().getName() + "]时发生异常.", e); - } - } - - /** - * 在服务调用之后,返回响应之前拦截 - * - * @param ropRequest - */ - private void invokeBeforceResponseOfInterceptors(RopRequest ropRequest) { - RopRequestContext ropRequestContext = ropRequest.getRopRequestContext(); - Interceptor tempInterceptor = null; - try { - if (interceptors != null && interceptors.size() > 0) { - for (Interceptor interceptor : interceptors) { - interceptor.beforeResponse(ropRequestContext); - } - } - } catch (Throwable e) { - ropRequestContext.setRopResponse(new ServiceUnavailableErrorResponse(ropRequestContext.getMethod(), ropRequestContext.getLocale(), e)); - logger.error("在执行拦截器[" + tempInterceptor.getClass().getName() + "]时发生异常.", e); - } - } - - private void writeResponse(Object ropResponse, HttpServletResponse httpServletResponse, MessageFormat messageFormat, String jsonpCallback) { - try { - if (!(ropResponse instanceof ErrorResponse) && messageFormat == MessageFormat.stream) { - if (logger.isDebugEnabled()) { - logger.debug("使用{}输出方式,由服务自身负责响应输出工作.", MessageFormat.stream); - } - return; - } - if (logger.isDebugEnabled()) { - logger.debug("输出响应:" + MessageMarshallerUtils.getMessage(ropResponse, messageFormat)); - } - RopMarshaller ropMarshaller = xmlMarshallerRop; - String contentType = APPLICATION_XML; - if (messageFormat == MessageFormat.json) { - ropMarshaller = jsonMarshallerRop; - contentType = APPLICATION_JSON; - } - httpServletResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); - httpServletResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, "*"); - httpServletResponse.setCharacterEncoding(Constants.UTF8); - httpServletResponse.setContentType(contentType); - - if (jsonpCallback != null) { - httpServletResponse.getOutputStream().write(jsonpCallback.getBytes()); - httpServletResponse.getOutputStream().write('('); - } - ropMarshaller.marshaller(ropResponse, httpServletResponse.getOutputStream()); - if (jsonpCallback != null) { - httpServletResponse.getOutputStream().write(')'); - httpServletResponse.getOutputStream().write(';'); - } - } catch (IOException e) { - throw new RopException(e); - } - } - - private Object doService(RopRequest ropRequest) { - Object ropResponse = null; - RopRequestContext context = ropRequest.getRopRequestContext(); - if (context.getMethod() == null) { - ropResponse = new ErrorResponse(MainErrors.getError( - MainErrorType.MISSING_METHOD, context.getLocale(), - SystemParameterNames.getMethod())); - } else if (!ropContext.isValidMethod(context.getMethod())) { - MainError invalidMethodError = MainErrors.getError( - MainErrorType.INVALID_METHOD, context.getLocale(),context.getMethod()); - ropResponse = new ErrorResponse(invalidMethodError); - } else { - try { - ropResponse = serviceMethodAdapter.invokeServiceMethod(ropRequest); - } catch (Exception e) { //出错则招聘服务不可用的异常 - if (logger.isInfoEnabled()) { - logger.info("调用" + context.getMethod() + "时发生异常,异常信息为:" + e.getMessage()); - e.printStackTrace(); - } - ropResponse = new ServiceUnavailableErrorResponse(context.getMethod(), context.getLocale(), e); - } - } - return ropResponse; - } - - /** - * 设置国际化资源信息 - */ - private void initMessageSource() { - HashSet baseNamesSet = new HashSet(); - baseNamesSet.add(I18N_ROP_ERROR);//ROP自动的资源 - - if (extErrorBasename == null && extErrorBasenames == null) { - baseNamesSet.add(DEFAULT_EXT_ERROR_BASE_NAME); - } else { - if (extErrorBasename != null) { - baseNamesSet.add(extErrorBasename); - } - if (extErrorBasenames != null) { - baseNamesSet.addAll(Arrays.asList(extErrorBasenames)); - } - } - String[] totalBaseNames = baseNamesSet.toArray(new String[0]); - - if (logger.isInfoEnabled()) { - logger.info("加载错误码国际化资源:{}", StringUtils.join(totalBaseNames, ",")); - } - ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource(); - bundleMessageSource.setBasenames(totalBaseNames); - MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(bundleMessageSource); - MainErrors.setErrorMessageSourceAccessor(messageSourceAccessor); - SubErrors.setErrorMessageSourceAccessor(messageSourceAccessor); - } - - public SecurityManager getSecurityManager() { - return securityManager; - } - - - public FormattingConversionService getFormattingConversionService() { - return formattingConversionService; - } - - public ThreadPoolExecutor getThreadPoolExecutor() { - return threadPoolExecutor; - } - - public RopEventMulticaster getRopEventMulticaster() { - return ropEventMulticaster; - } - - public List getInterceptors() { - return interceptors; - } - - public List getListeners() { - return listeners; - } - - public boolean isSignEnable() { - return signEnable; - } - - public ApplicationContext getApplicationContext() { - return applicationContext; - } - - public String getExtErrorBasename() { - return extErrorBasename; - } - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.*; +import com.rop.config.SystemParameterNames; +import com.rop.event.*; +import com.rop.marshaller.JacksonJsonRopMarshaller; +import com.rop.marshaller.JaxbXmlRopMarshaller; +import com.rop.request.RopRequestMessageConverter; +import com.rop.request.UploadFileConverter; +import com.rop.response.ErrorResponse; +import com.rop.response.MainError; +import com.rop.response.MainErrorType; +import com.rop.response.RejectedServiceResponse; +import com.rop.response.ServiceUnavailableErrorResponse; +import com.rop.response.TimeoutErrorResponse; +import com.rop.security.*; +import com.rop.security.SecurityManager; +import com.rop.session.DefaultSessionManager; +import com.rop.session.SessionBindInterceptor; +import com.rop.session.SessionManager; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.MessageSourceAccessor; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.format.support.FormattingConversionServiceFactoryBean; +import org.springframework.util.Assert; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; +import java.util.*; +import java.util.concurrent.*; + +public class AnnotationServletServiceRouter implements ServiceRouter { + + public static final String APPLICATION_XML = "application/xml"; + + public static final String APPLICATION_JSON = "application/json"; + public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; + public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; + public static final String DEFAULT_EXT_ERROR_BASE_NAME = "i18n/rop/ropError"; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final String I18N_ROP_ERROR = "i18n/rop/error"; + + private ServiceMethodAdapter serviceMethodAdapter; + + private RopMarshaller xmlMarshaller; + + private RopMarshaller jsonMarshaller; + + private RequestContextBuilder requestContextBuilder; + + private SecurityManager securityManager; + + private FormattingConversionService formattingConversionService; + + private ThreadPoolExecutor threadPoolExecutor; + + private RopContext ropContext; + + private RopEventMulticaster ropEventMulticaster; + + private List interceptors = new ArrayList(); + + private List> listeners = new ArrayList>(); + + private boolean signEnable = true; + + private ApplicationContext applicationContext; + + // 所有服务方法的最大过期时间,单位为秒(0或负数代表不限制) + private int serviceTimeoutSeconds = Integer.MAX_VALUE; + + // 会话管理器 + private SessionManager sessionManager; + + // 服务调用频率管理器 + private InvokeTimesController invokeTimesController; + + // 线程摆渡类,用于线程变量过渡设置 + private Class threadFerryClass; + + // 扩展的错误代码国际化资源开始名称 + private String extErrorBasename; + // 扩展的错误代码国际化资源开始名称数组 + private String[] extErrorBasenames; + + @Override + public void service(HttpServletRequest request, HttpServletResponse response) { + // 获取服务方法最大过期时间 + String method = request.getParameter(SystemParameterNames.getMethod()); + String version = request.getParameter(SystemParameterNames.getVersion()); + if (logger.isDebugEnabled()) { + logger.debug("调用服务方法:" + method + "(" + version + ")"); + } + int serviceMethodTimeout = getServiceMethodTimeout(method, version); + long beginTime = System.currentTimeMillis(); + String jsonpCallback = getJsonpcallback(request); + MessageFormat format = ServletRequestContextBuilder.getResponseFormat(request); + Locale locale = ServletRequestContextBuilder.getLocale(request); + // 使用异常方式调用服务方法 + try { + // 执行线程摆渡 + ThreadFerry threadFerry = buildThreadFerryInstance(); + if (threadFerry != null) { + threadFerry.doInSrcThread(); + } + ServiceRunnable runnable = new ServiceRunnable(request, response, threadFerry); + Future future = this.threadPoolExecutor.submit(runnable); + while (!future.isDone()) { + future.get(serviceMethodTimeout, TimeUnit.SECONDS); + } + // 为了解决子线程在输出内容时超时,将正确执行的结果和超时异常信息同时输出给客户端的bug + if (runnable.ropRequestContext != null && runnable.ropRequestContext.getRopResponse() != null) { + writeResponse(runnable.ropRequestContext.getRopResponse(), response, format, jsonpCallback); + } + } catch (RejectedExecutionException e) {// 超过最大的服务平台的最大资源限制,无法提供服务 + log(method, version, "超过最大资源限制,无法提供服务。", e); + RopRequestContext ropRequestContext = buildRequestContextWhenException(request, beginTime); + RejectedServiceResponse ropResponse = new RejectedServiceResponse(ropRequestContext); + writeErrorResponse(ropResponse, request, response, jsonpCallback, beginTime); + } catch (TimeoutException e) {// 服务时间超限 + log(method, version, "服务调用超时。", e); + TimeoutErrorResponse ropResponse = new TimeoutErrorResponse(method, locale, serviceMethodTimeout); + writeErrorResponse(ropResponse, request, response, jsonpCallback, beginTime); + } catch (Exception throwable) {// 产生未知的错误 + log(method, version, "产生异常", throwable); + ServiceUnavailableErrorResponse ropResponse = new ServiceUnavailableErrorResponse(method, locale, + throwable); + writeErrorResponse(ropResponse, request, response, jsonpCallback, beginTime); + } finally { + try { + response.getOutputStream().flush(); + response.getOutputStream().close(); + } catch (IOException e) { + logger.error("关闭响应出错", e); + } + } + } + + /** + * 输出错误信息给调用方 + * + * @param errorResponse + * @param request + * @param response + * @param jsonpCallback + * @param beginTime + */ + private void writeErrorResponse(ErrorResponse errorResponse, HttpServletRequest request, + HttpServletResponse response, String jsonpCallback, long beginTime) { + MessageFormat format = ServletRequestContextBuilder.getResponseFormat(request); + writeResponse(errorResponse, response, format, jsonpCallback); + RopRequestContext ropRequestContext = buildRequestContextWhenException(request, beginTime); + fireAfterDoServiceEvent(ropRequestContext); + } + + /** + * 记录方法执行日志 + * + * @param method + * @param version + * @param msg + * @param e + */ + private void log(String method, String version, String msg, Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("调用服务方法:" + method + "(" + version + ")," + (msg == null ? "" : msg), e); + } + } + + /** + * 获取JSONP的参数名,如果没有返回 + * + * @param servletRequest + * @return + */ + private String getJsonpcallback(HttpServletRequest servletRequest) { + if (servletRequest.getParameterMap().containsKey(SystemParameterNames.getJsonp())) { + String callback = servletRequest.getParameter(SystemParameterNames.getJsonp()); + if (StringUtils.isEmpty(callback)) { + callback = "callback"; + } + return callback; + } else { + return null; + } + } + + /** + * 启动平台服务 + */ + @Override + public void startup() { + if (logger.isInfoEnabled()) { + logger.info("开始启动Rop框架..."); + } + Assert.notNull(this.applicationContext, "Spring上下文不能为空"); + if (serviceMethodAdapter == null) { + serviceMethodAdapter = new AnnotationServiceMethodAdapter(); + } + if (xmlMarshaller == null) { + xmlMarshaller = new JaxbXmlRopMarshaller(); + } + if (jsonMarshaller == null) { + jsonMarshaller = new JacksonJsonRopMarshaller(); + } + if (sessionManager == null) { + sessionManager = new DefaultSessionManager(); + } + if (invokeTimesController == null) { + invokeTimesController = new DefaultInvokeTimesController(); + } + // 初始化类型转换器 + if (this.formattingConversionService == null) { + this.formattingConversionService = getDefaultConversionService(); + } + registerConverters(formattingConversionService); + + // 实例化ServletRequestContextBuilder + this.requestContextBuilder = new ServletRequestContextBuilder(this.formattingConversionService); + + // 设置校验器 + if (this.securityManager == null) { + this.securityManager = new DefaultSecurityManager(); + } + + // 设置异步执行器 + if (this.threadPoolExecutor == null) { + this.threadPoolExecutor = new ThreadPoolExecutor(200, Integer.MAX_VALUE, 5 * 60, TimeUnit.SECONDS, + new LinkedBlockingQueue()); + } + + // 创建Rop上下文 + this.ropContext = buildRopContext(); + + // 初始化事件发布器 + this.ropEventMulticaster = buildRopEventMulticaster(); + + // 注册会话绑定拦截器 + this.addInterceptor(new SessionBindInterceptor()); + + // 初始化信息源 + initMessageSource(); + + // 产生Rop框架初始化事件 + fireAfterStartedRopEvent(); + + if (logger.isInfoEnabled()) { + logger.info("Rop框架启动成功!"); + } + } + + /** + * 注册数据转换器 + * + * @param conversionService + */ + private void registerConverters(FormattingConversionService conversionService) { + conversionService.addConverter(new RopRequestMessageConverter()); + conversionService.addConverter(new UploadFileConverter()); + } + + /** + * 创建线程摆渡类实例 + * + * @return object of ThreadFerry + */ + private ThreadFerry buildThreadFerryInstance() { + if (threadFerryClass != null) { + return BeanUtils.instantiate(threadFerryClass); + } else { + return null; + } + } + + /** + * 停止服务 + */ + @Override + public void shutdown() { + fireBeforeCloseRopEvent(); + threadPoolExecutor.shutdown(); + } + + /** + * 设置是否开启参数签名 + */ + public void setSignEnable(boolean signEnable) { + if (!signEnable && logger.isWarnEnabled()) { + logger.warn("rop close request message sign"); + } + this.signEnable = signEnable; + } + + /** + * 设置线程变量摆渡类 + */ + public void setThreadFerryClass(Class threadFerryClass) { + if (logger.isDebugEnabled()) { + logger.debug("ThreadFerry set to {}", threadFerryClass.getName()); + } + this.threadFerryClass = threadFerryClass; + } + + /** + * 设置服务超时控制器 + */ + public void setInvokeTimesController(InvokeTimesController invokeTimesController) { + if (logger.isDebugEnabled()) { + logger.debug("InvokeTimesController set to {}", invokeTimesController.getClass().getName()); + } + this.invokeTimesController = invokeTimesController; + } + + /** + * 设置服务超时时间 + */ + public void setServiceTimeoutSeconds(int serviceTimeoutSeconds) { + if (logger.isDebugEnabled()) { + logger.debug("serviceTimeoutSeconds set to {}", serviceTimeoutSeconds); + } + this.serviceTimeoutSeconds = serviceTimeoutSeconds; + } + + /** + * 设置安全管理对象 + */ + public void setSecurityManager(SecurityManager securityManager) { + if (logger.isDebugEnabled()) { + logger.debug("securityManager set to {}", securityManager.getClass().getName()); + } + this.securityManager = securityManager; + } + + /** + * 设置消息转换器服务对象 + */ + public void setFormattingConversionService(FormattingConversionService formatConversionService) { + if (logger.isDebugEnabled()) { + logger.debug("formatConversionService set to {}", formatConversionService.getClass().getName()); + } + this.formattingConversionService = formatConversionService; + } + + /** + * 设置session管理器对象 + */ + public void setSessionManager(SessionManager sessionManager) { + if (logger.isDebugEnabled()) { + logger.debug("sessionManager set to {}", sessionManager.getClass().getName()); + } + this.sessionManager = sessionManager; + } + + /** + * 获取默认的格式化转换器 + * + * @return + */ + private FormattingConversionService getDefaultConversionService() { + FormattingConversionServiceFactoryBean serviceFactoryBean = new FormattingConversionServiceFactoryBean(); + serviceFactoryBean.afterPropertiesSet(); + return serviceFactoryBean.getObject(); + } + + /** + * 设置扩展的错误消息代码国际化开始名称 + */ + public void setExtErrorBasename(String extErrorBasename) { + if (logger.isDebugEnabled()) { + logger.debug("extErrorBasename set to {}", extErrorBasename); + } + this.extErrorBasename = extErrorBasename; + } + + /** + * 设置扩展的错误消息代码国际化开始名称数组 + */ + public void setExtErrorBasenames(String[] extErrorBasenames) { + if (extErrorBasenames != null) { + List list = new ArrayList(); + for (String errorBasename : extErrorBasenames) { + if (StringUtils.isNotBlank(errorBasename)) { + list.add(errorBasename); + } + } + this.extErrorBasenames = list.toArray(new String[0]); + } + + if (logger.isDebugEnabled()) { + logger.debug("extErrorBasenames set to {}", Arrays.asList(extErrorBasenames)); + } + } + + /** + * 设置线程池执行器 + */ + public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { + this.threadPoolExecutor = threadPoolExecutor; + if (logger.isDebugEnabled()) { + logger.debug("threadPoolExecutor set to {}", threadPoolExecutor.getClass().getName()); + logger.debug("corePoolSize:{}", threadPoolExecutor.getCorePoolSize()); + logger.debug("maxPoolSize:{}", threadPoolExecutor.getMaximumPoolSize()); + logger.debug("keepAliveSeconds:{} seconds", threadPoolExecutor.getKeepAliveTime(TimeUnit.SECONDS)); + logger.debug("queueCapacity:{}", threadPoolExecutor.getQueue().remainingCapacity()); + } + } + + /** + * 设置spring的上下文对象 + */ + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + /** + * 获取rop框架的上下文对象 + * + * @return object of RopContext + */ + public RopContext getRopContext() { + return this.ropContext; + } + + /** + * 添加服务拦截器 + */ + public void addInterceptor(Interceptor interceptor) { + this.interceptors.add(interceptor); + if (logger.isDebugEnabled()) { + logger.debug("add interceptor {}", interceptor.getClass().getName()); + } + } + + /** + * 添加监听器 + */ + public void addListener(RopEventListener listener) { + this.listeners.add(listener); + if (logger.isDebugEnabled()) { + logger.debug("add listener {}", listener.getClass().getName()); + } + } + + /** + * 获取服务超时时间 + * + * @return 服务超时时间,单位是秒 + */ + public int getServiceTimeoutSeconds() { + return serviceTimeoutSeconds > 0 ? serviceTimeoutSeconds : Integer.MAX_VALUE; + } + + /** + * 获取服务方法超时时间,单位是秒 + * + * @param method + * @param version + * @return 服务方法超时时间,单位是秒 + */ + private int getServiceMethodTimeout(String method, String version) { + ServiceMethodHandler serviceMethodHandler = ropContext.getServiceMethodHandler(method, version); + if (serviceMethodHandler == null) { + return getServiceTimeoutSeconds(); + } else { + int methodTimeout = serviceMethodHandler.getServiceMethodDefinition().getTimeout(); + if (methodTimeout <= 0) { + return getServiceTimeoutSeconds(); + } else { + return methodTimeout; + } + } + } + + /** + * 调用服务线程执行器 + */ + private class ServiceRunnable implements Runnable { + + private HttpServletRequest servletRequest; + private HttpServletResponse servletResponse; + private ThreadFerry threadFerry; + private RopRequestContext ropRequestContext; + + private ServiceRunnable(HttpServletRequest servletRequest, HttpServletResponse servletResponse, + ThreadFerry threadFerry) { + this.servletRequest = servletRequest; + this.servletResponse = servletResponse; + this.threadFerry = threadFerry; + } + + @Override + public void run() { + if (threadFerry != null) { + threadFerry.doInDestThread(); + } + Object ropRequest; + try { + // 用系统级参数构造一个RequestContext实例(第一阶段绑定) + ropRequestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest, servletResponse); + // 验证系统级参数的合法性 + MainError mainError = securityManager.validateSystemParameters(ropRequestContext); + if (mainError != null) { + ropRequestContext.setRopResponse(new ErrorResponse(mainError)); + return; + } + // 绑定业务数据(第二阶段绑定) + ropRequest = requestContextBuilder.buildRopRequest(ropRequestContext); + // 进行其它检查业务数据合法性,业务安全等 + mainError = securityManager.validateOther(ropRequestContext); + if (mainError != null) { + ropRequestContext.setRopResponse(new ErrorResponse(mainError)); + return; + } + firePreDoServiceEvent(ropRequestContext); + // 服务处理前拦截 + invokeBeforceServiceOfInterceptors(ropRequestContext); + if (ropRequestContext.getRopResponse() == null) { // 拦截器未生成response + // 如果拦截器没有产生ropResponse时才调用服务方法 + ropRequestContext.setRopResponse(doService(ropRequest, ropRequestContext)); + // 输出响应前拦截 + invokeBeforceResponseOfInterceptors(ropRequestContext); + } + } catch (Exception e) { + if (ropRequestContext != null) { + String method = ropRequestContext.getMethod(); + Locale locale = ropRequestContext.getLocale(); + if (logger.isDebugEnabled()) { + String message = java.text.MessageFormat.format("service {0} call error", method); + logger.debug(message, e); + } + ServiceUnavailableErrorResponse ropResponse = new ServiceUnavailableErrorResponse(method, locale, e); + // 输出响应前拦截 + invokeBeforceResponseOfInterceptors(ropRequestContext); + ropRequestContext.setRopResponse(ropResponse); + } else { + throw new RopException("RopRequestContext is null.", e); + } + } finally { + if (ropRequestContext != null) { + // 发布服务完成事件 + ropRequestContext.setServiceEndTime(System.currentTimeMillis()); + // 完成一次服务请求,计算次数 + invokeTimesController.caculateInvokeTimes(ropRequestContext.getAppKey(), ropRequestContext.getSession()); + fireAfterDoServiceEvent(ropRequestContext); + } + } + } + + /** + * 调用服务方法实例 + * @param ropRequest + * @param context + * @return 服务方法输出消息对象 + */ + private Object doService(Object ropRequest, RopRequestContext context) { + Object ropResponse; + String method = context.getMethod(); + Locale locale = context.getLocale(); + if (method == null) { + String methodKey = SystemParameterNames.getMethod(); + MainError error = MainErrors.getError(MainErrorType.MISSING_METHOD, locale, methodKey); + ropResponse = new ErrorResponse(error); + } else if (!ropContext.isValidMethod(method)) { + MainError invalidMethodError = MainErrors.getError(MainErrorType.INVALID_METHOD, locale, method); + ropResponse = new ErrorResponse(invalidMethodError); + } else { + try { + ropResponse = serviceMethodAdapter.invokeServiceMethod(ropRequest, context); + } catch (Exception e) { // 出错则导致服务不可用的异常 + if (logger.isInfoEnabled()) { + logger.info("调用" + context.getMethod() + "时发生异常,异常信息为:" + e.getMessage()); + } + ropResponse = new ServiceUnavailableErrorResponse(method, locale, e); + } + } + return ropResponse; + } + + private void firePreDoServiceEvent(RopRequestContext ropRequestContext) { + ropEventMulticaster.multicastEvent(new PreDoServiceEvent(this, ropRequestContext)); + } + + /** + * 在服务调用之后,返回响应之前拦截 + * + * @param ropRequest + */ + private void invokeBeforceResponseOfInterceptors(RopRequestContext context) { + Interceptor tempInterceptor = null; + try { + if (interceptors != null && interceptors.isEmpty()) { + for (Interceptor interceptor : interceptors) { + tempInterceptor = interceptor; + interceptor.beforeResponse(context); + } + } + } catch (Exception e) { + context.setRopResponse(new ServiceUnavailableErrorResponse(context.getMethod(), context.getLocale(), e)); + if (tempInterceptor != null) { + logger.error("在执行拦截器[" + tempInterceptor.getClass().getName() + "]时发生异常.", e); + } + } + } + + /** + * 在服务调用之前拦截 + * + * @param ropRequestContext + */ + private void invokeBeforceServiceOfInterceptors(RopRequestContext ropRequestContext) { + ObjectHolder interceptorHolder = new ObjectHolder(); + try { + if (interceptors != null && !interceptors.isEmpty()) { + invokeInterceptors(interceptors, ropRequestContext, interceptorHolder); + } + Interceptor tempInterceptor = interceptorHolder.get(); + if (tempInterceptor != null && ropRequestContext.getRopResponse() != null && logger.isDebugEnabled()) { + logger.debug("拦截器[" + tempInterceptor.getClass().getName() + "]产生了一个RopResponse," + " 阻止本次服务请求继续,服务将直接返回。"); + } + } catch (Exception e) { + String method = ropRequestContext.getMethod(); + Locale locale = ropRequestContext.getLocale(); + ropRequestContext.setRopResponse(new ServiceUnavailableErrorResponse(method, locale, e)); + Interceptor tempInterceptor = interceptorHolder.get(); + if(tempInterceptor != null){ + logger.error("在执行拦截器[" + tempInterceptor.getClass().getName() + "]时发生异常.", e); + } + } + } + + /** + * 调用服务拦截器 + * @param interceptors + * @param ropRequestContext + * @return 有输出消息的拦截器对象 + */ + private void invokeInterceptors(List interceptors, RopRequestContext ropRequestContext, ObjectHolder interceptorHolder) { + for (Interceptor interceptor : interceptors) { + interceptorHolder.set(interceptor); + interceptor.beforeService(ropRequestContext); + // 如果有一个产生了响应,则阻止后续的调用 + if (ropRequestContext.getRopResponse() != null) { + return; + } + } + } + } + + private class ObjectHolder { + + private T object; + + public T get(){ + return object; + } + + public void set(T object){ + this.object = object; + } + } + /** + * 当发生异常时,创建一个请求上下文对象 + * + * @param request + * @param beginTime + * @return + */ + private RopRequestContext buildRequestContextWhenException(HttpServletRequest request, long beginTime) { + RopRequestContext ropRequestContext = requestContextBuilder.buildBySysParams(ropContext, request, null); + ropRequestContext.setServiceBeginTime(beginTime); + ropRequestContext.setServiceEndTime(System.currentTimeMillis()); + return ropRequestContext; + } + + private RopContext buildRopContext() { + DefaultRopContext defaultRopContext = new DefaultRopContext(this.applicationContext); + defaultRopContext.setSignEnable(this.signEnable); + defaultRopContext.setSessionManager(sessionManager); + return defaultRopContext; + } + + private RopEventMulticaster buildRopEventMulticaster() { + SimpleRopEventMulticaster simpleRopEventMulticaster = new SimpleRopEventMulticaster(); + // 设置异步执行器 + if (threadPoolExecutor != null) { + simpleRopEventMulticaster.setExecutor(threadPoolExecutor); + } + // 添加事件监听器 + if (listeners != null && !listeners.isEmpty()) { + for (RopEventListener ropEventListener : listeners) { + simpleRopEventMulticaster.addRopListener(ropEventListener); + } + } + return simpleRopEventMulticaster; + } + + /** + * 发布Rop启动后事件 + */ + private void fireAfterStartedRopEvent() { + AfterStartedRopEvent ropEvent = new AfterStartedRopEvent(this, this.ropContext); + this.ropEventMulticaster.multicastEvent(ropEvent); + } + + /** + * 发布Rop启动后事件 + */ + private void fireBeforeCloseRopEvent() { + PreCloseRopEvent ropEvent = new PreCloseRopEvent(this, this.ropContext); + this.ropEventMulticaster.multicastEvent(ropEvent); + } + + private void fireAfterDoServiceEvent(RopRequestContext ropRequestContext) { + this.ropEventMulticaster.multicastEvent(new AfterDoServiceEvent(this, ropRequestContext)); + } + + /** + * 输出消息给服务调用方 + * @param ropResponse + * @param httpServletResponse + * @param messageFormat + * @param jsonpCallback + */ + private void writeResponse(Object ropResponse, HttpServletResponse httpServletResponse, MessageFormat messageFormat, + String jsonpCallback) { + try { + if (!(ropResponse instanceof ErrorResponse) && messageFormat == MessageFormat.STREAM) { + if (logger.isDebugEnabled()) { + logger.debug("使用{}输出方式,由服务自身负责响应输出工作.", MessageFormat.STREAM); + } + return; + } + RopMarshaller ropMarshaller = xmlMarshaller; + String contentType = APPLICATION_XML; + if (messageFormat == MessageFormat.JSON) { + ropMarshaller = jsonMarshaller; + contentType = APPLICATION_JSON; + } + httpServletResponse.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); + httpServletResponse.addHeader(ACCESS_CONTROL_ALLOW_METHODS, "*"); + httpServletResponse.setContentType(contentType); + + if (jsonpCallback != null) { + httpServletResponse.getOutputStream().write(jsonpCallback.getBytes()); + httpServletResponse.getOutputStream().write('('); + } + ropMarshaller.marshaller(ropResponse, httpServletResponse.getOutputStream()); + if (jsonpCallback != null) { + httpServletResponse.getOutputStream().write(')'); + httpServletResponse.getOutputStream().write(';'); + } + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 设置国际化资源信息 + */ + private void initMessageSource() { + HashSet baseNamesSet = new HashSet(); + baseNamesSet.add(I18N_ROP_ERROR);// ROP自动的资源 + + if (extErrorBasename == null && extErrorBasenames == null) { + baseNamesSet.add(DEFAULT_EXT_ERROR_BASE_NAME); + } else { + if (extErrorBasename != null) { + baseNamesSet.add(extErrorBasename); + } + if (extErrorBasenames != null) { + baseNamesSet.addAll(Arrays.asList(extErrorBasenames)); + } + } + String[] totalBaseNames = baseNamesSet.toArray(new String[0]); + + if (logger.isInfoEnabled()) { + logger.info("加载错误码国际化资源:{}", StringUtils.join(totalBaseNames, ",")); + } + ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource(); + bundleMessageSource.setBasenames(totalBaseNames); + MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(bundleMessageSource); + MainErrors.setErrorMessageSourceAccessor(messageSourceAccessor); + SubErrors.setErrorMessageSourceAccessor(messageSourceAccessor); + } + + public SecurityManager getSecurityManager() { + return securityManager; + } + + public FormattingConversionService getFormattingConversionService() { + return formattingConversionService; + } + + public ThreadPoolExecutor getThreadPoolExecutor() { + return threadPoolExecutor; + } + + public RopEventMulticaster getRopEventMulticaster() { + return ropEventMulticaster; + } + + public List getInterceptors() { + return interceptors; + } + + public List> getListeners() { + return listeners; + } + + public boolean isSignEnable() { + return signEnable; + } + + public ApplicationContext getApplicationContext() { + return applicationContext; + } + + public String getExtErrorBasename() { + return extErrorBasename; + } + + public void setServiceMethodAdapter(ServiceMethodAdapter serviceMethodAdapter) { + this.serviceMethodAdapter = serviceMethodAdapter; + } + + public void setXmlMarshaller(RopMarshaller xmlMarshaller) { + this.xmlMarshaller = xmlMarshaller; + } + + public void setJsonMarshaller(RopMarshaller jsonMarshaller) { + this.jsonMarshaller = jsonMarshaller; + } } \ No newline at end of file diff --git a/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouterFactoryBean.java b/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouterFactoryBean.java index ad4a139..feb0322 100644 --- a/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouterFactoryBean.java +++ b/rop/src/main/java/com/rop/impl/AnnotationServletServiceRouterFactoryBean.java @@ -1,295 +1,377 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-7 - */ -package com.rop.impl; - -import com.rop.Interceptor; -import com.rop.RopException; -import com.rop.ThreadFerry; -import com.rop.config.InterceptorHolder; -import com.rop.config.RopEventListenerHodler; -import com.rop.event.RopEventListener; -import com.rop.security.*; -import com.rop.session.SessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.format.support.FormattingConversionService; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import java.util.*; -import java.util.concurrent.ThreadPoolExecutor; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class AnnotationServletServiceRouterFactoryBean - implements FactoryBean,ApplicationContextAware, InitializingBean, DisposableBean{ - - private static final String ALL_FILE_TYPES = "*"; - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private ApplicationContext applicationContext; - - private ThreadPoolExecutor threadPoolExecutor; - - private SessionManager sessionManager; - - private AppSecretManager appSecretManager; - - private ServiceAccessController serviceAccessController; - - private InvokeTimesController invokeTimesController; - - private boolean signEnable = true; - - private String extErrorBasename; - - private String[] extErrorBasenames; - - private int serviceTimeoutSeconds = -1; - - private Class threadFerryClass = DumbThreadFerry.class; - - private FormattingConversionService formattingConversionService; - - private AnnotationServletServiceRouter serviceRouter; - - //多值用逗号分隔,默认支持4种格式的文件 - private String uploadFileTypes = ALL_FILE_TYPES; - - //单位为K,默认为10M - private int uploadFileMaxSize = 10 * 1024; - - - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - - - public void destroy() throws Exception { - serviceRouter.shutdown(); - } - - - public Class getObjectType() { - return AnnotationServletServiceRouter.class; - } - - - public AnnotationServletServiceRouter getObject() throws Exception { - return this.serviceRouter; - } - - - public boolean isSingleton() { - return true; - } - - public void setInvokeTimesController(InvokeTimesController invokeTimesController) { - this.invokeTimesController = invokeTimesController; - } - - public void setThreadFerryClass(Class threadFerryClass) { - this.threadFerryClass = threadFerryClass; - } - - public void setThreadFerryClassName(String threadFerryClassName) { - try { - if (StringUtils.hasText(threadFerryClassName)) { - Class threadFerryClass = - ClassUtils.forName(threadFerryClassName, getClass().getClassLoader()); - if (!ClassUtils.isAssignable(ThreadFerry.class, threadFerryClass)) { - throw new RopException(threadFerryClassName + "没有实现" - + ThreadFerry.class.getName() + "接口"); - } - this.threadFerryClass = (Class)threadFerryClass; - } - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - } - - - public void afterPropertiesSet() throws Exception { - //实例化一个AnnotationServletServiceRouter - serviceRouter = new AnnotationServletServiceRouter(); - - //设置国际化错误资源 - if (extErrorBasename != null) { - serviceRouter.setExtErrorBasename(extErrorBasename); - } - - if (extErrorBasenames != null) { - serviceRouter.setExtErrorBasenames(extErrorBasenames); - } - - DefaultSecurityManager securityManager = BeanUtils.instantiate(DefaultSecurityManager.class); - - securityManager.setSessionManager(sessionManager); - securityManager.setAppSecretManager(appSecretManager); - securityManager.setServiceAccessController(serviceAccessController); - securityManager.setInvokeTimesController(invokeTimesController); - securityManager.setFileUploadController(buildFileUploadController()); - - serviceRouter.setSecurityManager(securityManager); - serviceRouter.setThreadPoolExecutor(threadPoolExecutor); - serviceRouter.setSignEnable(signEnable); - serviceRouter.setServiceTimeoutSeconds(serviceTimeoutSeconds); - serviceRouter.setFormattingConversionService(formattingConversionService); - serviceRouter.setSessionManager(sessionManager); - serviceRouter.setThreadFerryClass(threadFerryClass); - serviceRouter.setInvokeTimesController(invokeTimesController); - - //注册拦截器 - ArrayList interceptors = getInterceptors(); - if (interceptors != null) { - for (Interceptor interceptor : interceptors) { - serviceRouter.addInterceptor(interceptor); - } - if (logger.isInfoEnabled()) { - logger.info("register total {} interceptors",interceptors.size()); - } - } - - //注册监听器 - ArrayList listeners = getListeners(); - if (listeners != null) { - for (RopEventListener listener : listeners) { - serviceRouter.addListener(listener); - } - if (logger.isInfoEnabled()) { - logger.info("register total {} listeners",listeners.size()); - } - } - - //设置Spring上下文信息 - serviceRouter.setApplicationContext(this.applicationContext); - - //启动之 - serviceRouter.startup(); - } - - private DefaultFileUploadController buildFileUploadController() { - Assert.notNull(this.uploadFileTypes, "Please set the updateFileTypes,if all,set *"); - if(ALL_FILE_TYPES.equals(uploadFileTypes.trim())){ - return new DefaultFileUploadController(this.uploadFileMaxSize); - }else { - String[] items = this.uploadFileTypes.split(","); - List fileTypes = Arrays.asList(items); - return new DefaultFileUploadController(fileTypes, this.uploadFileMaxSize); - } - } - - private ArrayList getInterceptors() { - Map interceptorMap = this.applicationContext.getBeansOfType(InterceptorHolder.class); - if (interceptorMap != null && interceptorMap.size() > 0) { - ArrayList interceptors = new ArrayList(interceptorMap.size()); - - //从Spring容器中获取Interceptor - for (InterceptorHolder interceptorHolder : interceptorMap.values()) { - interceptors.add(interceptorHolder.getInterceptor()); - } - - //根据getOrder()值排序 - Collections.sort(interceptors, new Comparator() { - public int compare(Interceptor o1, Interceptor o2) { - if (o1.getOrder() > o2.getOrder()) { - return 1; - } else if (o1.getOrder() < o2.getOrder()) { - return -1; - } else { - return 0; - } - } - }); - return interceptors; - } else { - return null; - } - } - - private ArrayList getListeners() { - Map listenerMap = this.applicationContext.getBeansOfType(RopEventListenerHodler.class); - if (listenerMap != null && listenerMap.size() > 0) { - ArrayList ropEventListeners = new ArrayList(listenerMap.size()); - - //从Spring容器中获取Interceptor - for (RopEventListenerHodler listenerHolder : listenerMap.values()) { - ropEventListeners.add(listenerHolder.getRopEventListener()); - } - return ropEventListeners; - } else { - return null; - } - } - - public void setFormattingConversionService(FormattingConversionService formattingConversionService) { - this.formattingConversionService = formattingConversionService; - } - - public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { - this.threadPoolExecutor = threadPoolExecutor; - } - - public void setSignEnable(boolean signEnable) { - this.signEnable = signEnable; - } - - public void setExtErrorBasename(String extErrorBasename) { - this.extErrorBasename = extErrorBasename; - } - - public void setExtErrorBasenames(String[] extErrorBasenames) { - this.extErrorBasenames = extErrorBasenames; - } - - public void setServiceTimeoutSeconds(int serviceTimeoutSeconds) { - this.serviceTimeoutSeconds = serviceTimeoutSeconds; - } - - public void setSessionManager(SessionManager sessionManager) { - this.sessionManager = sessionManager; - } - - public void setAppSecretManager(AppSecretManager appSecretManager) { - this.appSecretManager = appSecretManager; - } - - public void setServiceAccessController(ServiceAccessController serviceAccessController) { - this.serviceAccessController = serviceAccessController; - } - - public String getUploadFileTypes() { - return uploadFileTypes; - } - - public void setUploadFileTypes(String uploadFileTypes) { - this.uploadFileTypes = uploadFileTypes; - } - - public int getUploadFileMaxSize() { - return uploadFileMaxSize; - } - - public void setUploadFileMaxSize(int uploadFileMaxSize) { - this.uploadFileMaxSize = uploadFileMaxSize; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.Interceptor; +import com.rop.RopException; +import com.rop.RopMarshaller; +import com.rop.ServiceRouter; +import com.rop.ThreadFerry; +import com.rop.config.InterceptorHolder; +import com.rop.config.RopEventListenerHodler; +import com.rop.event.RopEvent; +import com.rop.event.RopEventListener; +import com.rop.security.*; +import com.rop.security.SecurityManager; +import com.rop.session.SessionManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +import java.util.*; +import java.util.concurrent.ThreadPoolExecutor; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class AnnotationServletServiceRouterFactoryBean + implements FactoryBean,ApplicationContextAware, InitializingBean, DisposableBean{ + + private static final String ALL_FILE_TYPES = "*"; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private ApplicationContext applicationContext; + + private ThreadPoolExecutor threadPoolExecutor; + + private SessionManager sessionManager; + + private AppSecretManager appSecretManager; + + private ServiceAccessController serviceAccessController; + + private InvokeTimesController invokeTimesController; + + private boolean signEnable = true; + + private String extErrorBasename; + + private String[] extErrorBasenames; + + private int serviceTimeoutSeconds = -1; + + private Class threadFerryClass = DumbThreadFerry.class; + + private FormattingConversionService formattingConversionService; + + private ServiceRouter serviceRouter; + + //多值用逗号分隔,默认支持4种格式的文件 + private String uploadFileTypes = ALL_FILE_TYPES; + + //单位为K,默认为10M + private int uploadFileMaxSize = 10 * 1024; + + private RopMarshaller xmlMarshaller; + + private RopMarshaller jsonMarshaller; + + private SecurityManager securityManager; + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + public void destroy() throws Exception { + serviceRouter.shutdown(); + } + + public Class getObjectType() { + return serviceRouter == null ? ServiceRouter.class : serviceRouter.getClass(); + } + + public ServiceRouter getObject() throws Exception { + return this.serviceRouter; + } + + public boolean isSingleton() { + return true; + } + + public void setInvokeTimesController(InvokeTimesController invokeTimesController) { + this.invokeTimesController = invokeTimesController; + } + + public void setThreadFerryClass(Class threadFerryClass) { + this.threadFerryClass = threadFerryClass; + } + + @SuppressWarnings("unchecked") + public void setThreadFerryClassName(String threadFerryClassName) { + try { + if (StringUtils.hasText(threadFerryClassName)) { + Class threadFerryClass = + ClassUtils.forName(threadFerryClassName, getClass().getClassLoader()); + if (!ClassUtils.isAssignable(ThreadFerry.class, threadFerryClass)) { + throw new RopException(threadFerryClassName + "没有实现" + + ThreadFerry.class.getName() + "接口"); + } + this.threadFerryClass = (Class)threadFerryClass; + } + } catch (ClassNotFoundException e) { + throw new IllegalArgumentException(e); + } + } + + public void afterPropertiesSet() throws Exception { + if(serviceRouter == null){ + serviceRouter = new AnnotationServletServiceRouter(); + } + //设置国际化错误资源 + if (extErrorBasename != null) { + serviceRouter.setExtErrorBasename(extErrorBasename); + } + if (extErrorBasenames != null) { + serviceRouter.setExtErrorBasenames(extErrorBasenames); + } + if(securityManager == null){ + securityManager = findOrCreateBean(SecurityManager.class, DefaultSecurityManager.class); + } + if(sessionManager == null){ + sessionManager = findBean(SessionManager.class); + } + if(sessionManager != null){ + securityManager.setSessionManager(sessionManager); + serviceRouter.setSessionManager(sessionManager); + } + if(appSecretManager == null){ + appSecretManager = findOrCreateBean(AppSecretManager.class, FileBaseAppSecretManager.class); + } + securityManager.setAppSecretManager(appSecretManager); + if(serviceAccessController == null){ + serviceAccessController = findOrCreateBean(ServiceAccessController.class, DefaultServiceAccessController.class); + } + securityManager.setServiceAccessController(serviceAccessController); + if(invokeTimesController == null){ + invokeTimesController = findOrCreateBean(InvokeTimesController.class, DefaultInvokeTimesController.class); + } + serviceRouter.setInvokeTimesController(invokeTimesController); + securityManager.setInvokeTimesController(invokeTimesController); + securityManager.setFileUploadController(buildFileUploadController()); + serviceRouter.setSecurityManager(securityManager); + serviceRouter.setThreadPoolExecutor(threadPoolExecutor); + serviceRouter.setSignEnable(signEnable); + serviceRouter.setServiceTimeoutSeconds(serviceTimeoutSeconds); + FormattingConversionService conversionService = getFormattingConversionService(); + if(conversionService != null){ + serviceRouter.setFormattingConversionService(conversionService); + } + serviceRouter.setThreadFerryClass(threadFerryClass); + if(jsonMarshaller != null){ + serviceRouter.setJsonMarshaller(jsonMarshaller); + } + if(xmlMarshaller != null){ + serviceRouter.setXmlMarshaller(xmlMarshaller); + } + //注册拦截器 + ArrayList interceptors = getInterceptors(); + if (interceptors != null) { + for (Interceptor interceptor : interceptors) { + serviceRouter.addInterceptor(interceptor); + } + if (logger.isInfoEnabled()) { + logger.info("register total {} interceptors",interceptors.size()); + } + } + //注册监听器 + ArrayList> listeners = getListeners(); + if (listeners != null) { + for (RopEventListener listener : listeners) { + serviceRouter.addListener(listener); + } + if (logger.isInfoEnabled()) { + logger.info("register total {} listeners",listeners.size()); + } + } + //设置Spring上下文信息 + serviceRouter.setApplicationContext(this.applicationContext); + //启动之 + serviceRouter.startup(); + } + + protected T findOrCreateBean(Class type, Class defaultType){ + T bean = findBean(type); + if(bean != null){ + return bean; + } + return BeanUtils.instantiate(defaultType == null ? type : defaultType); + } + + protected T findBean(Class type){ + Map map = applicationContext.getBeansOfType(type); + if(map != null && map.size() > 0){ + for(T obj : map.values()){ + return obj; + } + } + return null; + } + + private FileUploadController buildFileUploadController() { + FileUploadController uploadController = findBean(FileUploadController.class); + if(uploadController != null){ + return uploadController; + } + Assert.notNull(this.uploadFileTypes, "Please set the updateFileTypes,if all,set *"); + if(ALL_FILE_TYPES.equals(uploadFileTypes.trim())){ + return new DefaultFileUploadController(this.uploadFileMaxSize); + }else { + String[] items = this.uploadFileTypes.split(","); + List fileTypes = Arrays.asList(items); + return new DefaultFileUploadController(fileTypes, this.uploadFileMaxSize); + } + } + + protected FormattingConversionService getFormattingConversionService(){ + if(formattingConversionService != null){ + return formattingConversionService; + } + formattingConversionService = findBean(FormattingConversionService.class); + if(formattingConversionService != null){ + return formattingConversionService; + } + return null; + } + + private ArrayList getInterceptors() { + Map interceptorMap = this.applicationContext.getBeansOfType(InterceptorHolder.class); + if (interceptorMap != null && interceptorMap.size() > 0) { + ArrayList interceptors = new ArrayList(interceptorMap.size()); + + //从Spring容器中获取Interceptor + for (InterceptorHolder interceptorHolder : interceptorMap.values()) { + interceptors.add(interceptorHolder.getInterceptor()); + } + + //根据getOrder()值排序 + Collections.sort(interceptors, new Comparator() { + public int compare(Interceptor o1, Interceptor o2) { + if (o1.getOrder() > o2.getOrder()) { + return 1; + } else if (o1.getOrder() < o2.getOrder()) { + return -1; + } else { + return 0; + } + } + }); + return interceptors; + } else { + return null; + } + } + + private ArrayList> getListeners() { + Map listenerMap = this.applicationContext.getBeansOfType(RopEventListenerHodler.class); + if (listenerMap != null && listenerMap.size() > 0) { + ArrayList> ropEventListeners = new ArrayList>(listenerMap.size()); + + //从Spring容器中获取Interceptor + for (RopEventListenerHodler listenerHolder : listenerMap.values()) { + ropEventListeners.add(listenerHolder.getRopEventListener()); + } + return ropEventListeners; + } else { + return null; + } + } + + public void setFormattingConversionService(FormattingConversionService formattingConversionService) { + this.formattingConversionService = formattingConversionService; + } + + public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) { + this.threadPoolExecutor = threadPoolExecutor; + } + + public void setSignEnable(boolean signEnable) { + this.signEnable = signEnable; + } + + public void setExtErrorBasename(String extErrorBasename) { + this.extErrorBasename = extErrorBasename; + } + + public void setExtErrorBasenames(String[] extErrorBasenames) { + this.extErrorBasenames = extErrorBasenames; + } + + public void setServiceTimeoutSeconds(int serviceTimeoutSeconds) { + this.serviceTimeoutSeconds = serviceTimeoutSeconds; + } + + public void setSessionManager(SessionManager sessionManager) { + this.sessionManager = sessionManager; + } + + public void setAppSecretManager(AppSecretManager appSecretManager) { + this.appSecretManager = appSecretManager; + } + + public void setServiceAccessController(ServiceAccessController serviceAccessController) { + this.serviceAccessController = serviceAccessController; + } + + public String getUploadFileTypes() { + return uploadFileTypes; + } + + public void setUploadFileTypes(String uploadFileTypes) { + this.uploadFileTypes = uploadFileTypes; + } + + public int getUploadFileMaxSize() { + return uploadFileMaxSize; + } + + public void setUploadFileMaxSize(int uploadFileMaxSize) { + this.uploadFileMaxSize = uploadFileMaxSize; + } + + public void setXmlMarshaller(RopMarshaller xmlMarshaller) { + this.xmlMarshaller = xmlMarshaller; + } + + public void setJsonMarshaller(RopMarshaller jsonMarshaller) { + this.jsonMarshaller = jsonMarshaller; + } + + public void setServiceRouter(ServiceRouter serviceRouter) { + this.serviceRouter = serviceRouter; + } + + public void setSecurityManager(SecurityManager securityManager) { + this.securityManager = securityManager; + } +} + diff --git a/rop/src/main/java/com/rop/impl/DefaultRopContext.java b/rop/src/main/java/com/rop/impl/DefaultRopContext.java index 6414844..8ccaf27 100644 --- a/rop/src/main/java/com/rop/impl/DefaultRopContext.java +++ b/rop/src/main/java/com/rop/impl/DefaultRopContext.java @@ -1,314 +1,310 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop.impl; - -import com.rop.*; -import com.rop.annotation.*; -import com.rop.config.SystemParameterNames; -import com.rop.request.UploadFile; -import com.rop.session.SessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.core.annotation .AnnotationUtils; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.*; - -/** - *
- *    ROP框架的上下文
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultRopContext implements RopContext { - - protected static Logger logger = LoggerFactory.getLogger(DefaultRopContext.class); - - private final Map serviceHandlerMap = new HashMap(); - - private final Set serviceMethods = new HashSet(); - - private boolean signEnable; - - private SessionManager sessionManager; - - public DefaultRopContext(ApplicationContext context) { - registerFromContext(context); - } - - - public void addServiceMethod(String methodName, String version, ServiceMethodHandler serviceMethodHandler) { - serviceMethods.add(methodName); - serviceHandlerMap.put(ServiceMethodHandler.methodWithVersion(methodName, version), serviceMethodHandler); - } - - - public ServiceMethodHandler getServiceMethodHandler(String methodName, String version) { - return serviceHandlerMap.get(ServiceMethodHandler.methodWithVersion(methodName, version)); - } - - - - public boolean isValidMethod(String methodName) { - return serviceMethods.contains(methodName); - } - - - public boolean isValidVersion(String methodName, String version) { - return serviceHandlerMap.containsKey(ServiceMethodHandler.methodWithVersion(methodName, version)); - } - - - public boolean isVersionObsoleted(String methodName, String version) { - return false; //To change body of implemented methods use File | Settings | File Templates. - } - - - public Map getAllServiceMethodHandlers() { - return serviceHandlerMap; - } - - - public boolean isSignEnable() { - return signEnable; - } - - - public SessionManager getSessionManager() { - return this.sessionManager; - } - - public void setSessionManager(SessionManager sessionManager) { - this.sessionManager = sessionManager; - } - - public void setSignEnable(boolean signEnable) { - this.signEnable = signEnable; - } - - /** - * 扫描Spring容器中的Bean,查找有标注{@link ServiceMethod}注解的服务方法,将它们注册到{@link RopContext}中缓存起来。 - * - * @throws org.springframework.beans.BeansException - * - */ - private void registerFromContext(final ApplicationContext context) throws BeansException { - if (logger.isDebugEnabled()) { - logger.debug("对Spring上下文中的Bean进行扫描,查找ROP服务方法: " + context); - } - String[] beanNames = context.getBeanNamesForType(Object.class); - for (final String beanName : beanNames) { - Class handlerType = context.getType(beanName); - //只对标注 ServiceMethodBean的Bean进行扫描 - if(AnnotationUtils.findAnnotation(handlerType,ServiceMethodBean.class) != null){ - ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - ReflectionUtils.makeAccessible(method); - - ServiceMethod serviceMethod = AnnotationUtils.findAnnotation(method,ServiceMethod.class); - ServiceMethodBean serviceMethodBean =AnnotationUtils.findAnnotation(method.getDeclaringClass(),ServiceMethodBean.class); - - ServiceMethodDefinition definition = null; - if (serviceMethodBean != null) { - definition = buildServiceMethodDefinition(serviceMethodBean, serviceMethod); - } else { - definition = buildServiceMethodDefinition(serviceMethod); - } - ServiceMethodHandler serviceMethodHandler = new ServiceMethodHandler(); - serviceMethodHandler.setServiceMethodDefinition(definition); - - //1.set handler - serviceMethodHandler.setHandler(context.getBean(beanName)); //handler - serviceMethodHandler.setHandlerMethod(method); //handler'method - - - if (method.getParameterTypes().length > 1) {//handler method's parameter - throw new RopException(method.getDeclaringClass().getName() + "." + method.getName() - + "的入参只能是" + RopRequest.class.getName() + "或无入参。"); - } else if (method.getParameterTypes().length == 1) { - Class paramType = method.getParameterTypes()[0]; - if (!ClassUtils.isAssignable(RopRequest.class, paramType)) { - throw new RopException(method.getDeclaringClass().getName() + "." + method.getName() - + "的入参必须是" + RopRequest.class.getName()); - } - boolean ropRequestImplType = !(paramType.isAssignableFrom(RopRequest.class) || - paramType.isAssignableFrom(AbstractRopRequest.class)); - serviceMethodHandler.setRopRequestImplType(ropRequestImplType); - serviceMethodHandler.setRequestType((Class) paramType); - } else { - logger.info(method.getDeclaringClass().getName() + "." + method.getName() + "无入参"); - } - - //2.set sign fieldNames - serviceMethodHandler.setIgnoreSignFieldNames(getIgnoreSignFieldNames(serviceMethodHandler.getRequestType())); - - //3.set fileItemFieldNames - serviceMethodHandler.setUploadFileFieldNames(getFileItemFieldNames(serviceMethodHandler.getRequestType())); - - addServiceMethod(definition.getMethod(), definition.getVersion(), serviceMethodHandler); - - if (logger.isDebugEnabled()) { - logger.debug("注册服务方法:" + method.getDeclaringClass().getCanonicalName() + - "#" + method.getName() + "(..)"); - } - } - }, - new ReflectionUtils.MethodFilter() { - public boolean matches(Method method) { - return !method.isSynthetic() && AnnotationUtils.findAnnotation(method, ServiceMethod.class) != null; - } - } - ); - } - } - if (context.getParent() != null) { - registerFromContext(context.getParent()); - } - if (logger.isInfoEnabled()) { - logger.info("共注册了" + serviceHandlerMap.size() + "个服务方法"); - } - } - - private ServiceMethodDefinition buildServiceMethodDefinition(ServiceMethod serviceMethod) { - ServiceMethodDefinition definition = new ServiceMethodDefinition(); - definition.setMethod(serviceMethod.method()); - definition.setMethodTitle(serviceMethod.title()); - definition.setMethodGroup(serviceMethod.group()); - definition.setMethodGroupTitle(serviceMethod.groupTitle()); - definition.setTags(serviceMethod.tags()); - definition.setTimeout(serviceMethod.timeout()); - definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethod.ignoreSign())); - definition.setVersion(serviceMethod.version()); - definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethod.needInSession())); - definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethod.obsoleted())); - definition.setHttpAction(serviceMethod.httpAction()); - return definition; - } - - private ServiceMethodDefinition buildServiceMethodDefinition(ServiceMethodBean serviceMethodBean, ServiceMethod serviceMethod) { - ServiceMethodDefinition definition = new ServiceMethodDefinition(); - definition.setMethodGroup(serviceMethodBean.group()); - definition.setMethodGroupTitle(serviceMethodBean.groupTitle()); - definition.setTags(serviceMethodBean.tags()); - definition.setTimeout(serviceMethodBean.timeout()); - definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethodBean.ignoreSign())); - definition.setVersion(serviceMethodBean.version()); - definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethodBean.needInSession())); - definition.setHttpAction(serviceMethodBean.httpAction()); - definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethodBean.obsoleted())); - - //如果ServiceMethod所提供的值和ServiceMethodGroup不一样,覆盖之 - definition.setMethod(serviceMethod.method()); - definition.setMethodTitle(serviceMethod.title()); - - if (!ServiceMethodDefinition.DEFAULT_GROUP.equals(serviceMethod.group())) { - definition.setMethodGroup(serviceMethod.group()); - } - - if (!ServiceMethodDefinition.DEFAULT_GROUP_TITLE.equals(serviceMethod.groupTitle())) { - definition.setMethodGroupTitle(serviceMethod.groupTitle()); - } - - if (serviceMethod.tags() != null && serviceMethod.tags().length > 0) { - definition.setTags(serviceMethod.tags()); - } - - if (serviceMethod.timeout() > 0) { - definition.setTimeout(serviceMethod.timeout()); - } - - if (serviceMethod.ignoreSign() != IgnoreSignType.DEFAULT) { - definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethod.ignoreSign())); - } - - if (StringUtils.hasText(serviceMethod.version())) { - definition.setVersion(serviceMethod.version()); - } - - if (serviceMethod.needInSession() != NeedInSessionType.DEFAULT) { - definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethod.needInSession())); - } - - if (serviceMethod.obsoleted() != ObsoletedType.DEFAULT) { - definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethod.obsoleted())); - } - - if (serviceMethod.httpAction().length > 0) { - definition.setHttpAction(serviceMethod.httpAction()); - } - - return definition; - } - - public static List getIgnoreSignFieldNames(Class requestType) { - final ArrayList igoreSignFieldNames = new ArrayList(1); - igoreSignFieldNames.add(SystemParameterNames.getSign()); - if (requestType != null) { - if (logger.isDebugEnabled()) { - logger.debug("获取" + requestType.getCanonicalName() + "不需要签名的属性"); - } - ReflectionUtils.doWithFields(requestType, new ReflectionUtils.FieldCallback() { - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - igoreSignFieldNames.add(field.getName()); - } - }, - new ReflectionUtils.FieldFilter() { - public boolean matches(Field field) { - - //属性类标注了@IgnoreSign - IgnoreSign typeIgnore = AnnotationUtils.findAnnotation(field.getType(), IgnoreSign.class); - - //属性定义处标注了@IgnoreSign - IgnoreSign varIgnoreSign = field.getAnnotation(IgnoreSign.class); - - //属性定义处标注了@Temporary - Temporary varTemporary = field.getAnnotation(Temporary.class); - - return typeIgnore != null || varIgnoreSign != null || varTemporary != null; - } - } - ); - if (igoreSignFieldNames.size() > 1 && logger.isDebugEnabled()) { - logger.debug(requestType.getCanonicalName() + "不需要签名的属性:" + igoreSignFieldNames.toString()); - } - } - return igoreSignFieldNames; - } - - private List getFileItemFieldNames(Class requestType) { - final ArrayList fileItemFieldNames = new ArrayList(1); - if (requestType != null) { - if (logger.isDebugEnabled()) { - logger.debug("获取" + requestType.getCanonicalName() + "类型为FileItem的字段名"); - } - - ReflectionUtils.doWithFields(requestType, new ReflectionUtils.FieldCallback() { - public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { - fileItemFieldNames.add(field.getName()); - } - }, - new ReflectionUtils.FieldFilter() { - public boolean matches(Field field) { - return ClassUtils.isAssignable(UploadFile.class, field.getType()); - } - } - ); - - } - return fileItemFieldNames; - } - - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.*; +import com.rop.annotation.*; +import com.rop.config.SystemParameterNames; +import com.rop.converter.UploadFile; +import com.rop.session.SessionManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.*; + +/** + *
+ *    ROP框架的上下文
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultRopContext implements RopContext { + + protected static Logger logger = LoggerFactory.getLogger(DefaultRopContext.class); + + private final Map serviceHandlerMap = new HashMap(); + + private final Set serviceMethods = new HashSet(); + + private boolean signEnable; + + private SessionManager sessionManager; + + public DefaultRopContext(ApplicationContext context) { + registerFromContext(context); + } + + public void addServiceMethod(String methodName, String version, ServiceMethodHandler serviceMethodHandler) { + serviceMethods.add(methodName); + serviceHandlerMap.put(ServiceMethodHandler.methodWithVersion(methodName, version), serviceMethodHandler); + } + + public ServiceMethodHandler getServiceMethodHandler(String methodName, String version) { + return serviceHandlerMap.get(ServiceMethodHandler.methodWithVersion(methodName, version)); + } + + public boolean isValidMethod(String methodName) { + return serviceMethods.contains(methodName); + } + + public boolean isValidVersion(String methodName, String version) { + return serviceHandlerMap.containsKey(ServiceMethodHandler.methodWithVersion(methodName, version)); + } + + public boolean isVersionObsoleted(String methodName, String version) { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + public Map getAllServiceMethodHandlers() { + return serviceHandlerMap; + } + + public boolean isSignEnable() { + return signEnable; + } + + public SessionManager getSessionManager() { + return this.sessionManager; + } + + public void setSessionManager(SessionManager sessionManager) { + this.sessionManager = sessionManager; + } + + public void setSignEnable(boolean signEnable) { + this.signEnable = signEnable; + } + + /** + * 扫描Spring容器中的Bean,查找有标注{@link ServiceMethod}注解的服务方法,将它们注册到{@link RopContext}中缓存起来。 + * + * @throws org.springframework.beans.BeansException + * + */ + private void registerFromContext(final ApplicationContext context) throws BeansException { + if (logger.isDebugEnabled()) { + logger.debug("对Spring上下文中的Bean进行扫描,查找ROP服务方法: " + context); + } + String[] beanNames = context.getBeanNamesForType(Object.class); + for (final String beanName : beanNames) { + Class handlerType = context.getType(beanName); + //只对标注 ServiceMethodBean的Bean进行扫描 + if(AnnotationUtils.findAnnotation(handlerType,ServiceMethodBean.class) != null){ + ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { + public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { + ReflectionUtils.makeAccessible(method); + + ServiceMethod serviceMethod = AnnotationUtils.findAnnotation(method,ServiceMethod.class); + ServiceMethodBean serviceMethodBean =AnnotationUtils.findAnnotation(method.getDeclaringClass(),ServiceMethodBean.class); + + ServiceMethodDefinition definition = null; + if (serviceMethodBean != null) { + definition = buildServiceMethodDefinition(serviceMethodBean, serviceMethod); + } else { + definition = buildServiceMethodDefinition(serviceMethod); + } + ServiceMethodHandler serviceMethodHandler = new ServiceMethodHandler(); + serviceMethodHandler.setServiceMethodDefinition(definition); + + //1.set handler + serviceMethodHandler.setHandler(context.getBean(beanName)); //handler + serviceMethodHandler.setHandlerMethod(method); //handler'method + Class[] classes = method.getParameterTypes(); + List list = new ArrayList(); + List fileFields = new ArrayList(); + if(classes.length > 0){ + for(Class clazz : classes){ + List ignores = getIgnoreSignFieldNames(clazz); + List fileFieldNames = getFileItemFieldNames(clazz); + if(ignores != null && ignores.size() > 0){ + list.addAll(ignores); + } + if(fileFieldNames != null && fileFieldNames.size() > 0){ + fileFields.addAll(fileFieldNames); + } + } + } + //2.set sign fieldNames + serviceMethodHandler.setIgnoreSignFieldNames(list); + //3.set fileItemFieldNames + serviceMethodHandler.setUploadFileFieldNames(fileFields); + addServiceMethod(definition.getMethod(), definition.getVersion(), serviceMethodHandler); + if (logger.isDebugEnabled()) { + logger.debug("注册服务方法:" + method.getDeclaringClass().getCanonicalName() + + "#" + method.getName() + "(..)"); + } + } + }, + new ReflectionUtils.MethodFilter() { + public boolean matches(Method method) { + return !method.isSynthetic() && AnnotationUtils.findAnnotation(method, ServiceMethod.class) != null; + } + } + ); + } + } + if (context.getParent() != null) { + registerFromContext(context.getParent()); + } + if (logger.isInfoEnabled()) { + logger.info("共注册了" + serviceHandlerMap.size() + "个服务方法"); + } + } + + private ServiceMethodDefinition buildServiceMethodDefinition(ServiceMethod serviceMethod) { + ServiceMethodDefinition definition = new ServiceMethodDefinition(); + definition.setMethod(serviceMethod.method()); + definition.setMethodTitle(serviceMethod.title()); + definition.setMethodGroup(serviceMethod.group()); + definition.setMethodGroupTitle(serviceMethod.groupTitle()); + definition.setTags(serviceMethod.tags()); + definition.setTimeout(serviceMethod.timeout()); + definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethod.ignoreSign())); + definition.setVersion(serviceMethod.version()); + definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethod.needInSession())); + definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethod.obsoleted())); + definition.setHttpAction(serviceMethod.httpAction()); + return definition; + } + + private ServiceMethodDefinition buildServiceMethodDefinition(ServiceMethodBean serviceMethodBean, ServiceMethod serviceMethod) { + ServiceMethodDefinition definition = new ServiceMethodDefinition(); + definition.setMethodGroup(serviceMethodBean.group()); + definition.setMethodGroupTitle(serviceMethodBean.groupTitle()); + definition.setTags(serviceMethodBean.tags()); + definition.setTimeout(serviceMethodBean.timeout()); + definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethodBean.ignoreSign())); + definition.setVersion(serviceMethodBean.version()); + definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethodBean.needInSession())); + definition.setHttpAction(serviceMethodBean.httpAction()); + definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethodBean.obsoleted())); + + //如果ServiceMethod所提供的值和ServiceMethodGroup不一样,覆盖之 + definition.setMethod(serviceMethod.method()); + definition.setMethodTitle(serviceMethod.title()); + + if (!ServiceMethodDefinition.DEFAULT_GROUP.equals(serviceMethod.group())) { + definition.setMethodGroup(serviceMethod.group()); + } + + if (!ServiceMethodDefinition.DEFAULT_GROUP_TITLE.equals(serviceMethod.groupTitle())) { + definition.setMethodGroupTitle(serviceMethod.groupTitle()); + } + + if (serviceMethod.tags() != null && serviceMethod.tags().length > 0) { + definition.setTags(serviceMethod.tags()); + } + + if (serviceMethod.timeout() > 0) { + definition.setTimeout(serviceMethod.timeout()); + } + + if (serviceMethod.ignoreSign() != IgnoreSignType.DEFAULT) { + definition.setIgnoreSign(IgnoreSignType.isIgnoreSign(serviceMethod.ignoreSign())); + } + + if (StringUtils.hasText(serviceMethod.version())) { + definition.setVersion(serviceMethod.version()); + } + + if (serviceMethod.needInSession() != NeedInSessionType.DEFAULT) { + definition.setNeedInSession(NeedInSessionType.isNeedInSession(serviceMethod.needInSession())); + } + + if (serviceMethod.obsoleted() != ObsoletedType.DEFAULT) { + definition.setObsoleted(ObsoletedType.isObsoleted(serviceMethod.obsoleted())); + } + + if (serviceMethod.httpAction().length > 0) { + definition.setHttpAction(serviceMethod.httpAction()); + } + + return definition; + } + + public List getIgnoreSignFieldNames(Class requestType) { + final ArrayList igoreSignFieldNames = new ArrayList(1); + igoreSignFieldNames.add(SystemParameterNames.getSign()); + igoreSignFieldNames.add(SystemParameterNames.getJsonp()); + if (requestType != null) { + if (logger.isDebugEnabled()) { + logger.debug("获取" + requestType.getCanonicalName() + "不需要签名的属性"); + } + ReflectionUtils.doWithFields(requestType, new ReflectionUtils.FieldCallback() { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + igoreSignFieldNames.add(field.getName()); + } + }, + new ReflectionUtils.FieldFilter() { + public boolean matches(Field field) { + + //属性类标注了@IgnoreSign + IgnoreSign typeIgnore = AnnotationUtils.findAnnotation(field.getType(), IgnoreSign.class); + + //属性定义处标注了@IgnoreSign + IgnoreSign varIgnoreSign = field.getAnnotation(IgnoreSign.class); + + //属性定义处标注了@Temporary + Temporary varTemporary = field.getAnnotation(Temporary.class); + + return typeIgnore != null || varIgnoreSign != null || varTemporary != null; + } + } + ); + if (igoreSignFieldNames.size() > 1 && logger.isDebugEnabled()) { + logger.debug(requestType.getCanonicalName() + "不需要签名的属性:" + igoreSignFieldNames.toString()); + } + } + return igoreSignFieldNames; + } + + private List getFileItemFieldNames(Class requestType) { + final ArrayList fileItemFieldNames = new ArrayList(1); + if (requestType != null) { + if (logger.isDebugEnabled()) { + logger.debug("获取" + requestType.getCanonicalName() + "类型为FileItem的字段名"); + } + + ReflectionUtils.doWithFields(requestType, new ReflectionUtils.FieldCallback() { + public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { + fileItemFieldNames.add(field.getName()); + } + }, + new ReflectionUtils.FieldFilter() { + public boolean matches(Field field) { + return ClassUtils.isAssignable(UploadFile.class, field.getType()); + } + } + ); + + } + return fileItemFieldNames; + } + + +} + diff --git a/rop/src/main/java/com/rop/impl/DefaultServiceAccessController.java b/rop/src/main/java/com/rop/impl/DefaultServiceAccessController.java index 1ad08a0..ad90a3d 100644 --- a/rop/src/main/java/com/rop/impl/DefaultServiceAccessController.java +++ b/rop/src/main/java/com/rop/impl/DefaultServiceAccessController.java @@ -1,30 +1,41 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop.impl; - -import com.rop.security.ServiceAccessController; -import com.rop.session.Session; - -/** - *
- * 功能说明:对调用的方法进行安全性检查
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultServiceAccessController implements ServiceAccessController { - - - public boolean isAppGranted(String appKey, String method, String version) { - return true; - } - - - public boolean isUserGranted(Session session, String method, String version) { - return true; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.security.ServiceAccessController; +import com.rop.session.Session; + +/** + *
+ * 功能说明:对调用的方法进行安全性检查
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultServiceAccessController implements ServiceAccessController { + + + public boolean isAppGranted(String appKey, String method, String version) { + return true; + } + + + public boolean isUserGranted(Session session, String method, String version) { + return true; + } +} + diff --git a/rop/src/main/java/com/rop/impl/DumbThreadFerry.java b/rop/src/main/java/com/rop/impl/DumbThreadFerry.java index 6df1c4e..7256dec 100644 --- a/rop/src/main/java/com/rop/impl/DumbThreadFerry.java +++ b/rop/src/main/java/com/rop/impl/DumbThreadFerry.java @@ -1,22 +1,33 @@ -/** - * 版权声明: 版权所有 违者必究 2014 - * 日 期:14-2-12 - */ -package com.rop.impl; - -import com.rop.ThreadFerry; - -/** - * 不进行任何操作的实现类,仅为方便逻辑的运行 - * @author : chenxh(quickselect@163.com) - * @date: 14-2-12 - */ -public class DumbThreadFerry implements ThreadFerry { - - public void doInSrcThread() { - } - - - public void doInDestThread() { - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.ThreadFerry; + +/** + * 不进行任何操作的实现类,仅为方便逻辑的运行 + * @author : chenxh(quickselect@163.com) + * @date: 14-2-12 + */ +public class DumbThreadFerry implements ThreadFerry { + + public void doInSrcThread() { + } + + + public void doInDestThread() { + } +} diff --git a/rop/src/main/java/com/rop/impl/ServletRequestContextBuilder.java b/rop/src/main/java/com/rop/impl/ServletRequestContextBuilder.java index 0d84b95..3c1ca9c 100644 --- a/rop/src/main/java/com/rop/impl/ServletRequestContextBuilder.java +++ b/rop/src/main/java/com/rop/impl/ServletRequestContextBuilder.java @@ -1,244 +1,259 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-1 - */ -package com.rop.impl; - -import com.rop.*; -import com.rop.annotation.HttpAction; -import com.rop.config.SystemParameterNames; -import com.rop.security.MainErrorType; -import com.rop.security.MainErrors; -import com.rop.session.SessionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.propertyeditors.LocaleEditor; -import org.springframework.format.support.FormattingConversionService; -import org.springframework.util.StringUtils; -import org.springframework.validation.BindingResult; -import org.springframework.validation.ObjectError; -import org.springframework.validation.Validator; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import org.springframework.web.bind.ServletRequestDataBinder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -/** - *
- *    构建{@link com.rop.RopRequestContext}实例
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ServletRequestContextBuilder implements RequestContextBuilder { - - //通过前端的负载均衡服务器时,请求对象中的IP会变成负载均衡服务器的IP,因此需要特殊处理,下同。 - public static final String X_REAL_IP = "X-Real-IP"; - - public static final String X_FORWARDED_FOR = "X-Forwarded-For"; - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private FormattingConversionService conversionService; - - private Validator validator; - - public ServletRequestContextBuilder(FormattingConversionService conversionService) { - this.conversionService = conversionService; - } - - - public SimpleRopRequestContext buildBySysParams(RopContext ropContext, - Object request, - Object response) { - if (!(request instanceof HttpServletRequest)) { - throw new IllegalArgumentException("请求对象必须是HttpServletRequest的类型"); - } - if(response != null && !(response instanceof HttpServletResponse)){ - throw new IllegalArgumentException("请求对象必须是HttpServletResponse的类型"); - } - - HttpServletRequest servletRequest = (HttpServletRequest) request; - SimpleRopRequestContext requestContext = new SimpleRopRequestContext(ropContext); - - //设置请求对象及参数列表 - requestContext.setRawRequestObject(servletRequest); - if (response != null) { - requestContext.setRawResponseObject(response); - } - requestContext.setAllParams(getRequestParams(servletRequest)); - requestContext.setIp(getRemoteAddr(servletRequest)); //感谢melin所指出的BUG - - //设置服务的系统级参数 - requestContext.setAppKey(servletRequest.getParameter(SystemParameterNames.getAppKey())); - requestContext.setSessionId(servletRequest.getParameter(SystemParameterNames.getSessionId())); - requestContext.setMethod(servletRequest.getParameter(SystemParameterNames.getMethod())); - requestContext.setVersion(servletRequest.getParameter(SystemParameterNames.getVersion())); - requestContext.setLocale(getLocale(servletRequest)); - requestContext.setFormat(getFormat(servletRequest)); - requestContext.setMessageFormat(getResponseFormat(servletRequest)); - requestContext.setSign(servletRequest.getParameter(SystemParameterNames.getSign())); - requestContext.setHttpAction(HttpAction.fromValue(servletRequest.getMethod())); - - //设置服务处理器 - ServiceMethodHandler serviceMethodHandler = - ropContext.getServiceMethodHandler(requestContext.getMethod(), requestContext.getVersion()); - requestContext.setServiceMethodHandler(serviceMethodHandler); - - return requestContext; - } - - private String getRemoteAddr(HttpServletRequest request) { - String remoteIp = request.getHeader(X_REAL_IP); //nginx反向代理 - if (StringUtils.hasText(remoteIp)) { - return remoteIp; - } else { - remoteIp = request.getHeader(X_FORWARDED_FOR);//apache反射代理 - if (StringUtils.hasText(remoteIp)) { - String[] ips = remoteIp.split(","); - for (String ip : ips) { - if (!"null".equalsIgnoreCase(ip)) { - return ip; - } - } - } - return request.getRemoteAddr(); - } - } - - /** - * 将{@link HttpServletRequest}的数据绑定到{@link com.rop.RopRequestContext}的{@link com.rop.RopRequest}中,同时使用 - * JSR 303对请求数据进行校验,将错误信息设置到{@link com.rop.RopRequestContext}的属性列表中。 - * - * @param ropRequestContext - */ - - public RopRequest buildRopRequest(RopRequestContext ropRequestContext) { - AbstractRopRequest ropRequest = null; - if (ropRequestContext.getServiceMethodHandler().isRopRequestImplType()) { - HttpServletRequest request = - (HttpServletRequest) ropRequestContext.getRawRequestObject(); - BindingResult bindingResult = doBind(request, ropRequestContext.getServiceMethodHandler().getRequestType()); - ropRequest = buildRopRequestFromBindingResult(ropRequestContext, bindingResult); - - List allErrors = bindingResult.getAllErrors(); - ropRequestContext.setAttribute(SimpleRopRequestContext.SPRING_VALIDATE_ERROR_ATTRNAME, allErrors); - } else { - ropRequest = new DefaultRopRequest(); - } - ropRequest.setRopRequestContext(ropRequestContext); - return ropRequest; - } - - - private String getFormat(HttpServletRequest servletRequest) { - String messageFormat = servletRequest.getParameter(SystemParameterNames.getFormat()); - if (messageFormat == null) { - return MessageFormat.xml.name(); - } else { - return messageFormat; - } - } - - public static Locale getLocale(HttpServletRequest webRequest) { - if (webRequest.getParameter(SystemParameterNames.getLocale()) != null) { - try { - LocaleEditor localeEditor = new LocaleEditor(); - localeEditor.setAsText(webRequest.getParameter(SystemParameterNames.getLocale())); - Locale locale = (Locale) localeEditor.getValue(); - if (isValidLocale(locale)) { - return locale; - } - } catch (Exception e) { - return Locale.SIMPLIFIED_CHINESE; - } - } - return Locale.SIMPLIFIED_CHINESE; - } - - private static boolean isValidLocale(Locale locale) { - if (Locale.SIMPLIFIED_CHINESE.equals(locale) || Locale.ENGLISH.equals(locale)) { - return true; - } else { - try { - //check error resource file exists - MainErrors.getError(MainErrorType.INVALID_APP_KEY, locale); - } catch (Exception e) { - return false; - } - return true; - } - } - - - public static MessageFormat getResponseFormat(HttpServletRequest servletRequest) { - String messageFormat = servletRequest.getParameter(SystemParameterNames.getFormat()); - if (MessageFormat.isValidFormat(messageFormat)) { - return MessageFormat.getFormat(messageFormat); - } else { - return MessageFormat.xml; - } - } - - private AbstractRopRequest buildRopRequestFromBindingResult(RopRequestContext ropRequestContext, BindingResult bindingResult) { - AbstractRopRequest ropRequest = (AbstractRopRequest) bindingResult.getTarget(); - if (ropRequest instanceof AbstractRopRequest) { - AbstractRopRequest abstractRopRequest = ropRequest; - abstractRopRequest.setRopRequestContext(ropRequestContext); - } else { - logger.warn(ropRequest.getClass().getName() + "不是扩展于" + AbstractRopRequest.class.getName() + - ",无法设置" + RopRequestContext.class.getName()); - } - return ropRequest; - } - - private HashMap getRequestParams(HttpServletRequest request) { - Map srcParamMap = request.getParameterMap(); - HashMap destParamMap = new HashMap(srcParamMap.size()); - for (Object obj : srcParamMap.keySet()) { - String[] values = (String[]) srcParamMap.get(obj); - if (values != null && values.length > 0) { - destParamMap.put((String) obj, values[0]); - } else { - destParamMap.put((String) obj, null); - } - } - return destParamMap; - } - - - private BindingResult doBind(HttpServletRequest webRequest, Class requestType) { - RopRequest bindObject = BeanUtils.instantiateClass(requestType); - ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(bindObject, "bindObject"); - dataBinder.setConversionService(getFormattingConversionService()); - dataBinder.setValidator(getValidator()); - dataBinder.bind(webRequest); - dataBinder.validate(); - return dataBinder.getBindingResult(); - } - - private Validator getValidator() { - if (this.validator == null) { - LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); - localValidatorFactoryBean.afterPropertiesSet(); - this.validator = localValidatorFactoryBean; - } - return this.validator; - } - - public FormattingConversionService getFormattingConversionService() { - return conversionService; - } - - //默认的{@link RopRequest}实现类 - private class DefaultRopRequest extends AbstractRopRequest { - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.*; +import com.rop.annotation.HttpAction; +import com.rop.config.SystemParameterNames; +import com.rop.response.MainErrorType; +import com.rop.security.MainErrors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.propertyeditors.LocaleEditor; +import org.springframework.format.support.FormattingConversionService; +import org.springframework.util.StringUtils; +import org.springframework.validation.BindingResult; +import org.springframework.validation.ObjectError; +import org.springframework.validation.Validator; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.web.bind.ServletRequestDataBinder; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +/** + *
+ *    构建{@link com.rop.RopRequestContext}实例
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ServletRequestContextBuilder implements RequestContextBuilder { + + //通过前端的负载均衡服务器时,请求对象中的IP会变成负载均衡服务器的IP,因此需要特殊处理,下同。 + public static final String X_REAL_IP = "X-Real-IP"; + + public static final String X_FORWARDED_FOR = "X-Forwarded-For"; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private FormattingConversionService conversionService; + + private Validator validator; + + public ServletRequestContextBuilder(FormattingConversionService conversionService) { + this.conversionService = conversionService; + } + + + public SimpleRopRequestContext buildBySysParams(RopContext ropContext, + HttpServletRequest request, HttpServletResponse response) { + SimpleRopRequestContext requestContext = new SimpleRopRequestContext(ropContext); + + //设置请求对象及参数列表 + requestContext.setRawRequestObject(request); + if (response != null) { + requestContext.setRawResponseObject(response); + } + requestContext.setAllParams(getRequestParams(request)); + requestContext.setIp(getRemoteAddr(request)); //感谢melin所指出的BUG + + //设置服务的系统级参数 + requestContext.setAppKey(request.getParameter(SystemParameterNames.getAppKey())); + requestContext.setSessionId(request.getParameter(SystemParameterNames.getSessionId())); + requestContext.setMethod(request.getParameter(SystemParameterNames.getMethod())); + requestContext.setVersion(request.getParameter(SystemParameterNames.getVersion())); + requestContext.setLocale(getLocale(request)); + requestContext.setFormat(getFormat(request)); + requestContext.setMessageFormat(getResponseFormat(request)); + requestContext.setSign(request.getParameter(SystemParameterNames.getSign())); + requestContext.setHttpAction(HttpAction.fromValue(request.getMethod())); + + //设置服务处理器 + ServiceMethodHandler serviceMethodHandler = + ropContext.getServiceMethodHandler(requestContext.getMethod(), requestContext.getVersion()); + requestContext.setServiceMethodHandler(serviceMethodHandler); + + return requestContext; + } + + private String getRemoteAddr(HttpServletRequest request) { + String remoteIp = request.getHeader(X_REAL_IP); //nginx反向代理 + if (StringUtils.hasText(remoteIp)) { + return remoteIp; + } else { + remoteIp = request.getHeader(X_FORWARDED_FOR);//apache反射代理 + if (StringUtils.hasText(remoteIp)) { + String[] ips = remoteIp.split(","); + for (String ip : ips) { + if (!"null".equalsIgnoreCase(ip)) { + return ip; + } + } + } + return request.getRemoteAddr(); + } + } + + /** + * 将{@link HttpServletRequest}的数据绑定到{@link com.rop.RopRequestContext}的{@link com.rop.RopRequest}中,同时使用 + * JSR 303对请求数据进行校验,将错误信息设置到{@link com.rop.RopRequestContext}的属性列表中。 + * + * @param ropRequestContext + */ + public Object buildRopRequest(RopRequestContext ropRequestContext) { + ServiceMethodHandler methodHandler = ropRequestContext.getServiceMethodHandler(); + Class[] classes = methodHandler.getHandlerMethod().getParameterTypes(); + Object[] args = new Object[classes.length]; + if(classes.length < 1){ + return args; + } + HttpServletRequest request = ropRequestContext.getRawRequestObject(); + List errors = new ArrayList(); + for(int i = 0; i < args.length; i++){ + Class clazz = classes[i]; + if(HttpServletRequest.class.isAssignableFrom(clazz)){ + args[i] = request; + }else if(RopRequestContext.class.isAssignableFrom(clazz)){ + args[i] = ropRequestContext; + }else if(RopContext.class.isAssignableFrom(clazz)){ + args[i] = ropRequestContext.getRopContext(); + }else if(HttpServletResponse.class.isAssignableFrom(clazz)){ + args[i] = ropRequestContext.getRopResponse(); + }else if(RopRequest.class.equals(clazz) || AbstractRopRequest.class.equals(clazz)){ + args[i] = new DefaultRopRequest(); + }else{ + BindingResult bindingResult = doBind(request, clazz); + args[i] = buildRopRequestFromBindingResult(ropRequestContext, bindingResult); + List allErrors = bindingResult.getAllErrors(); + if(allErrors != null && allErrors.size() > 0){ + errors.addAll(allErrors); + } + } + } + ropRequestContext.setAttribute(SimpleRopRequestContext.SPRING_VALIDATE_ERROR_ATTRNAME, errors.isEmpty() ? null : errors); + return args; + } + + + private String getFormat(HttpServletRequest servletRequest) { + String messageFormat = servletRequest.getParameter(SystemParameterNames.getFormat()); + if (messageFormat == null) { + return MessageFormat.XML.name(); + } else { + return messageFormat; + } + } + + public static Locale getLocale(HttpServletRequest webRequest) { + if (webRequest.getParameter(SystemParameterNames.getLocale()) != null) { + try { + LocaleEditor localeEditor = new LocaleEditor(); + localeEditor.setAsText(webRequest.getParameter(SystemParameterNames.getLocale())); + Locale locale = (Locale) localeEditor.getValue(); + if (isValidLocale(locale)) { + return locale; + } + } catch (Exception e) { + return Locale.SIMPLIFIED_CHINESE; + } + } + return Locale.SIMPLIFIED_CHINESE; + } + + private static boolean isValidLocale(Locale locale) { + if (Locale.SIMPLIFIED_CHINESE.equals(locale) || Locale.ENGLISH.equals(locale)) { + return true; + } else { + try { + //check error resource file exists + MainErrors.getError(MainErrorType.INVALID_APP_KEY, locale); + } catch (Exception e) { + return false; + } + return true; + } + } + + public static MessageFormat getResponseFormat(HttpServletRequest servletRequest) { + String messageFormat = servletRequest.getParameter(SystemParameterNames.getFormat()); + if (MessageFormat.isValidFormat(messageFormat)) { + return MessageFormat.getFormat(messageFormat); + } else { + return MessageFormat.XML; + } + } + + private Object buildRopRequestFromBindingResult(RopRequestContext ropRequestContext, BindingResult bindingResult) { + Object ropRequest = bindingResult.getTarget(); + if(ropRequest instanceof RopRequest){ + ((RopRequest)ropRequest).setRopRequestContext(ropRequestContext); + } + return ropRequest; + } + + private HashMap getRequestParams(HttpServletRequest request) { + @SuppressWarnings("unchecked") + Map srcParamMap = request.getParameterMap(); + HashMap destParamMap = new HashMap(srcParamMap.size()); + for (Map.Entry entry : srcParamMap.entrySet()) { + String[] values = entry.getValue(); + if (values != null && values.length > 0) { + destParamMap.put(entry.getKey(), values[0]); + } else { + destParamMap.put(entry.getKey(), null); + } + } + return destParamMap; + } + + private BindingResult doBind(HttpServletRequest webRequest, Class requestType) { + Object bindObject = BeanUtils.instantiateClass(requestType); + ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(bindObject, "bindObject"); + dataBinder.setConversionService(getFormattingConversionService()); + dataBinder.setValidator(getValidator()); + dataBinder.bind(webRequest); + dataBinder.validate(); + return dataBinder.getBindingResult(); + } + + private Validator getValidator() { + if (this.validator == null) { + LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); + localValidatorFactoryBean.afterPropertiesSet(); + this.validator = localValidatorFactoryBean; + } + return this.validator; + } + + public FormattingConversionService getFormattingConversionService() { + return conversionService; + } + + //默认的{@link RopRequest}实现类 + private class DefaultRopRequest extends AbstractRopRequest { + } +} + diff --git a/rop/src/main/java/com/rop/impl/SimpleRopRequestContext.java b/rop/src/main/java/com/rop/impl/SimpleRopRequestContext.java index c401037..3c1a702 100644 --- a/rop/src/main/java/com/rop/impl/SimpleRopRequestContext.java +++ b/rop/src/main/java/com/rop/impl/SimpleRopRequestContext.java @@ -1,311 +1,308 @@ -/** - * - * 日 期:12-2-27 - */ -package com.rop.impl; - -import com.rop.*; -import com.rop.annotation.HttpAction; -import com.rop.security.MainError; -import com.rop.session.Session; -import com.rop.utils.RopUtils; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -/** - * @author 陈雄华 - * @version 1.0 - */ -public class SimpleRopRequestContext implements RopRequestContext { - - public static final String SPRING_VALIDATE_ERROR_ATTRNAME = "$SPRING_VALIDATE_ERROR_ATTRNAME"; - - private RopContext ropContext; - - private String method; - - private String version; - - private String appKey; - - private String sessionId; - - private Locale locale; - - private String format; - - public static ThreadLocal messageFormat = new ThreadLocal(); - - private String sign; - - private Map attributes = new HashMap(); - - private ServiceMethodHandler serviceMethodHandler; - - private MainError mainError; - - private Object ropResponse; - - private RopRequest ropRequest; - - private long serviceBeginTime = -1; - - private long serviceEndTime = -1; - - private String ip; - - private HttpAction httpAction; - - private Object rawRequestObject; - - private Object rawResponseObject; - - private Map allParams; - - private String requestId = RopUtils.getUUID(); - - private Session session; - - - public long getServiceBeginTime() { - return this.serviceBeginTime; - } - - - public long getServiceEndTime() { - return this.serviceEndTime; - } - - - public void setServiceBeginTime(long serviceBeginTime) { - this.serviceBeginTime = serviceBeginTime; - } - - - public void setServiceEndTime(long serviceEndTime) { - this.serviceEndTime = serviceEndTime; - } - - - public String getFormat() { - return this.format; - } - - public void setFormat(String format) { - this.format = format; - } - - - public Object getRawRequestObject() { - return this.rawRequestObject; - } - - - public Object getRawResponseObject() { - return this.rawResponseObject; - } - - public void setRawRequestObject(Object rawRequestObject) { - this.rawRequestObject = rawRequestObject; - } - - public void setRawResponseObject(Object rawResponseObject) { - this.rawResponseObject = rawResponseObject; - } - - public SimpleRopRequestContext(RopContext ropContext) { - this.ropContext = ropContext; - this.serviceBeginTime = System.currentTimeMillis(); - } - - - - public String getIp() { - return this.ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - - public RopContext getRopContext() { - return ropContext; - } - - - public String getMethod() { - return this.method; - } - - public void setMethod(String method) { - this.method = method; - } - - - public String getSessionId() { - return this.sessionId; - } - - - public Session getSession() { - if (session == null && ropContext != null && - ropContext.getSessionManager() != null && getSessionId() != null) { - session = ropContext.getSessionManager().getSession(getSessionId()); - } - return session; - } - - - public void addSession(String sessionId, Session session) { - this.sessionId = sessionId; - this.session = session; - if (ropContext != null && ropContext.getSessionManager() != null) { - ropContext.getSessionManager().addSession(sessionId, session); - } - } - - - public void removeSession() { - if (ropContext != null && ropContext.getSessionManager() != null) { - ropContext.getSessionManager().removeSession(getSessionId()); - } - } - - - public Locale getLocale() { - return this.locale; - } - - public ServiceMethodHandler getServiceMethodHandler() { - return this.serviceMethodHandler; - } - - - public MessageFormat getMessageFormat() { - return messageFormat.get(); - } - - - public Object getRopResponse() { - return this.ropResponse; - } - - public String getAppKey() { - return this.appKey; - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - public void setServiceMethodHandler(ServiceMethodHandler serviceMethodHandler) { - this.serviceMethodHandler = serviceMethodHandler; - } - - public void setMessageFormat(MessageFormat messageFormat) { - this.messageFormat.set(messageFormat); - } - - - public void setRopResponse(Object ropResponse) { - this.ropResponse = ropResponse; - } - - public void setSessionId(String sessionId) { - this.sessionId = sessionId; - } - - public void setAppKey(String appKey) { - this.appKey = appKey; - } - - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - - public String getSign() { - return sign; - } - - public void setSign(String sign) { - this.sign = sign; - } - - public void setMainError(MainError mainError) { - this.mainError = mainError; - } - - public MainError getMainError() { - return this.mainError; - } - - - public Object getAttribute(String name) { - return this.attributes.get(name); - } - - - public void setAttribute(String name, Object value) { - this.attributes.put(name, value); - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - - public boolean isSignEnable() { - return ropContext.isSignEnable() && !getServiceMethodDefinition().isIgnoreSign(); - } - - - public ServiceMethodDefinition getServiceMethodDefinition() { - return serviceMethodHandler.getServiceMethodDefinition(); - } - - - public Map getAllParams() { - return this.allParams; - } - - public void setAllParams(Map allParams) { - this.allParams = allParams; - } - - - public String getParamValue(String paramName) { - if (allParams != null) { - return allParams.get(paramName); - } else { - return null; - } - } - - public void setHttpAction(HttpAction httpAction) { - this.httpAction = httpAction; - } - - - public HttpAction getHttpAction() { - return this.httpAction; - } - - - public String getRequestId() { - return this.requestId; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.*; +import com.rop.annotation.HttpAction; +import com.rop.response.MainError; +import com.rop.session.Session; +import com.rop.utils.RopUtils; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author 陈雄华 + * @version 1.0 + */ +public class SimpleRopRequestContext implements RopRequestContext { + + public static final String SPRING_VALIDATE_ERROR_ATTRNAME = "$SPRING_VALIDATE_ERROR_ATTRNAME"; + + private RopContext ropContext; + + private String method; + + private String version; + + private String appKey; + + private String sessionId; + + private Locale locale; + + private String format; + + public static ThreadLocal messageFormat = new ThreadLocal(); + + private String sign; + + private Map attributes = new HashMap(); + + private ServiceMethodHandler serviceMethodHandler; + + private MainError mainError; + + private Object ropResponse; + + private long serviceBeginTime = -1; + + private long serviceEndTime = -1; + + private String ip; + + private HttpAction httpAction; + + private HttpServletRequest rawRequestObject; + + private HttpServletResponse rawResponseObject; + + private Map allParams; + + private String requestId = RopUtils.getUUID(); + + private Session session; + + + public long getServiceBeginTime() { + return this.serviceBeginTime; + } + + + public long getServiceEndTime() { + return this.serviceEndTime; + } + + + public void setServiceBeginTime(long serviceBeginTime) { + this.serviceBeginTime = serviceBeginTime; + } + + + public void setServiceEndTime(long serviceEndTime) { + this.serviceEndTime = serviceEndTime; + } + + + public String getFormat() { + return this.format; + } + + public void setFormat(String format) { + this.format = format; + } + + + public HttpServletRequest getRawRequestObject() { + return this.rawRequestObject; + } + + + public HttpServletResponse getRawResponseObject() { + return this.rawResponseObject; + } + + public void setRawRequestObject(HttpServletRequest rawRequestObject) { + this.rawRequestObject = rawRequestObject; + } + + public void setRawResponseObject(HttpServletResponse rawResponseObject) { + this.rawResponseObject = rawResponseObject; + } + + public SimpleRopRequestContext(RopContext ropContext) { + this.ropContext = ropContext; + this.serviceBeginTime = System.currentTimeMillis(); + } + + public String getIp() { + return this.ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public RopContext getRopContext() { + return ropContext; + } + + public String getMethod() { + return this.method; + } + + public void setMethod(String method) { + this.method = method; + } + + + public String getSessionId() { + return this.sessionId; + } + + public Session getSession() { + if (session == null && ropContext != null && + ropContext.getSessionManager() != null && getSessionId() != null) { + session = ropContext.getSessionManager().getSession(getSessionId()); + } + return session; + } + + public void addSession(String sessionId, Session session) { + this.sessionId = sessionId; + this.session = session; + if (ropContext != null && ropContext.getSessionManager() != null) { + ropContext.getSessionManager().addSession(sessionId, session); + } + } + + public void removeSession() { + if (ropContext != null && ropContext.getSessionManager() != null) { + ropContext.getSessionManager().removeSession(getSessionId()); + } + } + + public Locale getLocale() { + return this.locale; + } + + public ServiceMethodHandler getServiceMethodHandler() { + return this.serviceMethodHandler; + } + + + public MessageFormat getMessageFormat() { + return messageFormat.get(); + } + + + public Object getRopResponse() { + return this.ropResponse; + } + + public String getAppKey() { + return this.appKey; + } + + public void setLocale(Locale locale) { + this.locale = locale; + } + + public void setServiceMethodHandler(ServiceMethodHandler serviceMethodHandler) { + this.serviceMethodHandler = serviceMethodHandler; + } + + public void setMessageFormat(MessageFormat messageFormat) { + SimpleRopRequestContext.messageFormat.set(messageFormat); + } + + public void setRopResponse(Object ropResponse) { + this.ropResponse = ropResponse; + } + + public void setSessionId(String sessionId) { + this.sessionId = sessionId; + } + + public void setAppKey(String appKey) { + this.appKey = appKey; + } + + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getSign() { + return sign; + } + + public void setSign(String sign) { + this.sign = sign; + } + + public void setMainError(MainError mainError) { + this.mainError = mainError; + } + + public MainError getMainError() { + return this.mainError; + } + + public Object getAttribute(String name) { + return this.attributes.get(name); + } + + public void setAttribute(String name, Object value) { + this.attributes.put(name, value); + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + + public boolean isSignEnable() { + return ropContext.isSignEnable() && !getServiceMethodDefinition().isIgnoreSign(); + } + + + public ServiceMethodDefinition getServiceMethodDefinition() { + return serviceMethodHandler.getServiceMethodDefinition(); + } + + + public Map getAllParams() { + return this.allParams; + } + + public void setAllParams(Map allParams) { + this.allParams = allParams; + } + + public String getParamValue(String paramName) { + if (allParams != null) { + return allParams.get(paramName); + } else { + return null; + } + } + + public void setHttpAction(HttpAction httpAction) { + this.httpAction = httpAction; + } + + public HttpAction getHttpAction() { + return this.httpAction; + } + + public String getRequestId() { + return this.requestId; + } +} + diff --git a/rop/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java b/rop/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java deleted file mode 100644 index 618c3e2..0000000 --- a/rop/src/main/java/com/rop/marshaller/JacksonJsonRopMarshaller.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * - * 日 期:12-2-27 - */ -package com.rop.marshaller; - -import com.rop.RopException; -import com.rop.RopMarshaller; -import org.codehaus.jackson.JsonEncoding; -import org.codehaus.jackson.JsonGenerator; -import org.codehaus.jackson.map.AnnotationIntrospector; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.map.annotate.JsonSerialize; -import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; - -import java.io.IOException; -import java.io.OutputStream; - -/** - *
- *    将响应对象流化成JSON。 {@link ObjectMapper}是线程安全的。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class JacksonJsonRopMarshaller implements RopMarshaller { - - private static ObjectMapper objectMapper; - - public void marshaller(Object object, OutputStream outputStream) { - try { - JsonGenerator jsonGenerator = getObjectMapper().getJsonFactory().createJsonGenerator(outputStream, JsonEncoding.UTF8); - getObjectMapper().writeValue(jsonGenerator, object); - } catch (IOException e) { - throw new RopException(e); - } - } - - private ObjectMapper getObjectMapper() throws IOException { - if (this.objectMapper == null) { - ObjectMapper objectMapper = new ObjectMapper(); - AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); - SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); - serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE) - .with(SerializationConfig.Feature.INDENT_OUTPUT) - .withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL) - .withSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY) - .withAnnotationIntrospector(introspector); - objectMapper.setSerializationConfig(serializationConfig); - this.objectMapper = objectMapper; - } - return this.objectMapper; - } -} - diff --git a/rop/src/main/java/com/rop/marshaller/MessageMarshallerUtils.java b/rop/src/main/java/com/rop/marshaller/MessageMarshallerUtils.java deleted file mode 100644 index f78dc92..0000000 --- a/rop/src/main/java/com/rop/marshaller/MessageMarshallerUtils.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * 日 期:12-5-29 - */ -package com.rop.marshaller; - -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.dataformat.xml.XmlMapper; -import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; -import com.rop.MessageFormat; -import com.rop.RopException; -import com.rop.RopMarshaller; -import com.rop.RopRequest; -import org.codehaus.jackson.JsonEncoding; -import org.codehaus.jackson.JsonGenerator; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Map; - -/** - *
- *   对请求响应的对象转成相应的报文。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class MessageMarshallerUtils { - - protected static final Logger logger = LoggerFactory.getLogger(MessageMarshallerUtils.class); - - private static final String UTF_8 = "utf-8"; - - private static ObjectMapper jsonObjectMapper = new ObjectMapper(); - - private static RopMarshaller xmlRopResponseMarshaller = new JaxbXmlRopMarshaller(); - - static { - SerializationConfig serializationConfig = jsonObjectMapper.getSerializationConfig(); - serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE) - .with(SerializationConfig.Feature.INDENT_OUTPUT); - } - - private static XmlMapper xmlObjectMapper = new XmlMapper(); - - static { - xmlObjectMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, false); - xmlObjectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - } - - /** - * 将请求对象转换为String - * - * @param request - * @param format - * @return - */ - public static String getMessage(RopRequest request, MessageFormat format) { - try { - ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - if (format == MessageFormat.json) { - if (request.getRopRequestContext() != null) { - jsonObjectMapper.writeValue(bos, request.getRopRequestContext().getAllParams()); - } else { - return ""; - } - } else { - if (request.getRopRequestContext() != null) { - xmlObjectMapper.writeValue(bos, request.getRopRequestContext().getAllParams()); - } else { - return ""; - } - } - return bos.toString(UTF_8); - } catch (Exception e) { - throw new RopException(e); - } - } - - /** - * 将请求对象转换为String - * - * @param allParams - * @return - */ - public static String asUrlString(Map allParams) { - StringBuilder sb = new StringBuilder(256); - boolean first = true; - for (Map.Entry entry : allParams.entrySet()) { - if (!first) { - sb.append("&"); - } - first = false; - sb.append(entry.getKey()); - sb.append("="); - sb.append(entry.getValue()); - } - return sb.toString(); - } - - - /** - * 将{@link RopRequest}转换为字符串 - * - * @param object - * @param format - * @return - */ - public static String getMessage(Object object, MessageFormat format) { - if (object == null) { - return "NONE MSG"; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - try { - if (format == MessageFormat.json) { - JsonGenerator jsonGenerator = jsonObjectMapper.getJsonFactory().createJsonGenerator(bos, JsonEncoding.UTF8); - jsonObjectMapper.writeValue(jsonGenerator, object); - } else { - xmlRopResponseMarshaller.marshaller(object, bos); - } - return bos.toString(UTF_8); - } catch (Throwable e) { - throw new RopException(e); - } finally { - try { - bos.close(); - } catch (IOException ee) { - logger.error("消息转换异常", ee); - } - } - } - -} - diff --git a/rop/src/main/java/com/rop/request/IllegalUploadFileFormatException.java b/rop/src/main/java/com/rop/request/IllegalUploadFileFormatException.java deleted file mode 100644 index a556953..0000000 --- a/rop/src/main/java/com/rop/request/IllegalUploadFileFormatException.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.request; - -/** - *
- *    上传文件字符串转换时发生错误
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class IllegalUploadFileFormatException extends IllegalArgumentException { - - public IllegalUploadFileFormatException() { - super(); - } - - public IllegalUploadFileFormatException(String s) { - super(s); - } - - public IllegalUploadFileFormatException(String message, Throwable cause) { - super(message, cause); - } - - public IllegalUploadFileFormatException(Throwable cause) { - super(cause); - } -} - diff --git a/rop/src/main/java/com/rop/request/RopConverter.java b/rop/src/main/java/com/rop/request/RopConverter.java deleted file mode 100644 index 6d8f94c..0000000 --- a/rop/src/main/java/com/rop/request/RopConverter.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-3 - */ -package com.rop.request; - -import org.springframework.core.convert.converter.Converter; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface RopConverter extends Converter { - - /** - * 从T转换成S - * @param target - * @return - */ - S unconvert(T target); - - /** - * 获取源类型 - * @return - */ - Class getSourceClass(); - - /** - * 获取目标类型 - * @return - */ - Class getTargetClass(); -} - diff --git a/rop/src/main/java/com/rop/request/RopRequestMessageConverter.java b/rop/src/main/java/com/rop/request/RopRequestMessageConverter.java index a0ece89..a5b7fad 100644 --- a/rop/src/main/java/com/rop/request/RopRequestMessageConverter.java +++ b/rop/src/main/java/com/rop/request/RopRequestMessageConverter.java @@ -1,113 +1,101 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.request; - -import com.rop.MessageFormat; -import com.rop.RopException; -import com.rop.RopRequestParseException; -import com.rop.impl.SimpleRopRequestContext; -import org.codehaus.jackson.JsonParser; -import org.codehaus.jackson.map.AnnotationIntrospector; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.xc.JaxbAnnotationIntrospector; -import org.springframework.core.convert.TypeDescriptor; -import org.springframework.core.convert.converter.ConditionalGenericConverter; -import org.springframework.http.converter.HttpMessageConversionException; -import org.springframework.util.Assert; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import java.io.StringReader; -import java.util.Collections; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *
- *     将参数中的XML或JSON转换为对象的属性对象
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopRequestMessageConverter implements ConditionalGenericConverter { - - private static final ConcurrentMap jaxbContexts = new ConcurrentHashMap(); - - private static final ObjectMapper objectMapper = new ObjectMapper(); - - static { - AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); - SerializationConfig serializationConfig = objectMapper.getSerializationConfig(); - serializationConfig = serializationConfig.without(SerializationConfig.Feature.WRAP_ROOT_VALUE) - .withAnnotationIntrospector(introspector); - objectMapper.setSerializationConfig(serializationConfig); - } - - - /** - * 如果目标属性类有标注JAXB的注解,则使用该转换器 - * - * @param sourceType - * @param targetType - * @return - */ - public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - Class clazz = targetType.getObjectType(); - return clazz.isAnnotationPresent(XmlRootElement.class) || clazz.isAnnotationPresent(XmlType.class); - } - - public Set getConvertibleTypes() { - return Collections.singleton(new ConvertiblePair(String.class, Object.class)); - } - - public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { - try { - if (SimpleRopRequestContext.messageFormat.get() == MessageFormat.json) {//输入格式为JSON - JsonParser jsonParser = objectMapper.getJsonFactory().createJsonParser((String) source); - return jsonParser.readValueAs(targetType.getObjectType()); - } else { - Unmarshaller unmarshaller = createUnmarshaller(targetType.getObjectType()); - StringReader reader = new StringReader((String) source); - return unmarshaller.unmarshal(reader); - } - } catch (Exception e) { - throw new RopRequestParseException((String) source, e); - } - } - - private Unmarshaller createUnmarshaller(Class clazz) throws JAXBException { - try { - JAXBContext jaxbContext = getJaxbContext(clazz); - return jaxbContext.createUnmarshaller(); - } catch (JAXBException ex) { - throw new RopException( - "Could not create Unmarshaller for class [" + clazz + "]: " + ex.getMessage(), ex); - } - } - - private JAXBContext getJaxbContext(Class clazz) { - Assert.notNull(clazz, "'clazz' must not be null"); - JAXBContext jaxbContext = jaxbContexts.get(clazz); - if (jaxbContext == null) { - try { - jaxbContext = JAXBContext.newInstance(clazz); - jaxbContexts.putIfAbsent(clazz, jaxbContext); - } catch (JAXBException ex) { - throw new HttpMessageConversionException( - "Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex); - } - } - return jaxbContext; - } - - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.request; + +import com.rop.MessageFormat; +import com.rop.RopRequestParseException; +import com.rop.RopUnmarshaller; +import com.rop.impl.SimpleRopRequestContext; +import com.rop.unmarshaller.JacksonJsonRopUnmarshaller; +import com.rop.unmarshaller.JaxbXmlRopUnmarshaller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.core.convert.converter.ConditionalGenericConverter; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import java.util.Collections; +import java.util.Set; + +/** + *
+ *     将参数中的XML或JSON转换为对象的属性对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class RopRequestMessageConverter implements ConditionalGenericConverter { + + private RopUnmarshaller xmlUnmarshaller; + + private RopUnmarshaller jsonUnmarshaller; + + /** + * 如果目标属性类有标注JAXB的注解,则使用该转换器 + * + * @param sourceType + * @param targetType + * @return + */ + public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { + Class clazz = targetType.getObjectType(); + return clazz.isAnnotationPresent(XmlRootElement.class) || clazz.isAnnotationPresent(XmlType.class); + } + + public Set getConvertibleTypes() { + return Collections.singleton(new ConvertiblePair(String.class, Object.class)); + } + + public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { + try { + if (SimpleRopRequestContext.messageFormat.get() == MessageFormat.JSON) {//输入格式为JSON + return getJsonUnmarshaller().unmarshaller((String)source, targetType.getObjectType()); + } else { + return getXmlUnmarshaller().unmarshaller((String)source, targetType.getObjectType()); + } + } catch (Exception e) { + throw new RopRequestParseException((String) source, e); + } + } + + public RopUnmarshaller getXmlUnmarshaller() { + if(xmlUnmarshaller == null){ + xmlUnmarshaller = new JaxbXmlRopUnmarshaller(); + } + return xmlUnmarshaller; + } + + @Autowired(required=false) + public void setXmlUnmarshaller(RopUnmarshaller xmlUnmarshaller) { + this.xmlUnmarshaller = xmlUnmarshaller; + } + + public RopUnmarshaller getJsonUnmarshaller() { + if(jsonUnmarshaller == null){ + jsonUnmarshaller = new JacksonJsonRopUnmarshaller(); + } + return jsonUnmarshaller; + } + + @Autowired(required=false) + public void setJsonUnmarshaller(RopUnmarshaller jsonUnmarshaller) { + this.jsonUnmarshaller = jsonUnmarshaller; + } +} + diff --git a/rop/src/main/java/com/rop/request/UploadFileConverter.java b/rop/src/main/java/com/rop/request/UploadFileConverter.java index cc332e4..5bbf4f3 100644 --- a/rop/src/main/java/com/rop/request/UploadFileConverter.java +++ b/rop/src/main/java/com/rop/request/UploadFileConverter.java @@ -1,39 +1,33 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.request; - -/** - *
- *   将以BASE64位编码字符串转换为字节数组的{@link UploadFile}对象
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class UploadFileConverter implements RopConverter { - - - public UploadFile convert(String source) { - String fileType = UploadFileUtils.getFileType(source); - byte[] contentBytes = UploadFileUtils.decode(source); - return new UploadFile(fileType, contentBytes); - } - - - public String unconvert(UploadFile target) { - return UploadFileUtils.encode(target); - } - - - public Class getSourceClass() { - return String.class; - } - - - public Class getTargetClass() { - return UploadFile.class; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.request; + +import org.springframework.core.convert.converter.Converter; + +import com.rop.converter.UploadFile; + +/** + *
+ *   将以BASE64位编码字符串转换为字节数组的{@link UploadFile}对象
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class UploadFileConverter extends com.rop.converter.UploadFileConverter implements Converter{ + +} + diff --git a/rop/src/main/java/com/rop/response/BusinessServiceErrorResponse.java b/rop/src/main/java/com/rop/response/BusinessServiceErrorResponse.java index ed34fe5..5058bc7 100644 --- a/rop/src/main/java/com/rop/response/BusinessServiceErrorResponse.java +++ b/rop/src/main/java/com/rop/response/BusinessServiceErrorResponse.java @@ -1,87 +1,98 @@ -/** - * - * 日 期:12-2-23 - */ -package com.rop.response; - -import com.rop.RopRequestContext; -import com.rop.security.*; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.ArrayList; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class BusinessServiceErrorResponse extends ErrorResponse { - - private static final String ISV = "isv."; - - private static final String SERVICE_ERROR = "-service-error:"; - - //注意,这个不能删除,否则无法进行流化 - public BusinessServiceErrorResponse() { - } - - - /** - * 服务发生错误的错误响应,错误码的格式为:isv.***-service-error:###,假设 - * serviceName为book.upload,error_code为INVLIAD_USERNAME_OR_PASSWORD,则错误码会被格式化为: - * isv.book-upload-service-error:INVLIAD_USERNAME_OR_PASSWORD - * - * @param serviceName 服务名,如book.upload,会被自动转换为book-upload - * @param errorCode 错误的代码,如INVLIAD_USERNAME_OR_PASSWORD,在错误码的后面,一般为大写或数字。 - * @param locale 本地化对象 - * @param params 错误信息的参数,如错误消息的值为this is a {0} error,则传入的参数为big时,错误消息格式化为: - * this is a big error - */ - @Deprecated - public BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params) { - MainError mainError = MainErrors.getError(MainErrorType.BUSINESS_LOGIC_ERROR,locale); - - serviceName = transform(serviceName); - String subErrorCode = ISV + serviceName + SERVICE_ERROR + errorCode; - SubError subError = SubErrors.getSubError(subErrorCode, subErrorCode, locale, params); - ArrayList subErrors = new ArrayList(); - subErrors.add(subError); - - setMainError(mainError); - setSubErrors(subErrors); - } - - /** - * 服务发生错误的错误响应,错误码的格式为:isv.***-service-error:###,假设 - * serviceName为file.upload,error_code为INVLIAD_USERNAME_OR_PASSWORD,则错误码会被格式化为: - * isv.file-upload-service-error:INVLIAD_USERNAME_OR_PASSWORD - * - * @param context 请求上下文 - * @param errorCode 错误的代码,如INVLIAD_USERNAME_OR_PASSWORD,在错误码的后面,一般为大写或数字。 - * @param params 错误信息的参数,如错误消息的值为this is a {0} error,则传入的参数为big时,错误消息格式化为: - * this is a big error - */ - public BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) { - MainError mainError = MainErrors.getError(MainErrorType.BUSINESS_LOGIC_ERROR,context.getLocale(), - context.getMethod(),context.getVersion()); - - String serviceName = transform(context.getMethod()); - String subErrorCode = ISV + serviceName + SERVICE_ERROR + errorCode; - SubError subError = SubErrors.getSubError(subErrorCode, subErrorCode, context.getLocale(),params); - ArrayList subErrors = new ArrayList(); - subErrors.add(subError); - - setMainError(mainError); - setSubErrors(subErrors); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import com.rop.RopRequestContext; +import com.rop.security.*; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class BusinessServiceErrorResponse extends ErrorResponse { + + private static final String ISV = "isv."; + + private static final String SERVICE_ERROR = "-service-error:"; + + //注意,这个不能删除,否则无法进行流化 + public BusinessServiceErrorResponse() { + } + + + /** + * 服务发生错误的错误响应,错误码的格式为:isv.***-service-error:###,假设 + * serviceName为book.upload,error_code为INVLIAD_USERNAME_OR_PASSWORD,则错误码会被格式化为: + * isv.book-upload-service-error:INVLIAD_USERNAME_OR_PASSWORD + * + * @param serviceName 服务名,如book.upload,会被自动转换为book-upload + * @param errorCode 错误的代码,如INVLIAD_USERNAME_OR_PASSWORD,在错误码的后面,一般为大写或数字。 + * @param locale 本地化对象 + * @param params 错误信息的参数,如错误消息的值为this is a {0} error,则传入的参数为big时,错误消息格式化为: + * this is a big error + */ + @Deprecated + public BusinessServiceErrorResponse(String serviceName, String errorCode, Locale locale, Object... params) { + MainError mainError = MainErrors.getError(MainErrorType.BUSINESS_LOGIC_ERROR,locale); + + serviceName = transform(serviceName); + String subErrorCode = ISV + serviceName + SERVICE_ERROR + errorCode; + SubError subError = SubErrors.getSubError(subErrorCode, subErrorCode, locale, params); + ArrayList subErrors = new ArrayList(); + subErrors.add(subError); + + setMainError(mainError); + setSubErrors(subErrors); + } + + /** + * 服务发生错误的错误响应,错误码的格式为:isv.***-service-error:###,假设 + * serviceName为file.upload,error_code为INVLIAD_USERNAME_OR_PASSWORD,则错误码会被格式化为: + * isv.file-upload-service-error:INVLIAD_USERNAME_OR_PASSWORD + * + * @param context 请求上下文 + * @param errorCode 错误的代码,如INVLIAD_USERNAME_OR_PASSWORD,在错误码的后面,一般为大写或数字。 + * @param params 错误信息的参数,如错误消息的值为this is a {0} error,则传入的参数为big时,错误消息格式化为: + * this is a big error + */ + public BusinessServiceErrorResponse(RopRequestContext context,String errorCode,Object... params) { + MainError mainError = MainErrors.getError(MainErrorType.BUSINESS_LOGIC_ERROR,context.getLocale(), + context.getMethod(),context.getVersion()); + + String serviceName = transform(context.getMethod()); + String subErrorCode = ISV + serviceName + SERVICE_ERROR + errorCode; + SubError subError = SubErrors.getSubError(subErrorCode, subErrorCode, context.getLocale(),params); + ArrayList subErrors = new ArrayList(); + subErrors.add(subError); + + setMainError(mainError); + setSubErrors(subErrors); + } + +} + diff --git a/rop/src/main/java/com/rop/response/NotExistErrorResponse.java b/rop/src/main/java/com/rop/response/NotExistErrorResponse.java index e0c6ece..ea29d06 100644 --- a/rop/src/main/java/com/rop/response/NotExistErrorResponse.java +++ b/rop/src/main/java/com/rop/response/NotExistErrorResponse.java @@ -1,59 +1,67 @@ -/** - * - * 日 期:12-2-23 - */ -package com.rop.response; - -import com.rop.security.MainError; -import com.rop.security.SubError; -import com.rop.security.SubErrorType; -import com.rop.security.SubErrors; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.ArrayList; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class NotExistErrorResponse extends ErrorResponse { - - public static final String ISV = "isv."; - public static final String NOT_EXIST_INVALID = "-not-exist:invalid-"; - - //注意,这个不能删除,否则无法进行流化 - public NotExistErrorResponse() { - } - - /** - * 对象不存在的错误对象。当根据queryFieldName查询objectName时,查不到记录,则返回该错误对象。 - * - * @param objectName 对象的名称 - * @param queryFieldName 查询字段的名称 - * @param locale 本地化对象 - * @param params 错误信息的参数,如错误消息的值为:use '{0}'({1})can't find '{2}' object ,则传入的参数为001时,错误消息格式化为: - * can't find user by 001 - */ - public NotExistErrorResponse(String objectName, String queryFieldName, Object queryFieldValue, Locale locale) { - MainError mainError = SubErrors.getMainError(SubErrorType.ISV_NOT_EXIST, locale); - String subErrorCode = SubErrors.getSubErrorCode(SubErrorType.ISV_NOT_EXIST, objectName, queryFieldName); - - SubError subError = SubErrors.getSubError(subErrorCode, SubErrorType.ISV_NOT_EXIST.value(), locale, - queryFieldName, queryFieldValue,objectName); - ArrayList subErrors = new ArrayList(); - subErrors.add(subError); - - setMainError(mainError); - setSubErrors(subErrors); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import com.rop.security.SubErrors; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class NotExistErrorResponse extends ErrorResponse { + + public static final String ISV = "isv."; + public static final String NOT_EXIST_INVALID = "-not-exist:invalid-"; + + //注意,这个不能删除,否则无法进行流化 + public NotExistErrorResponse() { + } + + /** + * 对象不存在的错误对象。当根据queryFieldName查询objectName时,查不到记录,则返回该错误对象。 + * + * @param objectName 对象的名称 + * @param queryFieldName 查询字段的名称 + * @param locale 本地化对象 + * @param params 错误信息的参数,如错误消息的值为:use '{0}'({1})can't find '{2}' object ,则传入的参数为001时,错误消息格式化为: + * can't find user by 001 + */ + public NotExistErrorResponse(String objectName, String queryFieldName, Object queryFieldValue, Locale locale) { + MainError mainError = SubErrors.getMainError(SubErrorType.ISV_NOT_EXIST, locale); + String subErrorCode = SubErrors.getSubErrorCode(SubErrorType.ISV_NOT_EXIST, objectName, queryFieldName); + + SubError subError = SubErrors.getSubError(subErrorCode, SubErrorType.ISV_NOT_EXIST.value(), locale, + queryFieldName, queryFieldValue,objectName); + ArrayList subErrors = new ArrayList(); + subErrors.add(subError); + + setMainError(mainError); + setSubErrors(subErrors); + } +} + diff --git a/rop/src/main/java/com/rop/response/RejectedServiceResponse.java b/rop/src/main/java/com/rop/response/RejectedServiceResponse.java index 36ca07b..7f1def9 100644 --- a/rop/src/main/java/com/rop/response/RejectedServiceResponse.java +++ b/rop/src/main/java/com/rop/response/RejectedServiceResponse.java @@ -1,38 +1,46 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-2 - */ -package com.rop.response; - -import com.rop.RopRequestContext; -import com.rop.security.MainError; -import com.rop.security.MainErrorType; -import com.rop.security.MainErrors; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.Locale; - -/** - *
- *   当服务平台资源耗尽(超过最大线程数且列队排满后)
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class RejectedServiceResponse extends ErrorResponse { - - public RejectedServiceResponse() { - } - - public RejectedServiceResponse(RopRequestContext context) { - MainError mainError = MainErrors.getError(MainErrorType.FORBIDDEN_REQUEST, context.getLocale(), - context.getMethod(),context.getVersion()); - setMainError(mainError); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import com.rop.RopRequestContext; +import com.rop.security.MainErrors; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ *   当服务平台资源耗尽(超过最大线程数且列队排满后)
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class RejectedServiceResponse extends ErrorResponse { + + public RejectedServiceResponse() { + } + + public RejectedServiceResponse(RopRequestContext context) { + MainError mainError = MainErrors.getError(MainErrorType.FORBIDDEN_REQUEST, context.getLocale(), + context.getMethod(),context.getVersion()); + setMainError(mainError); + } +} + diff --git a/rop/src/main/java/com/rop/response/ServiceUnavailableErrorResponse.java b/rop/src/main/java/com/rop/response/ServiceUnavailableErrorResponse.java index 88099bb..64c7975 100644 --- a/rop/src/main/java/com/rop/response/ServiceUnavailableErrorResponse.java +++ b/rop/src/main/java/com/rop/response/ServiceUnavailableErrorResponse.java @@ -1,81 +1,88 @@ -/** - * - * 日 期:12-2-23 - */ -package com.rop.response; - -import com.rop.security.MainError; -import com.rop.security.SubError; -import com.rop.security.SubErrorType; -import com.rop.security.SubErrors; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class ServiceUnavailableErrorResponse extends ErrorResponse { - - private static final String ISP = "isp."; - - private static final String SERVICE_UNAVAILABLE = "-service-unavailable"; - - //注意,这个不能删除,否则无法进行流化 - public ServiceUnavailableErrorResponse() { - } - - public ServiceUnavailableErrorResponse(String method, Locale locale) { - MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale); - String errorCodeKey = ISP + transform(method) + SERVICE_UNAVAILABLE; - SubError subError = SubErrors.getSubError(errorCodeKey, - SubErrorType.ISP_SERVICE_UNAVAILABLE.value(), - locale, method,"NONE","NONE"); - ArrayList subErrors = new ArrayList(); - subErrors.add(subError); - - setMainError(mainError); - setSubErrors(subErrors); - } - - public ServiceUnavailableErrorResponse(String method, Locale locale, Throwable throwable) { - MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale); - - ArrayList subErrors = new ArrayList(); - - String errorCodeKey = ISP + transform(method) + SERVICE_UNAVAILABLE; - Throwable srcThrowable = throwable; - if(throwable.getCause() != null){ - srcThrowable = throwable.getCause(); - } - SubError subError = SubErrors.getSubError(errorCodeKey, - SubErrorType.ISP_SERVICE_UNAVAILABLE.value(), - locale, - method, srcThrowable.getClass().getName(),getThrowableInfo(throwable)); - subErrors.add(subError); - - setSubErrors(subErrors); - setMainError(mainError); - } - - private String getThrowableInfo(Throwable throwable) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); - PrintStream printStream = new PrintStream(outputStream); - throwable.printStackTrace(printStream); - return outputStream.toString(); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import com.rop.security.SubErrors; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class ServiceUnavailableErrorResponse extends ErrorResponse { + + private static final String ISP = "isp."; + + private static final String SERVICE_UNAVAILABLE = "-service-unavailable"; + + //注意,这个不能删除,否则无法进行流化 + public ServiceUnavailableErrorResponse() { + } + + public ServiceUnavailableErrorResponse(String method, Locale locale) { + MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale); + String errorCodeKey = ISP + transform(method) + SERVICE_UNAVAILABLE; + SubError subError = SubErrors.getSubError(errorCodeKey, + SubErrorType.ISP_SERVICE_UNAVAILABLE.value(), + locale, method,"NONE","NONE"); + ArrayList subErrors = new ArrayList(); + subErrors.add(subError); + + setMainError(mainError); + setSubErrors(subErrors); + } + + public ServiceUnavailableErrorResponse(String method, Locale locale, Throwable throwable) { + MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_UNAVAILABLE, locale); + + ArrayList subErrors = new ArrayList(); + + String errorCodeKey = ISP + transform(method) + SERVICE_UNAVAILABLE; + Throwable srcThrowable = throwable; + if(throwable.getCause() != null){ + srcThrowable = throwable.getCause(); + } + SubError subError = SubErrors.getSubError(errorCodeKey, + SubErrorType.ISP_SERVICE_UNAVAILABLE.value(), + locale, + method, srcThrowable.getClass().getName(),getThrowableInfo(throwable)); + subErrors.add(subError); + + setSubErrors(subErrors); + setMainError(mainError); + } + + private String getThrowableInfo(Throwable throwable) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); + PrintStream printStream = new PrintStream(outputStream); + throwable.printStackTrace(printStream); + return outputStream.toString(); + } +} + diff --git a/rop/src/main/java/com/rop/response/TimeoutErrorResponse.java b/rop/src/main/java/com/rop/response/TimeoutErrorResponse.java index 4c0862e..275de49 100644 --- a/rop/src/main/java/com/rop/response/TimeoutErrorResponse.java +++ b/rop/src/main/java/com/rop/response/TimeoutErrorResponse.java @@ -1,54 +1,62 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.response; - -import com.rop.security.MainError; -import com.rop.security.SubError; -import com.rop.security.SubErrorType; -import com.rop.security.SubErrors; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.ArrayList; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "error") -public class TimeoutErrorResponse extends ErrorResponse { - - private static final String ISP = "isp."; - - private static final String SERVICE_TIMEOUT = "-service-timeout"; - - public TimeoutErrorResponse() { - } - - public TimeoutErrorResponse(String method, Locale locale, int timeout) { - MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_TIMEOUT, locale); - - ArrayList subErrors = new ArrayList(); - - String errorCodeKey = ISP + transform(method) + SERVICE_TIMEOUT; - SubError subError = SubErrors.getSubError(errorCodeKey, - SubErrorType.ISP_SERVICE_TIMEOUT.value(), - locale, - method, timeout); - subErrors.add(subError); - - setSubErrors(subErrors); - setMainError(mainError); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.response; + +import com.rop.security.SubErrors; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.ArrayList; +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class TimeoutErrorResponse extends ErrorResponse { + + private static final String ISP = "isp."; + + private static final String SERVICE_TIMEOUT = "-service-timeout"; + + public TimeoutErrorResponse() { + } + + public TimeoutErrorResponse(String method, Locale locale, int timeout) { + MainError mainError = SubErrors.getMainError(SubErrorType.ISP_SERVICE_TIMEOUT, locale); + + ArrayList subErrors = new ArrayList(); + + String errorCodeKey = ISP + transform(method) + SERVICE_TIMEOUT; + SubError subError = SubErrors.getSubError(errorCodeKey, + SubErrorType.ISP_SERVICE_TIMEOUT.value(), + locale, + method, timeout); + subErrors.add(subError); + + setSubErrors(subErrors); + setMainError(mainError); + } + +} + diff --git a/rop/src/main/java/com/rop/security/AppSecretManager.java b/rop/src/main/java/com/rop/security/AppSecretManager.java index 273e7f7..6f6c63a 100644 --- a/rop/src/main/java/com/rop/security/AppSecretManager.java +++ b/rop/src/main/java/com/rop/security/AppSecretManager.java @@ -1,33 +1,44 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-3-1 - */ -package com.rop.security; - -/** - *
- *    应用键管理器,可根据appKey获取对应的secret.
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface AppSecretManager { - - /** - * 获取应用程序的密钥 - * - * @param appKey - * @return - */ - String getSecret(String appKey); - - /** - * 是否是合法的appKey - * - * @param appKey - * @return - */ - boolean isValidAppKey(String appKey); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +/** + *
+ *    应用键管理器,可根据appKey获取对应的secret.
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface AppSecretManager { + + /** + * 获取应用程序的密钥 + * + * @param appKey + * @return {@link String} + */ + String getSecret(String appKey); + + /** + * 是否是合法的appKey + * + * @param appKey + * @return {@link Boolean} + */ + boolean isValidAppKey(String appKey); +} + diff --git a/rop/src/main/java/com/rop/security/DefaultFileUploadController.java b/rop/src/main/java/com/rop/security/DefaultFileUploadController.java index 4a095ea..378c972 100644 --- a/rop/src/main/java/com/rop/security/DefaultFileUploadController.java +++ b/rop/src/main/java/com/rop/security/DefaultFileUploadController.java @@ -1,91 +1,102 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-2 - */ -package com.rop.security; - -import org.springframework.util.CollectionUtils; - -import java.util.ArrayList; -import java.util.List; - -/** - *
- *    1.如果maxSize为非正数,则表示不限制大小;
- *    2.如果allowAllTypes为true表示不限制文件类型;
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultFileUploadController implements FileUploadController { - - private List fileTypes; - - private int maxSize = -1; - - private boolean allowAllTypes = false; - - public DefaultFileUploadController(int maxSize) { - this.allowAllTypes = true; - this.maxSize = maxSize; - } - - /** - * @param fileTypes - * @param maxSize 最大文件大小,单位为k - */ - public DefaultFileUploadController(List fileTypes, int maxSize) { - ArrayList tempFileTypes = new ArrayList(fileTypes.size()); - for (String fileType : fileTypes) { - tempFileTypes.add(fileType.toLowerCase()); - } - this.fileTypes = tempFileTypes; - this.maxSize = maxSize; - } - - - public boolean isAllowFileType(String fileType) { - if(allowAllTypes){ - return true; - }else{ - if(fileType == null){ - return false; - }else{ - fileType = fileType.toLowerCase(); - return fileTypes.contains(fileType); - } - } - } - - - public boolean isExceedMaxSize(int fileSize) { - if(maxSize > 0){ - return fileSize > maxSize * 1024; - }else{ - return false; - } - } - - - public String getAllowFileTypes() { - if (CollectionUtils.isEmpty(fileTypes)) { - return ""; - }else{ - StringBuilder sb = new StringBuilder(); - String seprator = ""; - for (String fileType : fileTypes) { - sb.append(seprator); - sb.append(fileType); - seprator = ","; - } - return sb.toString(); - } - } - - - public int getMaxSize() { - return this.maxSize; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import org.springframework.util.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; + +/** + *
+ *    1.如果maxSize为非正数,则表示不限制大小;
+ *    2.如果allowAllTypes为true表示不限制文件类型;
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultFileUploadController implements FileUploadController { + + private List fileTypes; + + private int maxSize = -1; + + private boolean allowAllTypes = false; + + public DefaultFileUploadController(int maxSize) { + this.allowAllTypes = true; + this.maxSize = maxSize; + } + + /** + * @param fileTypes + * @param maxSize 最大文件大小,单位为k + */ + public DefaultFileUploadController(List fileTypes, int maxSize) { + ArrayList tempFileTypes = new ArrayList(fileTypes.size()); + for (String fileType : fileTypes) { + tempFileTypes.add(fileType.toLowerCase()); + } + this.fileTypes = tempFileTypes; + this.maxSize = maxSize; + } + + + public boolean isAllowFileType(String fileType) { + if(allowAllTypes){ + return true; + }else{ + if(fileType == null){ + return false; + }else{ + fileType = fileType.toLowerCase(); + return fileTypes.contains(fileType); + } + } + } + + + public boolean isExceedMaxSize(int fileSize) { + if(maxSize > 0){ + return fileSize > maxSize * 1024; + }else{ + return false; + } + } + + + public String getAllowFileTypes() { + if (CollectionUtils.isEmpty(fileTypes)) { + return ""; + }else{ + StringBuilder sb = new StringBuilder(); + String seprator = ""; + for (String fileType : fileTypes) { + sb.append(seprator); + sb.append(fileType); + seprator = ","; + } + return sb.toString(); + } + } + + + public int getMaxSize() { + return this.maxSize; + } +} + diff --git a/rop/src/main/java/com/rop/security/DefaultInvokeTimesController.java b/rop/src/main/java/com/rop/security/DefaultInvokeTimesController.java index f094123..0e64f42 100644 --- a/rop/src/main/java/com/rop/security/DefaultInvokeTimesController.java +++ b/rop/src/main/java/com/rop/security/DefaultInvokeTimesController.java @@ -1,43 +1,54 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-7-30 - */ -package com.rop.security; - -import com.rop.session.Session; - -/** - *
- *    默认的实现
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultInvokeTimesController implements InvokeTimesController { - - - public void caculateInvokeTimes(String appKey, Session session) { - } - - - public boolean isUserInvokeLimitExceed(String appKey, Session session) { - return false; - } - - - public boolean isSessionInvokeLimitExceed(String appKey, String sessionId) { - return false; - } - - - public boolean isAppInvokeLimitExceed(String appKey) { - return false; - } - - - public boolean isAppInvokeFrequencyExceed(String appKey) { - return false; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.session.Session; + +/** + *
+ *    默认的实现
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultInvokeTimesController implements InvokeTimesController { + + + public void caculateInvokeTimes(String appKey, Session session) { + } + + + public boolean isUserInvokeLimitExceed(String appKey, Session session) { + return false; + } + + + public boolean isSessionInvokeLimitExceed(String appKey, String sessionId) { + return false; + } + + + public boolean isAppInvokeLimitExceed(String appKey) { + return false; + } + + + public boolean isAppInvokeFrequencyExceed(String appKey) { + return false; + } +} + diff --git a/rop/src/main/java/com/rop/security/DefaultSecurityManager.java b/rop/src/main/java/com/rop/security/DefaultSecurityManager.java index 93477e7..a278f77 100644 --- a/rop/src/main/java/com/rop/security/DefaultSecurityManager.java +++ b/rop/src/main/java/com/rop/security/DefaultSecurityManager.java @@ -1,474 +1,456 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop.security; - -import com.rop.*; -import com.rop.annotation.HttpAction; -import com.rop.config.SystemParameterNames; -import com.rop.impl.DefaultServiceAccessController; -import com.rop.impl.SimpleRopRequestContext; -import com.rop.request.UploadFileUtils; -import com.rop.session.SessionManager; -import com.rop.utils.RopUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.validation.FieldError; -import org.springframework.validation.ObjectError; - -import java.util.*; - -/** - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultSecurityManager implements SecurityManager { - - protected Logger logger = LoggerFactory.getLogger(getClass()); - - protected ServiceAccessController serviceAccessController = new DefaultServiceAccessController(); - - protected AppSecretManager appSecretManager = new FileBaseAppSecretManager(); - - protected SessionManager sessionManager; - - protected InvokeTimesController invokeTimesController; - - protected FileUploadController fileUploadController; - - private static final Map INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS = new LinkedHashMap(); - - static { - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("typeMismatch", SubErrorType.ISV_PARAMETERS_MISMATCH); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("NotNull", SubErrorType.ISV_MISSING_PARAMETER); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("NotEmpty", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Size", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Range", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Pattern", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Min", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Max", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("DecimalMin", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("DecimalMax", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Digits", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Past", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Future", SubErrorType.ISV_INVALID_PARAMETE); - INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("AssertFalse", SubErrorType.ISV_INVALID_PARAMETE); - } - - - public MainError validateSystemParameters(RopRequestContext context) { - RopContext ropContext = context.getRopContext(); - MainError mainError = null; - - //1.检查appKey - if (context.getAppKey() == null) { - return MainErrors.getError(MainErrorType.MISSING_APP_KEY, context.getLocale(), - context.getMethod(),context.getVersion(), - SystemParameterNames.getAppKey()); - } - if (!appSecretManager.isValidAppKey(context.getAppKey())) { - return MainErrors.getError(MainErrorType.INVALID_APP_KEY, context.getLocale(), - context.getMethod(),context.getVersion(), - context.getAppKey()); - } - - - //2.检查会话 - mainError = checkSession(context); - if (mainError != null) { - return mainError; - } - - //3.检查method参数 - if (context.getMethod() == null) { - return MainErrors.getError(MainErrorType.MISSING_METHOD, context.getLocale(), - SystemParameterNames.getMethod()); - } else { - if (!ropContext.isValidMethod(context.getMethod())) { - return MainErrors.getError(MainErrorType.INVALID_METHOD, - context.getLocale(),context.getMethod()); - } - } - - //4.检查v参数 - if (context.getVersion() == null) { - return MainErrors.getError(MainErrorType.MISSING_VERSION, context.getLocale(), - context.getMethod(), - SystemParameterNames.getVersion()); - } else { - if (!ropContext.isValidVersion(context.getMethod(), context.getVersion())) { - return MainErrors.getError( - MainErrorType.UNSUPPORTED_VERSION, context.getLocale(), - context.getMethod(), context.getVersion()); - } - } - - //5.检查签名正确性 - mainError = checkSign(context); - if (mainError != null) { - return mainError; - } - - //6.检查服务方法的版本是否已经过期 - if (context.getServiceMethodDefinition().isObsoleted()) { - return MainErrors.getError(MainErrorType.METHOD_OBSOLETED, context.getLocale(), - context.getMethod(), context.getVersion()); - } - - //7.检查请求HTTP方法的匹配性 - mainError = validateHttpAction(context); - if (mainError != null) { - return mainError; - } - - //8.检查 format - if (!MessageFormat.isValidFormat(context.getFormat())) { - return MainErrors.getError(MainErrorType.INVALID_FORMAT, context.getLocale(), - context.getMethod(),context.getVersion(),context.getFormat()); - } - - return null; - } - - - public MainError validateOther(RopRequestContext rrctx) { - - MainError mainError = null; - - //1.判断应用/用户是否有权访问目标服务 - mainError = checkServiceAccessAllow(rrctx); - if (mainError != null) { - return mainError; - } - - //2.判断应用/会话/用户访问服务的次数或频度是否超限 - mainError = checkInvokeTimesLimit(rrctx); - if (mainError != null) { - return mainError; - } - - //3.如果是上传文件的服务,检查文件类型和大小是否满足要求 - mainError = checkUploadFile(rrctx); - if (mainError != null) { - return mainError; - } - - //4.检查业务参数合法性 - mainError = validateBusinessParams(rrctx); - if (mainError != null) { - return mainError; - } - - return null; - } - - private MainError checkUploadFile(RopRequestContext rrctx) { - ServiceMethodHandler serviceMethodHandler = rrctx.getServiceMethodHandler(); - if (serviceMethodHandler != null && serviceMethodHandler.hasUploadFiles()) { - List fileFieldNames = serviceMethodHandler.getUploadFileFieldNames(); - for (String fileFieldName : fileFieldNames) { - String paramValue = rrctx.getParamValue(fileFieldName); - if (paramValue != null) { - if (paramValue.indexOf("@") < 0) { - return MainErrors.getError( - MainErrorType.UPLOAD_FAIL, rrctx.getLocale(), - rrctx.getMethod(), rrctx.getVersion(), "MESSAGE_VALID:not contain '@'."); - } else { - String fileType = UploadFileUtils.getFileType(paramValue); - if (!fileUploadController.isAllowFileType(fileType)) { - return MainErrors.getError( - MainErrorType.UPLOAD_FAIL, rrctx.getLocale(), - rrctx.getMethod(), rrctx.getVersion(), - "FILE_TYPE_NOT_ALLOW:the valid file types is:" + fileUploadController.getAllowFileTypes()); - } - byte[] fileContent = UploadFileUtils.decode(paramValue); - if (fileUploadController.isExceedMaxSize(fileContent.length)) { - return MainErrors.getError( - MainErrorType.UPLOAD_FAIL, rrctx.getLocale(), - rrctx.getMethod(), rrctx.getVersion(), - "EXCEED_MAX_SIZE:" + fileUploadController.getMaxSize() + "k"); - } - } - } - } - } - return null; - } - - - public void setInvokeTimesController(InvokeTimesController invokeTimesController) { - this.invokeTimesController = invokeTimesController; - } - - - public void setServiceAccessController(ServiceAccessController serviceAccessController) { - this.serviceAccessController = serviceAccessController; - } - - - public void setAppSecretManager(AppSecretManager appSecretManager) { - this.appSecretManager = appSecretManager; - } - - - public void setSessionManager(SessionManager sessionManager) { - this.sessionManager = sessionManager; - } - - - public void setFileUploadController(FileUploadController fileUploadController) { - this.fileUploadController = fileUploadController; - } - - private MainError checkInvokeTimesLimit(RopRequestContext rrctx) { - if (invokeTimesController.isAppInvokeFrequencyExceed(rrctx.getAppKey())) { - return MainErrors.getError(MainErrorType.EXCEED_APP_INVOKE_FREQUENCY_LIMITED, rrctx.getLocale()); - } else if (invokeTimesController.isAppInvokeLimitExceed(rrctx.getAppKey())) { - return MainErrors.getError(MainErrorType.EXCEED_APP_INVOKE_LIMITED, rrctx.getLocale()); - } else if (invokeTimesController.isSessionInvokeLimitExceed(rrctx.getAppKey(), rrctx.getSessionId())) { - return MainErrors.getError(MainErrorType.EXCEED_SESSION_INVOKE_LIMITED, rrctx.getLocale()); - } else if (invokeTimesController.isUserInvokeLimitExceed(rrctx.getAppKey(), rrctx.getSession())) { - return MainErrors.getError(MainErrorType.EXCEED_USER_INVOKE_LIMITED, rrctx.getLocale()); - } else { - return null; - } - } - - /** - * 校验是否是合法的HTTP动作 - * - * @param ropRequestContext - */ - private MainError validateHttpAction(RopRequestContext ropRequestContext) { - MainError mainError = null; - HttpAction[] httpActions = ropRequestContext.getServiceMethodDefinition().getHttpAction(); - if (httpActions.length > 0) { - boolean isValid = false; - for (HttpAction httpAction : httpActions) { - if (httpAction == ropRequestContext.getHttpAction()) { - isValid = true; - break; - } - } - if (!isValid) { - mainError = MainErrors.getError( - MainErrorType.HTTP_ACTION_NOT_ALLOWED, ropRequestContext.getLocale(), - ropRequestContext.getMethod(), ropRequestContext.getVersion(), - ropRequestContext.getHttpAction()); - } - } - return mainError; - } - - public ServiceAccessController getServiceAccessController() { - return serviceAccessController; - } - - public AppSecretManager getAppSecretManager() { - return appSecretManager; - } - - private MainError checkServiceAccessAllow(RopRequestContext smc) { - if (!getServiceAccessController().isAppGranted(smc.getAppKey(), smc.getMethod(), smc.getVersion())) { - MainError mainError = SubErrors.getMainError(SubErrorType.ISV_INVALID_PERMISSION, smc.getLocale()); - SubError subError = SubErrors.getSubError(SubErrorType.ISV_INVALID_PERMISSION.value(), - SubErrorType.ISV_INVALID_PERMISSION.value(), - smc.getLocale()); - mainError.addSubError(subError); - if (mainError != null && logger.isErrorEnabled()) { - logger.debug("未向ISV开放该服务的执行权限(" + smc.getMethod() + ")"); - } - return mainError; - } else { - if (!getServiceAccessController().isUserGranted(smc.getSession(), smc.getMethod(), smc.getVersion())) { - MainError mainError = MainErrors.getError( - MainErrorType.INSUFFICIENT_USER_PERMISSIONS, smc.getLocale(), - smc.getMethod(), smc.getVersion()); - SubError subError = SubErrors.getSubError(SubErrorType.ISV_INVALID_PERMISSION.value(), - SubErrorType.ISV_INVALID_PERMISSION.value(), - smc.getLocale()); - mainError.addSubError(subError); - if (mainError != null && logger.isErrorEnabled()) { - logger.debug("未向会话用户开放该服务的执行权限(" + smc.getMethod() + ")"); - } - return mainError; - } - return null; - } - } - - private MainError validateBusinessParams(RopRequestContext context) { - List errorList = - (List) context.getAttribute(SimpleRopRequestContext.SPRING_VALIDATE_ERROR_ATTRNAME); - - //将Bean数据绑定时产生的错误转换为Rop的错误 - if (errorList != null && errorList.size() > 0) { - return toMainErrorOfSpringValidateErrors(errorList, context.getLocale(),context); - } else { - return null; - } - } - - /** - * 检查签名的有效性 - * - * @param context - * @return - */ - private MainError checkSign(RopRequestContext context) { - - //系统级签名开启,且服务方法需求签名 - if (context.isSignEnable()) { - if (!context.getServiceMethodDefinition().isIgnoreSign()) { - if (context.getSign() == null) { - return MainErrors.getError(MainErrorType.MISSING_SIGNATURE, context.getLocale(), - context.getMethod(),context.getVersion(), - SystemParameterNames.getSign()); - } else { - - //获取需要签名的参数 - List ignoreSignFieldNames = context.getServiceMethodHandler().getIgnoreSignFieldNames(); - HashMap needSignParams = new HashMap(); - for (Map.Entry entry : context.getAllParams().entrySet()) { - if (!ignoreSignFieldNames.contains(entry.getKey())) { - needSignParams.put(entry.getKey(), entry.getValue()); - } - } - - //查看密钥是否存在,不存在则说明appKey是非法的 - String signSecret = getAppSecretManager().getSecret(context.getAppKey()); - if (signSecret == null) { - throw new RopException("无法获取" + context.getAppKey() + "对应的密钥"); - } - - String signValue = RopUtils.sign(needSignParams, signSecret); - if (!signValue.equals(context.getSign())) { - if (logger.isErrorEnabled()) { - logger.error(context.getAppKey() + "的签名不合法,请检查"); - } - return MainErrors.getError( - MainErrorType.INVALID_SIGNATURE, context.getLocale(), - context.getMethod(),context.getVersion()); - } else { - return null; - } - } - } else { - if (logger.isWarnEnabled()) { - logger.warn(context.getMethod() + "忽略了签名"); - } - return null; - } - } else { - if (logger.isDebugEnabled()) { - logger.warn("{}{}服务方法未开启签名", context.getMethod(), context.getVersion()); - } - return null; - } - } - - - /** - * 是否是合法的会话 - * - * @param context - * @return - */ - private MainError checkSession(RopRequestContext context) { - //需要进行session检查 - if (context.getServiceMethodHandler() != null && - context.getServiceMethodHandler().getServiceMethodDefinition().isNeedInSession()) { - if (context.getSessionId() == null) { - return MainErrors.getError(MainErrorType.MISSING_SESSION, context.getLocale(), - context.getMethod(), context.getVersion(), SystemParameterNames.getSessionId()); - } else { - if (!isValidSession(context)) { - return MainErrors.getError(MainErrorType.INVALID_SESSION, context.getLocale(), - context.getMethod(), context.getVersion(),context.getSessionId()); - } - } - } - return null; - } - - private boolean isValidSession(RopRequestContext smc) { - if (sessionManager.getSession(smc.getSessionId()) == null) { - if (logger.isDebugEnabled()) { - logger.debug(smc.getSessionId() + "会话不存在,请检查。"); - } - return false; - } else { - return true; - } - } - - /** - * 将通过JSR 303框架校验的错误转换为Rop的错误体系 - * - * @param allErrors - * @param locale - * @return - */ - private MainError toMainErrorOfSpringValidateErrors( - List allErrors, Locale locale,RopRequestContext context) { - if (hastSubErrorType(allErrors, SubErrorType.ISV_MISSING_PARAMETER)) { - return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_MISSING_PARAMETER,context); - } else if (hastSubErrorType(allErrors, SubErrorType.ISV_PARAMETERS_MISMATCH)) { - return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_PARAMETERS_MISMATCH,context); - } else { - return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_INVALID_PARAMETE,context); - } - } - - /** - * 判断错误列表中是否包括指定的子错误 - * - * @param allErrors - * @param subErrorType1 - * @return - */ - private boolean hastSubErrorType(List allErrors, SubErrorType subErrorType1) { - for (ObjectError objectError : allErrors) { - if (objectError instanceof FieldError) { - FieldError fieldError = (FieldError) objectError; - if (INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.containsKey(fieldError.getCode())) { - SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode()); - if (tempSubErrorType == subErrorType1) { - return true; - } - } - } - } - return false; - } - - /** - * 生成对应子错误的错误类 - * - * @param allErrors - * @param locale - * @param subErrorType - * @return - */ - private MainError getBusinessParameterMainError( - List allErrors, Locale locale, SubErrorType subErrorType,RopRequestContext context) { - MainError mainError = SubErrors.getMainError(subErrorType, locale,context.getMethod(),context.getVersion()); - for (ObjectError objectError : allErrors) { - if (objectError instanceof FieldError) { - FieldError fieldError = (FieldError) objectError; - SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode()); - if (tempSubErrorType == subErrorType) { - String subErrorCode = - SubErrors.getSubErrorCode( - tempSubErrorType, fieldError.getField(), fieldError.getRejectedValue()); - SubError subError = SubErrors.getSubError(subErrorCode, tempSubErrorType.value(), locale, - fieldError.getField(), fieldError.getRejectedValue()); - mainError.addSubError(subError); - } - } - } - return mainError; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.*; +import com.rop.annotation.HttpAction; +import com.rop.config.SystemParameterNames; +import com.rop.impl.DefaultServiceAccessController; +import com.rop.impl.SimpleRopRequestContext; +import com.rop.converter.UploadFileUtils; +import com.rop.response.MainError; +import com.rop.response.MainErrorType; +import com.rop.response.SubError; +import com.rop.response.SubErrorType; +import com.rop.session.SessionManager; +import com.rop.sign.DigestSignHandler; +import com.rop.sign.SignHandler; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.validation.FieldError; +import org.springframework.validation.ObjectError; + +import java.util.*; + +/** + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultSecurityManager implements SecurityManager { + + protected Logger logger = LoggerFactory.getLogger(getClass()); + + protected ServiceAccessController serviceAccessController = new DefaultServiceAccessController(); + + protected AppSecretManager appSecretManager = new FileBaseAppSecretManager(); + + protected SessionManager sessionManager; + + protected InvokeTimesController invokeTimesController; + + protected FileUploadController fileUploadController; + + protected SignHandler signHandler; + + private static final Map INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS = new LinkedHashMap(); + + static { + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("typeMismatch", SubErrorType.ISV_PARAMETERS_MISMATCH); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("NotNull", SubErrorType.ISV_MISSING_PARAMETER); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("NotEmpty", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Size", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Range", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Pattern", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Min", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Max", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("DecimalMin", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("DecimalMax", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Digits", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Past", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("Future", SubErrorType.ISV_INVALID_PARAMETE); + INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.put("AssertFalse", SubErrorType.ISV_INVALID_PARAMETE); + } + + public MainError validateSystemParameters(RopRequestContext context) { + RopContext ropContext = context.getRopContext(); + MainError mainError = null; + String method = context.getMethod(); + String version = context.getVersion(); + Locale locale = context.getLocale(); + // 1.检查appKey + if (context.getAppKey() == null) { + return MainErrors.getError(MainErrorType.MISSING_APP_KEY, locale, method, + version, SystemParameterNames.getAppKey()); + } + if (!appSecretManager.isValidAppKey(context.getAppKey())) { + return MainErrors.getError(MainErrorType.INVALID_APP_KEY, locale, method, + version, context.getAppKey()); + } + // 2.检查会话 + mainError = checkSession(context); + if (mainError != null) { + return mainError; + } + // 3.检查method参数 + if (context.getMethod() == null) { + return MainErrors.getError(MainErrorType.MISSING_METHOD, locale, + SystemParameterNames.getMethod()); + } else { + if (!ropContext.isValidMethod(context.getMethod())) { + return MainErrors.getError(MainErrorType.INVALID_METHOD, locale, method); + } + } + // 4.检查v参数 + if (context.getVersion() == null) { + return MainErrors.getError(MainErrorType.MISSING_VERSION, locale, method, + SystemParameterNames.getVersion()); + } else { + if (!ropContext.isValidVersion(context.getMethod(), context.getVersion())) { + return MainErrors.getError(MainErrorType.UNSUPPORTED_VERSION, locale, method, version); + } + } + // 5.检查签名正确性 + mainError = checkSign(context); + if (mainError != null) { + return mainError; + } + // 6.检查服务方法的版本是否已经过期 + if (context.getServiceMethodDefinition().isObsoleted()) { + return MainErrors.getError(MainErrorType.METHOD_OBSOLETED, locale, method, version); + } + // 7.检查请求HTTP方法的匹配性 + mainError = validateHttpAction(context); + if (mainError != null) { + return mainError; + } + // 8.检查 format + if (!MessageFormat.isValidFormat(context.getFormat())) { + return MainErrors.getError(MainErrorType.INVALID_FORMAT, locale, method, version, context.getFormat()); + } + return null; + } + + public MainError validateOther(RopRequestContext rrctx) { + MainError mainError = null; + // 1.判断应用/用户是否有权访问目标服务 + mainError = checkServiceAccessAllow(rrctx); + if (mainError != null) { + return mainError; + } + // 2.判断应用/会话/用户访问服务的次数或频度是否超限 + mainError = checkInvokeTimesLimit(rrctx); + if (mainError != null) { + return mainError; + } + // 3.如果是上传文件的服务,检查文件类型和大小是否满足要求 + mainError = checkUploadFile(rrctx); + if (mainError != null) { + return mainError; + } + // 4.检查业务参数合法性 + mainError = validateBusinessParams(rrctx); + if (mainError != null) { + return mainError; + } + return null; + } + + private MainError checkUploadFile(RopRequestContext rrctx) { + ServiceMethodHandler serviceMethodHandler = rrctx.getServiceMethodHandler(); + if (serviceMethodHandler == null || !serviceMethodHandler.hasUploadFiles()) { + return null; + } + Locale locale = rrctx.getLocale(); + String method = rrctx.getMethod(); + String version = rrctx.getVersion(); + List fileFieldNames = serviceMethodHandler.getUploadFileFieldNames(); + MainErrorType type = MainErrorType.UPLOAD_FAIL; + for (String fileFieldName : fileFieldNames) { + String paramValue = rrctx.getParamValue(fileFieldName); + if (paramValue != null) { + if (paramValue.indexOf("@") < 0) { + String msg = "MESSAGE_VALID:not contain '@'."; + return MainErrors.getError(type, locale, method, version, msg); + } else { + String fileType = UploadFileUtils.getFileType(paramValue); + if (!fileUploadController.isAllowFileType(fileType)) { + String msg = "FILE_TYPE_NOT_ALLOW:the valid file types is:" + + fileUploadController.getAllowFileTypes(); + return MainErrors.getError(type, locale, method, version, msg); + } + byte[] fileContent = UploadFileUtils.decode(paramValue); + if (fileUploadController.isExceedMaxSize(fileContent.length)) { + String msg = "EXCEED_MAX_SIZE:" + fileUploadController.getMaxSize() + "k"; + return MainErrors.getError(type, locale, method, version, msg); + } + } + } + } + return null; + } + + public void setInvokeTimesController(InvokeTimesController invokeTimesController) { + this.invokeTimesController = invokeTimesController; + } + + public void setServiceAccessController(ServiceAccessController serviceAccessController) { + this.serviceAccessController = serviceAccessController; + } + + public void setAppSecretManager(AppSecretManager appSecretManager) { + this.appSecretManager = appSecretManager; + } + + public void setSessionManager(SessionManager sessionManager) { + this.sessionManager = sessionManager; + } + + public void setFileUploadController(FileUploadController fileUploadController) { + this.fileUploadController = fileUploadController; + } + + private MainError checkInvokeTimesLimit(RopRequestContext rrctx) { + if (invokeTimesController.isAppInvokeFrequencyExceed(rrctx.getAppKey())) { + return MainErrors.getError(MainErrorType.EXCEED_APP_INVOKE_FREQUENCY_LIMITED, rrctx.getLocale()); + } else if (invokeTimesController.isAppInvokeLimitExceed(rrctx.getAppKey())) { + return MainErrors.getError(MainErrorType.EXCEED_APP_INVOKE_LIMITED, rrctx.getLocale()); + } else if (invokeTimesController.isSessionInvokeLimitExceed(rrctx.getAppKey(), rrctx.getSessionId())) { + return MainErrors.getError(MainErrorType.EXCEED_SESSION_INVOKE_LIMITED, rrctx.getLocale()); + } else if (invokeTimesController.isUserInvokeLimitExceed(rrctx.getAppKey(), rrctx.getSession())) { + return MainErrors.getError(MainErrorType.EXCEED_USER_INVOKE_LIMITED, rrctx.getLocale()); + } else { + return null; + } + } + + /** + * 校验是否是合法的HTTP动作 + * + * @param ropRequestContext + */ + private MainError validateHttpAction(RopRequestContext ropRequestContext) { + MainError mainError = null; + HttpAction[] httpActions = ropRequestContext.getServiceMethodDefinition().getHttpAction(); + if (httpActions.length > 0) { + boolean isValid = false; + HttpAction action = ropRequestContext.getHttpAction(); + for (HttpAction httpAction : httpActions) { + if (httpAction == action) { + isValid = true; + break; + } + } + if (!isValid) { + Locale locale = ropRequestContext.getLocale(); + String method = ropRequestContext.getMethod(); + String version = ropRequestContext.getVersion(); + mainError = MainErrors.getError(MainErrorType.HTTP_ACTION_NOT_ALLOWED, + locale, method, version, action); + } + } + return mainError; + } + + public ServiceAccessController getServiceAccessController() { + return serviceAccessController; + } + + public AppSecretManager getAppSecretManager() { + return appSecretManager; + } + + private MainError checkServiceAccessAllow(RopRequestContext smc) { + if (!getServiceAccessController().isAppGranted(smc.getAppKey(), smc.getMethod(), smc.getVersion())) { + MainError mainError = SubErrors.getMainError(SubErrorType.ISV_INVALID_PERMISSION, smc.getLocale()); + SubError subError = SubErrors.getSubError(SubErrorType.ISV_INVALID_PERMISSION.value(), + SubErrorType.ISV_INVALID_PERMISSION.value(), smc.getLocale()); + mainError.addSubError(subError); + if (mainError != null && logger.isErrorEnabled()) { + logger.debug("未向ISV开放该服务的执行权限(" + smc.getMethod() + ")"); + } + return mainError; + } else { + if (!getServiceAccessController().isUserGranted(smc.getSession(), smc.getMethod(), smc.getVersion())) { + MainError mainError = MainErrors.getError(MainErrorType.INSUFFICIENT_USER_PERMISSIONS, smc.getLocale(), + smc.getMethod(), smc.getVersion()); + SubError subError = SubErrors.getSubError(SubErrorType.ISV_INVALID_PERMISSION.value(), + SubErrorType.ISV_INVALID_PERMISSION.value(), smc.getLocale()); + mainError.addSubError(subError); + if (mainError != null && logger.isErrorEnabled()) { + logger.debug("未向会话用户开放该服务的执行权限(" + smc.getMethod() + ")"); + } + return mainError; + } + return null; + } + } + + private MainError validateBusinessParams(RopRequestContext context) { + @SuppressWarnings("unchecked") + List errorList = (List) context + .getAttribute(SimpleRopRequestContext.SPRING_VALIDATE_ERROR_ATTRNAME); + + // 将Bean数据绑定时产生的错误转换为Rop的错误 + if (errorList != null && errorList.size() > 0) { + return toMainErrorOfSpringValidateErrors(errorList, context.getLocale(), context); + } else { + return null; + } + } + + /** + * 检查签名的有效性 + * + * @param context + * @return + */ + private MainError checkSign(RopRequestContext context) { + String method = context.getMethod(); + String version = context.getVersion(); + if (!context.isSignEnable() || context.getServiceMethodDefinition().isIgnoreSign()) { + if (logger.isDebugEnabled()) { + logger.warn("{}{}服务方法未开启签名", method, version); + } + return null; + } + Locale locale = context.getLocale(); + String signKey = SystemParameterNames.getSign(); + // 系统级签名开启,且服务方法需求签名 + if (context.getSign() == null) { + return MainErrors.getError(MainErrorType.MISSING_SIGNATURE, locale, method, version, signKey); + } else { + // 获取需要签名的参数 + List ignoreSignFieldNames = context.getServiceMethodHandler().getIgnoreSignFieldNames(); + List ignoreSigns = SystemParameterNames.getIgnoreSignFieldNames(); + if (ignoreSigns != null && ignoreSigns.size() > 0) { + ignoreSignFieldNames.addAll(ignoreSigns); + } + if (!getSignHandler().signCheck(context.getSign(), context.getAllParams(), ignoreSignFieldNames)) { + if (logger.isErrorEnabled()) { + logger.error(context.getAppKey() + "的签名不合法,请检查"); + } + return MainErrors.getError(MainErrorType.INVALID_SIGNATURE, locale, method, version); + } else { + return null; + } + } + } + + /** + * 是否是合法的会话 + * + * @param context + * @return + */ + private MainError checkSession(RopRequestContext context) { + // 不需要进行session检查 + if (context.getServiceMethodHandler() == null + || !context.getServiceMethodHandler().getServiceMethodDefinition().isNeedInSession()) { + return null; + } + // 需要进行session检查 + if (context.getSessionId() == null) { + return MainErrors.getError(MainErrorType.MISSING_SESSION, context.getLocale(), context.getMethod(), + context.getVersion(), SystemParameterNames.getSessionId()); + } else { + if (!isValidSession(context)) { + return MainErrors.getError(MainErrorType.INVALID_SESSION, context.getLocale(), context.getMethod(), + context.getVersion(), context.getSessionId()); + } + } + return null; + } + + private boolean isValidSession(RopRequestContext smc) { + if (sessionManager.getSession(smc.getSessionId()) == null) { + if (logger.isDebugEnabled()) { + logger.debug(smc.getSessionId() + "会话不存在,请检查。"); + } + return false; + } else { + return true; + } + } + + /** + * 将通过JSR 303框架校验的错误转换为Rop的错误体系 + * + * @param allErrors + * @param locale + * @return + */ + private MainError toMainErrorOfSpringValidateErrors(List allErrors, Locale locale, + RopRequestContext context) { + if (hastSubErrorType(allErrors, SubErrorType.ISV_MISSING_PARAMETER)) { + return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_MISSING_PARAMETER, context); + } else if (hastSubErrorType(allErrors, SubErrorType.ISV_PARAMETERS_MISMATCH)) { + return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_PARAMETERS_MISMATCH, context); + } else { + return getBusinessParameterMainError(allErrors, locale, SubErrorType.ISV_INVALID_PARAMETE, context); + } + } + + /** + * 判断错误列表中是否包括指定的子错误 + * + * @param allErrors + * @param subErrorType1 + * @return + */ + private boolean hastSubErrorType(List allErrors, SubErrorType subErrorType1) { + for (ObjectError objectError : allErrors) { + if (objectError instanceof FieldError) { + FieldError fieldError = (FieldError) objectError; + if (INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.containsKey(fieldError.getCode())) { + SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode()); + if (tempSubErrorType == subErrorType1) { + return true; + } + } + } + } + return false; + } + + /** + * 生成对应子错误的错误类 + * + * @param allErrors + * @param locale + * @param subErrorType + * @return + */ + private MainError getBusinessParameterMainError(List allErrors, Locale locale, + SubErrorType subErrorType, RopRequestContext context) { + MainError mainError = SubErrors.getMainError(subErrorType, locale, context.getMethod(), context.getVersion()); + for (ObjectError objectError : allErrors) { + if (objectError instanceof FieldError) { + FieldError fieldError = (FieldError) objectError; + SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode()); + if (tempSubErrorType == subErrorType) { + String subErrorCode = SubErrors.getSubErrorCode(tempSubErrorType, fieldError.getField(), + fieldError.getRejectedValue()); + SubError subError = SubErrors.getSubError(subErrorCode, tempSubErrorType.value(), locale, + fieldError.getField(), fieldError.getRejectedValue()); + mainError.addSubError(subError); + } + } + } + return mainError; + } + + public void setSignHandler(SignHandler signHandler) { + this.signHandler = signHandler; + } + + public SignHandler getSignHandler() { + if(signHandler == null){ + signHandler = new DigestSignHandler("SHA-1", appSecretManager); + } + return signHandler; + } +} diff --git a/rop/src/main/java/com/rop/security/FileBaseAppSecretManager.java b/rop/src/main/java/com/rop/security/FileBaseAppSecretManager.java index a1fe3c1..76493f9 100644 --- a/rop/src/main/java/com/rop/security/FileBaseAppSecretManager.java +++ b/rop/src/main/java/com/rop/security/FileBaseAppSecretManager.java @@ -1,62 +1,73 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-3-1 - */ -package com.rop.security; - -import com.rop.RopException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.PropertiesLoaderUtils; - -import java.io.IOException; -import java.util.Properties; - -/** - *
- *   基于文件管理的应用密钥
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class FileBaseAppSecretManager implements AppSecretManager { - - private static final String ROP_APP_SECRET_PROPERTIES = "rop.appSecret.properties"; - - private String appSecretFile = ROP_APP_SECRET_PROPERTIES; - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private Properties properties; - - public String getSecret(String appKey) { - if (properties == null) { - try { - DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); - Resource resource = resourceLoader.getResource(appSecretFile); - properties = PropertiesLoaderUtils.loadProperties(resource); - } catch (IOException e) { - throw new RopException("在类路径下找不到rop.appSecret.properties的应用密钥的属性文件", e); - } - } - String secret = properties.getProperty(appKey); - - if (secret == null) { - logger.error("不存在应用键为{0}的密钥,请检查应用密钥的配置文件。", appKey); - } - return secret; - } - - public void setAppSecretFile(String appSecretFile) { - this.appSecretFile = appSecretFile; - } - - - public boolean isValidAppKey(String appKey) { - return getSecret(appKey) != null; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.RopException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PropertiesLoaderUtils; + +import java.io.IOException; +import java.util.Properties; + +/** + *
+ *   基于文件管理的应用密钥
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class FileBaseAppSecretManager implements AppSecretManager { + + private static final String ROP_APP_SECRET_PROPERTIES = "rop.appSecret.properties"; + + private String appSecretFile = ROP_APP_SECRET_PROPERTIES; + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private Properties properties; + + public String getSecret(String appKey) { + if (properties == null) { + try { + DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); + Resource resource = resourceLoader.getResource(appSecretFile); + properties = PropertiesLoaderUtils.loadProperties(resource); + } catch (IOException e) { + throw new RopException("在类路径下找不到rop.appSecret.properties的应用密钥的属性文件", e); + } + } + String secret = properties.getProperty(appKey); + + if (secret == null) { + logger.error("不存在应用键为{0}的密钥,请检查应用密钥的配置文件。", appKey); + } + return secret; + } + + public void setAppSecretFile(String appSecretFile) { + this.appSecretFile = appSecretFile; + } + + + public boolean isValidAppKey(String appKey) { + return getSecret(appKey) != null; + } +} + diff --git a/rop/src/main/java/com/rop/security/FileUploadController.java b/rop/src/main/java/com/rop/security/FileUploadController.java index 0810af4..80ee501 100644 --- a/rop/src/main/java/com/rop/security/FileUploadController.java +++ b/rop/src/main/java/com/rop/security/FileUploadController.java @@ -1,43 +1,54 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.security; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface FileUploadController { - - /** - * 上传文件的类型是否是允许 - * @param fileType - * @return - */ - boolean isAllowFileType(String fileType); - - /** - * 是否超过了上传大小的限制 - * @param fileSize - * @return - */ - boolean isExceedMaxSize(int fileSize); - - /** - * 获取支持上传的文件格式 - * @return - */ - String getAllowFileTypes(); - - /** - * 获取最大的文件大小,单位为K - * @return - */ - int getMaxSize(); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface FileUploadController { + + /** + * 上传文件的类型是否是允许 + * @param fileType + * @return + */ + boolean isAllowFileType(String fileType); + + /** + * 是否超过了上传大小的限制 + * @param fileSize + * @return + */ + boolean isExceedMaxSize(int fileSize); + + /** + * 获取支持上传的文件格式 + * @return + */ + String getAllowFileTypes(); + + /** + * 获取最大的文件大小,单位为K + * @return + */ + int getMaxSize(); +} + diff --git a/rop/src/main/java/com/rop/security/InvokeTimesController.java b/rop/src/main/java/com/rop/security/InvokeTimesController.java index 61b5519..f6ffdbe 100644 --- a/rop/src/main/java/com/rop/security/InvokeTimesController.java +++ b/rop/src/main/java/com/rop/security/InvokeTimesController.java @@ -1,54 +1,65 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-7-30 - */ -package com.rop.security; - -import com.rop.session.Session; - -/** - *
- *   服务访问次数及频率的控制管理器
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface InvokeTimesController { - - /** - * 计算应用、会话及用户服务调度总数 - * @param appKey - * @param session - */ - void caculateInvokeTimes(String appKey, Session session); - - /** - * 用户服务访问次数是否超限 - * @param session - * @return - */ - boolean isUserInvokeLimitExceed(String appKey, Session session); - - /** - * 某个会话的服务访问次数是否超限 - * @param sessionId - * @return - */ - boolean isSessionInvokeLimitExceed(String appKey, String sessionId); - - /** - * 应用的服务访问次数是否超限 - * @param appKey - * @return - */ - boolean isAppInvokeLimitExceed(String appKey); - - /** - * 应用对服务的访问频率是否超限 - * @param appKey - * @return - */ - boolean isAppInvokeFrequencyExceed(String appKey); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.session.Session; + +/** + *
+ *   服务访问次数及频率的控制管理器
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface InvokeTimesController { + + /** + * 计算应用、会话及用户服务调度总数 + * @param appKey + * @param session + */ + void caculateInvokeTimes(String appKey, Session session); + + /** + * 用户服务访问次数是否超限 + * @param session + * @return + */ + boolean isUserInvokeLimitExceed(String appKey, Session session); + + /** + * 某个会话的服务访问次数是否超限 + * @param sessionId + * @return + */ + boolean isSessionInvokeLimitExceed(String appKey, String sessionId); + + /** + * 应用的服务访问次数是否超限 + * @param appKey + * @return + */ + boolean isAppInvokeLimitExceed(String appKey); + + /** + * 应用对服务的访问频率是否超限 + * @param appKey + * @return + */ + boolean isAppInvokeFrequencyExceed(String appKey); +} + diff --git a/rop/src/main/java/com/rop/security/MainError.java b/rop/src/main/java/com/rop/security/MainError.java deleted file mode 100644 index ed277d5..0000000 --- a/rop/src/main/java/com/rop/security/MainError.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop.security; - -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface MainError { - - String getCode(); - - String getMessage(); - - String getSolution(); - - List getSubErrors(); - - MainError addSubError(SubError subError); - -} - diff --git a/rop/src/main/java/com/rop/security/MainErrors.java b/rop/src/main/java/com/rop/security/MainErrors.java index 4fee9c3..6b2c3d9 100644 --- a/rop/src/main/java/com/rop/security/MainErrors.java +++ b/rop/src/main/java/com/rop/security/MainErrors.java @@ -1,64 +1,78 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.NoSuchMessageException; -import org.springframework.context.support.MessageSourceAccessor; -import org.springframework.util.Assert; - -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class MainErrors { - - protected static Logger logger = LoggerFactory.getLogger(MainErrors.class); - - private static final String ERROR_CODE_PREFIX = "ERROR_"; - private static final String ERROR_SOLUTION_SUBFIX = "_SOLUTION"; - // 错误信息的国际化信息 - private static MessageSourceAccessor errorMessageSourceAccessor; - - public static MainError getError(MainErrorType mainErrorType,Locale locale,Object... params) { - String errorMessage = getErrorMessage(ERROR_CODE_PREFIX + mainErrorType.value(),locale,params); - String errorSolution = getErrorSolution(ERROR_CODE_PREFIX + mainErrorType.value() + ERROR_SOLUTION_SUBFIX, locale); - return new SimpleMainError(mainErrorType.value(), errorMessage, errorSolution); - } - - public static void setErrorMessageSourceAccessor(MessageSourceAccessor errorMessageSourceAccessor) { - MainErrors.errorMessageSourceAccessor = errorMessageSourceAccessor; - } - - private static String getErrorMessage(String code, Locale locale,Object... params) { - try { - Assert.notNull(errorMessageSourceAccessor, "请先设置错误消息的国际化资源"); - return errorMessageSourceAccessor.getMessage(code, params, locale); - } catch (NoSuchMessageException e) { - logger.error("不存在对应的错误键:{},请检查是否在i18n/rop/error的错误资源", code); - throw e; - } - } - - private static String getErrorSolution(String code, Locale locale) { - try { - Assert.notNull(errorMessageSourceAccessor, "请先设置错误解决方案的国际化资源"); - return errorMessageSourceAccessor.getMessage(code, new Object[]{}, locale); - } catch (NoSuchMessageException e) { - logger.error("不存在对应的错误键:{},请检查是否在i18n/rop/error的错误资源", code); - throw e; - } - } - - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.support.MessageSourceAccessor; +import org.springframework.util.Assert; + +import com.rop.response.MainError; +import com.rop.response.MainErrorType; + +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class MainErrors { + + protected static Logger logger = LoggerFactory.getLogger(MainErrors.class); + + private static final String ERROR_CODE_PREFIX = "ERROR_"; + private static final String ERROR_SOLUTION_SUBFIX = "_SOLUTION"; + // 错误信息的国际化信息 + private static MessageSourceAccessor errorMessageSourceAccessor; + + public static MainError getError(MainErrorType mainErrorType,Locale locale,Object... params) { + String errorMessage = getErrorMessage(ERROR_CODE_PREFIX + mainErrorType.value(),locale,params); + String errorSolution = getErrorSolution(ERROR_CODE_PREFIX + mainErrorType.value() + ERROR_SOLUTION_SUBFIX, locale); + return new SimpleMainError(mainErrorType.value(), errorMessage, errorSolution); + } + + public static void setErrorMessageSourceAccessor(MessageSourceAccessor errorMessageSourceAccessor) { + MainErrors.errorMessageSourceAccessor = errorMessageSourceAccessor; + } + + private static String getErrorMessage(String code, Locale locale,Object... params) { + try { + Assert.notNull(errorMessageSourceAccessor, "请先设置错误消息的国际化资源"); + return errorMessageSourceAccessor.getMessage(code, params, locale); + } catch (NoSuchMessageException e) { + logger.error("不存在对应的错误键:{},请检查是否在i18n/rop/error的错误资源", code); + throw e; + } + } + + private static String getErrorSolution(String code, Locale locale) { + try { + Assert.notNull(errorMessageSourceAccessor, "请先设置错误解决方案的国际化资源"); + return errorMessageSourceAccessor.getMessage(code, new Object[]{}, locale); + } catch (NoSuchMessageException e) { + logger.error("不存在对应的错误键:{},请检查是否在i18n/rop/error的错误资源", code); + throw e; + } + } + + +} + diff --git a/rop/src/main/java/com/rop/security/SecurityManager.java b/rop/src/main/java/com/rop/security/SecurityManager.java index 3b79159..7657f82 100644 --- a/rop/src/main/java/com/rop/security/SecurityManager.java +++ b/rop/src/main/java/com/rop/security/SecurityManager.java @@ -1,70 +1,89 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop.security; - -import com.rop.RopRequestContext; -import com.rop.session.SessionManager; - -/** - *
- *   负责对请求数据、会话、业务安全、应用密钥安全进行检查并返回相应的错误
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface SecurityManager { - - /** - * 对请求服务的上下文进行检查校验 - * - * @param ropRequestContext - * @return - */ - MainError validateSystemParameters(RopRequestContext ropRequestContext); - - /** - * 验证其它的事项:包括业务参数,业务安全性,会话安全等 - * - * @param ropRequestContext - * @return - */ - MainError validateOther(RopRequestContext ropRequestContext); - - /** - * 获取安全管理器 - * - * @return - */ - void setServiceAccessController(ServiceAccessController serviceAccessController); - - /** - * 获取应用密钥管理器 - * - * @return - */ - void setAppSecretManager(AppSecretManager appSecretManager); - - /** - * 设置会话管理器,以验证会话的合法性 - * - * @return - */ - void setSessionManager(SessionManager sessionManager); - - - /** - * 设置服务调度次数管理器 - * @param invokeTimesController - */ - void setInvokeTimesController(InvokeTimesController invokeTimesController); - - /** - * 文件上传控制器 - * @param fileUploadController - */ - void setFileUploadController(FileUploadController fileUploadController); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.RopRequestContext; +import com.rop.response.MainError; +import com.rop.session.SessionManager; +import com.rop.sign.SignHandler; + +/** + *
+ *   负责对请求数据、会话、业务安全、应用密钥安全进行检查并返回相应的错误
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface SecurityManager { + + /** + * 对请求服务的上下文进行检查校验 + * + * @param ropRequestContext + * @return + */ + MainError validateSystemParameters(RopRequestContext ropRequestContext); + + /** + * 验证其它的事项:包括业务参数,业务安全性,会话安全等 + * + * @param ropRequestContext + * @return + */ + MainError validateOther(RopRequestContext ropRequestContext); + + /** + * 获取安全管理器 + * + * @return + */ + void setServiceAccessController(ServiceAccessController serviceAccessController); + + /** + * 获取应用密钥管理器 + * + * @return + */ + void setAppSecretManager(AppSecretManager appSecretManager); + + /** + * 设置签名处理接口对象 + * @param signHandler + */ + void setSignHandler(SignHandler signHandler); + + /** + * 设置会话管理器,以验证会话的合法性 + * + * @return + */ + void setSessionManager(SessionManager sessionManager); + + + /** + * 设置服务调度次数管理器 + * @param invokeTimesController + */ + void setInvokeTimesController(InvokeTimesController invokeTimesController); + + /** + * 文件上传控制器 + * @param fileUploadController + */ + void setFileUploadController(FileUploadController fileUploadController); +} + diff --git a/rop/src/main/java/com/rop/security/ServiceAccessController.java b/rop/src/main/java/com/rop/security/ServiceAccessController.java index 98303ef..827de09 100644 --- a/rop/src/main/java/com/rop/security/ServiceAccessController.java +++ b/rop/src/main/java/com/rop/security/ServiceAccessController.java @@ -1,34 +1,45 @@ -/** - * - * 日 期:12-2-13 - */ -package com.rop.security; - -import com.rop.session.Session; - -/** - *
- *    安全控制控制器,决定用户是否有。
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public interface ServiceAccessController { - - /** - * 服务方法是否向ISV开放 - * @param method - * @param userId - * @return - */ - boolean isAppGranted(String appKey, String method, String version); - - /** - * 服务方法是否向当前用户开放 - * @param ropRequestContext - * @return - */ - boolean isUserGranted(Session session,String method,String version); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import com.rop.session.Session; + +/** + *
+ *    安全控制控制器,决定用户是否有。
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public interface ServiceAccessController { + + /** + * 服务方法是否向ISV开放 + * @param method + * @param userId + * @return {@link Boolean} + */ + boolean isAppGranted(String appKey, String method, String version); + + /** + * 服务方法是否向当前用户开放 + * @param ropRequestContext + * @return {@link Boolean} + */ + boolean isUserGranted(Session session,String method,String version); +} + diff --git a/rop/src/main/java/com/rop/security/SimpleMainError.java b/rop/src/main/java/com/rop/security/SimpleMainError.java index 6be4293..9b1e0f7 100644 --- a/rop/src/main/java/com/rop/security/SimpleMainError.java +++ b/rop/src/main/java/com/rop/security/SimpleMainError.java @@ -1,59 +1,73 @@ -/** - * - * 日 期:12-2-14 - */ -package com.rop.security; - -import java.util.ArrayList; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SimpleMainError implements MainError { - - private String code; - - private String message; - - private String solution; - - private List subErrors = new ArrayList(); - - public SimpleMainError(String code, String message, String solution) { - this.code = code; - this.message = message; - this.solution = solution; - } - - public String getCode() { - return code; - } - - public String getMessage() { - return message; - } - - public String getSolution() { - return solution; - } - - public List getSubErrors() { - return this.subErrors; - } - - public void setSubErrors(List subErrors) { - this.subErrors = subErrors; - } - - public MainError addSubError(SubError subError) { - this.subErrors.add(subError); - return this; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import java.util.ArrayList; +import java.util.List; + +import com.rop.response.MainError; +import com.rop.response.SubError; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SimpleMainError implements MainError { + + private String code; + + private String message; + + private String solution; + + private List subErrors = new ArrayList(); + + public SimpleMainError(String code, String message, String solution) { + this.code = code; + this.message = message; + this.solution = solution; + } + + public String getCode() { + return code; + } + + public String getMessage() { + return message; + } + + public String getSolution() { + return solution; + } + + public List getSubErrors() { + return this.subErrors; + } + + public void setSubErrors(List subErrors) { + this.subErrors = subErrors; + } + + public MainError addSubError(SubError subError) { + this.subErrors.add(subError); + return this; + } +} + diff --git a/rop/src/main/java/com/rop/security/SubErrors.java b/rop/src/main/java/com/rop/security/SubErrors.java index 58cee1c..7f33f64 100644 --- a/rop/src/main/java/com/rop/security/SubErrors.java +++ b/rop/src/main/java/com/rop/security/SubErrors.java @@ -1,101 +1,117 @@ -/** - * - * 日 期:12-2-11 - */ -package com.rop.security; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.NoSuchMessageException; -import org.springframework.context.support.MessageSourceAccessor; - -import java.util.EnumMap; -import java.util.Locale; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class SubErrors { - - protected static Logger logger = LoggerFactory.getLogger(SubErrors.class); - - //子错误和主错误对应Map,key为子错误代码,值为主错误代码 - private static final EnumMap SUBERROR_MAINERROR_MAPPINGS = - new EnumMap(SubErrorType.class); - - static { - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISP_SERVICE_UNAVAILABLE, MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISP_SERVICE_TIMEOUT, MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISV_MISSING_PARAMETER, MainErrorType.MISSING_REQUIRED_ARGUMENTS); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISV_PARAMETERS_MISMATCH, MainErrorType.INVALID_ARGUMENTS); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISV_INVALID_PARAMETE, MainErrorType.INVALID_ARGUMENTS); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISV_NOT_EXIST, MainErrorType.INVALID_ARGUMENTS); - SUBERROR_MAINERROR_MAPPINGS.put( - SubErrorType.ISV_INVALID_PERMISSION, MainErrorType.INSUFFICIENT_ISV_PERMISSIONS); - } - - private static MessageSourceAccessor messageSourceAccessor; - private static final String PARAM_1 = "xxx"; - private static final String PARAM_2 = "yyy"; - - public static void setErrorMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) { - SubErrors.messageSourceAccessor = messageSourceAccessor; - } - - /** - * 获取对应子错误的主错误 - * - * @param subErrorType - * @param locale - * @return - */ - public static MainError getMainError(SubErrorType subErrorType, Locale locale, Object... params) { - return MainErrors.getError(SUBERROR_MAINERROR_MAPPINGS.get(subErrorType), locale,params); - } - - - /** - * @param subErrorCode 子错误代码 - * @param subErrorKey 子错误信息键 - * @param locale 本地化 - * @param params 本地化消息参数 - * @return - */ - public static SubError getSubError(String subErrorCode, String subErrorKey, Locale locale, Object... params) { - try { - String parsedSubErrorMessage = messageSourceAccessor.getMessage(subErrorKey, params, locale); - return new SubError(subErrorCode, parsedSubErrorMessage); - } catch (NoSuchMessageException e) { - logger.error("不存在对应的错误键:{},请检查是否正确配置了应用的错误资源," + - "默认位置:i18n/rop/ropError", subErrorCode); - throw e; - } - } - - public static String getSubErrorCode(SubErrorType subErrorType, Object... params) { - String subErrorCode = subErrorType.value(); - if (params.length > 0) { - if (params.length == 1) { - subErrorCode = subErrorCode.replace(PARAM_1, (String) params[0]); - } else { - subErrorCode = subErrorCode.replace(PARAM_1, (String) params[0]); - if (params[1] != null) { - subErrorCode = subErrorCode.replace(PARAM_2, (String) params[1]); - } - } - } - return subErrorCode; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.security; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.NoSuchMessageException; +import org.springframework.context.support.MessageSourceAccessor; + +import com.rop.response.MainError; +import com.rop.response.MainErrorType; +import com.rop.response.SubError; +import com.rop.response.SubErrorType; + +import java.util.EnumMap; +import java.util.Locale; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class SubErrors { + + protected static Logger logger = LoggerFactory.getLogger(SubErrors.class); + + //子错误和主错误对应Map,key为子错误代码,值为主错误代码 + private static final EnumMap SUBERROR_MAINERROR_MAPPINGS = + new EnumMap(SubErrorType.class); + + static { + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISP_SERVICE_UNAVAILABLE, MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISP_SERVICE_TIMEOUT, MainErrorType.SERVICE_CURRENTLY_UNAVAILABLE); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISV_MISSING_PARAMETER, MainErrorType.MISSING_REQUIRED_ARGUMENTS); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISV_PARAMETERS_MISMATCH, MainErrorType.INVALID_ARGUMENTS); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISV_INVALID_PARAMETE, MainErrorType.INVALID_ARGUMENTS); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISV_NOT_EXIST, MainErrorType.INVALID_ARGUMENTS); + SUBERROR_MAINERROR_MAPPINGS.put( + SubErrorType.ISV_INVALID_PERMISSION, MainErrorType.INSUFFICIENT_ISV_PERMISSIONS); + } + + private static MessageSourceAccessor messageSourceAccessor; + private static final String PARAM_1 = "xxx"; + private static final String PARAM_2 = "yyy"; + + public static void setErrorMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) { + SubErrors.messageSourceAccessor = messageSourceAccessor; + } + + /** + * 获取对应子错误的主错误 + * + * @param subErrorType + * @param locale + * @return + */ + public static MainError getMainError(SubErrorType subErrorType, Locale locale, Object... params) { + return MainErrors.getError(SUBERROR_MAINERROR_MAPPINGS.get(subErrorType), locale,params); + } + + + /** + * @param subErrorCode 子错误代码 + * @param subErrorKey 子错误信息键 + * @param locale 本地化 + * @param params 本地化消息参数 + * @return + */ + public static SubError getSubError(String subErrorCode, String subErrorKey, Locale locale, Object... params) { + try { + String parsedSubErrorMessage = messageSourceAccessor.getMessage(subErrorKey, params, locale); + return new SubError(subErrorCode, parsedSubErrorMessage); + } catch (NoSuchMessageException e) { + logger.error("不存在对应的错误键:{},请检查是否正确配置了应用的错误资源," + + "默认位置:i18n/rop/ropError", subErrorCode); + throw e; + } + } + + public static String getSubErrorCode(SubErrorType subErrorType, Object... params) { + String subErrorCode = subErrorType.value(); + if (params.length > 0) { + if (params.length == 1) { + subErrorCode = subErrorCode.replace(PARAM_1, (String) params[0]); + } else { + subErrorCode = subErrorCode.replace(PARAM_1, (String) params[0]); + if (params[1] != null) { + subErrorCode = subErrorCode.replace(PARAM_2, (String) params[1]); + } + } + } + return subErrorCode; + } +} + diff --git a/rop/src/main/java/com/rop/session/AbstractAuthRequest.java b/rop/src/main/java/com/rop/session/AbstractAuthRequest.java deleted file mode 100644 index d99fe94..0000000 --- a/rop/src/main/java/com/rop/session/AbstractAuthRequest.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.rop.session; - -/** - * @author : chenxh - * @date: 13-8-13 - */ -public abstract class AbstractAuthRequest implements AuthRequest { - - private Object detail; - - - public Object getDetail() { - return detail; - } - - public void setDetail(Object detail) { - this.detail = detail; - } - -} diff --git a/rop/src/main/java/com/rop/session/AbstractAuthenticationManager.java b/rop/src/main/java/com/rop/session/AbstractAuthenticationManager.java deleted file mode 100644 index e58b5b6..0000000 --- a/rop/src/main/java/com/rop/session/AbstractAuthenticationManager.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.rop.session; - - -/** - * @author : chenxh - * @date: 13-8-13 - */ -public abstract class AbstractAuthenticationManager implements AuthenticationManager { - - private String[] appKeys = null; - - private boolean _default = false; - - - public String[] appkeys() { - return appKeys; - } - - - public boolean isDefault() { - return _default; - } - - public void setAppKeys(String[] appKeys) { - this.appKeys = appKeys; - } - - public void setDefault(boolean _default) { - this._default = _default; - } -} diff --git a/rop/src/main/java/com/rop/session/AbstractSession.java b/rop/src/main/java/com/rop/session/AbstractSession.java index 53970c2..3bae177 100644 --- a/rop/src/main/java/com/rop/session/AbstractSession.java +++ b/rop/src/main/java/com/rop/session/AbstractSession.java @@ -1,63 +1,69 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-21 - */ -package com.rop.session; - -import com.rop.CommonConstant; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public abstract class AbstractSession implements Session { - - private Map attributes = new HashMap(); - - - public void setAttribute(String name, Object obj) { - markChanged(); - attributes.put(name, obj); - } - - - public Object getAttribute(String name) { - markChanged(); - return attributes.get(name); - } - - - public Map getAllAttributes() { - Map tempAttributes = new HashMap(attributes.size()); - for (Map.Entry entry : attributes.entrySet()) { - if (!CommonConstant.SESSION_CHANGED.equals(entry.getKey())) { - tempAttributes.put(entry.getKey(),entry.getValue()); - } - } - return tempAttributes; - } - - - public void removeAttribute(String name) { - markChanged(); - attributes.remove(name); - } - - - public boolean isChanged() { - return attributes.containsKey(CommonConstant.SESSION_CHANGED); - } - - private void markChanged(){ - attributes.put(CommonConstant.SESSION_CHANGED,Boolean.TRUE); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +import com.rop.CommonConstant; + +import java.util.HashMap; +import java.util.Map; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@SuppressWarnings("serial") +public abstract class AbstractSession implements Session { + + private Map attributes = new HashMap(); + + public void setAttribute(String name, Object obj) { + markChanged(); + attributes.put(name, obj); + } + + public Object getAttribute(String name) { + markChanged(); + return attributes.get(name); + } + + public Map getAllAttributes() { + Map tempAttributes = new HashMap(attributes.size()); + for (Map.Entry entry : attributes.entrySet()) { + if (!CommonConstant.SESSION_CHANGED.equals(entry.getKey())) { + tempAttributes.put(entry.getKey(),entry.getValue()); + } + } + return tempAttributes; + } + + public void removeAttribute(String name) { + markChanged(); + attributes.remove(name); + } + + public boolean isChanged() { + return attributes.containsKey(CommonConstant.SESSION_CHANGED); + } + + private void markChanged(){ + attributes.put(CommonConstant.SESSION_CHANGED,Boolean.TRUE); + } +} + diff --git a/rop/src/main/java/com/rop/session/AuthRequest.java b/rop/src/main/java/com/rop/session/AuthRequest.java deleted file mode 100644 index e58bb76..0000000 --- a/rop/src/main/java/com/rop/session/AuthRequest.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.rop.session; - -/** - * 认证请求 - * @author : chenxh - * @date: 13-8-12 - */ -public interface AuthRequest{ - - /** - * 认证的主体,对于常见的用户名/密码的认证请求来说,认证主体即是用户名。 - * - * @return - */ - Object getPrincipal(); - - /** - * 认证的凭据,对于常见的用户名/密码的认证请求来说,凭据即是密码。 - * - * @return - */ - Object getCredential(); - - /** - * 认证主体的其它信息,如IP地址,所属单位等信息 - * - * @return - */ - Object getDetail(); -} diff --git a/rop/src/main/java/com/rop/session/AuthResponse.java b/rop/src/main/java/com/rop/session/AuthResponse.java deleted file mode 100644 index 8cb51a9..0000000 --- a/rop/src/main/java/com/rop/session/AuthResponse.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.rop.session; - -import java.util.HashMap; -import java.util.Map; - -/** - *认证结果,如果认证成功,则设置{@link Session},否则设置{@link #errorCode},{@link #errorCode}必须 - * 在ROP的国际化文件中定义。 - * @author : chenxh - * @date: 13-8-13 - */ -public class AuthResponse { - - private Session ropSession; - - private boolean authenticated = false; - - private String errorCode; - - public Session getRopSession() { - return ropSession; - } - - public void setRopSession(Session logonSession) { - this.ropSession = logonSession; - this.authenticated = true; - } - - public boolean isAuthenticated() { - return authenticated; - } - - public String getErrorCode() { - return errorCode; - } - - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } -} diff --git a/rop/src/main/java/com/rop/session/AuthenticationManager.java b/rop/src/main/java/com/rop/session/AuthenticationManager.java deleted file mode 100644 index a48ef73..0000000 --- a/rop/src/main/java/com/rop/session/AuthenticationManager.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.rop.session; - -/** - * @author : chenxh - * @date: 13-8-12 - */ -public interface AuthenticationManager { - - /** - * 对{@link AuthRequest}进行认证,并产生{@link AuthResponse}。如果认证成功,需要生成{@link com.rop.session.Session} - * - * @param authRequest - * @return - */ - AuthResponse authenticate(AuthRequest authRequest); - - /** - * 哪些应用使用这个认证管理器 - * - * @return - */ - String[] appkeys(); - - /** - * 是否是默认的认证器,如果某个应用没有对应的认证器,将采用默认的认证器 - * - * @return - */ - boolean isDefault(); - -} diff --git a/rop/src/main/java/com/rop/session/AuthenticationService.java b/rop/src/main/java/com/rop/session/AuthenticationService.java deleted file mode 100644 index 2d4201c..0000000 --- a/rop/src/main/java/com/rop/session/AuthenticationService.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Copyright: 版权所有 违者必究 2013 - */ -package com.rop.session; - -/** - * 其中T是登录请求的类,而R是注销请求的类 - * @author : chenxh - * @date: 13-10-16 - */ - -import com.rop.RopRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.UUID; - -public abstract class AuthenticationService { - - protected Logger logger = LoggerFactory.getLogger(this.getClass()); - /** - * 获取应用对应的认证管理器 - * @param appkey - * @return - */ - public abstract AuthenticationManager getAuthenticationManager(String appkey); - - /** - * 该方法在子类在实现,并打上@ServiceMethod注解,作为登录的服务方法 - * @param loginRequest - * @return - */ - public abstract Object logon(T logonRequest); - - - /** - * 该方法在子类在实现,并打上@ServiceMethod注解,作为注销的服务方法 - * @param loginRequest - * @return - */ - public abstract Object logout(R logoutRequest); - - /** - * 对登录请求进行认证,在子类的{@link #logon(com.rop.RopRequest)}调用. - * @param request - * @return - */ - protected AuthResponse authentication(T request) { - String appKey = request.getRopRequestContext().getAppKey(); - AuthenticationManager authenticationManager = getAuthenticationManager(appKey); - AuthRequest authRequest = toAuthRequest(request); - return authenticationManager.authenticate(authRequest); - } - - - /** - * 将{@code logonRequest}转换为{@link AuthRequest} - * @param logonRequest - * @return - */ - protected abstract AuthRequest toAuthRequest(Object logonRequest); - - /** - * 该方法在子类的{@link #logout(com.rop.RopRequest)}方法中调用. - * @param logoutRequest - * @return - */ - protected void removeSession(R logoutRequest){ - logoutRequest.getRopRequestContext().removeSession(); - } - - private String uuid() { - UUID uuid = UUID.randomUUID(); - return uuid.toString().toUpperCase(); - } - -} diff --git a/rop/src/main/java/com/rop/session/DefaultSessionManager.java b/rop/src/main/java/com/rop/session/DefaultSessionManager.java index 36e5c01..27266da 100644 --- a/rop/src/main/java/com/rop/session/DefaultSessionManager.java +++ b/rop/src/main/java/com/rop/session/DefaultSessionManager.java @@ -1,34 +1,49 @@ -package com.rop.session; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * @author libinsong@gmail.com - * @author 陈雄华 itstamen@qq.com - */ -public final class DefaultSessionManager implements SessionManager { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private final Map sessionCache = new ConcurrentHashMap(128, 0.75f, 32); - - - public void addSession(String sessionId, Session session) { - sessionCache.put(sessionId, session); - } - - - public Session getSession(String sessionId) { - return sessionCache.get(sessionId); - } - - - public void removeSession(String sessionId) { - sessionCache.remove(sessionId); - } - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author libinsong@gmail.com + * @author 陈雄华 itstamen@qq.com + */ +public final class DefaultSessionManager implements SessionManager { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private final Map sessionCache = new ConcurrentHashMap(128, 0.75f, 32); + + + public void addSession(String sessionId, Session session) { + sessionCache.put(sessionId, session); + } + + + public Session getSession(String sessionId) { + return sessionCache.get(sessionId); + } + + + public void removeSession(String sessionId) { + sessionCache.remove(sessionId); + } + } \ No newline at end of file diff --git a/rop/src/main/java/com/rop/session/RopSessionHolder.java b/rop/src/main/java/com/rop/session/RopSessionHolder.java index a21c5e9..d9544cd 100644 --- a/rop/src/main/java/com/rop/session/RopSessionHolder.java +++ b/rop/src/main/java/com/rop/session/RopSessionHolder.java @@ -1,26 +1,38 @@ -/** - * Copyright: 版权所有 违者必究 2013 - */ -package com.rop.session; - -/** - * 线程绑定的会话执有器,使请求线程范围的调用堆栈的所有对象都可以通过{@link #get()}这个静态方法获取会话。 - * {@link RopSessionHolder}依赖于{@link SessionBindInterceptor}拦截器工作。 - * @author : chenxh(quickselect@163.com) - * @date: 13-10-16 - */ -public class RopSessionHolder { - - private static ThreadLocal ropSession = new ThreadLocal(); - - public static void put(Session session){ - ropSession.set(session); - } - public static Session get(){ - return ropSession.get(); - } - - public static T get(Class sessionClazz){ - return (T)ropSession.get(); - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +/** + * 线程绑定的会话执有器,使请求线程范围的调用堆栈的所有对象都可以通过{@link #get()}这个静态方法获取会话。 + * {@link RopSessionHolder}依赖于{@link SessionBindInterceptor}拦截器工作。 + * @author : chenxh(quickselect@163.com) + * @date: 13-10-16 + */ +public class RopSessionHolder { + + private static ThreadLocal ropSession = new ThreadLocal(); + + public static void put(Session session){ + ropSession.set(session); + } + public static Session get(){ + return ropSession.get(); + } + + public static T get(Class sessionClazz){ + return sessionClazz.cast(ropSession.get()); + } +} diff --git a/rop/src/main/java/com/rop/session/Session.java b/rop/src/main/java/com/rop/session/Session.java index d5f7adb..081faa4 100644 --- a/rop/src/main/java/com/rop/session/Session.java +++ b/rop/src/main/java/com/rop/session/Session.java @@ -1,52 +1,66 @@ -package com.rop.session; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -/** - * @author chenxh - */ -public interface Session extends Serializable { - - /** - * 设置属性 - * @param name - * @param obj - */ - void setAttribute(String name, Object obj); - - /** - * 获取属性 - * @param name - * @return - */ - Object getAttribute(String name); - - /** - * 获取所有的属性 - * @return - */ - Map getAllAttributes(); - - /** - * 删除属性条目 - * @param name - */ - void removeAttribute(String name); - - /** - * ROP使用外部缓存管理器保存{@link Session}的内容,在每次接收到请求时,从外部缓存服务器复制会话并反序列化出 - * 会话对象{@link Session}。在处理请求时,业务逻辑允许更改{@link Session}中的内容,所以需要在{@link Session} - * 内容发生变化后,将 {@link Session}重写到外部缓存中。 - * - * 如果每次访问会话后,ROP都重写会话,将比较影响性能,往往大部分的请求并不会更改会话的内容。 - * 所以需要有一种机制在{@link Session}内容发生变更后告之ROP,以便ROP在{@link Session}内容发生变化时, - * 在请求结束时,将其同步到外部缓存服务器中。 - * - * ROP根据{@code isChanged}判断会话内容是否有变化,监测到会话内容的变化,它将自动执行会话重写操作,以便将本 - * 些更改同步到外部缓存服务器中。 - */ - boolean isChanged(); - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +import java.io.Serializable; +import java.util.Map; + +/** + * @author chenxh + */ +public interface Session extends Serializable { + + /** + * 设置属性 + * @param name + * @param obj + */ + void setAttribute(String name, Object obj); + + /** + * 获取属性 + * @param name + * @return + */ + Object getAttribute(String name); + + /** + * 获取所有的属性 + * @return + */ + Map getAllAttributes(); + + /** + * 删除属性条目 + * @param name + */ + void removeAttribute(String name); + + /** + * ROP使用外部缓存管理器保存{@link Session}的内容,在每次接收到请求时,从外部缓存服务器复制会话并反序列化出 + * 会话对象{@link Session}。在处理请求时,业务逻辑允许更改{@link Session}中的内容,所以需要在{@link Session} + * 内容发生变化后,将 {@link Session}重写到外部缓存中。 + * + * 如果每次访问会话后,ROP都重写会话,将比较影响性能,往往大部分的请求并不会更改会话的内容。 + * 所以需要有一种机制在{@link Session}内容发生变更后告之ROP,以便ROP在{@link Session}内容发生变化时, + * 在请求结束时,将其同步到外部缓存服务器中。 + * + * ROP根据{@code isChanged}判断会话内容是否有变化,监测到会话内容的变化,它将自动执行会话重写操作,以便将本 + * 些更改同步到外部缓存服务器中。 + */ + boolean isChanged(); + } \ No newline at end of file diff --git a/rop/src/main/java/com/rop/session/SessionBindInterceptor.java b/rop/src/main/java/com/rop/session/SessionBindInterceptor.java index 83d3d6c..49980de 100644 --- a/rop/src/main/java/com/rop/session/SessionBindInterceptor.java +++ b/rop/src/main/java/com/rop/session/SessionBindInterceptor.java @@ -1,45 +1,57 @@ -/** - * Copyright: 版权所有 违者必究 2013 - */ -package com.rop.session; - -import com.rop.AbstractInterceptor; -import com.rop.CommonConstant; -import com.rop.RopRequestContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 将{@link Session}绑定到{@link RopSessionHolder}中,默认注册。 - * - * @author : chenxh(quickselect@163.com) - * @date: 13-10-16 - */ -public class SessionBindInterceptor extends AbstractInterceptor { - - protected Logger logger = LoggerFactory.getLogger(this.getClass()); - - - public void beforeService(RopRequestContext ropRequestContext) { - Session session = ropRequestContext.getSession(); - if (session != null) { - RopSessionHolder.put(session); - if (logger.isDebugEnabled()) { - logger.debug("会话绑定到{}中", RopSessionHolder.class.getCanonicalName()); - } - } - } - - - public void beforeResponse(RopRequestContext ropRequestContext) { - Session session = ropRequestContext.getSession(); - if (session != null && session.isChanged()) { - session.removeAttribute(CommonConstant.SESSION_CHANGED); - SessionManager sessionManager = ropRequestContext.getRopContext().getSessionManager(); - sessionManager.addSession(ropRequestContext.getSessionId(), session); - if (logger.isDebugEnabled()) { - logger.debug("会话内容发生更改,将其同步到外部缓存管理器中。"); - } - } - } -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +import com.rop.AbstractInterceptor; +import com.rop.CommonConstant; +import com.rop.RopRequestContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 将{@link Session}绑定到{@link RopSessionHolder}中,默认注册。 + * + * @author : chenxh(quickselect@163.com) + * @date: 13-10-16 + */ +public class SessionBindInterceptor extends AbstractInterceptor { + + protected Logger logger = LoggerFactory.getLogger(this.getClass()); + + + public void beforeService(RopRequestContext ropRequestContext) { + Session session = ropRequestContext.getSession(); + if (session != null) { + RopSessionHolder.put(session); + if (logger.isDebugEnabled()) { + logger.debug("会话绑定到{}中", RopSessionHolder.class.getCanonicalName()); + } + } + } + + + public void beforeResponse(RopRequestContext ropRequestContext) { + Session session = ropRequestContext.getSession(); + if (session != null && session.isChanged()) { + session.removeAttribute(CommonConstant.SESSION_CHANGED); + SessionManager sessionManager = ropRequestContext.getRopContext().getSessionManager(); + sessionManager.addSession(ropRequestContext.getSessionId(), session); + if (logger.isDebugEnabled()) { + logger.debug("会话内容发生更改,将其同步到外部缓存管理器中。"); + } + } + } +} diff --git a/rop/src/main/java/com/rop/session/SessionManager.java b/rop/src/main/java/com/rop/session/SessionManager.java index 4915e2d..b35f2de 100644 --- a/rop/src/main/java/com/rop/session/SessionManager.java +++ b/rop/src/main/java/com/rop/session/SessionManager.java @@ -1,34 +1,49 @@ -package com.rop.session; - -/** - * 会话管理器 - * - * @author libinsong@gmail.com - * @author 陈雄华 - */ -public interface SessionManager { - - /** - * 注册一个会话 - * - * @param session - */ - void addSession(String sessionId, Session session); - - /** - * 从注册表中获取会话 - * - * @param sessionId - * @return - */ - Session getSession(String sessionId); - - /** - * 移除这个会话 - * - * @param sessionId - * @return - */ - void removeSession(String sessionId); -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +/** + * 会话管理器 + * + * @author libinsong@gmail.com + * @author 陈雄华 + */ +public interface SessionManager { + + /** + * 注册一个会话 + * + * @param session + */ + void addSession(String sessionId, Session session); + + /** + * 从注册表中获取会话 + * + * @param sessionId + * @return + */ + Session getSession(String sessionId); + + /** + * 移除这个会话 + * + * @param sessionId + * @return + */ + void removeSession(String sessionId); +} + diff --git a/rop/src/main/java/com/rop/session/SimpleSession.java b/rop/src/main/java/com/rop/session/SimpleSession.java index 03ae72c..1bfd865 100644 --- a/rop/src/main/java/com/rop/session/SimpleSession.java +++ b/rop/src/main/java/com/rop/session/SimpleSession.java @@ -1,14 +1,30 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-21 - */ -package com.rop.session; - -/** - * - * @author 陈雄华 - * @version 1.0 - */ -public class SimpleSession extends AbstractSession { -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.session; + +/** + * + * @author 陈雄华 + * @version 1.0 + */ +public class SimpleSession extends AbstractSession { + + /** + * + */ + private static final long serialVersionUID = 1L; +} + diff --git a/rop/src/main/java/com/rop/session/UserNamePasswordAuthRequest.java b/rop/src/main/java/com/rop/session/UserNamePasswordAuthRequest.java deleted file mode 100644 index 7aea506..0000000 --- a/rop/src/main/java/com/rop/session/UserNamePasswordAuthRequest.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.rop.session; - -/** - * 基础用户名及密码的认证 - * @author : chenxh(quickselect@163.com) - * @date: 13-8-13 - */ -public class UserNamePasswordAuthRequest extends AbstractAuthRequest { - - private String userName; - - private String password; - - public UserNamePasswordAuthRequest(String userName, String password) { - this.userName = userName; - this.password = password; - } - - - public Object getPrincipal() { - return userName; - } - - - public Object getCredential() { - return password; - } -} diff --git a/rop/src/main/java/com/rop/sign/DigestSignHandler.java b/rop/src/main/java/com/rop/sign/DigestSignHandler.java new file mode 100644 index 0000000..5042089 --- /dev/null +++ b/rop/src/main/java/com/rop/sign/DigestSignHandler.java @@ -0,0 +1,119 @@ +package com.rop.sign; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.util.Collection; +import java.util.Map; + +import com.rop.RopException; +import com.rop.config.SystemParameterNames; +import com.rop.security.AppSecretManager; +import com.rop.sign.SignHandler; +import com.rop.utils.RopUtils; + +/** + * 消息摘要数字签名处理实现 + * @author liangruisen + */ +public class DigestSignHandler implements SignHandler { + + public DigestSignHandler() { + super(); + } + + public DigestSignHandler(String algorithm, AppSecretManager appSecretManager) { + super(); + this.algorithm = algorithm; + } + + protected AppSecretManager appSecretManager; + + protected String algorithm = "SHA-1"; + + /** + * 产生签名 + * @see com.rop.sign.SignHandler#sign(java.util.Map) + */ + @Override + public String sign(Map paramMap) { + return sign(paramMap, null); + } + + /** + * 产生签名 + * @see com.rop.sign.SignHandler#sign(java.util.Map, java.util.Collection) + */ + @Override + public String sign(Map paramValues, Collection ignore) { + try { + String appKey = paramValues.get(SystemParameterNames.getAppKey()); + String secret = appSecretManager.getSecret(appKey); + StringBuilder sb = new StringBuilder(); + sb.append(secret); + sb.append(RopUtils.getSignContent(paramValues, ignore)); + sb.append(secret); + byte[] sha1Digest = getDigest(sb.toString()); + return byte2hex(sha1Digest); + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 获取消息摘要 + * @param data + * @return + * @throws IOException + */ + protected byte[] getDigest(String data) throws IOException { + byte[] bytes = null; + try { + MessageDigest md = MessageDigest.getInstance(algorithm); + bytes = md.digest(data.getBytes()); + } catch (GeneralSecurityException gse) { + throw new IOException(gse.getMessage()); + } + return bytes; + } + + /** + * 检查签名是否正确 + * @see com.rop.sign.SignHandler#signCheck(java.lang.String, java.util.Map, java.util.Collection) + */ + @Override + public boolean signCheck(String sign, Map paramMap, Collection ignore) { + String signValue = sign(paramMap, ignore); + return signValue.equals(sign); + } + + /** + * 检查签名是否正确 + * @see com.rop.sign.SignHandler#signCheck(java.lang.String, java.util.Map) + */ + @Override + public boolean signCheck(String sign, Map paramMap) { + return signCheck(sign, paramMap, null); + } + + /** + * 二进制转十六进制字符串 + * @param bytes + * @return + */ + protected String byte2hex(byte[] bytes) { + StringBuilder sign = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + String hex = Integer.toHexString(bytes[i] & 0xFF); + if (hex.length() == 1) { + sign.append("0"); + } + sign.append(hex.toUpperCase()); + } + return sign.toString(); + } + + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } +} diff --git a/rop/src/main/java/com/rop/sign/HmacDigestSignHandler.java b/rop/src/main/java/com/rop/sign/HmacDigestSignHandler.java new file mode 100644 index 0000000..9e07866 --- /dev/null +++ b/rop/src/main/java/com/rop/sign/HmacDigestSignHandler.java @@ -0,0 +1,71 @@ +package com.rop.sign; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.Collection; +import java.util.Map; + +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +import com.rop.RopException; +import com.rop.config.SystemParameterNames; +import com.rop.security.AppSecretManager; +import com.rop.utils.RopUtils; + +/** + * hmac消息摘要数字签名处理实现 + * @author liangruisen + */ +public class HmacDigestSignHandler extends DigestSignHandler { + + public HmacDigestSignHandler() { + super("HmacSHA1", null); + } + + public HmacDigestSignHandler(AppSecretManager appSecretManager) { + super("HmacSHA1", appSecretManager); + } + + public HmacDigestSignHandler(String algorithm, AppSecretManager appSecretManager) { + super(algorithm, appSecretManager); + } + + /** + * 产生签名 + * @see com.rop.sign.DigestSignHandler#sign(java.util.Map, java.util.Collection) + */ + @Override + public String sign(Map paramValues, Collection ignore) { + try { + String signContent = RopUtils.getSignContent(paramValues, ignore); + String appKey = paramValues.get(SystemParameterNames.getAppKey()); + String secret = appSecretManager.getSecret(appKey); + byte[] sha1Digest = getDigest(secret, signContent); + return byte2hex(sha1Digest); + } catch (IOException e) { + throw new RopException(e); + } + } + + /** + * 获取消息摘要 + * @param secret + * @param data + * @return + * @throws IOException + */ + protected byte[] getDigest(String secret, String data) throws IOException { + byte[] bytes = null; + try { + SecretKey secretKey = new SecretKeySpec(secret.getBytes(), algorithm); + Mac mac = Mac.getInstance(secretKey.getAlgorithm()); + mac.init(secretKey); + bytes = mac.doFinal(data.getBytes()); + } catch (GeneralSecurityException gse) { + throw new IOException(gse.toString()); + } + return bytes; + } +} diff --git a/rop/src/main/java/com/rop/sign/RsaDigestSignHandler.java b/rop/src/main/java/com/rop/sign/RsaDigestSignHandler.java new file mode 100644 index 0000000..c8fb32d --- /dev/null +++ b/rop/src/main/java/com/rop/sign/RsaDigestSignHandler.java @@ -0,0 +1,249 @@ +package com.rop.sign; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Collection; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.Cache; +import org.springframework.cache.Cache.ValueWrapper; +import org.springframework.cache.CacheManager; +import org.springframework.core.io.Resource; + +import com.rop.config.SystemParameterNames; +import com.rop.security.AppSecretManager; +import com.rop.utils.RopUtils; + +/** + * RSA数字签名 + */ +public class RsaDigestSignHandler extends DigestSignHandler { + + private static final String CACHE_NAME = RsaDigestSignHandler.class.getName(); + + /** + * 平台证书私钥 + */ + private PrivateKey privateKey; + + /** + * 平台证书私钥base64字符串 + */ + private String privateKeyData; + + /** + * 平台证书私钥文件 + */ + private Resource privateKeyLocation; + + private AppSecretManager appSecretManager; + + private CacheManager cacheManager; + + private String cacheName = CACHE_NAME; + + @PostConstruct + public void init() { + if (privateKey == null && StringUtils.isNotBlank(privateKeyData)) { + try{ + privateKey = getPrivateKeyFromPKCS8("RSA", new ByteArrayInputStream(privateKeyData.getBytes())); + }catch(RuntimeException e){ + throw e; + }catch(Exception e){ + throw new IllegalArgumentException(e); + } + } + if (privateKey == null && privateKeyLocation != null) { + InputStream input = null; + try { + input = privateKeyLocation.getInputStream(); + privateKey = getPrivateKeyFromPKCS8("RSA", input); + } catch (Exception e) { + throw new IllegalArgumentException(e); + }finally{ + IOUtils.closeQuietly(input); + } + } + } + + /** + * 获取平台的私钥 + * @return PrivateKey + */ + public PrivateKey getPrivateKey(){ + if(privateKey == null){ + init(); + } + if (privateKey == null) { + throw new IllegalArgumentException( + "privateKey or privateKeyData or privateKeyLocation argument is required; it must not be null"); + } + return privateKey; + } + + /** + * 从输入流中读取证书的私钥 + * @param algorithm + * @param ins + * @return PrivateKey + * @throws Exception + */ + public PrivateKey getPrivateKeyFromPKCS8(String algorithm, InputStream ins) throws Exception { + if (ins == null || StringUtils.isEmpty(algorithm)) { + return null; + } + KeyFactory keyFactory = KeyFactory.getInstance(algorithm); + byte[] encodedKey = IOUtils.toByteArray(ins); + encodedKey = Base64.decodeBase64(encodedKey); + return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey)); + } + + /** + * 从输入流中读取证书的公钥 + * @param algorithm + * @param ins + * @return PublicKey + * @throws Exception + */ + public PublicKey getPublicKeyFromPKCS8(String algorithm, InputStream ins) throws Exception { + if (ins == null || StringUtils.isEmpty(algorithm)) { + return null; + } + KeyFactory keyFactory = KeyFactory.getInstance(algorithm); + byte[] encodedKey = IOUtils.toByteArray(ins); + encodedKey = Base64.decodeBase64(encodedKey); + return keyFactory.generatePublic(new PKCS8EncodedKeySpec(encodedKey)); + } + + /** + * 根据appKey获取客户端的公钥 + * @param appKey + * @return PublicKey + * @throws Exception + */ + public PublicKey getPublicKey(String appKey) throws Exception{ + PublicKey key = getPublicKeyFromCache(appKey); + if(key != null){ + return key; + } + if (appSecretManager == null) { + throw new IllegalArgumentException("appSecretManager argument is required; it must not be null"); + } + String keyData = appSecretManager.getSecret(appKey); + key = getPublicKeyFromPKCS8("RSA", new ByteArrayInputStream(keyData.getBytes())); + putPublicKeyToCache(appKey, key); + return key; + } + + /** + * 将客户端的公钥放入到缓存中 + * @param appKey + * @param key + */ + private void putPublicKeyToCache(String appKey, PublicKey key){ + if(cacheManager == null){ + return; + } + try{ + Cache cache = cacheManager.getCache(cacheName); + if(cache == null){ + return; + } + cache.put(appKey, key); + }catch(Exception e){ + } + } + + /** + * 从缓存中获取客户端的公钥 + * @param appKey + * @return PublicKey + */ + private PublicKey getPublicKeyFromCache(String appKey){ + if(cacheManager == null){ + return null; + } + try{ + Cache cache = cacheManager.getCache(cacheName); + if(cache == null){ + return null; + } + ValueWrapper wrapper = cache.get(appKey); + return (PublicKey) (wrapper == null ? null : wrapper.get()); + }catch(Exception e){ + } + return null; + } + + /** + * 产生签名 + * @see com.rop.sign.DigestSignHandler#sign(java.util.Map, java.util.Collection) + */ + @Override + public String sign(Map paramValues, Collection ignore) { + String signValue = RopUtils.getSignContent(paramValues, ignore); + try{ + Signature signature = Signature.getInstance("SHA1WithRSA"); + signature.initSign(getPrivateKey()); + signature.update(signValue.getBytes()); + return Base64.encodeBase64String(signature.sign()); + }catch(Exception e){ + throw new IllegalArgumentException(e); + } + } + + /** + * 检查签名是否正确 + * @see com.rop.sign.DigestSignHandler#signCheck(java.lang.String, java.util.Map, java.util.Collection) + */ + @Override + public boolean signCheck(String sign, Map paramMap, Collection ignore) { + String signValue = RopUtils.getSignContent(paramMap, ignore); + try{ + String appKey = paramMap.get(SystemParameterNames.getAppKey()); + Signature signature = Signature.getInstance("SHA1WithRSA"); + signature.initVerify(getPublicKey(appKey)); + signature.update(signValue.getBytes()); + return signature.verify(Base64.decodeBase64(sign)); + }catch(Exception e){ + throw new IllegalArgumentException(e); + } + } + + public void setPrivateKey(PrivateKey privateKey) { + this.privateKey = privateKey; + } + + public void setPrivateKeyData(String privateKeyData) { + this.privateKeyData = privateKeyData; + } + + public void setPrivateKeyLocation(Resource privateKeyLocation) { + this.privateKeyLocation = privateKeyLocation; + } + + @Autowired(required=false) + public void setCacheManager(CacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + @javax.annotation.Resource + public void setAppSecretManager(AppSecretManager appSecretManager) { + this.appSecretManager = appSecretManager; + } + + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } +} \ No newline at end of file diff --git a/rop/src/main/java/com/rop/utils/RopUtils.java b/rop/src/main/java/com/rop/utils/RopUtils.java deleted file mode 100644 index 73b5098..0000000 --- a/rop/src/main/java/com/rop/utils/RopUtils.java +++ /dev/null @@ -1,127 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-2 - */ -package com.rop.utils; - -import com.rop.Constants; -import com.rop.RopException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.GeneralSecurityException; -import java.security.MessageDigest; -import java.util.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class RopUtils { - - private static final Logger logger = LoggerFactory.getLogger(RopUtils.class); - - /** - * 使用secret对paramValues按以下算法进行签名:
- * uppercase(hex(sha1(secretkey1value1key2value2...secret)) - * - * @param paramValues 参数列表 - * @param secret - * @return - */ - public static String sign(Map paramValues, String secret) { - return sign(paramValues,null,secret); - } - - /** - * 对paramValues进行签名,其中ignoreParamNames这些参数不参与签名 - * @param paramValues - * @param ignoreParamNames - * @param secret - * @return - */ - public static String sign(Map paramValues, List ignoreParamNames,String secret) { - try { - StringBuilder sb = new StringBuilder(); - List paramNames = new ArrayList(paramValues.size()); - paramNames.addAll(paramValues.keySet()); - if(ignoreParamNames != null && ignoreParamNames.size() > 0){ - for (String ignoreParamName : ignoreParamNames) { - paramNames.remove(ignoreParamName); - } - } - Collections.sort(paramNames); - - sb.append(secret); - for (String paramName : paramNames) { - sb.append(paramName).append(paramValues.get(paramName)); - } - sb.append(secret); - byte[] sha1Digest = getSHA1Digest(sb.toString()); - return byte2hex(sha1Digest); - } catch (IOException e) { - throw new RopException(e); - } - } - - public static String utf8Encoding(String value, String sourceCharsetName) { - try { - return new String(value.getBytes(sourceCharsetName), Constants.UTF8); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } - } - - private static byte[] getSHA1Digest(String data) throws IOException { - byte[] bytes = null; - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - bytes = md.digest(data.getBytes(Constants.UTF8)); - } catch (GeneralSecurityException gse) { - throw new IOException(gse.getMessage()); - } - return bytes; - } - - private static byte[] getMD5Digest(String data) throws IOException { - byte[] bytes = null; - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - bytes = md.digest(data.getBytes(Constants.UTF8)); - } catch (GeneralSecurityException gse) { - throw new IOException(gse.getMessage()); - } - return bytes; - } - - /** - * 二进制转十六进制字符串 - * - * @param bytes - * @return - */ - private static String byte2hex(byte[] bytes) { - StringBuilder sign = new StringBuilder(); - for (int i = 0; i < bytes.length; i++) { - String hex = Integer.toHexString(bytes[i] & 0xFF); - if (hex.length() == 1) { - sign.append("0"); - } - sign.append(hex.toUpperCase()); - } - return sign.toString(); - } - - public static String getUUID() { - UUID uuid = UUID.randomUUID(); - return uuid.toString().toUpperCase(); - } - -} - diff --git a/rop/src/main/resources/META-INF/MANIFEST.MF b/rop/src/main/resources/META-INF/MANIFEST.MF index faa8dd2..1f7d07e 100644 --- a/rop/src/main/resources/META-INF/MANIFEST.MF +++ b/rop/src/main/resources/META-INF/MANIFEST.MF @@ -1,6 +1,6 @@ -Manifest-Version: 1.0 -Archiver-Version: Plexus Archiver -Created-By: Apache Maven -Built-By: Thinkpad -Build-Jdk: 1.6.0_43 - +Manifest-Version: 1.0 +Archiver-Version: Plexus Archiver +Created-By: Apache Maven +Built-By: Thinkpad +Build-Jdk: 1.6.0_43 + diff --git a/rop/src/main/resources/META-INF/spring.schemas b/rop/src/main/resources/META-INF/spring.schemas index 1342bbd..34a3fa9 100644 --- a/rop/src/main/resources/META-INF/spring.schemas +++ b/rop/src/main/resources/META-INF/spring.schemas @@ -1 +1,2 @@ -http\://www.rop.com/schema/rop/rop-1.0.xsd=com/rop/rop-1.0.xsd \ No newline at end of file +http\://www.rop.com/schema/rop/rop-1.0.xsd=com/rop/rop-1.0.xsd +http\://www.rop.com/schema/rop/rop-2.0.xsd=com/rop/rop-2.0.xsd \ No newline at end of file diff --git a/rop/src/main/resources/com/rop/rop-1.0.xsd b/rop/src/main/resources/com/rop/rop-1.0.xsd index cc092e4..7bf496b 100644 --- a/rop/src/main/resources/com/rop/rop-1.0.xsd +++ b/rop/src/main/resources/com/rop/rop-1.0.xsd @@ -1,105 +1,105 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rop/src/main/resources/com/rop/rop-2.0.xsd b/rop/src/main/resources/com/rop/rop-2.0.xsd new file mode 100644 index 0000000..b4598e8 --- /dev/null +++ b/rop/src/main/resources/com/rop/rop-2.0.xsd @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/rop/src/main/resources/i18n/rop/error_en.properties b/rop/src/main/resources/i18n/rop/error_en.properties index 16da094..a47f194 100644 --- a/rop/src/main/resources/i18n/rop/error_en.properties +++ b/rop/src/main/resources/i18n/rop/error_en.properties @@ -1,85 +1,85 @@ -###\u9519\u8BEF\u63CF\u8FF0\u4FE1\u606F -########################################################################################################################## -ERROR_1 = service is not available -ERROR_2 = Insufficient permissions to developers -ERROR_3 = service method ({0}, {1}) user permissions -ERROR_4 = service method ({0}, {1}) image upload failed, reason is: {2} -ERROR_5 = service method ({0}, {1}) HTTP method {2} be banned -ERROR_6 = service method ({0}, {1}) coding errors -ERROR_7 = service method ({0}, {1}) request is prohibited -ERROR_8 = service method ({0}, {1}) is invalid -ERROR_9 = service method ({0}, {1}) business logic errors -ERROR_20 = service method ({0}, {1}) lack of session parameters: {2} -ERROR_21 = service method ({0}, {1}) session ID: {2} is invalid -ERROR_22 = service method ({0}, {1}) lack of application of key parameters: {2} -ERROR_23 = service method ({0}, {1}) the application of the key parameters {2} is invalid -ERROR_24 = service method ({0}, {1}) need the signature, the lack of signature parameters: {2} -ERROR_25 = service method ({0}, {1}) signature is invalid -ERROR_26 = service request lacks the method name parameters: {0} -ERROR_27 = call there is no service method: {0} -ERROR_28 = service method ({0}) lack of version parameters: {1} -ERROR_29 = service method ({0}) there is no corresponding version ({1}) -ERROR_30 = service method ({0}) does not support the corresponding version ({1}) -ERROR_31 = service method ({0}, {1}) message data format is invalid ({2}) -ERROR_32 = service method ({0}, {1}) lack the necessary parameters -ERROR_33 = service method ({0}, {1}) parameter is illegal -ERROR_34 = service method ({0}, {1}) transfinite in call number -ERROR_35 = user session to invoke the service overrun -ERROR_36 = the number of applications to invoke the service overrun -ERROR_37 = application invokes the service frequency of overrun - -########################################################################################################################## - -###\u9519\u8BEF\u89E3\u51B3\u65B9\u6848 -########################################################################################################################## -ERROR_1_SOLUTION=Please save the error message and contact the manager of the open platform -ERROR_2_SOLUTION=Insufficient ISV Permissions -ERROR_3_SOLUTION=Insufficient User Permissions -ERROR_4_SOLUTION=check the file type or size is valid -ERROR_5_SOLUTION=Use the correct HTTP method(GET or POST) -ERROR_6_SOLUTION=Invalid encoding,please using the utf-8 to encoding you request parameter's value. -ERROR_7_SOLUTION=Banned request, because the openplatform is overload,please try again. -ERROR_8_SOLUTION=Method has been out of date, please use the new version or the other alternative methods -ERROR_9_SOLUTION=Please understand service called pre-conditions, check whether meet the business logic. -ERROR_20_SOLUTION=add the sessionId system parameter -ERROR_21_SOLUTION=Invalid session, please get legal session -ERROR_22_SOLUTION=add the appKey system parameter -ERROR_23_SOLUTION=Invalid appKey, please use the legal appKey (by service providers offer you) -ERROR_24_SOLUTION=add sign system parameter -ERROR_25_SOLUTION=Signature is invalid, please press the right to request the algorithm of data signature:\ - SHA1( ), \ - attention parameter list in alphabetical order -ERROR_26_SOLUTION=add the method system parameter -ERROR_27_SOLUTION=check the method system parameter is right -ERROR_28_SOLUTION=add the version system parameter -ERROR_29_SOLUTION=check version system parameter is right -ERROR_30_SOLUTION=check version system parameter is right -ERROR_31_SOLUTION=check format system parameter is right(xml or json) -ERROR_32_SOLUTION=check the Required application parameter is provided (refer the subError message) -ERROR_33_SOLUTION=check the Required application parameter is valid(refer the subError message) -ERROR_34_SOLUTION=Wait for a while try again later -ERROR_35_SOLUTION=Quit application and try again later -ERROR_36_SOLUTION=Please check the number of authorized by invoking services -ERROR_37_SOLUTION=Reduce the frequency of invoking services - -########################################################################################################################## - -###ISP\u5B50\u9519\u8BEF -########################################################################################################################## -isp.xxx-service-unavailable = call the back-end service {0} thrown exception:{1}, the service is unavailable.\ - \n exception info is :\n{2} -isp.xxx-service-timeout = invoke service {0} execeed timeout in {1} seconds; -########################################################################################################################## - - -###ISVs sub-error -########################################################################################################################## -isv.xxx-not-exist\:invalid-yyy = use "{0}" of "{1}" can not find "{2}" object -isv.missing-parameter\:xxx = the lack of the necessary parameters {0} -isv.parameters-mismatch\:xxx-and-yyy = incoming parameter {0} and {1} does not match. -isv.invalid-paramete\:xxx = parameter {0} is invalid, format, wrong, illegal values, crossing the boundary -isv.invalid-permission = permission denied, unauthorized access -########################################################################################################################## - - - +###\u9519\u8BEF\u63CF\u8FF0\u4FE1\u606F +########################################################################################################################## +ERROR_1 = service is not available +ERROR_2 = Insufficient permissions to developers +ERROR_3 = service method ({0}, {1}) user permissions +ERROR_4 = service method ({0}, {1}) image upload failed, reason is: {2} +ERROR_5 = service method ({0}, {1}) HTTP method {2} be banned +ERROR_6 = service method ({0}, {1}) coding errors +ERROR_7 = service method ({0}, {1}) request is prohibited +ERROR_8 = service method ({0}, {1}) is invalid +ERROR_9 = service method ({0}, {1}) business logic errors +ERROR_20 = service method ({0}, {1}) lack of session parameters: {2} +ERROR_21 = service method ({0}, {1}) session ID: {2} is invalid +ERROR_22 = service method ({0}, {1}) lack of application of key parameters: {2} +ERROR_23 = service method ({0}, {1}) the application of the key parameters {2} is invalid +ERROR_24 = service method ({0}, {1}) need the signature, the lack of signature parameters: {2} +ERROR_25 = service method ({0}, {1}) signature is invalid +ERROR_26 = service request lacks the method name parameters: {0} +ERROR_27 = call there is no service method: {0} +ERROR_28 = service method ({0}) lack of version parameters: {1} +ERROR_29 = service method ({0}) there is no corresponding version ({1}) +ERROR_30 = service method ({0}) does not support the corresponding version ({1}) +ERROR_31 = service method ({0}, {1}) message data format is invalid ({2}) +ERROR_32 = service method ({0}, {1}) lack the necessary parameters +ERROR_33 = service method ({0}, {1}) parameter is illegal +ERROR_34 = service method ({0}, {1}) transfinite in call number +ERROR_35 = user session to invoke the service overrun +ERROR_36 = the number of applications to invoke the service overrun +ERROR_37 = application invokes the service frequency of overrun + +########################################################################################################################## + +###\u9519\u8BEF\u89E3\u51B3\u65B9\u6848 +########################################################################################################################## +ERROR_1_SOLUTION=Please save the error message and contact the manager of the open platform +ERROR_2_SOLUTION=Insufficient ISV Permissions +ERROR_3_SOLUTION=Insufficient User Permissions +ERROR_4_SOLUTION=check the file type or size is valid +ERROR_5_SOLUTION=Use the correct HTTP method(GET or POST) +ERROR_6_SOLUTION=Invalid encoding,please using the utf-8 to encoding you request parameter's value. +ERROR_7_SOLUTION=Banned request, because the openplatform is overload,please try again. +ERROR_8_SOLUTION=Method has been out of date, please use the new version or the other alternative methods +ERROR_9_SOLUTION=Please understand service called pre-conditions, check whether meet the business logic. +ERROR_20_SOLUTION=add the sessionId system parameter +ERROR_21_SOLUTION=Invalid session, please get legal session +ERROR_22_SOLUTION=add the appKey system parameter +ERROR_23_SOLUTION=Invalid appKey, please use the legal appKey (by service providers offer you) +ERROR_24_SOLUTION=add sign system parameter +ERROR_25_SOLUTION=Signature is invalid, please press the right to request the algorithm of data signature:\ + SHA1( ), \ + attention parameter list in alphabetical order +ERROR_26_SOLUTION=add the method system parameter +ERROR_27_SOLUTION=check the method system parameter is right +ERROR_28_SOLUTION=add the version system parameter +ERROR_29_SOLUTION=check version system parameter is right +ERROR_30_SOLUTION=check version system parameter is right +ERROR_31_SOLUTION=check format system parameter is right(xml or json) +ERROR_32_SOLUTION=check the Required application parameter is provided (refer the subError message) +ERROR_33_SOLUTION=check the Required application parameter is valid(refer the subError message) +ERROR_34_SOLUTION=Wait for a while try again later +ERROR_35_SOLUTION=Quit application and try again later +ERROR_36_SOLUTION=Please check the number of authorized by invoking services +ERROR_37_SOLUTION=Reduce the frequency of invoking services + +########################################################################################################################## + +###ISP\u5B50\u9519\u8BEF +########################################################################################################################## +isp.xxx-service-unavailable = call the back-end service {0} thrown exception:{1}, the service is unavailable.\ + \n exception info is :\n{2} +isp.xxx-service-timeout = invoke service {0} execeed timeout in {1} seconds; +########################################################################################################################## + + +###ISVs sub-error +########################################################################################################################## +isv.xxx-not-exist\:invalid-yyy = use "{0}" of "{1}" can not find "{2}" object +isv.missing-parameter\:xxx = the lack of the necessary parameters {0} +isv.parameters-mismatch\:xxx-and-yyy = incoming parameter {0} and {1} does not match. +isv.invalid-paramete\:xxx = parameter {0} is invalid, format, wrong, illegal values, crossing the boundary +isv.invalid-permission = permission denied, unauthorized access +########################################################################################################################## + + + diff --git a/rop/src/main/resources/i18n/rop/error_zh_CN.properties b/rop/src/main/resources/i18n/rop/error_zh_CN.properties index ce255e0..5ee691f 100644 --- a/rop/src/main/resources/i18n/rop/error_zh_CN.properties +++ b/rop/src/main/resources/i18n/rop/error_zh_CN.properties @@ -1,82 +1,82 @@ -###\u9519\u8BEF\u63CF\u8FF0\u4FE1\u606F -########################################################################################################################## -ERROR_1 =\u670D\u52A1\u4E0D\u53EF\u7528 -ERROR_2 =\u5F00\u53D1\u8005\u6743\u9650\u4E0D\u8DB3 -ERROR_3 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7528\u6237\u6743\u9650\u4E0D\u8DB3 -ERROR_4=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u56FE\u7247\u4E0A\u4F20\u5931\u8D25,\u539F\u56E0\u4E3A:{2} -ERROR_5 =\u670D\u52A1\u65B9\u6CD5({0}:{1})HTTP\u65B9\u6CD5{2}\u88AB\u7981\u6B62 -ERROR_6 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F16\u7801\u9519\u8BEF -ERROR_7 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u8BF7\u6C42\u88AB\u7981\u6B62 -ERROR_8 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u5DF2\u7ECF\u4F5C\u5E9F -ERROR_9 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u4E1A\u52A1\u903B\u8F91\u51FA\u9519 -ERROR_20=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u4F1A\u8BDD\u53C2\u6570:{2} -ERROR_21=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u4F1A\u8BDDID:{2}\u65E0\u6548 -ERROR_22=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u5E94\u7528\u952E\u53C2\u6570:{2} -ERROR_23=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u5E94\u7528\u952E\u53C2\u6570{2}\u65E0\u6548 -ERROR_24=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u9700\u8981\u7B7E\u540D,\u7F3A\u5C11\u7B7E\u540D\u53C2\u6570:{2} -ERROR_25=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u7B7E\u540D\u65E0\u6548 -ERROR_26=\u670D\u52A1\u8BF7\u6C42\u7F3A\u5C11\u65B9\u6CD5\u540D\u53C2\u6570:{0} -ERROR_27=\u8C03\u7528\u4E0D\u5B58\u5728\u7684\u670D\u52A1\u65B9\u6CD5:{0} -ERROR_28=\u670D\u52A1\u65B9\u6CD5({0})\u7F3A\u5C11\u7248\u672C\u53C2\u6570:{1} -ERROR_29=\u670D\u52A1\u65B9\u6CD5({0})\u4E0D\u5B58\u5728\u5BF9\u5E94\u7684\u7248\u672C({1}) -ERROR_30=\u670D\u52A1\u65B9\u6CD5({0})\u4E0D\u652F\u6301\u5BF9\u5E94\u7684\u7248\u672C\u53F7({1}) -ERROR_31=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u62A5\u6587\u6570\u636E\u683C\u5F0F\u65E0\u6548({2}) -ERROR_32=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u5FC5\u8981\u7684\u53C2\u6570 -ERROR_33=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u53C2\u6570\u975E\u6CD5 -ERROR_34=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u8C03\u7528\u6B21\u6570\u8D85\u9650 -ERROR_35=\u7528\u6237\u4F1A\u8BDD\u8C03\u7528\u670D\u52A1\u7684\u6B21\u6570\u8D85\u9650 -ERROR_36=\u5E94\u7528\u8C03\u7528\u670D\u52A1\u7684\u6B21\u6570\u8D85\u9650 -ERROR_37=\u5E94\u7528\u8C03\u7528\u670D\u52A1\u7684\u9891\u7387\u8D85\u9650 -########################################################################################################################## - - -###\u9519\u8BEF\u89E3\u51B3\u65B9\u6848 -########################################################################################################################## -ERROR_1_SOLUTION =\u670D\u52A1\u76EE\u524D\u65E0\u6CD5\u4F7F\u7528\uFF0C\u8BF7\u4FDD\u5B58\u597D\u9519\u8BEF\u4FE1\u606F\u5E76\u548C\u670D\u52A1\u5E73\u53F0\u7BA1\u7406\u5458\u8054\u7CFB -ERROR_2_SOLUTION =\u4E0D\u8DB3\u7684ISV\u6743\u9650\uFF0C\u8BF7\u548C\u7BA1\u7406\u5458\u8054\u7CFB -ERROR_3_SOLUTION =\u7528\u6237\u6743\u9650\u4E0D\u8DB3\uFF0C\u8BF7\u548C\u7BA1\u7406\u5458\u8054\u7CFB -ERROR_4_SOLUTION=\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u7C7B\u578B\u53CA\u5927\u5C0F\u662F\u5426\u5408\u6CD5 -ERROR_5_SOLUTION =\u8BF7\u4F7F\u7528\u5408\u9002\u7684HTTP\u65B9\u6CD5\uFF08GET\u6216POST\uFF09 -ERROR_6_SOLUTION =\u65E0\u6548\u7684\u7F16\u7801\uFF0C\u8BF7\u5BF9\u4F7F\u7528UTF-8\u5BF9\u8BF7\u6C42\u53C2\u6570\u503C\u8FDB\u884C\u7F16\u7801 -ERROR_7_SOLUTION =\u7981\u6B62\u8BF7\u6C42\uFF0C\u56E0\u670D\u52A1\u5E73\u53F0\u5DF2\u7ECF\u6EE1\u8D1F\u8377\uFF0C\u8BF7\u7A0D\u5019\u518D\u8BD5 -ERROR_8_SOLUTION =\u65B9\u6CD5\u5DF2\u8FC7\u65F6\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7248\u672C\u6216\u5176\u5B83\u66FF\u4EE3\u7684\u65B9\u6CD5 -ERROR_9_SOLUTION =\u8BF7\u4E86\u89E3\u670D\u52A1\u8C03\u7528\u7684\u524D\u7F6E\u6761\u4EF6\uFF0C\u68C0\u67E5\u662F\u5426\u6EE1\u8DB3\u4E1A\u52A1\u903B\u8F91 -ERROR_20_SOLUTION=\u5C06\u6DFB\u52A0\u4F1A\u8BDDID\u8BF7\u6C42\u53C2\u6570 -ERROR_21_SOLUTION=\u65E0\u6548\u7684\u4F1A\u8BDD,\u8BF7\u91CD\u65B0\u767B\u5F55\u4EE5\u83B7\u53D6\u5408\u6CD5\u7684\u4F1A\u8BDD -ERROR_22_SOLUTION=\u7F3A\u5C11appKey\uFF0C\u8BF7\u5411\u670D\u52A1\u7AEF\u83B7\u53D6\u5408\u6CD5\u7684appKey -ERROR_23_SOLUTION=\u65E0\u6548\u7684appKey,\u8BF7\u4F7F\u7528\u5408\u6CD5\u7684appKey\uFF08\u7531\u670D\u52A1\u63D0\u4F9B\u5546\u6388\u4E88\u4F60\uFF09 -ERROR_24_SOLUTION=\u7F3A\u5C11\u7B7E\u540D\u53C2\u6570\uFF0C\u8BF7\u6DFB\u52A0\u7B7E\u540D\u8BF7\u6C42\u53C2\u6570 -ERROR_25_SOLUTION=\u7B7E\u540D\u65E0\u6548\uFF0C\u8BF7\u6309\u6B63\u786E\u7684\u7B97\u6CD5\u5BF9\u8BF7\u6C42\u6570\u636E\u8FDB\u884C\u7B7E\u540D:\ - SHA1( ),\u6CE8\u610F\u53C2\u6570\u5217\u8868\u6309\u5B57\u6BCD\u987A\u5E8F\u6392\u5217 -ERROR_26_SOLUTION=\u7F3A\u5C11\u65B9\u6CD5,\u8BF7\u6DFB\u52A0\u4E0A\u670D\u52A1\u65B9\u6CD5\u7684\u8BF7\u6C42\u53C2\u6570 -ERROR_27_SOLUTION=\u65E0\u6548\u7684\u65B9\u6CD5\uFF0C\u8BF7\u68C0\u67E5\u670D\u52A1\u65B9\u6CD5\u540D\u662F\u5426\u6B63\u786E -ERROR_28_SOLUTION=\u7F3A\u5C11\u7248\u672C\u53C2\u6570\uFF0C\u8BF7\u6307\u5B9A\u670D\u52A1\u65B9\u6CD5\u7684\u7248\u672C\u53F7 -ERROR_29_SOLUTION=\u975E\u6CD5\u7684\u7248\u672C\u53F7\uFF0C\u8FD9\u4E2A\u670D\u52A1\u65B9\u6CD5\u7684\u7248\u672C\u53F7\u662F\u9519\u8BEF\u7684\uFF0C\u8BF7\u68C0\u67E5 -ERROR_30_SOLUTION=\u8FD9\u4E2A\u7248\u672C\u53F7\u5DF2\u7ECF\u4E0D\u652F\u6301\uFF0C\u5982\u5DF2\u7ECF\u8FC7\u671F\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684\u670D\u52A1\u65B9\u6CD5\u7248\u672C -ERROR_31_SOLUTION=\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u5408\u6CD5\u7684\u62A5\u6587\u683C\u5F0F\u4E3Axml,json\u53CAstream,\u8BF7\u68C0\u67E5 -ERROR_32_SOLUTION=\u8BF7\u67E5\u770B\u6839\u636E\u670D\u52A1\u63A5\u53E3\uFF0C\u6DFB\u52A0\u5FC5\u987B\u7684\u53C2\u6570 -ERROR_33_SOLUTION=\u8BF7\u67E5\u770B\u6839\u636E\u670D\u52A1\u63A5\u53E3\u5BF9\u53C2\u6570\u683C\u5F0F\u7684\u8981\u6C42 -ERROR_34_SOLUTION=\u7B49\u5F85\u7247\u523B\uFF0C\u7A0D\u5019\u518D\u8BD5 -ERROR_35_SOLUTION=\u9000\u51FA\u7CFB\u7EDF\uFF0C\u7A0D\u5019\u518D\u8BD5 -ERROR_36_SOLUTION=\u8BF7\u68C0\u67E5\u5E94\u7528\u6388\u6743\u8BBF\u95EE\u670D\u52A1\u7684\u6B21\u6570 -ERROR_37_SOLUTION=\u8BF7\u964D\u4F4E\u670D\u52A1\u8BBF\u95EE\u7684\u9891\u7387 -########################################################################################################################## - -###ISP\u5B50\u9519\u8BEF -########################################################################################################################## -isp.xxx-service-unavailable=\u8C03\u7528\u540E\u7AEF\u670D\u52A1{0}\u629B\u5F02\u5E38:{1}\uFF0C\u670D\u52A1\u4E0D\u53EF\u7528\u3002\ - \n\u5F02\u5E38\u4FE1\u606F:\n{2} -isp.xxx-service-timeout = \u8C03\u7528{0}\u670D\u52A1\u8D85\u65F6\uFF0C\u8BE5\u670D\u52A1\u7684\u8D85\u65F6\u9650\u5236\u4E3A{1}\u79D2\uFF0C\u8BF7\u548C\u670D\u52A1\u5E73\u53F0\u63D0\u4F9B\u5546\u8054\u7CFB\u3002 -########################################################################################################################## - - - -###ISV\u5B50\u9519\u8BEF -########################################################################################################################## -isv.xxx-not-exist\:invalid-yyy= \u6839\u636E'{0}'({1})\u65E0\u6CD5\u83B7\u53D6\u5230'{2}'\u5BF9\u8C61 -isv.missing-parameter\:xxx=\u7F3A\u5C11\u5FC5\u8981\u7684\u53C2\u6570{0} -isv.invalid-paramete\:xxx=\u53C2\u6570{0}\u65E0\u6548\uFF0C\u683C\u5F0F\u4E0D\u5BF9\u3001\u975E\u6CD5\u503C\u3001\u8D8A\u754C\u7B49 -isv.invalid-permission=\u6743\u9650\u4E0D\u591F\u3001\u975E\u6CD5\u8BBF\u95EE -isv.parameters-mismatch\:xxx-and-yyy=\u4F20\u5165\u7684\u53C2\u6570{0}\u548C{1}\u4E0D\u5339\u914D -########################################################################################################################## - +###\u9519\u8BEF\u63CF\u8FF0\u4FE1\u606F +########################################################################################################################## +ERROR_1 =\u670D\u52A1\u4E0D\u53EF\u7528 +ERROR_2 =\u5F00\u53D1\u8005\u6743\u9650\u4E0D\u8DB3 +ERROR_3 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7528\u6237\u6743\u9650\u4E0D\u8DB3 +ERROR_4=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u56FE\u7247\u4E0A\u4F20\u5931\u8D25,\u539F\u56E0\u4E3A:{2} +ERROR_5 =\u670D\u52A1\u65B9\u6CD5({0}:{1})HTTP\u65B9\u6CD5{2}\u88AB\u7981\u6B62 +ERROR_6 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F16\u7801\u9519\u8BEF +ERROR_7 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u8BF7\u6C42\u88AB\u7981\u6B62 +ERROR_8 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u5DF2\u7ECF\u4F5C\u5E9F +ERROR_9 =\u670D\u52A1\u65B9\u6CD5({0}:{1})\u4E1A\u52A1\u903B\u8F91\u51FA\u9519 +ERROR_20=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u4F1A\u8BDD\u53C2\u6570:{2} +ERROR_21=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u4F1A\u8BDDID:{2}\u65E0\u6548 +ERROR_22=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u5E94\u7528\u952E\u53C2\u6570:{2} +ERROR_23=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u5E94\u7528\u952E\u53C2\u6570{2}\u65E0\u6548 +ERROR_24=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u9700\u8981\u7B7E\u540D,\u7F3A\u5C11\u7B7E\u540D\u53C2\u6570:{2} +ERROR_25=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u7B7E\u540D\u65E0\u6548 +ERROR_26=\u670D\u52A1\u8BF7\u6C42\u7F3A\u5C11\u65B9\u6CD5\u540D\u53C2\u6570:{0} +ERROR_27=\u8C03\u7528\u4E0D\u5B58\u5728\u7684\u670D\u52A1\u65B9\u6CD5:{0} +ERROR_28=\u670D\u52A1\u65B9\u6CD5({0})\u7F3A\u5C11\u7248\u672C\u53C2\u6570:{1} +ERROR_29=\u670D\u52A1\u65B9\u6CD5({0})\u4E0D\u5B58\u5728\u5BF9\u5E94\u7684\u7248\u672C({1}) +ERROR_30=\u670D\u52A1\u65B9\u6CD5({0})\u4E0D\u652F\u6301\u5BF9\u5E94\u7684\u7248\u672C\u53F7({1}) +ERROR_31=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u62A5\u6587\u6570\u636E\u683C\u5F0F\u65E0\u6548({2}) +ERROR_32=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7F3A\u5C11\u5FC5\u8981\u7684\u53C2\u6570 +ERROR_33=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u53C2\u6570\u975E\u6CD5 +ERROR_34=\u670D\u52A1\u65B9\u6CD5({0}:{1})\u7684\u8C03\u7528\u6B21\u6570\u8D85\u9650 +ERROR_35=\u7528\u6237\u4F1A\u8BDD\u8C03\u7528\u670D\u52A1\u7684\u6B21\u6570\u8D85\u9650 +ERROR_36=\u5E94\u7528\u8C03\u7528\u670D\u52A1\u7684\u6B21\u6570\u8D85\u9650 +ERROR_37=\u5E94\u7528\u8C03\u7528\u670D\u52A1\u7684\u9891\u7387\u8D85\u9650 +########################################################################################################################## + + +###\u9519\u8BEF\u89E3\u51B3\u65B9\u6848 +########################################################################################################################## +ERROR_1_SOLUTION =\u670D\u52A1\u76EE\u524D\u65E0\u6CD5\u4F7F\u7528\uFF0C\u8BF7\u4FDD\u5B58\u597D\u9519\u8BEF\u4FE1\u606F\u5E76\u548C\u670D\u52A1\u5E73\u53F0\u7BA1\u7406\u5458\u8054\u7CFB +ERROR_2_SOLUTION =\u4E0D\u8DB3\u7684ISV\u6743\u9650\uFF0C\u8BF7\u548C\u7BA1\u7406\u5458\u8054\u7CFB +ERROR_3_SOLUTION =\u7528\u6237\u6743\u9650\u4E0D\u8DB3\uFF0C\u8BF7\u548C\u7BA1\u7406\u5458\u8054\u7CFB +ERROR_4_SOLUTION=\u4E0A\u4F20\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u7C7B\u578B\u53CA\u5927\u5C0F\u662F\u5426\u5408\u6CD5 +ERROR_5_SOLUTION =\u8BF7\u4F7F\u7528\u5408\u9002\u7684HTTP\u65B9\u6CD5\uFF08GET\u6216POST\uFF09 +ERROR_6_SOLUTION =\u65E0\u6548\u7684\u7F16\u7801\uFF0C\u8BF7\u5BF9\u4F7F\u7528UTF-8\u5BF9\u8BF7\u6C42\u53C2\u6570\u503C\u8FDB\u884C\u7F16\u7801 +ERROR_7_SOLUTION =\u7981\u6B62\u8BF7\u6C42\uFF0C\u56E0\u670D\u52A1\u5E73\u53F0\u5DF2\u7ECF\u6EE1\u8D1F\u8377\uFF0C\u8BF7\u7A0D\u5019\u518D\u8BD5 +ERROR_8_SOLUTION =\u65B9\u6CD5\u5DF2\u8FC7\u65F6\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7248\u672C\u6216\u5176\u5B83\u66FF\u4EE3\u7684\u65B9\u6CD5 +ERROR_9_SOLUTION =\u8BF7\u4E86\u89E3\u670D\u52A1\u8C03\u7528\u7684\u524D\u7F6E\u6761\u4EF6\uFF0C\u68C0\u67E5\u662F\u5426\u6EE1\u8DB3\u4E1A\u52A1\u903B\u8F91 +ERROR_20_SOLUTION=\u5C06\u6DFB\u52A0\u4F1A\u8BDDID\u8BF7\u6C42\u53C2\u6570 +ERROR_21_SOLUTION=\u65E0\u6548\u7684\u4F1A\u8BDD,\u8BF7\u91CD\u65B0\u767B\u5F55\u4EE5\u83B7\u53D6\u5408\u6CD5\u7684\u4F1A\u8BDD +ERROR_22_SOLUTION=\u7F3A\u5C11appKey\uFF0C\u8BF7\u5411\u670D\u52A1\u7AEF\u83B7\u53D6\u5408\u6CD5\u7684appKey +ERROR_23_SOLUTION=\u65E0\u6548\u7684appKey,\u8BF7\u4F7F\u7528\u5408\u6CD5\u7684appKey\uFF08\u7531\u670D\u52A1\u63D0\u4F9B\u5546\u6388\u4E88\u4F60\uFF09 +ERROR_24_SOLUTION=\u7F3A\u5C11\u7B7E\u540D\u53C2\u6570\uFF0C\u8BF7\u6DFB\u52A0\u7B7E\u540D\u8BF7\u6C42\u53C2\u6570 +ERROR_25_SOLUTION=\u7B7E\u540D\u65E0\u6548\uFF0C\u8BF7\u6309\u6B63\u786E\u7684\u7B97\u6CD5\u5BF9\u8BF7\u6C42\u6570\u636E\u8FDB\u884C\u7B7E\u540D:\ + SHA1( ),\u6CE8\u610F\u53C2\u6570\u5217\u8868\u6309\u5B57\u6BCD\u987A\u5E8F\u6392\u5217 +ERROR_26_SOLUTION=\u7F3A\u5C11\u65B9\u6CD5,\u8BF7\u6DFB\u52A0\u4E0A\u670D\u52A1\u65B9\u6CD5\u7684\u8BF7\u6C42\u53C2\u6570 +ERROR_27_SOLUTION=\u65E0\u6548\u7684\u65B9\u6CD5\uFF0C\u8BF7\u68C0\u67E5\u670D\u52A1\u65B9\u6CD5\u540D\u662F\u5426\u6B63\u786E +ERROR_28_SOLUTION=\u7F3A\u5C11\u7248\u672C\u53C2\u6570\uFF0C\u8BF7\u6307\u5B9A\u670D\u52A1\u65B9\u6CD5\u7684\u7248\u672C\u53F7 +ERROR_29_SOLUTION=\u975E\u6CD5\u7684\u7248\u672C\u53F7\uFF0C\u8FD9\u4E2A\u670D\u52A1\u65B9\u6CD5\u7684\u7248\u672C\u53F7\u662F\u9519\u8BEF\u7684\uFF0C\u8BF7\u68C0\u67E5 +ERROR_30_SOLUTION=\u8FD9\u4E2A\u7248\u672C\u53F7\u5DF2\u7ECF\u4E0D\u652F\u6301\uFF0C\u5982\u5DF2\u7ECF\u8FC7\u671F\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684\u670D\u52A1\u65B9\u6CD5\u7248\u672C +ERROR_31_SOLUTION=\u6570\u636E\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u5408\u6CD5\u7684\u62A5\u6587\u683C\u5F0F\u4E3Axml,json\u53CAstream,\u8BF7\u68C0\u67E5 +ERROR_32_SOLUTION=\u8BF7\u67E5\u770B\u6839\u636E\u670D\u52A1\u63A5\u53E3\uFF0C\u6DFB\u52A0\u5FC5\u987B\u7684\u53C2\u6570 +ERROR_33_SOLUTION=\u8BF7\u67E5\u770B\u6839\u636E\u670D\u52A1\u63A5\u53E3\u5BF9\u53C2\u6570\u683C\u5F0F\u7684\u8981\u6C42 +ERROR_34_SOLUTION=\u7B49\u5F85\u7247\u523B\uFF0C\u7A0D\u5019\u518D\u8BD5 +ERROR_35_SOLUTION=\u9000\u51FA\u7CFB\u7EDF\uFF0C\u7A0D\u5019\u518D\u8BD5 +ERROR_36_SOLUTION=\u8BF7\u68C0\u67E5\u5E94\u7528\u6388\u6743\u8BBF\u95EE\u670D\u52A1\u7684\u6B21\u6570 +ERROR_37_SOLUTION=\u8BF7\u964D\u4F4E\u670D\u52A1\u8BBF\u95EE\u7684\u9891\u7387 +########################################################################################################################## + +###ISP\u5B50\u9519\u8BEF +########################################################################################################################## +isp.xxx-service-unavailable=\u8C03\u7528\u540E\u7AEF\u670D\u52A1{0}\u629B\u5F02\u5E38:{1}\uFF0C\u670D\u52A1\u4E0D\u53EF\u7528\u3002\ + \n\u5F02\u5E38\u4FE1\u606F:\n{2} +isp.xxx-service-timeout = \u8C03\u7528{0}\u670D\u52A1\u8D85\u65F6\uFF0C\u8BE5\u670D\u52A1\u7684\u8D85\u65F6\u9650\u5236\u4E3A{1}\u79D2\uFF0C\u8BF7\u548C\u670D\u52A1\u5E73\u53F0\u63D0\u4F9B\u5546\u8054\u7CFB\u3002 +########################################################################################################################## + + + +###ISV\u5B50\u9519\u8BEF +########################################################################################################################## +isv.xxx-not-exist\:invalid-yyy= \u6839\u636E'{0}'({1})\u65E0\u6CD5\u83B7\u53D6\u5230'{2}'\u5BF9\u8C61 +isv.missing-parameter\:xxx=\u7F3A\u5C11\u5FC5\u8981\u7684\u53C2\u6570{0} +isv.invalid-paramete\:xxx=\u53C2\u6570{0}\u65E0\u6548\uFF0C\u683C\u5F0F\u4E0D\u5BF9\u3001\u975E\u6CD5\u503C\u3001\u8D8A\u754C\u7B49 +isv.invalid-permission=\u6743\u9650\u4E0D\u591F\u3001\u975E\u6CD5\u8BBF\u95EE +isv.parameters-mismatch\:xxx-and-yyy=\u4F20\u5165\u7684\u53C2\u6570{0}\u548C{1}\u4E0D\u5339\u914D +########################################################################################################################## + diff --git a/rop/src/test/java/com/rop/annotation/HttpActionTest.java b/rop/src/test/java/com/rop/annotation/HttpActionTest.java index b475f47..8da4981 100644 --- a/rop/src/test/java/com/rop/annotation/HttpActionTest.java +++ b/rop/src/test/java/com/rop/annotation/HttpActionTest.java @@ -1,31 +1,42 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-8 - */ -package com.rop.annotation; - -import org.testng.annotations.Test; - -import static org.testng.AssertJUnit.assertEquals; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class HttpActionTest { - - @Test - public void testValueOf() { - assertEquals(HttpAction.valueOf("GET"), HttpAction.GET); - } - - @Test(expectedExceptions = {IllegalArgumentException.class}) - public void invalidValueOf() { - assertEquals(HttpAction.valueOf("get"), HttpAction.GET); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.annotation; + +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertEquals; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class HttpActionTest { + + @Test + public void testValueOf() { + assertEquals(HttpAction.valueOf("GET"), HttpAction.GET); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void invalidValueOf() { + assertEquals(HttpAction.valueOf("get"), HttpAction.GET); + } +} + diff --git a/rop/src/test/java/com/rop/client/DefaultRopClientTest.java b/rop/src/test/java/com/rop/client/DefaultRopClientTest.java deleted file mode 100644 index 4fa50d5..0000000 --- a/rop/src/test/java/com/rop/client/DefaultRopClientTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.client; - -import org.testng.annotations.Test; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultRopClientTest { - - private RopClient ropClient = new DefaultRopClient("http://localhost:8088/router", "00001", "abcdeabcdeabcdeabcdeabcde"); - - @Test - public void testPostWithSession() throws Exception { - - } -} - diff --git a/rop/src/test/java/com/rop/concurrent/FetureTest.java b/rop/src/test/java/com/rop/concurrent/FetureTest.java index eef8ca1..ee25239 100644 --- a/rop/src/test/java/com/rop/concurrent/FetureTest.java +++ b/rop/src/test/java/com/rop/concurrent/FetureTest.java @@ -1,51 +1,62 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-5 - */ -package com.rop.concurrent; - -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.concurrent.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class FetureTest { - - @Test - public void testFetureInterrupt() { - final ExecutorService exec = Executors.newFixedThreadPool(5); - Callable call = new Callable() { - public String call() throws Exception { - Thread.sleep(500); - return "Feture"; - } - }; - Future task = exec.submit(call); - String result = null; - try { - while (!task.isDone()) { - result = task.get(200, TimeUnit.MILLISECONDS); - } - } catch (InterruptedException e) { - result = "InterruptedException"; - } catch (ExecutionException e) { - result = "ExecutionException"; - } catch (TimeoutException e) { - result = "TimeoutException"; - } - - Assert.assertEquals(result, "TimeoutException"); - - //关闭线程池 - exec.shutdown(); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.concurrent; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.concurrent.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class FetureTest { + + @Test + public void testFetureInterrupt() { + final ExecutorService exec = Executors.newFixedThreadPool(5); + Callable call = new Callable() { + public String call() throws Exception { + Thread.sleep(500); + return "Feture"; + } + }; + Future task = exec.submit(call); + String result = null; + try { + while (!task.isDone()) { + result = task.get(200, TimeUnit.MILLISECONDS); + } + } catch (InterruptedException e) { + result = "InterruptedException"; + } catch (ExecutionException e) { + result = "ExecutionException"; + } catch (TimeoutException e) { + result = "TimeoutException"; + } + + Assert.assertEquals(result, "TimeoutException"); + + //关闭线程池 + exec.shutdown(); + } +} + diff --git a/rop/src/test/java/com/rop/impl/Addresss.java b/rop/src/test/java/com/rop/impl/Addresss.java index 5066900..4ebb74f 100644 --- a/rop/src/test/java/com/rop/impl/Addresss.java +++ b/rop/src/test/java/com/rop/impl/Addresss.java @@ -1,59 +1,70 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.impl; - -import javax.validation.constraints.Pattern; -import javax.xml.bind.annotation.*; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "address") -public class Addresss { - - @XmlAttribute - @Pattern(regexp = "\\w{4,30}") - private String zoneCode; - - @XmlAttribute - private String doorCode; - - - @XmlElementWrapper(name = "streets") - @XmlElement(name = "street") - private List streets; - - public String getZoneCode() { - return zoneCode; - } - - public void setZoneCode(String zoneCode) { - this.zoneCode = zoneCode; - } - - public String getDoorCode() { - return doorCode; - } - - public void setDoorCode(String doorCode) { - this.doorCode = doorCode; - } - - public List getStreets() { - return streets; - } - - public void setStreets(List streets) { - this.streets = streets; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import javax.validation.constraints.Pattern; +import javax.xml.bind.annotation.*; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "address") +public class Addresss { + + @XmlAttribute + @Pattern(regexp = "\\w{4,30}") + private String zoneCode; + + @XmlAttribute + private String doorCode; + + + @XmlElementWrapper(name = "streets") + @XmlElement(name = "street") + private List streets; + + public String getZoneCode() { + return zoneCode; + } + + public void setZoneCode(String zoneCode) { + this.zoneCode = zoneCode; + } + + public String getDoorCode() { + return doorCode; + } + + public void setDoorCode(String doorCode) { + this.doorCode = doorCode; + } + + public List getStreets() { + return streets; + } + + public void setStreets(List streets) { + this.streets = streets; + } +} + diff --git a/rop/src/test/java/com/rop/impl/CreateUserRequest.java b/rop/src/test/java/com/rop/impl/CreateUserRequest.java index cb5ea64..9ec6378 100644 --- a/rop/src/test/java/com/rop/impl/CreateUserRequest.java +++ b/rop/src/test/java/com/rop/impl/CreateUserRequest.java @@ -1,55 +1,66 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-2-29 - */ -package com.rop.impl; - -import com.rop.annotation.IgnoreSign; - -import javax.validation.Valid; -import javax.validation.constraints.Pattern; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class CreateUserRequest { - - @Pattern(regexp = "\\w{4,30}") - private String userName; - - @Valid - private Addresss address; - - @IgnoreSign - private String remark; - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - public Addresss getAddress() { - return address; - } - - public void setAddress(Addresss address) { - this.address = address; - } - - public String getRemark() { - return remark; - } - - public void setRemark(String remark) { - this.remark = remark; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.annotation.IgnoreSign; + +import javax.validation.Valid; +import javax.validation.constraints.Pattern; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class CreateUserRequest { + + @Pattern(regexp = "\\w{4,30}") + private String userName; + + @Valid + private Addresss address; + + @IgnoreSign + private String remark; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public Addresss getAddress() { + return address; + } + + public void setAddress(Addresss address) { + this.address = address; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } +} + diff --git a/rop/src/test/java/com/rop/impl/DefaultRopContextTest.java b/rop/src/test/java/com/rop/impl/DefaultRopContextTest.java index d8c469c..dabd8a5 100644 --- a/rop/src/test/java/com/rop/impl/DefaultRopContextTest.java +++ b/rop/src/test/java/com/rop/impl/DefaultRopContextTest.java @@ -1,209 +1,220 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-31 - */ -package com.rop.impl; - -import com.rop.AbstractRopRequest; -import com.rop.RopContext; -import com.rop.ServiceMethodDefinition; -import com.rop.ServiceMethodHandler; -import com.rop.annotation.*; -import com.rop.request.UploadFile; -import org.springframework.context.ApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; -import org.testng.annotations.Test; - -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.testng.Assert.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class DefaultRopContextTest { - - @Test - public void testWithoutGroupService() { - ApplicationContext context = mock(ApplicationContext.class); - when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"service1"}); - Class withoutGroupServiceClass = WithoutGroupService.class; - when(context.getType("service1")).thenReturn(withoutGroupServiceClass); - - RopContext registryMethod = new DefaultRopContext(context); - ServiceMethodHandler handler = registryMethod.getServiceMethodHandler("service.method1", "1.0"); - ServiceMethodDefinition definition = handler.getServiceMethodDefinition(); - assertNotNull(definition); - assertEquals(definition.getMethod(), "service.method1"); - assertEquals(definition.getMethodTitle(), "测试方法1"); - assertEquals(definition.getMethodGroup(), "GROUP1"); - assertEquals(definition.getMethodGroupTitle(), "分组1"); - - assertEquals(definition.getTags(), new String[]{"TAG1", "TAG2"}); - assertEquals(definition.isIgnoreSign(), true); - assertEquals(definition.isNeedInSession(), false); - assertEquals(definition.getTimeout(), 100); - assertEquals(definition.getVersion(), "1.0"); - } - - @Test - public void testWithGroupService() { - ApplicationContext context = mock(ApplicationContext.class); - - when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"service1"}); - Class withGroupServiceClass = WithGroupService.class; - when(context.getType("service1")).thenReturn(withGroupServiceClass); - RopContext ropContext = new DefaultRopContext(context); - - //method1:都在ServiceMethodGroup中定义,在ServiceMethod中直接采用 - ServiceMethodHandler handler = ropContext.getServiceMethodHandler("service.method1", "1.0"); - ServiceMethodDefinition definition = handler.getServiceMethodDefinition(); - assertNotNull(definition); - assertEquals(definition.getMethod(), "service.method1"); - assertEquals(definition.getMethodTitle(), "测试方法1"); - assertEquals(definition.getMethodGroup(), "GROUP1"); - assertEquals(definition.getMethodGroupTitle(), "分组1"); - assertEquals(definition.getTags(), new String[]{"TAG1", "TAG2"}); - assertEquals(definition.isIgnoreSign(), true); - assertEquals(definition.isNeedInSession(), false); - assertEquals(definition.getTimeout(), 100); - assertEquals(definition.getVersion(), "1.0"); - - //method2:在ServiceMethodGroup中定义,在ServiceMethod显式覆盖之 - ServiceMethodHandler handler2 = ropContext.getServiceMethodHandler("service.method2", "2.0"); - ServiceMethodDefinition definition2 = handler2.getServiceMethodDefinition(); - assertNotNull(definition2); - assertEquals(definition2.getMethod(), "service.method2"); - assertEquals(definition2.getMethodTitle(), "测试方法2"); - assertEquals(definition2.getMethodGroup(), "GROUP2"); - assertEquals(definition2.getMethodGroupTitle(), "分组2"); - assertEquals(definition2.getTags(), new String[]{"TAG11", "TAG21"}); - assertEquals(definition2.isIgnoreSign(), false); - assertEquals(definition2.isNeedInSession(), true); - assertEquals(definition2.getTimeout(), 200); - assertEquals(definition2.getVersion(), "2.0"); - } - - @Test - public void testIngoreSignField() { - ApplicationContext context = mock(ApplicationContext.class); - - when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"method1"}); - Class serviceClass = IgnoreSignRopRequestService.class; - when(context.getType("method1")).thenReturn(serviceClass); - - RopContext ropContext = new DefaultRopContext(context); - - ServiceMethodHandler method1 = ropContext.getServiceMethodHandler("method1", "1.0"); - List ignoreSignFieldNames = method1.getIgnoreSignFieldNames(); - assertNotNull(ignoreSignFieldNames); - assertEquals(ignoreSignFieldNames.size(), 4); - assertTrue(ignoreSignFieldNames.contains("field1")); - assertTrue(ignoreSignFieldNames.contains("field3")); - assertTrue(ignoreSignFieldNames.contains("sign")); - } - - @ServiceMethodBean - public class IgnoreSignRopRequestService { - - @ServiceMethod(method = "method1", version = "1.0") - public Object method1(FooRopRequest request) { - return null; - } - } - - public class FooRopRequest extends AbstractRopRequest { - - @IgnoreSign - private String field1; - - private String field2; - - @IgnoreSign - private int field3; - - private int field4; - - public String getField1() { - return field1; - } - - public void setField1(String field1) { - this.field1 = field1; - } - - public String getField2() { - return field2; - } - - public void setField2(String field2) { - this.field2 = field2; - } - - public int getField3() { - return field3; - } - - public void setField3(int field3) { - this.field3 = field3; - } - - public int getField4() { - return field4; - } - - public void setField4(int field4) { - this.field4 = field4; - } - } - - @ServiceMethodBean - public class WithoutGroupService { - - @ServiceMethod(method = "service.method1", title = "测试方法1", group = "GROUP1", groupTitle = "分组1", - tags = {"TAG1", "TAG2"}, ignoreSign = IgnoreSignType.YES, - needInSession = NeedInSessionType.NO, timeout = 100, version = "1.0") - public Object service1() { - return null; - } - } - - @ServiceMethodBean(group = "GROUP1", groupTitle = "分组1", - tags = {"TAG1", "TAG2"}, ignoreSign = IgnoreSignType.YES, - needInSession = NeedInSessionType.NO, timeout = 100, version = "1.0") - public class WithGroupService { - - @ServiceMethod(method = "service.method1", version = "1.0", title = "测试方法1") - public Object service1() { - return null; - } - - @ServiceMethod(method = "service.method2", title = "测试方法2", group = "GROUP2", groupTitle = "分组2", - tags = {"TAG11", "TAG21"}, ignoreSign = IgnoreSignType.NO, - needInSession = NeedInSessionType.YES, timeout = 200, version = "2.0") - public Object service2() { - return null; - } - } - - @Test - public void annotationTest(){ - IgnoreSign annotation = AnnotationUtils.findAnnotation(UploadFile.class, IgnoreSign.class); - assertNotNull(annotation); - annotation = AnnotationUtils.findAnnotation(ExtUploadFile.class, IgnoreSign.class); - assertNotNull(annotation); - } - - public static void main(String[] args) { - System.out.println("中国人民!"); - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.AbstractRopRequest; +import com.rop.RopContext; +import com.rop.ServiceMethodDefinition; +import com.rop.ServiceMethodHandler; +import com.rop.annotation.*; +import com.rop.converter.UploadFile; +import org.springframework.context.ApplicationContext; +import org.springframework.core.annotation.AnnotationUtils; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.Assert.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class DefaultRopContextTest { + + @Test + public void testWithoutGroupService() { + ApplicationContext context = mock(ApplicationContext.class); + when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"service1"}); + Class withoutGroupServiceClass = WithoutGroupService.class; + when(context.getType("service1")).thenReturn(withoutGroupServiceClass); + + RopContext registryMethod = new DefaultRopContext(context); + ServiceMethodHandler handler = registryMethod.getServiceMethodHandler("service.method1", "1.0"); + ServiceMethodDefinition definition = handler.getServiceMethodDefinition(); + assertNotNull(definition); + assertEquals(definition.getMethod(), "service.method1"); + assertEquals(definition.getMethodTitle(), "测试方法1"); + assertEquals(definition.getMethodGroup(), "GROUP1"); + assertEquals(definition.getMethodGroupTitle(), "分组1"); + + assertEquals(definition.getTags(), new String[]{"TAG1", "TAG2"}); + assertEquals(definition.isIgnoreSign(), true); + assertEquals(definition.isNeedInSession(), false); + assertEquals(definition.getTimeout(), 100); + assertEquals(definition.getVersion(), "1.0"); + } + + @Test + public void testWithGroupService() { + ApplicationContext context = mock(ApplicationContext.class); + + when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"service1"}); + Class withGroupServiceClass = WithGroupService.class; + when(context.getType("service1")).thenReturn(withGroupServiceClass); + RopContext ropContext = new DefaultRopContext(context); + + //method1:都在ServiceMethodGroup中定义,在ServiceMethod中直接采用 + ServiceMethodHandler handler = ropContext.getServiceMethodHandler("service.method1", "1.0"); + ServiceMethodDefinition definition = handler.getServiceMethodDefinition(); + assertNotNull(definition); + assertEquals(definition.getMethod(), "service.method1"); + assertEquals(definition.getMethodTitle(), "测试方法1"); + assertEquals(definition.getMethodGroup(), "GROUP1"); + assertEquals(definition.getMethodGroupTitle(), "分组1"); + assertEquals(definition.getTags(), new String[]{"TAG1", "TAG2"}); + assertEquals(definition.isIgnoreSign(), true); + assertEquals(definition.isNeedInSession(), false); + assertEquals(definition.getTimeout(), 100); + assertEquals(definition.getVersion(), "1.0"); + + //method2:在ServiceMethodGroup中定义,在ServiceMethod显式覆盖之 + ServiceMethodHandler handler2 = ropContext.getServiceMethodHandler("service.method2", "2.0"); + ServiceMethodDefinition definition2 = handler2.getServiceMethodDefinition(); + assertNotNull(definition2); + assertEquals(definition2.getMethod(), "service.method2"); + assertEquals(definition2.getMethodTitle(), "测试方法2"); + assertEquals(definition2.getMethodGroup(), "GROUP2"); + assertEquals(definition2.getMethodGroupTitle(), "分组2"); + assertEquals(definition2.getTags(), new String[]{"TAG11", "TAG21"}); + assertEquals(definition2.isIgnoreSign(), false); + assertEquals(definition2.isNeedInSession(), true); + assertEquals(definition2.getTimeout(), 200); + assertEquals(definition2.getVersion(), "2.0"); + } + + @Test + public void testIngoreSignField() { + ApplicationContext context = mock(ApplicationContext.class); + + when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"method1"}); + Class serviceClass = IgnoreSignRopRequestService.class; + when(context.getType("method1")).thenReturn(serviceClass); + + RopContext ropContext = new DefaultRopContext(context); + + ServiceMethodHandler method1 = ropContext.getServiceMethodHandler("method1", "1.0"); + List ignoreSignFieldNames = method1.getIgnoreSignFieldNames(); + assertNotNull(ignoreSignFieldNames); + assertEquals(ignoreSignFieldNames.size(), 4); + assertTrue(ignoreSignFieldNames.contains("field1")); + assertTrue(ignoreSignFieldNames.contains("field3")); + assertTrue(ignoreSignFieldNames.contains("sign")); + } + + @ServiceMethodBean + public class IgnoreSignRopRequestService { + + @ServiceMethod(method = "method1", version = "1.0") + public Object method1(FooRopRequest request) { + return null; + } + } + + public class FooRopRequest extends AbstractRopRequest { + + @IgnoreSign + private String field1; + + private String field2; + + @IgnoreSign + private int field3; + + private int field4; + + public String getField1() { + return field1; + } + + public void setField1(String field1) { + this.field1 = field1; + } + + public String getField2() { + return field2; + } + + public void setField2(String field2) { + this.field2 = field2; + } + + public int getField3() { + return field3; + } + + public void setField3(int field3) { + this.field3 = field3; + } + + public int getField4() { + return field4; + } + + public void setField4(int field4) { + this.field4 = field4; + } + } + + @ServiceMethodBean + public class WithoutGroupService { + + @ServiceMethod(method = "service.method1", title = "测试方法1", group = "GROUP1", groupTitle = "分组1", + tags = {"TAG1", "TAG2"}, ignoreSign = IgnoreSignType.YES, + needInSession = NeedInSessionType.NO, timeout = 100, version = "1.0") + public Object service1() { + return null; + } + } + + @ServiceMethodBean(group = "GROUP1", groupTitle = "分组1", + tags = {"TAG1", "TAG2"}, ignoreSign = IgnoreSignType.YES, + needInSession = NeedInSessionType.NO, timeout = 100, version = "1.0") + public class WithGroupService { + + @ServiceMethod(method = "service.method1", version = "1.0", title = "测试方法1") + public Object service1() { + return null; + } + + @ServiceMethod(method = "service.method2", title = "测试方法2", group = "GROUP2", groupTitle = "分组2", + tags = {"TAG11", "TAG21"}, ignoreSign = IgnoreSignType.NO, + needInSession = NeedInSessionType.YES, timeout = 200, version = "2.0") + public Object service2() { + return null; + } + } + + @Test + public void annotationTest(){ + IgnoreSign annotation = AnnotationUtils.findAnnotation(UploadFile.class, IgnoreSign.class); + assertNotNull(annotation); + annotation = AnnotationUtils.findAnnotation(ExtUploadFile.class, IgnoreSign.class); + assertNotNull(annotation); + } + + public static void main(String[] args) { + System.out.println("中国人民!"); + } + +} + diff --git a/rop/src/test/java/com/rop/impl/ExtUploadFile.java b/rop/src/test/java/com/rop/impl/ExtUploadFile.java index b524d45..86981ac 100644 --- a/rop/src/test/java/com/rop/impl/ExtUploadFile.java +++ b/rop/src/test/java/com/rop/impl/ExtUploadFile.java @@ -1,28 +1,39 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-1 - */ -package com.rop.impl; - -import com.rop.request.UploadFile; - -import java.io.File; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ExtUploadFile extends UploadFile { - public ExtUploadFile(String fileType, byte[] content) { - super(fileType, content); - } - - public ExtUploadFile(File file) { - super(file); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.converter.UploadFile; + +import java.io.File; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ExtUploadFile extends UploadFile { + public ExtUploadFile(String fileType, byte[] content) { + super(fileType, content); + } + + public ExtUploadFile(File file) { + super(file); + } +} + diff --git a/rop/src/test/java/com/rop/impl/FormattingConversionServiceTest.java b/rop/src/test/java/com/rop/impl/FormattingConversionServiceTest.java index aac2b03..cf362ce 100644 --- a/rop/src/test/java/com/rop/impl/FormattingConversionServiceTest.java +++ b/rop/src/test/java/com/rop/impl/FormattingConversionServiceTest.java @@ -1,73 +1,84 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.impl; - -import com.rop.request.RopRequestMessageConverter; -import org.springframework.beans.BeanUtils; -import org.springframework.core.convert.ConversionService; -import org.springframework.format.support.FormattingConversionServiceFactoryBean; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.validation.Validator; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import org.springframework.web.bind.ServletRequestDataBinder; -import org.testng.annotations.Test; - -import java.util.HashSet; -import java.util.Set; - -import static org.testng.Assert.*; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class FormattingConversionServiceTest { - - @Test - public void testDoBind() { - FormattingConversionServiceFactoryBean serviceFactoryBean = new FormattingConversionServiceFactoryBean(); - Set converters = new HashSet(); - converters.add(new RopRequestMessageConverter()); - serviceFactoryBean.setConverters(converters); - - serviceFactoryBean.afterPropertiesSet(); - ConversionService conversionService = serviceFactoryBean.getObject(); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setParameter("userName", "tom"); - request.setParameter("address", - "\n" + - "
\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "
"); - - CreateUserRequest bindObject = BeanUtils.instantiateClass(CreateUserRequest.class); - ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(bindObject, "bindObject"); - dataBinder.setConversionService(conversionService); - dataBinder.setValidator(getValidator()); - dataBinder.bind(request); - dataBinder.validate(); - - assertTrue(dataBinder.getBindingResult().hasErrors()); - assertEquals(dataBinder.getBindingResult().getErrorCount(), 2); - CreateUserRequest createUserRequest = (CreateUserRequest) dataBinder.getBindingResult().getTarget(); - assertNotNull(createUserRequest.getAddress()); - assertNotNull(createUserRequest.getAddress().getStreets()); - assertTrue(createUserRequest.getAddress().getStreets().size() > 0); - } - - private Validator getValidator() { - LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); - localValidatorFactoryBean.afterPropertiesSet(); - return localValidatorFactoryBean; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.request.RopRequestMessageConverter; +import org.springframework.beans.BeanUtils; +import org.springframework.core.convert.ConversionService; +import org.springframework.format.support.FormattingConversionServiceFactoryBean; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.validation.Validator; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.web.bind.ServletRequestDataBinder; +import org.testng.annotations.Test; + +import java.util.HashSet; +import java.util.Set; + +import static org.testng.Assert.*; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class FormattingConversionServiceTest { + + @Test + public void testDoBind() { + FormattingConversionServiceFactoryBean serviceFactoryBean = new FormattingConversionServiceFactoryBean(); + Set converters = new HashSet(); + converters.add(new RopRequestMessageConverter()); + serviceFactoryBean.setConverters(converters); + + serviceFactoryBean.afterPropertiesSet(); + ConversionService conversionService = serviceFactoryBean.getObject(); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setParameter("userName", "tom"); + request.setParameter("address", + "\n" + + "
\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
"); + + CreateUserRequest bindObject = BeanUtils.instantiateClass(CreateUserRequest.class); + ServletRequestDataBinder dataBinder = new ServletRequestDataBinder(bindObject, "bindObject"); + dataBinder.setConversionService(conversionService); + dataBinder.setValidator(getValidator()); + dataBinder.bind(request); + dataBinder.validate(); + + assertTrue(dataBinder.getBindingResult().hasErrors()); + assertEquals(dataBinder.getBindingResult().getErrorCount(), 2); + CreateUserRequest createUserRequest = (CreateUserRequest) dataBinder.getBindingResult().getTarget(); + assertNotNull(createUserRequest.getAddress()); + assertNotNull(createUserRequest.getAddress().getStreets()); + assertTrue(createUserRequest.getAddress().getStreets().size() > 0); + } + + private Validator getValidator() { + LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); + localValidatorFactoryBean.afterPropertiesSet(); + return localValidatorFactoryBean; + } +} + diff --git a/rop/src/test/java/com/rop/impl/RopRequestMessageConverterTest.java b/rop/src/test/java/com/rop/impl/RopRequestMessageConverterTest.java index 409a67c..c98a333 100644 --- a/rop/src/test/java/com/rop/impl/RopRequestMessageConverterTest.java +++ b/rop/src/test/java/com/rop/impl/RopRequestMessageConverterTest.java @@ -1,66 +1,77 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-29 - */ -package com.rop.impl; - -import com.rop.MessageFormat; -import com.rop.RopContext; -import com.rop.request.RopRequestMessageConverter; -import org.springframework.core.convert.TypeDescriptor; -import org.testng.annotations.Test; - -import static org.mockito.Mockito.mock; -import static org.testng.Assert.*; - - -/** - * @author 陈雄华 - * @version 1.0 - */ -public class RopRequestMessageConverterTest { - - @Test - public void testConvertOfXmlFormat() throws Exception { - RopContext ropContext = mock(RopContext.class); - SimpleRopRequestContext context = new SimpleRopRequestContext(ropContext); - context.setMessageFormat(MessageFormat.xml); - - TypeDescriptor addrTypeDescriptor = TypeDescriptor.valueOf(Addresss.class); - TypeDescriptor strTypeDescriptor = TypeDescriptor.valueOf(String.class); - RopRequestMessageConverter converter = new RopRequestMessageConverter(); - String addressStr = "\n" + - "
\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "
"; - Object destObj = converter.convert(addressStr, strTypeDescriptor, addrTypeDescriptor); - assertTrue(destObj instanceof Addresss); - Addresss addresss = (Addresss) destObj; - assertEquals(addresss.getZoneCode(), "001"); - assertEquals(addresss.getDoorCode(), "002"); - assertEquals(addresss.getStreets().size(), 2); - } - - @Test - public void testConvertOfJsonFormat() throws Exception { - RopContext ropContext = mock(RopContext.class); - SimpleRopRequestContext context = new SimpleRopRequestContext(ropContext); - context.setMessageFormat(MessageFormat.json); - - TypeDescriptor addrTypeDescriptor = TypeDescriptor.valueOf(Addresss.class); - TypeDescriptor strTypeDescriptor = TypeDescriptor.valueOf(String.class); - RopRequestMessageConverter converter = new RopRequestMessageConverter(); - String addressStr = "{\"zoneCode\":\"001\",\"doorCode\":\"002\",\"streets\":[{\"no\":\"001\",\"name\":\"street1\"}]}"; - Object destObj = converter.convert(addressStr, strTypeDescriptor, addrTypeDescriptor); - assertTrue(destObj instanceof Addresss); - Addresss addresss = (Addresss) destObj; - assertEquals(addresss.getZoneCode(), "001"); - assertEquals(addresss.getDoorCode(), "002"); - assertNotNull(addresss.getStreets()); - assertEquals(addresss.getStreets().size(), 1); - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.MessageFormat; +import com.rop.RopContext; +import com.rop.request.RopRequestMessageConverter; +import org.springframework.core.convert.TypeDescriptor; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.mock; +import static org.testng.Assert.*; + + +/** + * @author 陈雄华 + * @version 1.0 + */ +public class RopRequestMessageConverterTest { + + @Test + public void testConvertOfXmlFormat() throws Exception { + RopContext ropContext = mock(RopContext.class); + SimpleRopRequestContext context = new SimpleRopRequestContext(ropContext); + context.setMessageFormat(MessageFormat.XML); + + TypeDescriptor addrTypeDescriptor = TypeDescriptor.valueOf(Addresss.class); + TypeDescriptor strTypeDescriptor = TypeDescriptor.valueOf(String.class); + RopRequestMessageConverter converter = new RopRequestMessageConverter(); + String addressStr = "\n" + + "
\n" + + " \n" + + " \n" + + " \n" + + " \n" + + "
"; + Object destObj = converter.convert(addressStr, strTypeDescriptor, addrTypeDescriptor); + assertTrue(destObj instanceof Addresss); + Addresss addresss = (Addresss) destObj; + assertEquals(addresss.getZoneCode(), "001"); + assertEquals(addresss.getDoorCode(), "002"); + assertEquals(addresss.getStreets().size(), 2); + } + + @Test + public void testConvertOfJsonFormat() throws Exception { + RopContext ropContext = mock(RopContext.class); + SimpleRopRequestContext context = new SimpleRopRequestContext(ropContext); + context.setMessageFormat(MessageFormat.JSON); + + TypeDescriptor addrTypeDescriptor = TypeDescriptor.valueOf(Addresss.class); + TypeDescriptor strTypeDescriptor = TypeDescriptor.valueOf(String.class); + RopRequestMessageConverter converter = new RopRequestMessageConverter(); + String addressStr = "{\"zoneCode\":\"001\",\"doorCode\":\"002\",\"streets\":[{\"no\":\"001\",\"name\":\"street1\"}]}"; + Object destObj = converter.convert(addressStr, strTypeDescriptor, addrTypeDescriptor); + assertTrue(destObj instanceof Addresss); + Addresss addresss = (Addresss) destObj; + assertEquals(addresss.getZoneCode(), "001"); + assertEquals(addresss.getDoorCode(), "002"); + assertNotNull(addresss.getStreets()); + assertEquals(addresss.getStreets().size(), 1); + } +} + diff --git a/rop/src/test/java/com/rop/impl/ServletRequestContextBuilderTest.java b/rop/src/test/java/com/rop/impl/ServletRequestContextBuilderTest.java index 1168ef6..f688740 100644 --- a/rop/src/test/java/com/rop/impl/ServletRequestContextBuilderTest.java +++ b/rop/src/test/java/com/rop/impl/ServletRequestContextBuilderTest.java @@ -1,159 +1,167 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-12 - */ -package com.rop.impl; - -import com.rop.MessageFormat; -import com.rop.RopContext; -import com.rop.ServiceMethodHandler; -import com.rop.config.SystemParameterNames; -import com.rop.session.SessionManager; -import org.springframework.format.support.FormattingConversionService; -import org.springframework.mock.web.MockHttpServletRequest; -import org.testng.annotations.Test; - -import java.util.Locale; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.testng.AssertJUnit.assertEquals; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ServletRequestContextBuilderTest { - - @Test - public void testIpParsed() { - FormattingConversionService conversionService = mock(FormattingConversionService.class); - SessionManager sessionManager = mock(SessionManager.class); - ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); - RopContext ropContext = mock(RopContext.class); - - //构造HttpServletRequest - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - servletRequest.setRemoteAddr("1.1.1.1"); - - //创建SimpleRequestContext - SimpleRopRequestContext requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); - assertEquals(requestContext.getIp(), "1.1.1.1"); - - servletRequest.setRemoteAddr("1.1.1.1"); - servletRequest.addHeader(ServletRequestContextBuilder.X_FORWARDED_FOR, "null,2.2.2.2,3.3.3.3"); - requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); - assertEquals(requestContext.getIp(), "2.2.2.2"); - - servletRequest.addHeader(ServletRequestContextBuilder.X_REAL_IP, "5.5.5.5"); - requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); - assertEquals(requestContext.getIp(), "5.5.5.5"); - - } - - /** - * 正常情况下的系统参数绑定 - * - * @throws Exception - */ - @Test - public void testBuildBySysParams1() throws Exception { - FormattingConversionService conversionService = mock(FormattingConversionService.class); - SessionManager sessionManager = mock(SessionManager.class); - ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); - - RopContext ropContext = mock(RopContext.class); - ServiceMethodHandler methodHandler = mock(ServiceMethodHandler.class); - when(ropContext.getServiceMethodHandler("method1", "3.0")).thenReturn(methodHandler); - - //构造HttpServletRequest - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - - servletRequest.setParameter(SystemParameterNames.getAppKey(), "appKey1"); - servletRequest.setParameter(SystemParameterNames.getSessionId(), "sessionId1"); - servletRequest.setParameter(SystemParameterNames.getMethod(), "method1"); - servletRequest.setParameter(SystemParameterNames.getVersion(), "3.0"); - servletRequest.setParameter(SystemParameterNames.getLocale(), "en_UK"); - servletRequest.setParameter(SystemParameterNames.getFormat(), "xml"); - servletRequest.setParameter(SystemParameterNames.getSign(), "sign1"); - servletRequest.setParameter("param1", "value1"); - servletRequest.setParameter("param2", "value2"); - servletRequest.setParameter("param3", "value3"); - - //创建SimpleRequestContext - SimpleRopRequestContext requestContext = - requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); - - assertEquals(requestContext.getAllParams().size(), 10); - assertEquals(requestContext.getParamValue("param1"), "value1"); - assertEquals(requestContext.getRawRequestObject(), servletRequest); - - assertEquals(requestContext.getAppKey(), "appKey1"); - assertEquals(requestContext.getSessionId(), "sessionId1"); - assertEquals(requestContext.getMethod(), "method1"); - assertEquals(requestContext.getVersion(), "3.0"); - assertEquals(requestContext.getLocale(), new Locale("zh", "CN")); - assertEquals(requestContext.getFormat(), "xml"); - assertEquals(requestContext.getMessageFormat(), MessageFormat.xml); - assertEquals(requestContext.getSign(), "sign1"); - - assertEquals(requestContext.getServiceMethodHandler(), methodHandler); - } - - /** - * 看错误的参数是否会被自动转为默认的 - * - * @throws Exception - */ - @Test - public void testBuildBySysParams2() throws Exception { - FormattingConversionService conversionService = mock(FormattingConversionService.class); - SessionManager sessionManager = mock(SessionManager.class); - ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); - RopContext ropContext = mock(RopContext.class); - - - //构造HttpServletRequest - MockHttpServletRequest servletRequest = new MockHttpServletRequest(); - servletRequest.setParameter(SystemParameterNames.getLocale(), "xxx"); - servletRequest.setParameter(SystemParameterNames.getFormat(), "xxx"); - - - //创建SimpleRequestContext - SimpleRopRequestContext requestContext = - requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); - assertEquals(requestContext.getLocale(), Locale.SIMPLIFIED_CHINESE); - assertEquals(requestContext.getFormat(), "xxx"); - assertEquals(requestContext.getMessageFormat(), MessageFormat.xml); - - } - - /** - * 非{@link javax.servlet.http.HttpServletRequest} - * - * @throws Exception - */ - @Test(expectedExceptions = {IllegalArgumentException.class}) - public void testBuildBySysParams3() throws Exception { - FormattingConversionService conversionService = mock(FormattingConversionService.class); - ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); - - RopContext ropContext = mock(RopContext.class); - ServiceMethodHandler methodHandler = mock(ServiceMethodHandler.class); - when(ropContext.getServiceMethodHandler("method1", "3.0")).thenReturn(methodHandler); - - //创建SimpleRequestContext - SimpleRopRequestContext requestContext = - requestContextBuilder.buildBySysParams(ropContext, new Object(),null); - } - - @Test - public void testBindBusinessParams() throws Exception { - - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import com.rop.MessageFormat; +import com.rop.RopContext; +import com.rop.ServiceMethodHandler; +import com.rop.config.SystemParameterNames; + +import org.springframework.format.support.FormattingConversionService; +import org.springframework.mock.web.MockHttpServletRequest; +import org.testng.annotations.Test; + +import java.util.Locale; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.AssertJUnit.assertEquals; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ServletRequestContextBuilderTest { + + @Test + public void testIpParsed() { + FormattingConversionService conversionService = mock(FormattingConversionService.class); + ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); + RopContext ropContext = mock(RopContext.class); + + //构造HttpServletRequest + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + servletRequest.setRemoteAddr("1.1.1.1"); + + //创建SimpleRequestContext + SimpleRopRequestContext requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); + assertEquals(requestContext.getIp(), "1.1.1.1"); + + servletRequest.setRemoteAddr("1.1.1.1"); + servletRequest.addHeader(ServletRequestContextBuilder.X_FORWARDED_FOR, "null,2.2.2.2,3.3.3.3"); + requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); + assertEquals(requestContext.getIp(), "2.2.2.2"); + + servletRequest.addHeader(ServletRequestContextBuilder.X_REAL_IP, "5.5.5.5"); + requestContext = requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); + assertEquals(requestContext.getIp(), "5.5.5.5"); + + } + + /** + * 正常情况下的系统参数绑定 + * + * @throws Exception + */ + @Test + public void testBuildBySysParams1() throws Exception { + FormattingConversionService conversionService = mock(FormattingConversionService.class); + ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); + + RopContext ropContext = mock(RopContext.class); + ServiceMethodHandler methodHandler = mock(ServiceMethodHandler.class); + when(ropContext.getServiceMethodHandler("method1", "3.0")).thenReturn(methodHandler); + + //构造HttpServletRequest + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + + servletRequest.setParameter(SystemParameterNames.getAppKey(), "appKey1"); + servletRequest.setParameter(SystemParameterNames.getSessionId(), "sessionId1"); + servletRequest.setParameter(SystemParameterNames.getMethod(), "method1"); + servletRequest.setParameter(SystemParameterNames.getVersion(), "3.0"); + servletRequest.setParameter(SystemParameterNames.getLocale(), "en_UK"); + servletRequest.setParameter(SystemParameterNames.getFormat(), "xml"); + servletRequest.setParameter(SystemParameterNames.getSign(), "sign1"); + servletRequest.setParameter("param1", "value1"); + servletRequest.setParameter("param2", "value2"); + servletRequest.setParameter("param3", "value3"); + + //创建SimpleRequestContext + SimpleRopRequestContext requestContext = + requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); + + assertEquals(requestContext.getAllParams().size(), 10); + assertEquals(requestContext.getParamValue("param1"), "value1"); + assertEquals(requestContext.getRawRequestObject(), servletRequest); + + assertEquals(requestContext.getAppKey(), "appKey1"); + assertEquals(requestContext.getSessionId(), "sessionId1"); + assertEquals(requestContext.getMethod(), "method1"); + assertEquals(requestContext.getVersion(), "3.0"); + assertEquals(requestContext.getLocale(), new Locale("zh", "CN")); + assertEquals(requestContext.getFormat(), "xml"); + assertEquals(requestContext.getMessageFormat(), MessageFormat.XML); + assertEquals(requestContext.getSign(), "sign1"); + + assertEquals(requestContext.getServiceMethodHandler(), methodHandler); + } + + /** + * 看错误的参数是否会被自动转为默认的 + * + * @throws Exception + */ + @Test + public void testBuildBySysParams2() throws Exception { + FormattingConversionService conversionService = mock(FormattingConversionService.class); + ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); + RopContext ropContext = mock(RopContext.class); + + + //构造HttpServletRequest + MockHttpServletRequest servletRequest = new MockHttpServletRequest(); + servletRequest.setParameter(SystemParameterNames.getLocale(), "xxx"); + servletRequest.setParameter(SystemParameterNames.getFormat(), "xxx"); + + + //创建SimpleRequestContext + SimpleRopRequestContext requestContext = + requestContextBuilder.buildBySysParams(ropContext, servletRequest,null); + assertEquals(requestContext.getLocale(), Locale.SIMPLIFIED_CHINESE); + assertEquals(requestContext.getFormat(), "xxx"); + assertEquals(requestContext.getMessageFormat(), MessageFormat.XML); + + } + + /** + * 非{@link javax.servlet.http.HttpServletRequest} + * + * @throws Exception + */ + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void testBuildBySysParams3() throws Exception { + FormattingConversionService conversionService = mock(FormattingConversionService.class); + ServletRequestContextBuilder requestContextBuilder = new ServletRequestContextBuilder(conversionService); + + RopContext ropContext = mock(RopContext.class); + ServiceMethodHandler methodHandler = mock(ServiceMethodHandler.class); + when(ropContext.getServiceMethodHandler("method1", "3.0")).thenReturn(methodHandler); + + //创建SimpleRequestContext + SimpleRopRequestContext requestContext = + requestContextBuilder.buildBySysParams(ropContext, new MockHttpServletRequest(), null); + } + + @Test + public void testBindBusinessParams() throws Exception { + + } +} + diff --git a/rop/src/test/java/com/rop/impl/Street.java b/rop/src/test/java/com/rop/impl/Street.java index 4b4fb0a..1e88569 100644 --- a/rop/src/test/java/com/rop/impl/Street.java +++ b/rop/src/test/java/com/rop/impl/Street.java @@ -1,46 +1,57 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-4-17 - */ -package com.rop.impl; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlRootElement; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "street") -public class Street { - - @XmlAttribute - private String no; - - @XmlAttribute - private String name; - - public String getNo() { - return no; - } - - public void setNo(String no) { - this.no = no; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.impl; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "street") +public class Street { + + @XmlAttribute + private String no; + + @XmlAttribute + private String name; + + public String getNo() { + return no; + } + + public void setNo(String no) { + this.no = no; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} + diff --git a/rop/src/test/java/com/rop/marshaller/Bar.java b/rop/src/test/java/com/rop/marshaller/Bar.java deleted file mode 100644 index ee05335..0000000 --- a/rop/src/test/java/com/rop/marshaller/Bar.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.marshaller; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-4-21 - */ -public class Bar { - - private String fld1 = "a"; - - private String fld2 = "b"; - - private Foo foo; - - public String getFld1() { - return fld1; - } - - public void setFld1(String fld1) { - this.fld1 = fld1; - } - - public String getFld2() { - return fld2; - } - - public void setFld2(String fld2) { - this.fld2 = fld2; - } - - public Foo getFoo() { - return foo; - } - - public void setFoo(Foo foo) { - this.foo = foo; - } -} diff --git a/rop/src/test/java/com/rop/marshaller/Foo.java b/rop/src/test/java/com/rop/marshaller/Foo.java deleted file mode 100644 index 2f221ef..0000000 --- a/rop/src/test/java/com/rop/marshaller/Foo.java +++ /dev/null @@ -1,66 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.marshaller; - -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -/** -* @author : chenxh(quickselect@163.com) -* @date: 14-4-21 -*/ -@XmlRootElement -public class Foo implements IFoo{ - private Boolean b1; - - private boolean b2; - - private Integer i1; - - private int i2; - - private String ok; - - public Boolean getB1() { - return b1; - } - - public void setB1(Boolean b1) { - this.b1 = b1; - } - - public boolean isB2() { - return b2; - } - - public void setB2(boolean b2) { - this.b2 = b2; - } - - public Integer getI1() { - return i1; - } - - - public void setI1(Integer i1) { - this.i1 = i1; - } - - public int getI2() { - return i2; - } - - public void setI2(int i2) { - this.i2 = i2; - } - - public String getOk() { - return ok; - } - - public void setOk(String ok) { - this.ok = ok; - } -} diff --git a/rop/src/test/java/com/rop/marshaller/IFoo.java b/rop/src/test/java/com/rop/marshaller/IFoo.java deleted file mode 100644 index 104c9f7..0000000 --- a/rop/src/test/java/com/rop/marshaller/IFoo.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.marshaller; - -import javax.xml.bind.annotation.XmlTransient; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-4-21 - */ -public interface IFoo { - - @XmlTransient - Integer getI1(); -} diff --git a/rop/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java b/rop/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java deleted file mode 100644 index 731ad2b..0000000 --- a/rop/src/test/java/com/rop/marshaller/JacksonJsonRopMarshallerTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.marshaller; - -import com.beust.jcommander.internal.Lists; -import com.beust.jcommander.internal.Maps; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.Map; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 14-3-27 - */ -public class JacksonJsonRopMarshallerTest { - - private JacksonJsonRopMarshaller marshaller = new JacksonJsonRopMarshaller(); - - @Test - public void test1(){ - Foo foo = new Foo(); - foo.setB1(true); - foo.setB2(true); - foo.setI1(1); - foo.setI2(1); - Bar bar = new Bar(); - bar.setFoo(foo); - marshaller.marshaller(bar,System.out); - } - - @Test - public void test2(){ - List lists = Lists.newArrayList(); - Foo f1 = new Foo(); - f1.setI2(2); - lists.add(f1); - Foo f2 = new Foo(); - f2.setI2(1); - lists.add(f2); - marshaller.marshaller(lists,System.out); - System.out.println("ddd"); - - Map maps= Maps.newLinkedHashMap(); - maps.put("1",f2); - maps.put("2",f1); - marshaller.marshaller(maps,System.out); - System.out.println("aaa"); - } - - -} diff --git a/rop/src/test/java/com/rop/marshaller/MessageMarshallerUtilsTest.java b/rop/src/test/java/com/rop/marshaller/MessageMarshallerUtilsTest.java deleted file mode 100644 index 7a1a27e..0000000 --- a/rop/src/test/java/com/rop/marshaller/MessageMarshallerUtilsTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-5-29 - */ -package com.rop.marshaller; - -import com.beust.jcommander.internal.Maps; -import com.rop.MessageFormat; -import com.rop.RopRequest; -import com.rop.RopRequestContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.annotations.Test; - -import java.util.*; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class MessageMarshallerUtilsTest { - - protected Logger logger = LoggerFactory.getLogger(getClass()); - - @Test - public void testMarshallerRopRequest() throws Exception { - RopRequest ropRequest = mock(RopRequest.class); - RopRequestContext msc = mock(RopRequestContext.class); - when(ropRequest.getRopRequestContext()).thenReturn(msc); - HashMap map = new HashMap(); - map.put("key1", "key1Value"); - map.put("key2", "key2Value"); - map.put("key3", "key3Value"); - when(msc.getAllParams()).thenReturn(map); - String message = MessageMarshallerUtils.getMessage(ropRequest, MessageFormat.json); - assertNotNull(message); - logger.info("json:{}",message); - assertTrue(message.indexOf("}") > -1); - assertTrue(message.indexOf("{") > -1); - assertTrue(message.indexOf("key1") > -1); - assertTrue(message.indexOf("key1Value") > -1); - - message = MessageMarshallerUtils.getMessage(ropRequest, MessageFormat.xml); - assertNotNull(message); - assertTrue(message.indexOf("<") > -1); - assertTrue(message.indexOf(">") > -1); - assertTrue(message.indexOf("key1") > -1); - assertTrue(message.indexOf("key1Value") > -1); - logger.info("xml:{}", message); - } - - @Test - public void testMarshallerRopResponse() throws Exception { - SampleResponse response = new SampleResponse(); - response.setUserId("tom"); - response.setCreateTime("20120101"); - - - List> table = new ArrayList>(); - HashMap row1 = new HashMap(); - row1.put("col1", "id1"); - row1.put("col2", "user1"); - row1.put("col3", 20); - row1.put("col4", 1000.34); - table.add(row1); - HashMap row2 = new HashMap(); - row2.put("col1", "id2"); - row2.put("col2", null); - row2.put("col3", 22); - row2.put("col4", 2000.34); - table.add(row2); - response.setTable(table); - - HashMap attaches = new HashMap(); - attaches.put("a","aa"); - attaches.put("b","bb"); - attaches.put("c","cc"); - response.setAttaches(attaches); - - String message = MessageMarshallerUtils.getMessage(response, MessageFormat.json); - assertTrue(message.indexOf("}") > -1); - assertTrue(message.indexOf("{") > -1); - assertTrue(message.indexOf("tom") > -1); - assertTrue(message.indexOf("20120101") > -1); - - logger.info("json:{}",message); - } -} - diff --git a/rop/src/test/java/com/rop/other/ClassTest.java b/rop/src/test/java/com/rop/other/ClassTest.java index c550067..1959cf5 100644 --- a/rop/src/test/java/com/rop/other/ClassTest.java +++ b/rop/src/test/java/com/rop/other/ClassTest.java @@ -1,45 +1,56 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.other; - -import com.rop.AbstractRopRequest; -import com.rop.RopRequest; -import org.testng.annotations.Test; - -import static org.testng.Assert.assertTrue; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class ClassTest { - - @Test - public void testAssignableFrom() { - assertTrue(!MyRopRequest.class.isAssignableFrom(RopRequest.class)); - assertTrue(!MyRopRequest.class.isAssignableFrom(AbstractRopRequest.class)); - assertTrue(AbstractRopRequest.class.isAssignableFrom(MyRopRequest.class)); - } - - @Test - public void modeInt() { - int len = 16 - 1; - for (int i = 0; i < 100; i++) { - int i1 = i & len; - System.out.println("i:" + i1); - assertTrue(i1 <= len); - } - } - - private class MyRopRequest extends AbstractRopRequest { - - } - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.other; + +import com.rop.AbstractRopRequest; +import com.rop.RopRequest; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertTrue; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class ClassTest { + + @Test + public void testAssignableFrom() { + assertTrue(!MyRopRequest.class.isAssignableFrom(RopRequest.class)); + assertTrue(!MyRopRequest.class.isAssignableFrom(AbstractRopRequest.class)); + assertTrue(AbstractRopRequest.class.isAssignableFrom(MyRopRequest.class)); + } + + @Test + public void modeInt() { + int len = 16 - 1; + for (int i = 0; i < 100; i++) { + int i1 = i & len; + System.out.println("i:" + i1); + assertTrue(i1 <= len); + } + } + + private class MyRopRequest extends AbstractRopRequest { + + } + +} + diff --git a/rop/src/test/java/com/rop/other/FunctionTest.java b/rop/src/test/java/com/rop/other/FunctionTest.java index 2867473..1455c37 100644 --- a/rop/src/test/java/com/rop/other/FunctionTest.java +++ b/rop/src/test/java/com/rop/other/FunctionTest.java @@ -1,43 +1,54 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-8-2 - */ -package com.rop.other; - -import org.testng.annotations.Test; - -import java.util.Arrays; -import java.util.List; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class FunctionTest { - - @Test - public void testStringSplit(){ - String str = "A,B"; - String[] items = str.split(","); - System.out.println("size:"+items.length); - for (String item : items) { - System.out.println("item:"+item); - } - } - - @Test - public void testArrayToList(){ - String str = "A,B"; - String[] items = str.split(","); - List list = Arrays.asList(items); - System.out.println("size:"+list.size()); - for (String s : list) { - System.out.println("item:"+s); - } - } -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.other; + +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class FunctionTest { + + @Test + public void testStringSplit(){ + String str = "A,B"; + String[] items = str.split(","); + System.out.println("size:"+items.length); + for (String item : items) { + System.out.println("item:"+item); + } + } + + @Test + public void testArrayToList(){ + String str = "A,B"; + String[] items = str.split(","); + List list = Arrays.asList(items); + System.out.println("size:"+list.size()); + for (String s : list) { + System.out.println("item:"+s); + } + } +} + diff --git a/rop/src/test/java/com/rop/other/MessageFormatTest.java b/rop/src/test/java/com/rop/other/MessageFormatTest.java index b2601e6..e2ea63e 100644 --- a/rop/src/test/java/com/rop/other/MessageFormatTest.java +++ b/rop/src/test/java/com/rop/other/MessageFormatTest.java @@ -1,24 +1,35 @@ -/** - * 版权声明: 版权所有 违者必究 2012 - * 日 期:12-6-6 - */ -package com.rop.other; - -import org.testng.annotations.Test; - -import java.text.MessageFormat; - -/** - * @author : chenxh(quickselect@163.com) - * @date: 2014/7/4 - */ -public class MessageFormatTest { - - @Test - public void testFormat(){ - String str = MessageFormat.format("aaa{0}bbb{1}", "X"); - System.out.println(str); - str = MessageFormat.format("aaa bbb", "X","Y"); - System.out.println(str); -} -} +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.other; + +import org.testng.annotations.Test; + +import java.text.MessageFormat; + +/** + * @author : chenxh(quickselect@163.com) + * @date: 2014/7/4 + */ +public class MessageFormatTest { + + @Test + public void testFormat(){ + String str = MessageFormat.format("aaa{0}bbb{1}", "X"); + System.out.println(str); + str = MessageFormat.format("aaa bbb", "X","Y"); + System.out.println(str); +} +} diff --git a/rop/src/test/java/com/rop/other/MyService.java b/rop/src/test/java/com/rop/other/MyService.java index 55e842e..ce2c571 100644 --- a/rop/src/test/java/com/rop/other/MyService.java +++ b/rop/src/test/java/com/rop/other/MyService.java @@ -1,18 +1,29 @@ -/** - * 版权声明:中图一购网络科技有限公司 版权所有 违者必究 2012 - * 日 期:12-6-30 - */ -package com.rop.other; - -/** - *
- * 功能说明:
- * 
- * - * @author 陈雄华 - * @version 1.0 - */ -public class MyService { - -} - +/* + * Copyright 2012-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.rop.other; + +/** + *
+ * 功能说明:
+ * 
+ * + * @author 陈雄华 + * @version 1.0 + */ +public class MyService { + +} +