Skip to content

Commit dc0f875

Browse files
committed
Merge pull request !97 from 胡贵/develop
2 parents 0fa5369 + acfd863 commit dc0f875

File tree

11 files changed

+118
-71
lines changed

11 files changed

+118
-71
lines changed

lts-admin/src/main/java/com/github/ltsopensource/admin/support/SystemInitListener.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import com.github.ltsopensource.core.commons.file.FileUtils;
44
import com.github.ltsopensource.core.commons.utils.PlatformUtils;
55
import com.github.ltsopensource.core.commons.utils.StringUtils;
6+
import com.github.ltsopensource.core.compiler.AbstractCompiler;
7+
import com.github.ltsopensource.core.constant.Constants;
68
import com.github.ltsopensource.core.json.JSONFactory;
79
import com.github.ltsopensource.core.logger.LoggerFactory;
810
import com.github.ltsopensource.core.spi.SpiExtensionKey;
@@ -26,6 +28,11 @@ public void contextInitialized(ServletContextEvent servletContextEvent) {
2628
}
2729
AppConfigurer.load(confPath);
2830

31+
String compiler = AppConfigurer.getProperty("configs." + Constants.COMPILER);
32+
if (StringUtils.isNotEmpty(compiler)) {
33+
AbstractCompiler.setCompiler(compiler);
34+
}
35+
2936
String jsonAdapter = AppConfigurer.getProperty("configs." + SpiExtensionKey.LTS_JSON);
3037
if (StringUtils.isNotEmpty(jsonAdapter)) {
3138
JSONFactory.setJSONAdapter(jsonAdapter);

lts-core/src/main/java/com/github/ltsopensource/core/cluster/AbstractJobNode.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88
import com.github.ltsopensource.core.commons.utils.GenericsUtils;
99
import com.github.ltsopensource.core.commons.utils.NetUtils;
1010
import com.github.ltsopensource.core.commons.utils.StringUtils;
11+
import com.github.ltsopensource.core.compiler.AbstractCompiler;
12+
import com.github.ltsopensource.core.constant.Constants;
1113
import com.github.ltsopensource.core.constant.EcTopic;
1214
import com.github.ltsopensource.core.factory.JobNodeConfigFactory;
1315
import com.github.ltsopensource.core.factory.NodeFactory;
@@ -140,6 +142,12 @@ public void destroy() {
140142
}
141143

142144
protected void initConfig() {
145+
146+
String compiler = config.getParameter(Constants.COMPILER);
147+
if (StringUtils.isNotEmpty(compiler)) {
148+
AbstractCompiler.setCompiler(compiler);
149+
}
150+
143151
appContext.setEventCenter(ServiceLoader.load(EventCenter.class, config));
144152

145153
appContext.setCommandBodyWrapper(new CommandBodyWrapper(config));

lts-core/src/main/java/com/github/ltsopensource/core/compiler/AbstractCompiler.java

Lines changed: 26 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,33 @@
88

99
/**
1010
* @author william.liangf
11+
* @author Robert HG ([email protected]) on 9/12/15.
1112
*/
1213
public abstract class AbstractCompiler implements Compiler {
1314

15+
private static Compiler COMPILER = new JavassistCompiler();
16+
17+
public static void setCompiler(Compiler compiler) {
18+
if (compiler == null) {
19+
throw new IllegalArgumentException("compiler should not be null");
20+
}
21+
AbstractCompiler.COMPILER = compiler;
22+
}
23+
24+
public static Compiler getCompiler() {
25+
return AbstractCompiler.COMPILER;
26+
}
27+
28+
public static void setCompiler(String compiler) {
29+
if ("javassist".equals(compiler)) {
30+
setCompiler(new JavassistCompiler());
31+
} else if ("jdk".equals(compiler)) {
32+
setCompiler(new JdkCompiler());
33+
} else {
34+
throw new IllegalArgumentException("compiler[" + compiler +"] error ");
35+
}
36+
}
37+
1438
private static final Pattern PACKAGE_PATTERN = Pattern.compile("package\\s+([$_a-zA-Z][$_a-zA-Z0-9\\.]*);");
1539

1640
private static final Pattern CLASS_PATTERN = Pattern.compile("class\\s+([$_a-zA-Z][$_a-zA-Z0-9]*)\\s+");
@@ -36,55 +60,19 @@ public Class<?> compile(String code) {
3660
return Class.forName(className, true, ClassHelper.getCallerClassLoader(getClass()));
3761
} catch (ClassNotFoundException e) {
3862
if (!code.endsWith("}")) {
39-
throw new IllegalStateException("The java code not endsWith \"}\", code: \n" + code + "\n");
63+
throw new IllegalStateException("The java code not endsWith \"}\", code: " + code + "");
4064
}
4165
try {
4266
return doCompile(className, code);
4367
} catch (RuntimeException t) {
4468
throw t;
4569
} catch (Throwable t) {
46-
throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: " + className + ", code: \n" + code + "\n, stack: " + StringUtils.toString(t));
70+
throw new IllegalStateException("Failed to compile class, cause: " + t.getMessage() + ", class: " + className + ", code: " + code + ", stack: " + StringUtils.toString(t));
4771
}
4872
}
4973
}
5074

5175
protected abstract Class<?> doCompile(String name, String source) throws Throwable;
5276

53-
public static void main(String[] args) {
54-
String code = "package com.github.ltsopensource.core.support.bean;\n" +
55-
"import com.github.ltsopensource.core.support.bean.BeanCopier;\n" +
56-
"import com.github.ltsopensource.queue.domain.JobPo;\n" +
57-
"public class JobPo2JobPoBeanCopier1 implements BeanCopier<JobPo,JobPo> {\n" +
58-
"public void copyProps(JobPo source, JobPo target){\n" +
59-
"target.setJobId(source.getJobId());\n" +
60-
"target.setJobType(source.getJobType());\n" +
61-
"target.setPriority(source.getPriority());\n" +
62-
"target.setTaskId(source.getTaskId());\n" +
63-
"target.setRealTaskId(source.getRealTaskId());\n" +
64-
"target.setGmtCreated(source.getGmtCreated());\n" +
65-
"target.setGmtModified(source.getGmtModified());\n" +
66-
"target.setSubmitNodeGroup(source.getSubmitNodeGroup());\n" +
67-
"target.setTaskTrackerNodeGroup(source.getTaskTrackerNodeGroup());\n" +
68-
"com.github.ltsopensource.core.support.bean.PropConverter<JobPo, java.util.Map<java.lang.String, java.lang.String>> extParamsConverter = (com.github.ltsopensource.core.support.bean.PropConverter<JobPo, java.util.Map<java.lang.String, java.lang.String>> )com.github.ltsopensource.core.support.bean.BeanCopierFactory.getConverter(1,\"extParams\");\n" +
69-
"target.setExtParams((java.util.Map<java.lang.String, java.lang.String>)extParamsConverter.convert(source));\n" +
70-
"com.github.ltsopensource.core.support.bean.PropConverter<JobPo, java.util.Map<java.lang.String, java.lang.String>> internalExtParamsConverter = (com.github.ltsopensource.core.support.bean.PropConverter<JobPo, java.util.Map<java.lang.String, java.lang.String>> )com.github.ltsopensource.core.support.bean.BeanCopierFactory.getConverter(1,\"internalExtParams\");\n" +
71-
"target.setInternalExtParams((java.util.Map<java.lang.String, java.lang.String>)internalExtParamsConverter.convert(source));\n" +
72-
"target.setTaskTrackerIdentity(source.getTaskTrackerIdentity());\n" +
73-
"target.setNeedFeedback(source.isNeedFeedback());\n" +
74-
"target.setCronExpression(source.getCronExpression());\n" +
75-
"target.setTriggerTime(source.getTriggerTime());\n" +
76-
"target.setRetryTimes(source.getRetryTimes());\n" +
77-
"target.setMaxRetryTimes(source.getMaxRetryTimes());\n" +
78-
"target.setRepeatCount(source.getRepeatCount());\n" +
79-
"target.setRepeatedCount(source.getRepeatedCount());\n" +
80-
"target.setRepeatInterval(source.getRepeatInterval());\n" +
81-
"target.setRelyOnPrevCycle(source.getRelyOnPrevCycle());\n" +
82-
"target.setLastGenerateTriggerTime(source.getLastGenerateTriggerTime());\n" +
83-
"}}";
84-
85-
Compiler compiler = new JavassistCompiler();
86-
compiler.compile(code);
87-
88-
}
8977
}
9078

lts-core/src/main/java/com/github/ltsopensource/core/compiler/JavassistCompiler.java

100644100755
Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1+
/*
2+
* Copyright 1999-2011 Alibaba Group.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
116
package com.github.ltsopensource.core.compiler;
217

318
import com.github.ltsopensource.core.commons.utils.ClassHelper;
@@ -93,7 +108,7 @@ public Class<?> doCompile(String name, String source) throws Throwable {
93108
} else if (FIELD_PATTERN.matcher(method).matches()) {
94109
cls.addField(CtField.make("private " + method, cls));
95110
} else {
96-
cls.addMethod(CtNewMethod.make("public " + method, cls));
111+
cls.addMethod(CtNewMethod.make(method, cls));
97112
}
98113
}
99114
}

lts-core/src/main/java/com/github/ltsopensource/core/compiler/JdkCompiler.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
package com.github.ltsopensource.core.compiler;
22

33
import com.github.ltsopensource.core.commons.utils.ClassHelper;
4+
import com.github.ltsopensource.core.logger.LoggerFactory;
45

56
import javax.tools.*;
67
import java.io.*;
7-
import java.lang.reflect.Method;
88
import java.net.URI;
99
import java.net.URISyntaxException;
1010
import java.net.URL;
@@ -18,7 +18,7 @@ public class JdkCompiler extends AbstractCompiler {
1818
public static final String CLASS_EXTENSION = ".class";
1919
public static final String JAVA_EXTENSION = ".java";
2020

21-
private JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
21+
private final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
2222

2323
private final DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
2424

@@ -30,13 +30,9 @@ public class JdkCompiler extends AbstractCompiler {
3030

3131
public JdkCompiler() {
3232
if (compiler == null) {
33-
try {
34-
Class<?> javacTool = Class.forName("com.sun.tools.javac.api.JavacTool");
35-
Method create = javacTool.getMethod("create");
36-
compiler = (JavaCompiler) create.invoke(null);
37-
} catch (Exception e) {
38-
throw new AssertionError(e);
39-
}
33+
throw new IllegalStateException(
34+
"Cannot find the system Java compiler. "
35+
+ "Check that your class path includes tools.jar");
4036
}
4137
options = new ArrayList<String>();
4238
// options.add("-target");

lts-core/src/main/java/com/github/ltsopensource/core/constant/Constants.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public interface Constants {
6969
String PROCESSOR_THREAD = "job.processor.thread";
7070
int DEFAULT_PROCESSOR_THREAD = 32 + AVAILABLE_PROCESSOR * 5;
7171

72-
int LATCH_TIMEOUT_MILLIS = 60 * 1000; // 60s
72+
int LATCH_TIMEOUT_MILLIS = 60 * 1000; // 60s
7373

7474
// 任务最多重试次数
7575
String JOB_MAX_RETRY_TIMES = "job.max.retry.times";
@@ -114,4 +114,6 @@ public interface Constants {
114114
String ONCE = "__LTS_ONCE";
115115

116116
String IS_RETRY_JOB = "__LTS_Is_Retry_Job";
117+
118+
String COMPILER = "java.compiler";
117119
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package com.github.ltsopensource.core.support.bean;
2+
3+
/**
4+
* @author Robert HG ([email protected]) on 4/17/16.
5+
*/
6+
public abstract class BeanCopierAdapter implements BeanCopier<Object, Object> {
7+
8+
public abstract void copyProps(Object sourceObj, Object targetObj);
9+
}

lts-core/src/main/java/com/github/ltsopensource/core/support/bean/BeanCopierFactory.java

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,32 @@
44
import com.github.ltsopensource.core.commons.utils.BeanUtils;
55
import com.github.ltsopensource.core.commons.utils.ClassHelper;
66
import com.github.ltsopensource.core.commons.utils.ReflectionUtils;
7+
import com.github.ltsopensource.core.compiler.AbstractCompiler;
78
import com.github.ltsopensource.core.compiler.Compiler;
8-
import com.github.ltsopensource.core.compiler.JdkCompiler;
99
import com.github.ltsopensource.core.exception.LtsRuntimeException;
1010
import com.github.ltsopensource.core.logger.Logger;
1111
import com.github.ltsopensource.core.logger.LoggerFactory;
1212

1313
import java.lang.reflect.Field;
1414
import java.lang.reflect.Method;
1515
import java.lang.reflect.Modifier;
16-
import java.lang.reflect.Type;
1716
import java.util.Map;
1817
import java.util.concurrent.ConcurrentHashMap;
1918
import java.util.concurrent.ConcurrentMap;
2019
import java.util.concurrent.atomic.AtomicInteger;
2120

2221
/**
2322
* @author Robert HG ([email protected]) on 4/2/16.
23+
* 为了兼容javaassist 去掉泛型
2424
*/
2525
public final class BeanCopierFactory {
2626

2727
private static final Logger LOGGER = LoggerFactory.getLogger(BeanCopierFactory.class);
2828

29-
private static Compiler COMPILER = new JdkCompiler();
29+
private static Compiler COMPILER = AbstractCompiler.getCompiler();
3030
private static final AtomicInteger SEQ = new AtomicInteger(0);
3131
private static final ConcurrentMap<Integer, Map<String, PropConverter<?, ?>>> SEQ_PROP_CVT_MAP = new ConcurrentHashMap<Integer, Map<String, PropConverter<?, ?>>>();
3232

33-
public static void setCompiler(Compiler compiler) {
34-
if (compiler == null) {
35-
throw new IllegalArgumentException("compiler should not be null");
36-
}
37-
BeanCopierFactory.COMPILER = compiler;
38-
}
39-
4033
public static <Source, Target> BeanCopier<Source, Target> createCopier(
4134
Class<?> sourceClass, Class<?> targetClass) {
4235
return createCopier(sourceClass, targetClass, false, null);
@@ -68,7 +61,13 @@ public static <Source, Target> BeanCopier<Source, Target> createCopier(
6861

6962
try {
7063
Class<?> beanCopierClazz = COMPILER.compile(getClassCode(sequence, sourceClass, targetClass, deepCopy, propCvtMap));
71-
return (BeanCopier<Source, Target>) beanCopierClazz.newInstance();
64+
final BeanCopierAdapter beanCopier = (BeanCopierAdapter) beanCopierClazz.newInstance();
65+
return new BeanCopier<Source, Target>() {
66+
@Override
67+
public void copyProps(Source source, Target target) {
68+
beanCopier.copyProps(source, target);
69+
}
70+
};
7271
} catch (Exception e) {
7372
throw new LtsRuntimeException("Generate BeanCopier error, sourceClass=" + sourceClass.getName() + ", targetClass=" + targetClass.getName(), e);
7473
}
@@ -82,13 +81,14 @@ private static String getClassCode(Integer sequence, Class<?> sourceClass, Class
8281
JavaSourceBean javaSourceBean = new JavaSourceBean();
8382
javaSourceBean.setPackageName(BeanCopierFactory.class.getPackage().getName());
8483

85-
javaSourceBean.addImport(BeanCopier.class.getName());
84+
javaSourceBean.addImport(BeanCopierAdapter.class.getName());
8685
javaSourceBean.addImport(sourceClass.getName());
8786
javaSourceBean.addImport(targetClass.getName());
87+
javaSourceBean.addImport(PropConverter.class.getName());
8888

8989
String beanCopierClassName = sourceClass.getSimpleName() + "2" + targetClass.getSimpleName() + BeanCopier.class.getSimpleName() + sequence;
9090
String classDefinitionCode = "public class " + beanCopierClassName +
91-
" implements " + BeanCopier.class.getSimpleName() + "<" + sourceClass.getSimpleName() + "," + targetClass.getSimpleName() + ">";
91+
" extends " + BeanCopierAdapter.class.getSimpleName();
9292

9393
javaSourceBean.setClassDefinition(classDefinitionCode);
9494

@@ -106,7 +106,9 @@ private static String getClassCode(Integer sequence, Class<?> sourceClass, Class
106106
private static String getMethodImplCode(Integer sequence, Class<?> sourceClass, Class<?> targetClass, boolean deepCopy, final Map<String, PropConverter<?, ?>> propCvtMap) throws Exception {
107107

108108
StringBuilder methodCode = new StringBuilder();
109-
methodCode.append("public void copyProps(").append(sourceClass.getSimpleName()).append(" source, ").append(targetClass.getSimpleName()).append(" target){\n");
109+
methodCode.append("public void copyProps(").append(Object.class.getName()).append(" sourceObj, ").append(Object.class.getName()).append(" targetObj){\n");
110+
methodCode.append(sourceClass.getSimpleName()).append(" source = ").append("(").append(sourceClass.getSimpleName()).append(")sourceObj;\n");
111+
methodCode.append(targetClass.getSimpleName()).append(" target = ").append("(").append(targetClass.getSimpleName()).append(")targetObj;\n");
110112

111113
// 这里查找了包括父类的属性
112114
Field[] targetFields = ReflectionUtils.findFields(targetClass);
@@ -116,7 +118,6 @@ private static String getMethodImplCode(Integer sequence, Class<?> sourceClass,
116118
// 是否含有set方法
117119
String methodNameSuffix = capitalize(field.getName());
118120
Class<?> targetFieldClass = field.getType();
119-
Type targetFieldType = field.getGenericType();
120121

121122
Method setMethod = ReflectionUtils.findMethod(targetClass, "set" + methodNameSuffix, targetFieldClass);
122123
if (setMethod != null) {
@@ -125,12 +126,12 @@ private static String getMethodImplCode(Integer sequence, Class<?> sourceClass,
125126
if (propCvtMap != null && propCvtMap.containsKey(field.getName())) {
126127

127128
String converterName = field.getName() + "Converter";
128-
String converterType = PropConverter.class.getName() + "<" + sourceClass.getSimpleName() + ", " + targetFieldType.toString() + "> ";
129+
String converterType = PropConverter.class.getSimpleName();
129130

130-
methodCode.append(converterType).append(converterName).append(" = (").append(converterType).append(")")
131+
methodCode.append(converterType).append(" ").append(converterName).append(" = (").append(converterType).append(")")
131132
.append(BeanCopierFactory.class.getName()).append(".getConverter(").append(sequence).append(",").append("\"").append(field.getName()).append("\");\n");
132133
methodCode.append("target.").append(setMethod.getName()).append("(")
133-
.append("(").append(targetFieldType.toString()).append(")").append(converterName).append(".convert(").append("source").append(")")
134+
.append("(").append(targetFieldClass.getName()).append(")").append(converterName).append(".convert(").append("source").append(")")
134135
.append(");\n");
135136
continue;
136137
}
@@ -154,7 +155,7 @@ private static String getMethodImplCode(Integer sequence, Class<?> sourceClass,
154155
} else {
155156
// 深度复制,对于非基本类型的采用流的方式拷贝
156157
methodCode.append("target.").append(setMethod.getName()).append("(")
157-
.append("(").append(targetFieldType.toString()).append(")")
158+
.append("(").append(targetFieldClass.getName()).append(")")
158159
.append(BeanUtils.class.getName()).append(".deepClone(")
159160
.append("source.").append(getMethod.getName()).append("()")
160161
.append(")")
@@ -184,7 +185,7 @@ private static String capitalize(String str) {
184185
/**
185186
* 会被动态类使用
186187
*/
187-
public static PropConverter<?, ?> getConverter(Integer sequence, String propName) {
188+
public static PropConverter<?, ?> getConverter(int sequence, String propName) {
188189
Map<String, PropConverter<?, ?>> map = SEQ_PROP_CVT_MAP.get(sequence);
189190
return map.get(propName);
190191
}

lts-core/src/test/java/com/github/ltsopensource/core/support/bean/BeanCopierFactoryTest.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.github.ltsopensource.core.support.bean;
22

3+
import com.github.ltsopensource.core.compiler.AbstractCompiler;
34
import com.github.ltsopensource.core.domain.Job;
5+
import com.github.ltsopensource.core.support.JobUtils;
46
import com.github.ltsopensource.queue.domain.JobPo;
57
import org.junit.Before;
68
import org.junit.Test;
@@ -24,6 +26,17 @@ public void init() {
2426
jobPo.setInternalExtParam("xxx", "fadsfsa");
2527
}
2628

29+
@Test
30+
public void testJdkCopy(){
31+
AbstractCompiler.setCompiler("jdk");
32+
JobUtils.copy(jobPo);
33+
}
34+
@Test
35+
public void testJavassistCopy(){
36+
AbstractCompiler.setCompiler("javassist");
37+
JobUtils.copy(jobPo);
38+
}
39+
2740
@Test
2841
public void testGetBeanCopier() throws Exception {
2942
BeanCopier<JobPo, JobPo> beanCopier = BeanCopierFactory.createCopier(JobPo.class, JobPo.class);

0 commit comments

Comments
 (0)