Skip to content

Commit

Permalink
update caf framework
Browse files Browse the repository at this point in the history
  • Loading branch information
Philip Zhang committed Aug 7, 2020
1 parent b88b115 commit 213bb10
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,11 @@ public String[] getParameterValues(String key) {
@Override
public Map<String, String[]> getParameterMap() {
if (parameterMap == null) {
Map<String, String[]> result = new LinkedHashMap<String, String[]>();
decode(getQueryString(), result);
decode(getPostBodyAsString(), result);
parameterMap = Collections.unmodifiableMap(result);
// Map<String, String[]> result = new LinkedHashMap<String, String[]>();
// decode(getQueryString(), result);
// decode(getPostBodyAsString(), result);
// parameterMap = Collections.unmodifiableMap(result);
parameterMap = getRequest().getParameterMap();
}
return parameterMap;
}
Expand All @@ -108,6 +109,8 @@ private Iterable<NameValuePair> decodeParams(String body) {
if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
List<NameValuePair> postParams = URLEncodedUtils.parse(IOUtils.toString(getReader()), UTF8_CHARSET);
params = Iterables.concat(params, postParams);
}else if (ct.getMimeType().equals(ContentType.MULTIPART_FORM_DATA.getMimeType())) {

}
}
} catch (IOException e) {
Expand Down Expand Up @@ -163,4 +166,4 @@ public int available() throws IOException {
}


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,12 @@ private void renderAsString(InvocationResult result, HttpServletRequest request,
}
byte [] value = result.getActualResult().toString().getBytes();
int length = value.length;
fillOrigin(result, request, response);
response.addHeader("X-Class", renderClass);
response.addHeader("X-Env-Type", result.getEnvType());
response.addHeader("X-Env-Name", result.getEnvName());
response.addHeader("Content-Length", Long.valueOf(length).toString());
response.addHeader("Access-Control-Expose-Headers", "X-Class, X-Redirect, X-Env-Type, X-Env-Name");
response.addHeader("Access-Control-Expose-Headers", "X-Class, X-Redirect, X-Env-Type, X-Env-Name, X-Action");

response.getOutputStream().write(value);;

Expand Down Expand Up @@ -228,7 +229,7 @@ protected void fillOrigin(InvocationResult result, HttpServletRequest request, H
response.addHeader("Access-Control-Allow-Origin", origin);
response.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// Access-Control-Expose-Headers
response.addHeader("Access-Control-Expose-Headers", "Set-Cookie, X-Redirect, X-Env-Type, X-Env-Name");
response.addHeader("Access-Control-Expose-Headers", "Set-Cookie, X-Redirect, X-Env-Type, X-Env-Name, X-Action");
response.addHeader("Access-Control-Allow-Credentials", "true");

}
Expand All @@ -255,7 +256,7 @@ protected void renderJson(InvocationResult result, HttpServletRequest request, H
response.addHeader("X-Class", renderClass);
response.addHeader("X-Env-Type", result.getEnvType());
response.addHeader("X-Env-Name", result.getEnvName());
response.addHeader("Access-Control-Expose-Headers", "X-Class, X-Redirect, X-Env-Type, X-Env-Name");
response.addHeader("Access-Control-Expose-Headers", "X-Class, X-Redirect, X-Env-Type, X-Env-Name, X-Action");
// Access-Control-Expose-Headers

log("Render JSON result with class: " + renderClass + "(" + renderLogResult(result.getActualResult()) + ")");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ public interface AccessControledService {
public Object checkAccess(BaseUserContext userContext,String methodName, Object[] parameters) throws Exception;
public void enforceAccess(BaseUserContext userContext, Object targetObject) throws Exception;

public void onAccess(BaseUserContext baseUserContext, String methodName, Object[] parameters);
default public void onAccess(BaseUserContext baseUserContext, String methodName, Object[] parameters) {}
default public void afterInvoke(BaseUserContext baseUserContext, String methodName, Object[] parameters, boolean success, Object result, Throwable throwable) {}

}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
public class UCInvocationServlet extends SimpleInvocationServlet{

/**
*
*
*/
private static final long serialVersionUID = 1L;

Expand All @@ -40,20 +40,20 @@ public void setApplicationContext(ApplicationContext pApplicationContext) {

@Override
public void init() throws ServletException {

super.init();
replaceBeans();
}

@Override
public void init(ServletConfig config) throws ServletException {

super.init(config);
replaceBeans();
}

protected boolean isAccessControledService(InvocationContext context){

int parameterLength = context.getParameters().length;
if(parameterLength == 0){
//no context and no parameter
Expand All @@ -62,7 +62,7 @@ protected boolean isAccessControledService(InvocationContext context){
Object firstParamter = context.getParameters()[0];
if(!(firstParamter instanceof BaseUserContext)){
//first parameter is not based on base user context, will not regard as access controlled service.

return false;
}
if(!(context instanceof UCInvocationContext)){
Expand All @@ -72,38 +72,38 @@ protected boolean isAccessControledService(InvocationContext context){
if(!(targetObject instanceof AccessControledService)){
return false;
}


//UCInvocationContext uInvocationContext = (UCInvocationContext)context;


return true;

}

protected InvocationResult invoke(InvocationContext context) throws ServletException
{

//check the user context before invoke
//before any call, check the URL


if(!isAccessControledService(context)){

return super.invoke(context);
}

Object targetObject = context.getTargetObject();
Object []parameters = context.getParameters();

AccessControledService targetService = (AccessControledService)targetObject;
UCInvocationContext ucInvocationContext = (UCInvocationContext)context;

try {
System.out.println("InvocationResult result = super.invoke(context); called");
String methodName = ucInvocationContext.getMethodToCall().getName();
BaseUserContext baseUserContext = ucInvocationContext.getUserContext();

targetService.onAccess(baseUserContext, methodName ,parameters);

Object checkResult = targetService.checkAccess(baseUserContext, methodName ,parameters);
Expand All @@ -115,36 +115,42 @@ protected InvocationResult invoke(InvocationContext context) throws ServletExcep
result.setInvocationContext(context);
return result;
}

//null means the request passed the access check
InvocationResult result = super.invoke(context);
if (result.getActualResult() instanceof Throwable){
targetService.afterInvoke(baseUserContext, methodName, parameters, false, null, (Throwable) result.getActualResult());
}else{
targetService.afterInvoke(baseUserContext, methodName, parameters, true, result.getActualResult(), null);
}
logExceptionResult(baseUserContext,result);

targetService.enforceAccess(baseUserContext, result.getActualResult());



return result;

} catch (Exception e) {

InvocationResult result=new SimpleInvocationResult();
result.setActualResult(e);
result.setActualResult(e);
result.setInvocationContext(context);
//InvocationResult result = super.invoke(context);
System.out.println("the call throws the exception not handled by the app layer, framework catches");
e.printStackTrace();

return result;
}

}


protected Method searchMethod(Class <?> clazz,String name){
for(Method m:clazz.getMethods()){
System.out.println("mmm: "+m.getName());
if(name.equals(m.getName())){

return m;
}
}
Expand All @@ -160,12 +166,12 @@ protected InvocationResult logExceptionResult(BaseUserContext baseUserContext, I
Class<?> clzz []=new Class[]{String.class, String.class, String.class};
//baseUserContext.getClass().getDeclaredMethod(name, parameterTypes)
//public void sendEmail(String to, String subject, String content)

//Method sendMailMethod = searchMethod(baseUserContext.getClass(),"sendMail");//.getMethod("sendMail", String.class, String.class, String.class);

Method sendMailMethod = baseUserContext.getClass().getMethod("sendEmail", String.class, String.class, String.class);


sendMailMethod.invoke(baseUserContext, getExceptionMonitorEmail(),
result.getActualResult().getClass().getSimpleName()+" from " + baseUserContext.getEnvironmentName(),
wrapExceptionToString((Throwable)result.getActualResult()));
Expand All @@ -174,15 +180,15 @@ protected InvocationResult logExceptionResult(BaseUserContext baseUserContext, I
e.printStackTrace();
//System.out.println("Method not found"+e);
}

return result;

//Class<?> parameterTypes;
//Method sendMailMethod = baseUserContext.getClass().getMethod("sendMail", parameterTypes);


}

protected Object getExceptionMonitorEmail() {
String envValue = System.getenv("EXCEPTION_MONITOR");
if (TextUtil.isBlank(envValue)) {
Expand All @@ -200,22 +206,22 @@ protected String wrapExceptionToString(Throwable result) {
}

/*
*
*
* public void sendEmail(String to, String subject, String content){
this.ensureSMTPService();
smtpService.send(to, subject, content);
}
*
*
* */
public void replaceBeans()
{
InternalBeanFactory.replaceFormBuilder(new UCFormBuilder());
InternalBeanFactory.replaceServletInvocationContextFactory(new UCInvocationContextFactory(mApplicationContext));

}




}
5 changes: 3 additions & 2 deletions bizcore/WEB-INF/caf_core_src/com/terapico/utils/JWTUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ public static DecodedJWT decodeToken(String token) {
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
return jwt;
} catch (JWTVerificationException exception){
exception.printStackTrace();
} catch (JWTVerificationException e){
// exception.printStackTrace();
System.out.println("[ Exception]: " + e.getMessage());
return null;
}
}
Expand Down
5 changes: 5 additions & 0 deletions bizcore/WEB-INF/caf_core_src/com/terapico/utils/TaskUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;

Expand Down Expand Up @@ -157,6 +159,9 @@ public synchronized static boolean checkTaskRunning(String taskName, boolean set
public static void runAsync(Runnable runnable) {
executor.execute(runnable);
}
public static <V> Future<V> runAsync(Callable<V> callable) {
return executor.submit(callable);
}

public synchronized static String addScheduleTask(String taskName, long intervalInMs, Runnable runnable) {
if (runningScheduleTask.containsKey(taskName)){
Expand Down
39 changes: 39 additions & 0 deletions bizcore/WEB-INF/caf_core_src/com/terapico/utils/TextUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -514,4 +514,43 @@ private static char convert(byte[] bytes) {
return result;
}

public static double calcMatchRate(String str, String target) {

int[][] d; // 矩阵
int n = str.length();
int m = target.length();
int i; // 遍历str的
int j; // 遍历target的
char ch1; // str的
char ch2; // target的
int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
if (n == 0 || m == 0) {
return 0;
}
d = new int[n + 1][m + 1];
for (i = 0; i <= n; i++) { // 初始化第一列
d[i][0] = i;
}

for (j = 0; j <= m; j++) { // 初始化第一行
d[0][j] = j;
}

for (i = 1; i <= n; i++) { // 遍历str
ch1 = str.charAt(i - 1);
// 去匹配target
for (j = 1; j <= m; j++) {
ch2 = target.charAt(j - 1);
if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
temp = 0;
} else {
temp = 1;
}
// 左边+1,上边+1, 左上角+temp取最小
d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + temp);
}
}

return (1 - (double) d[n][m] / Math.max(str.length(), target.length())) * 100.0;
}
}

0 comments on commit 213bb10

Please sign in to comment.