proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/PluginEntity.java
|
PluginEntity
|
initInstance
|
class PluginEntity {
/**
* 类名(全路径)
*/
private String className;
/**
* 类加载器
*/
private ClassLoader classLoader;
/**
* 优先级(大的优先)
*/
private int priority = 0;
/**
* 插件
*/
private Plugin plugin;
/**
* 插件属性(申明插件类与优先级)
*/
private Properties props;
public PluginEntity(ClassLoader classLoader, String className, Properties props) {
this.classLoader = classLoader;
this.className = className;
this.props = props;
}
/**
* @deprecated 2.2
*/
@Deprecated
public PluginEntity(Plugin plugin) {
this.plugin = plugin;
}
/**
* @deprecated 2.2
*/
@Deprecated
public PluginEntity(Plugin plugin, int priority) {
this.plugin = plugin;
this.priority = priority;
}
/**
* 获取优先级
*/
public int getPriority() {
return priority;
}
/**
* 设置优先级
*/
public void setPriority(int priority) {
this.priority = priority;
}
/**
* 获取插件
*/
public @Nullable Plugin getPlugin() {
return plugin;
}
public Properties getProps() {
return props;
}
public String getClassName() {
return className;
}
/**
* 初始化
*/
public void init(AppContext context) {
initInstance(context);
}
/**
* 启动
*/
public void start(AppContext context) {
if (plugin != null) {
try {
plugin.start(context);
} catch (RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new IllegalStateException("Plugin start failed", e);
}
}
}
/**
* 预停止
*/
public void prestop() {
if (plugin != null) {
try {
plugin.prestop();
} catch (Throwable e) {
//e.printStackTrace();
}
}
}
/**
* 停止
*/
public void stop() {
if (plugin != null) {
try {
plugin.stop();
} catch (Throwable e) {
//e.printStackTrace();
}
}
}
/**
* 初始化
*/
private void initInstance(AppContext context) {<FILL_FUNCTION_BODY>}
}
|
if (plugin == null) {
if (classLoader != null) {
plugin = ClassUtil.tryInstance(classLoader, className);
if (plugin == null) {
LogUtil.global().warn("The configured plugin cannot load: " + className);
} else {
if (plugin instanceof InitializingBean) {
try {
((InitializingBean) plugin).afterInjection();
} catch (RuntimeException e) {
throw e;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
}
}
}
| 720
| 150
| 870
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/PropsConverter.java
|
PropsConverter
|
convert
|
class PropsConverter {
private static PropsConverter global;
public static PropsConverter global() {
return global;
}
public static void globalSet(PropsConverter instance) {
if (instance != null) {
PropsConverter.global = instance;
}
}
static {
//(静态扩展约定:org.noear.solon.extend.impl.XxxxExt)
PropsConverter tmp = ClassUtil.tryInstance("org.noear.solon.extend.impl.PropsConverterExt");
if (tmp == null) {
global = new PropsConverter();
} else {
global = tmp;
}
}
/**
* 转换
*
* @param props 属性
* @param target 目标
* @param targetClz 目标类
* @param targetType 目标类型
*/
public <T> T convert(Properties props, T target, Class<T> targetClz, Type targetType) {<FILL_FUNCTION_BODY>}
public <T> T convert(Properties props, Class<T> targetClz) {
return convert(props, null, targetClz, null);
}
}
|
if (target == null) {
return ClassWrap.get(targetClz).newBy(props);
} else {
ClassWrap.get(target.getClass()).fill(target, props::getProperty);
return target;
}
| 313
| 63
| 376
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/PropsLoader.java
|
PropsLoader
|
load
|
class PropsLoader {
private static PropsLoader global;
public static PropsLoader global() {
return global;
}
public static void globalSet(PropsLoader instance) {
if(instance != null) {
PropsLoader.global = instance;
}
}
static {
//(静态扩展约定:org.noear.solon.extend.impl.XxxxExt)
PropsLoader tmp = ClassUtil.tryInstance("org.noear.solon.extend.impl.PropsLoaderExt");
if (tmp == null) {
global = new PropsLoader();
} else {
global = tmp;
}
}
/**
* 是否支持
*
* @param suffix 文件后缀
* */
public boolean isSupport(String suffix) {
if (suffix == null) {
return false;
}
return suffix.endsWith(".properties");
}
/**
* 加载 url 配置
* */
public Properties load(URL url) throws IOException {<FILL_FUNCTION_BODY>}
/**
* 构建 txt 配置
* */
public Properties build(String txt) throws IOException {
int idx1 = txt.indexOf("=");
int idx2 = txt.indexOf(":");
if (idx1 > 0 && (idx1 < idx2 || idx2 < 0)) {
Properties tmp = new Properties();
tmp.load(new StringReader(txt));
return tmp;
}
return new Properties();
}
}
|
if (url == null) {
return null;
}
String fileName = url.toString();
if (fileName.endsWith(".properties")) {
if(Solon.app() != null && Solon.cfg().isDebugMode()) {
LogUtil.global().trace(fileName);
}
Properties tmp = new Properties();
try (InputStreamReader reader = new InputStreamReader(url.openStream(), Solon.encoding())) {
tmp.load(reader);
}
return tmp;
}
throw new IllegalStateException("This profile is not supported: " + fileName);
| 400
| 155
| 555
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/ResourceScanner.java
|
ResourceScanner
|
doScanByJar
|
class ResourceScanner {
/**
* 扫描路径下的的资源(path 扫描路径)
*
* @param classLoader 类加载器
* @param path 路径
* @param filter 过滤条件
*/
public Set<String> scan(ClassLoader classLoader, String path, Predicate<String> filter) {
Set<String> urls = new LinkedHashSet<>();
if (classLoader == null) {
return urls;
}
try {
//1.查找资源
Enumeration<URL> roots = ResourceUtil.getResources(classLoader, path);
//2.资源遍历
while (roots.hasMoreElements()) {
//3.尝试扫描
scanDo(roots.nextElement(), path, filter, urls);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
return urls;
}
protected void scanDo(URL url, String path, Predicate<String> filter, Set<String> urls) throws IOException {
if ("file".equals(url.getProtocol())) {
//3.1.找到文件
//
String fp = URLDecoder.decode(url.getFile(), Solon.encoding());
doScanByFile(new File(fp), path, filter, urls);
} else if ("jar".equals(url.getProtocol())) {
//3.2.找到jar包
//
JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
doScanByJar(jar, path, filter, urls);
}
}
/**
* 在文件系统里查到目标
*
* @param dir 文件目录
* @param path 路径
* @param filter 过滤条件
*/
protected void doScanByFile(File dir, String path, Predicate<String> filter, Set<String> urls) {
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(f -> f.isDirectory() || filter.test(f.getName()));
if (dirfiles != null) {
for (File f : dirfiles) {
String p2 = path + "/" + f.getName();
// 如果是目录 则继续扫描
if (f.isDirectory()) {
doScanByFile(f, p2, filter, urls);
} else {
if (p2.startsWith("/")) {
urls.add(p2.substring(1));
} else {
urls.add(p2);
}
}
}
}
}
/**
* 在 jar 包里查找目标
*
* @param jar jar文件
* @param path 路径
* @param filter 过滤条件
*/
protected void doScanByJar(JarFile jar, String path, Predicate<String> filter, Set<String> urls) {<FILL_FUNCTION_BODY>}
}
|
Enumeration<JarEntry> entry = jar.entries();
while (entry.hasMoreElements()) {
JarEntry e = entry.nextElement();
String n = e.getName();
if (n.charAt(0) == '/') {
n = n.substring(1);
}
if (e.isDirectory() || !n.startsWith(path) || !filter.test(n)) {
// 非指定包路径, 非目标后缀
continue;
}
if (n.startsWith("/")) {
urls.add(n.substring(1));
} else {
urls.add(n);
}
}
| 825
| 182
| 1,007
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/aspect/Invocation.java
|
Invocation
|
argsAsMap
|
class Invocation {
private final Object target;
private final Object[] args;
private Map<String, Object> argsMap;
private final MethodHolder method;
private final List<InterceptorEntity> interceptors;
private int interceptorIndex = 0;
public Invocation(Object target, Object[] args, MethodHolder method, List<InterceptorEntity> interceptors) {
this.target = target;
this.args = args;
this.method = method;
this.interceptors = interceptors;
}
/**
* 目标对象
*/
public Object target() {
return target;
}
/**
* 目标对象类
*/
public Class<?> getTargetClz(){
return target.getClass();
}
/**
* 目标对象类注解
*/
public <T extends Annotation> T getTargetAnnotation(Class<T> annoClz) {
return target.getClass().getAnnotation(annoClz);
}
/**
* 参数
*/
public Object[] args() {
return args;
}
/**
* 参数Map模式
*/
public Map<String, Object> argsAsMap() {<FILL_FUNCTION_BODY>}
/**
* 函数
*/
public MethodHolder method() {
return method;
}
/**
* 函数注解
*/
public <T extends Annotation> T getMethodAnnotation(Class<T> annoClz) {
return method.getAnnotation(annoClz);
}
/**
* 调用
*/
public Object invoke() throws Throwable {
return interceptors.get(interceptorIndex++).doIntercept(this);
}
}
|
if (argsMap == null) {
Map<String, Object> tmp = new LinkedHashMap<>();
ParamWrap[] params = method.getParamWraps();
for (int i = 0, len = params.length; i < len; i++) {
tmp.put(params[i].getName(), args[i]);
}
//变成只读
argsMap = Collections.unmodifiableMap(tmp);
}
return argsMap;
| 463
| 121
| 584
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/convert/ConverterManager.java
|
ConverterManager
|
register
|
class ConverterManager {
private Map<Type, Map<Type, Converter>> cLib = new HashMap<>();
private Map<Type, Map<Class<?>, ConverterFactory>> cfLib = new HashMap<>();
/**
* 注册转换器
*
* @param converter 转换器
*/
public <S, T> void register(Converter<S, T> converter) {
Map<String, Type> giMap = GenericUtil.getGenericInfo(converter.getClass());
Type sType = null;
Type tType = null;
if (giMap != null) {
sType = giMap.get("S");
tType = giMap.get("T");
}
if (sType == null || sType == Object.class) {
throw new IllegalArgumentException("Invalid converter source type: " + converter.getClass().getName());
}
if (tType == null || tType == Object.class) {
throw new IllegalArgumentException("Invalid converter source type: " + converter.getClass().getName());
}
Map<Type, Converter> tmp = cLib.get(sType);
if (tmp == null) {
tmp = new HashMap<>();
cLib.put(sType, tmp);
}
tmp.put(tType, converter);
}
/**
* 注册转换器
*
* @param converterFactory 转换器工厂
*/
public <S, R> void register(ConverterFactory<S, R> converterFactory) {<FILL_FUNCTION_BODY>}
/**
* 查找转换器
*
* @param sourceType 源类型
* @param tagertType 目标类型
*/
public <S, T> Converter<S, T> find(Class<S> sourceType, Class<T> tagertType) {
Map<Type, Converter> cMap = cLib.get(sourceType);
if (cMap == null) {
return findInFactory(sourceType, tagertType);
} else {
Converter c = cMap.get(tagertType);
if (c == null) {
return findInFactory(sourceType, tagertType);
} else {
return c;
}
}
}
public <S, T> Converter<S, T> findInFactory(Class<S> sourceType, Class<T> tagertType) {
Map<Class<?>, ConverterFactory> cfMap = cfLib.get(sourceType);
if (cfMap == null) {
return null;
} else {
for (Map.Entry<Class<?>, ConverterFactory> kv : cfMap.entrySet()) {
if (kv.getKey().isAssignableFrom(tagertType)) {
return kv.getValue().getConverter(tagertType);
}
}
}
return null;
}
}
|
Map<String, Type> giMap = GenericUtil.getGenericInfo(converterFactory.getClass());
Type sType = null;
Type rType = null;
if (giMap != null) {
sType = giMap.get("S");
rType = giMap.get("R");
}
if (sType == null || sType == Object.class) {
throw new IllegalArgumentException("Invalid converterFactory source type: " + converterFactory.getClass().getName());
}
if (rType == null || rType == Object.class || (rType instanceof Class) == false) {
throw new IllegalArgumentException("Invalid converterFactory result type: " + converterFactory.getClass().getName());
}
Map<Class<?>, ConverterFactory> tmp = cfLib.get(sType);
if (tmp == null) {
tmp = new HashMap<>();
cfLib.put(sType, tmp);
}
tmp.put((Class<?>) rType, converterFactory);
| 746
| 259
| 1,005
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/event/EventBus.java
|
EventBus
|
publish1
|
class EventBus {
//异常订阅者
private static List<HH> sThrow = new ArrayList<>();
//其它订阅者
private static List<HH> sOther = new ArrayList<>();
//订阅管道
private static Map<Class<?>, EventListenPipeline<?>> sPipeline = new HashMap<>();
/**
* 异步推送事件(一般不推荐);
*
* @param event 事件(可以是任何对象)
*/
public static void publishAsync(Object event) {
if (event != null) {
RunUtil.async(() -> {
try {
publish0(event);
} catch (Throwable e) {
publish(e);
}
});
}
}
/**
* 异步推送事件(一般不推荐);
*
* @param event 事件(可以是任何对象)
* @deprecated 2.4
* @see #publishAsync(Object)
*/
@Deprecated
public static void pushAsync(Object event){
publishAsync(event);
}
/**
* 同步推送事件(不抛异常,不具有事务回滚传导性)
*
* @param event 事件(可以是任何对象)
*/
public static void publishTry(Object event) {
if (event != null) {
try {
publish0(event);
} catch (Throwable e) {
//不再转发异常,免得死循环
LogUtil.global().warn("EventBus publishTry failed!", e);
}
}
}
/**
* 同步推送事件(不抛异常,不具有事务回滚传导性)
*
* @param event 事件(可以是任何对象)
* @deprecated 2.4
* @see #publishTry(Object)
*/
@Deprecated
public static void pushTry(Object event){
publishTry(event);
}
/**
* 同步推送事件(会抛异常,可传导事务回滚)
*
* @param event 事件(可以是任何对象)
*/
public static void publish(Object event) throws RuntimeException {
if (event != null) {
try {
publish0(event);
} catch (Throwable e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new EventException("Event execution failed: " + event.getClass().getName(), e);
}
}
}
}
/**
* 同步推送事件(会抛异常,可传导事务回滚)
*
* @param event 事件(可以是任何对象)
* @deprecated 2.4
* @see #publish(Object)
*/
@Deprecated
public static void push(Object event) throws RuntimeException {
publish(event);
}
private static void publish0(Object event) throws Throwable {
if (event instanceof Throwable) {
//异常分发
publish1(sThrow, event, false);
} else {
//其它事件分发
publish1(sOther, event, true);
}
}
private static void publish1(List<HH> hhs, Object event, boolean thrown) throws Throwable {<FILL_FUNCTION_BODY>}
/**
* 订阅事件
*
* @param eventType 事件类型
* @param listener 事件监听者
*/
public static <T> void subscribe(Class<T> eventType, EventListener<T> listener) {
Utils.locker().lock();
try {
pipelineDo(eventType).add(listener);
} finally {
Utils.locker().unlock();
}
}
/**
* 订阅事件
*
* @param eventType 事件类型
* @param index 顺序位
* @param listener 事件监听者
*/
public static <T> void subscribe(Class<T> eventType, int index, EventListener<T> listener) {
Utils.locker().lock();
try {
pipelineDo(eventType).add(index, listener);
} finally {
Utils.locker().unlock();
}
}
/**
* 建立订阅管道
*
* @param eventType 事件类型
*/
private static <T> EventListenPipeline<T> pipelineDo(Class<T> eventType) {
EventListenPipeline<T> pipeline = (EventListenPipeline<T>) sPipeline.get(eventType);
if (pipeline == null) {
pipeline = new EventListenPipeline<>();
sPipeline.put(eventType, pipeline);
registerDo(eventType, pipeline);
}
return pipeline;
}
private static <T> void registerDo(Class<T> eventType, EventListener<T> listener) {
if (Throwable.class.isAssignableFrom(eventType)) {
sThrow.add(new HH(eventType, listener));
} else {
sOther.add(new HH(eventType, listener));
}
}
/**
* 取消事件订阅
*
* @param listener 事件监听者
*/
public static <T> void unsubscribe(EventListener<T> listener) {
Utils.locker().lock();
try {
Class<?>[] ets = GenericUtil.resolveTypeArguments(listener.getClass(), EventListener.class);
if (ets != null && ets.length > 0) {
pipelineDo((Class<T>) ets[0]).remove(listener);
}
} finally {
Utils.locker().unlock();
}
}
/**
* Listener Holder
*/
static class HH {
protected Class<?> t;
protected EventListener l;
public HH(Class<?> type, EventListener listener) {
this.t = type;
this.l = listener;
}
}
}
|
//用 i,可以避免遍历时添加监听的异常
for (int i = 0; i < hhs.size(); i++) {
HH h1 = hhs.get(i);
if (h1.t.isInstance(event)) {
try {
h1.l.onEvent(event);
} catch (Throwable e) {
if (thrown) {
throw e;
} else {
//此处不能再转发异常 //不然会死循环
e.printStackTrace();
}
}
}
}
| 1,590
| 147
| 1,737
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/event/EventListenPipeline.java
|
EventListenPipeline
|
remove
|
class EventListenPipeline<Event> implements EventListener<Event> {
private List<EH> list = new ArrayList<>();
/**
* 添加监听
*/
public void add(EventListener<Event> listener) {
add(0, listener);
}
/**
* 添加监听(带顺序位)
*
* @param index 顺序位
* @param listener 监听器
*/
public void add(int index, EventListener<Event> listener) {
list.add(new EH(index, listener));
list.sort(Comparator.comparing(EH::getIndex));
}
/**
* 移除监听
*
* @param listener 监听器
*/
public void remove(EventListener<Event> listener) {<FILL_FUNCTION_BODY>}
@Override
public void onEvent(Event event) throws Throwable {
//用 i,可以避免遍历时添加监听的异常
for (int i = 0; i < list.size(); i++) {
list.get(i).listener.onEvent(event);
}
}
static class EH<Event> {
int index;
EventListener<Event> listener;
EH(int index, EventListener<Event> listener) {
this.index = index;
this.listener = listener;
}
public int getIndex() {
return index;
}
}
}
|
for (int i = 0; i < list.size(); i++) {
if (listener.equals(list.get(i).listener)) {
list.remove(i);
i--;
}
}
| 381
| 60
| 441
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/ContextEmpty.java
|
ContextEmpty
|
filesMap
|
class ContextEmpty extends Context {
public static Context create(){
return new ContextEmpty();
}
public ContextEmpty(){
sessionState = new SessionStateEmpty();
}
private Object request = null;
@Override
public Object request() {
return request;
}
public ContextEmpty request(Object request){
this.request = request;
return this;
}
@Override
public String remoteIp() {
return null;
}
@Override
public int remotePort() {
return 0;
}
@Override
public String method() {
return null;
}
@Override
public String protocol() {
return null;
}
@Override
public URI uri() {
return null;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public String url() {
return null;
}
@Override
public long contentLength() {
return 0;
}
@Override
public String contentType() {
return null;
}
@Override
public String contentCharset() {
return null;
}
@Override
public String queryString() {
return null;
}
@Override
public InputStream bodyAsStream() throws IOException {
return null;
}
private NvMap paramMap = null;
@Override
public NvMap paramMap() {
if(paramMap == null){
paramMap = new NvMap();
}
return paramMap;
}
Map<String, List<String>> paramsMap = null;
@Override
public Map<String, List<String>> paramsMap() {
if(paramsMap == null){
paramsMap = new IgnoreCaseMap<>();
}
return paramsMap;
}
Map<String, List<UploadedFile>> filesMap = null;
@Override
public Map<String, List<UploadedFile>> filesMap() throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void filesDelete() throws IOException{
}
@Override
public String cookie(String key) {
return cookieMap().get(key);
}
@Override
public String cookie(String key, String def) {
return cookieMap().getOrDefault(key,def);
}
NvMap cookieMap = null;
@Override
public NvMap cookieMap() {
if(cookieMap == null){
cookieMap = new NvMap();
}
return cookieMap;
}
private NvMap headerMap = null;
@Override
public NvMap headerMap() {
if(headerMap == null){
headerMap = new NvMap();
}
return headerMap;
}
private Map<String, List<String>> headersMap;
@Override
public Map<String, List<String>> headersMap() {
if (headersMap == null) {
headersMap = new LinkedHashMap<>();
}
return headersMap;
}
@Override
public String sessionId() {
return null;
}
@Override
public <T> T session(String name, Class<T> clz) {
return null;
}
@Override
public <T> T sessionOrDefault(String name, @NonNull T def) {
return null;
}
@Override
public int sessionAsInt(String name) {
return 0;
}
@Override
public int sessionAsInt(String name, int def) {
return 0;
}
@Override
public long sessionAsLong(String name) {
return 0;
}
@Override
public long sessionAsLong(String name, long def) {
return 0;
}
@Override
public double sessionAsDouble(String name) {
return 0;
}
@Override
public double sessionAsDouble(String name, double def) {
return 0;
}
@Override
public void sessionSet(String name, Object val) {
}
@Override
public void sessionRemove(String name) {
}
@Override
public void sessionClear() {
}
private Object response = null;
@Override
public Object response() {
return response;
}
public ContextEmpty response(Object response) {
this.response = response;
return this;
}
@Override
protected void contentTypeDoSet(String contentType) {
}
@Override
public void output(byte[] bytes) {
}
@Override
public void output(InputStream stream) {
}
@Override
public OutputStream outputStream() {
return null;
}
@Override
public void outputAsFile(DownloadedFile file) throws IOException {
}
@Override
public void outputAsFile(File file) throws IOException {
}
@Override
public void headerSet(String key, String val) {
headerMap().put(key,val);
}
@Override
public void headerAdd(String key, String val) {
headerMap().put(key,val);
}
@Override
public String headerOfResponse(String name) {
return headerMap().get(name);
}
@Override
public void cookieSet(String key, String val, String domain, String path, int maxAge) {
cookieMap().put(key,val);
}
@Override
public void redirect(String url, int code) {
}
private int status = 200;
@Override
public int status() {
return status;
}
@Override
protected void statusDoSet(int status) {
this.status = status;
}
@Override
public void flush() throws IOException{
}
@Override
public void close() throws IOException {
}
@Override
public boolean asyncSupported() {
return false;
}
@Override
public void asyncStart(long timeout, ContextAsyncListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void asyncComplete() {
throw new UnsupportedOperationException();
}
}
|
if (filesMap == null) {
filesMap = new LinkedHashMap<>();
}
return filesMap;
| 1,641
| 34
| 1,675
|
<methods>public non-sealed void <init>() ,public java.lang.String accept() ,public org.noear.solon.core.handle.Action action() ,public abstract void asyncComplete() throws java.io.IOException,public abstract void asyncStart(long, org.noear.solon.core.handle.ContextAsyncListener) ,public void asyncStart() ,public abstract boolean asyncSupported() ,public T attr(java.lang.String, T) ,public T attr(java.lang.String) ,public void attrClear() ,public Map<java.lang.String,java.lang.Object> attrMap() ,public T attrOrDefault(java.lang.String, T) ,public void attrSet(java.lang.String, java.lang.Object) ,public void attrSet(Map<java.lang.String,java.lang.Object>) ,public boolean autoMultipart() ,public void autoMultipart(boolean) ,public java.lang.String body() throws java.io.IOException,public java.lang.String body(java.lang.String) throws java.io.IOException,public byte[] bodyAsBytes() throws java.io.IOException,public abstract java.io.InputStream bodyAsStream() throws java.io.IOException,public java.lang.String bodyNew() throws java.io.IOException,public void bodyNew(java.lang.String) ,public void charset(java.lang.String) ,public abstract void close() throws java.io.IOException,public abstract java.lang.String contentCharset() ,public abstract long contentLength() ,public void contentLength(long) ,public abstract java.lang.String contentType() ,public void contentType(java.lang.String) ,public java.lang.String contentTypeNew() ,public java.lang.Object controller() ,public java.lang.String cookie(java.lang.String) ,public java.lang.String cookie(java.lang.String, java.lang.String) ,public abstract org.noear.solon.core.NvMap cookieMap() ,public java.lang.String cookieOrDefault(java.lang.String, java.lang.String) ,public void cookieRemove(java.lang.String) ,public void cookieSet(java.lang.String, java.lang.String) ,public void cookieSet(java.lang.String, java.lang.String, int) ,public void cookieSet(java.lang.String, java.lang.String, java.lang.String, int) ,public abstract void cookieSet(java.lang.String, java.lang.String, java.lang.String, java.lang.String, int) ,public static org.noear.solon.core.handle.Context current() ,public org.noear.solon.core.handle.UploadedFile file(java.lang.String) throws java.io.IOException,public List<org.noear.solon.core.handle.UploadedFile> files(java.lang.String) throws java.io.IOException,public abstract void filesDelete() throws java.io.IOException,public abstract Map<java.lang.String,List<org.noear.solon.core.handle.UploadedFile>> filesMap() throws java.io.IOException,public abstract void flush() throws java.io.IOException,public void forward(java.lang.String) ,public boolean getHandled() ,public java.util.Locale getLocale() ,public boolean getRendered() ,public java.lang.String header(java.lang.String) ,public java.lang.String header(java.lang.String, java.lang.String) ,public abstract void headerAdd(java.lang.String, java.lang.String) ,public abstract org.noear.solon.core.NvMap headerMap() ,public abstract java.lang.String headerOfResponse(java.lang.String) ,public java.lang.String headerOrDefault(java.lang.String, java.lang.String) ,public abstract void headerSet(java.lang.String, java.lang.String) ,public java.lang.String[] headerValues(java.lang.String) ,public abstract Map<java.lang.String,List<java.lang.String>> headersMap() ,public java.lang.String ip() ,public boolean isFormUrlencoded() ,public boolean isMultipart() ,public boolean isMultipartFormData() ,public abstract boolean isSecure() ,public org.noear.solon.core.handle.Handler mainHandler() ,public abstract java.lang.String method() ,public abstract void output(byte[]) ,public abstract void output(java.io.InputStream) ,public void output(java.lang.String) ,public void output(java.lang.Throwable) ,public abstract void outputAsFile(org.noear.solon.core.handle.DownloadedFile) throws java.io.IOException,public abstract void outputAsFile(java.io.File) throws java.io.IOException,public void outputAsHtml(java.lang.String) ,public void outputAsJson(java.lang.String) ,public abstract java.io.OutputStream outputStream() throws java.io.IOException,public java.lang.String param(java.lang.String) ,public java.lang.String param(java.lang.String, java.lang.String) ,public T paramAsBean(Class<T>) ,public java.math.BigDecimal paramAsDecimal(java.lang.String) ,public java.math.BigDecimal paramAsDecimal(java.lang.String, java.math.BigDecimal) ,public double paramAsDouble(java.lang.String) ,public double paramAsDouble(java.lang.String, double) ,public int paramAsInt(java.lang.String) ,public int paramAsInt(java.lang.String, int) ,public long paramAsLong(java.lang.String) ,public long paramAsLong(java.lang.String, long) ,public abstract org.noear.solon.core.NvMap paramMap() ,public java.lang.String paramOrDefault(java.lang.String, java.lang.String) ,public void paramSet(java.lang.String, java.lang.String) ,public java.lang.String[] paramValues(java.lang.String) ,public void paramsAdd(java.lang.String, java.lang.String) ,public abstract Map<java.lang.String,List<java.lang.String>> paramsMap() ,public java.lang.String path() ,public java.lang.String pathAsLower() ,public java.lang.String pathAsUpper() ,public org.noear.solon.core.NvMap pathMap(java.lang.String) ,public void pathNew(java.lang.String) ,public java.lang.String pathNew() ,public abstract java.lang.String protocol() ,public java.lang.String protocolAsUpper() ,public abstract java.lang.String queryString() ,public java.lang.String realIp() ,public void redirect(java.lang.String) ,public abstract void redirect(java.lang.String, int) ,public abstract java.lang.String remoteIp() ,public abstract int remotePort() ,public boolean remoting() ,public void remotingSet(boolean) ,public final void render(java.lang.Object) throws java.lang.Throwable,public final void render(java.lang.String, Map<java.lang.String,?>) throws java.lang.Throwable,public final java.lang.String renderAndReturn(java.lang.Object) throws java.lang.Throwable,public abstract java.lang.Object request() ,public abstract java.lang.Object response() ,public final java.lang.Object session(java.lang.String) ,public abstract T session(java.lang.String, Class<T>) ,public T session(java.lang.String, T) ,public abstract double sessionAsDouble(java.lang.String) ,public abstract double sessionAsDouble(java.lang.String, double) ,public abstract int sessionAsInt(java.lang.String) ,public abstract int sessionAsInt(java.lang.String, int) ,public abstract long sessionAsLong(java.lang.String) ,public abstract long sessionAsLong(java.lang.String, long) ,public abstract void sessionClear() ,public abstract java.lang.String sessionId() ,public abstract T sessionOrDefault(java.lang.String, T) ,public abstract void sessionRemove(java.lang.String) ,public abstract void sessionSet(java.lang.String, java.lang.Object) ,public org.noear.solon.core.handle.SessionState sessionState() ,public void setHandled(boolean) ,public void setLocale(java.util.Locale) ,public void setRendered(boolean) ,public abstract int status() ,public void status(int) ,public void statusSet(int) ,public abstract java.net.URI uri() ,public abstract java.lang.String url() ,public java.lang.String userAgent() <variables>private boolean _remoting,private java.lang.String accept,private boolean allowMultipart,private Map<java.lang.String,java.lang.Object> attrMap,private java.lang.String body,private java.lang.String bodyNew,protected java.nio.charset.Charset charset,private java.lang.String contentTypeNew,public java.lang.Throwable errors,private boolean handled,java.lang.Boolean isFormUrlencoded,java.lang.Boolean isMultipart,java.lang.Boolean isMultipartFormData,private java.util.Locale locale,private java.lang.String path,private java.lang.String pathAsLower,private java.lang.String pathAsUpper,private java.lang.String pathNew,private java.lang.String protocolAsUpper,private java.lang.String realIp,private boolean rendered,public java.lang.Object result,protected org.noear.solon.core.handle.SessionState sessionState
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/ContextPathFilter.java
|
ContextPathFilter
|
doFilter
|
class ContextPathFilter implements Filter {
private final String contextPath0;
private final String contextPath1;
private final boolean forced;
public ContextPathFilter() {
this(Solon.cfg().serverContextPath(), Solon.cfg().serverContextPathForced());
}
/**
* @deprecated 2.6
* */
@Deprecated
public ContextPathFilter(boolean forced) {
this(Solon.cfg().serverContextPath(), forced);
}
/**
* @deprecated 2.6
* */
@Deprecated
public ContextPathFilter(String contextPath) {
this(contextPath, false);
}
/**
* @param contextPath '/demo/'
*/
public ContextPathFilter(String contextPath, boolean forced) {
this.forced = forced;
if (Utils.isEmpty(contextPath)) {
contextPath0 = null;
contextPath1 = null;
} else {
String newPath = null;
if (contextPath.endsWith("/")) {
newPath = contextPath;
} else {
newPath = contextPath + "/";
}
if (newPath.startsWith("/")) {
this.contextPath1 = newPath;
} else {
this.contextPath1 = "/" + newPath;
}
this.contextPath0 = contextPath1.substring(0, contextPath1.length() - 1);
//有可能是 ContextPathFilter 是用户手动添加的!需要补一下配置
Solon.cfg().serverContextPath(this.contextPath1);
}
}
@Override
public void doFilter(Context ctx, FilterChain chain) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
if (contextPath0 != null) {
if (ctx.pathNew().equals(contextPath0)) {
//www:888 加 abc 后,仍可以用 www:888/abc 打开
ctx.pathNew("/");
} else if (ctx.pathNew().startsWith(contextPath1)) {
ctx.pathNew(ctx.pathNew().substring(contextPath1.length() - 1));
} else {
if (forced) {
return;
}
}
}
chain.doFilter(ctx);
| 446
| 146
| 592
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/DownloadedFile.java
|
DownloadedFile
|
getContentSize
|
class DownloadedFile {
/**
* 内容类型(有些地方会动态构建,所以不能只读)
*/
private String contentType;
/**
* 内容大小
*/
private long contentSize;
/**
* 内容流
*/
private InputStream content;
/**
* 文件名(带扩展名,例:demo.jpg)
*/
private String name;
/**
* 是否附件(即下载模式)
*/
private boolean attachment = true;
/**
* 是否附件输出
*/
public boolean isAttachment() {
return attachment;
}
/**
* 作为附件输出
*/
public DownloadedFile asAttachment(boolean attachment) {
this.attachment = attachment;
return this;
}
/**
* 内容类型
*/
public String getContentType() {
return contentType;
}
/**
* 内容大小
*/
public long getContentSize() {<FILL_FUNCTION_BODY>}
/**
* 内容流
*/
public InputStream getContent() {
return content;
}
/**
* 文件名(带扩展名,例:demo.jpg)
*/
public String getName() {
return name;
}
public DownloadedFile() {
}
/**
* 构造函数
*
* @param contentType 内容类型
* @param contentSize 内容大小
* @param content 内容流
* @param name 文件名
*/
public DownloadedFile(String contentType, long contentSize, InputStream content, String name) {
this.contentType = contentType;
this.contentSize = contentSize;
this.content = content;
this.name = name;
}
/**
* 构造函数
*
* @param contentType 内容类型
* @param content 内容流
* @param name 文件名
*/
public DownloadedFile(String contentType, InputStream content, String name) {
this(contentType, 0, content, name);
}
/**
* 构造函数
*
* @param contentType 内容类型
* @param content 内容流
* @param name 文件名
*/
public DownloadedFile(String contentType, byte[] content, String name) {
this.contentType = contentType;
this.contentSize = content.length;
this.content = new ByteArrayInputStream(content);
this.name = name;
}
/**
* 构造函数
*
* @param file 文件
* @throws FileNotFoundException
*/
public DownloadedFile(File file) throws FileNotFoundException {
this(file, file.getName());
}
/**
* 构造函数
*
* @param file 文件
* @param name 名字
* @throws FileNotFoundException
* @since 2.5
*/
public DownloadedFile(File file, String name) throws FileNotFoundException {
this(file, name, Utils.mime(file.getName()));
}
public DownloadedFile(File file, String name, String contentType) throws FileNotFoundException {
this.contentType = contentType;
this.contentSize = file.length();
this.content = new FileInputStream(file);
this.name = name;
}
/**
* 将内容流迁移到目标文件
*
* @param file 目标文件
*/
public void transferTo(File file) throws IOException {
try (FileOutputStream stream = new FileOutputStream(file)) {
IoUtil.transferTo(content, stream);
}
}
/**
* 将内容流迁移到目标输出流
*
* @param stream 目标输出流
*/
public void transferTo(OutputStream stream) throws IOException {
IoUtil.transferTo(content, stream);
}
}
|
if (contentSize > 0) {
return contentSize;
} else {
try {
return content.available();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| 1,054
| 59
| 1,113
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/HandlerPipeline.java
|
HandlerPipeline
|
handle
|
class HandlerPipeline implements Handler {
private List<Handler> chain = new LinkedList<>();
/**
* 下一步
* */
public HandlerPipeline next(Handler handler) {
chain.add(handler);
return this;
}
/**
* 上一步
* */
public HandlerPipeline prev(Handler handler) {
chain.add(0, handler);
return this;
}
@Override
public void handle(Context ctx) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
for (Handler h : chain) {
if (ctx.getHandled()) {
break;
}
h.handle(ctx);
}
| 145
| 43
| 188
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/MethodHandler.java
|
MethodHandler
|
handle
|
class MethodHandler implements Handler {
private final BeanWrap bw;
private final MethodWrap mw;
private final boolean allowResult;
/**
* @param beanWrap Bean包装器
* @param method 函数(外部要控制访问权限)
* @param allowResult 允许传递结果
*/
public MethodHandler(BeanWrap beanWrap, Method method, boolean allowResult) {
this.bw = beanWrap;
this.mw = beanWrap.context().methodGet(method);
this.allowResult = allowResult;
}
/**
* 处理
*/
@Override
public void handle(Context c) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
Object tmp = Solon.app().chainManager().getExecuteHandlerDefault()
.executeHandle(c, bw.get(true), mw);
if (allowResult) {
c.result = tmp;
}
| 193
| 59
| 252
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/MethodTypeUtil.java
|
MethodTypeUtil
|
valueOf
|
class MethodTypeUtil {
static final Map<String, MethodType> enumMap = new HashMap<>();
static {
MethodType[] enumOrdinal = MethodType.class.getEnumConstants();
for (int i = 0; i < enumOrdinal.length; ++i) {
MethodType e = enumOrdinal[i];
enumMap.put(e.name(), e);
}
}
public static MethodType valueOf(String name) {<FILL_FUNCTION_BODY>}
}
|
MethodType tmp = enumMap.get(name);
if (tmp == null) {
return MethodType.UNKNOWN;
} else {
return tmp;
}
| 133
| 50
| 183
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/RenderManager.java
|
RenderManager
|
resolveRander
|
class RenderManager implements Render {
private static final Map<String, Render> _mapping = new HashMap<>();
private static final Map<String, Render> _lib = new HashMap<>();
//默认渲染器
private static Render _def = (d, c) -> {
if (d != null) {
c.output(d.toString());
}
};
private RenderManager() {
}
//不能放上面
public static Render global = new RenderManager();
/**
* 获取渲染器
* */
public static Render get(String name) {
Render tmp = _lib.get(name);
if (tmp == null) {
tmp = _mapping.get(name);
}
return tmp;
}
/**
* 登记渲染器
*
* @param render 渲染器
*/
public static void register(Render render) {
if(render == null){
return;
}
_def = render;
_lib.put(render.getClass().getSimpleName(), render);
_lib.put(render.getClass().getName(), render);
LogUtil.global().info("View: load: " + render.getClass().getSimpleName());
LogUtil.global().info("View: load: " + render.getClass().getName());
}
/**
* 映射后缀和渲染器的关系
*
* @param suffix 后缀(例:.ftl)
* @param render 渲染器
*/
public static void mapping(String suffix, Render render) {
if (render == null) {
return;
}
if (Utils.isNotEmpty(suffix)) {
//suffix=.ftl
_mapping.put(suffix, render);
LogUtil.global().info("Render mapping: " + suffix + "=" + render.getName());
}
}
/**
* 映射后缀和渲染器的关系
*
* @param suffix 后缀(例:.ftl)
* @param clzName 渲染器类名
*/
public static void mapping(String suffix, String clzName) {
if (suffix == null || clzName == null) {
return;
}
Render render = _lib.get(clzName);
if (render == null) {
LogUtil.global().warn("Render: " + clzName + " not exists!");
return;
//throw new IllegalStateException(classSimpleName + " not exists!");
}
_mapping.put(suffix, render);
LogUtil.global().info("Render mapping: " + suffix + "=" + clzName);
}
/**
* 渲染并返回
* */
public static String renderAndReturn(ModelAndView modelAndView) {
try {
return global.renderAndReturn(modelAndView, Context.current());
} catch (Throwable ex) {
ex = Utils.throwableUnwrap(ex);
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException(ex);
}
}
}
/**
* 渲染并返回
* */
@Override
public String renderAndReturn(Object data, Context ctx) throws Throwable {
if (data instanceof ModelAndView) {
ModelAndView mv = (ModelAndView) data;
if (Utils.isNotEmpty(mv.view())) {
//
//如果有视图
//
int suffix_idx = mv.view().lastIndexOf(".");
if (suffix_idx > 0) {
String suffix = mv.view().substring(suffix_idx);
Render render = _mapping.get(suffix);
if (render != null) {
//如果找到对应的渲染器
//
//同步上下文特性
ctx.attrMap().forEach((k, v) -> {
mv.putIfAbsent(k, v);
});
//视图渲染
return render.renderAndReturn(mv, ctx);
}
}
//如果没有则用默认渲染器
//
return _def.renderAndReturn(mv, ctx);
} else {
data = mv.model();
}
}
Render render = resolveRander(ctx);
if (render != null) {
return render.renderAndReturn(data, ctx);
} else {
//最后只有 def
//
return _def.renderAndReturn(data, ctx);
}
}
/**
* 渲染
*
* @param data 数据
* @param ctx 上下文
*/
@Override
public void render(Object data, Context ctx) throws Throwable {
if(data instanceof DataThrowable){
return;
}
//如果是模型视图
if (data instanceof ModelAndView) {
ModelAndView mv = (ModelAndView) data;
if (Utils.isEmpty(mv.view()) == false) {
//
//如果有视图
//
int suffix_idx = mv.view().lastIndexOf(".");
if (suffix_idx > 0) {
String suffix = mv.view().substring(suffix_idx);
Render render = _mapping.get(suffix);
if (render != null) {
//如果找到对应的渲染器
//
//同步上下文特性
ctx.attrMap().forEach((k, v) -> {
mv.putIfAbsent(k, v);
});
//视图渲染
render.render(mv, ctx);
return;
}
}
//如果没有则用默认渲染器
//
_def.render(mv, ctx);
return;
} else {
data = mv.model();
}
}
if(data instanceof File) {
ctx.outputAsFile((File) data);
return;
}
//如果是文件
if(data instanceof DownloadedFile) {
ctx.outputAsFile((DownloadedFile) data);
return;
}
if(data instanceof InputStream) {
ctx.output((InputStream) data);
return;
}
Render render = resolveRander(ctx);
if (render != null) {
render.render(data, ctx);
} else {
//最后只有 def
//
_def.render(data, ctx);
}
}
/**
* 分析出渲染器
*
* @since 1.6
* */
private Render resolveRander(Context ctx){<FILL_FUNCTION_BODY>}
}
|
//@json
//@type_json
//@xml
//@protobuf
//@hessian
//
Render render = null;
String mode = ctx.header("X-Serialization");
if (Utils.isEmpty(mode)) {
mode = ctx.attr("@render");
}
if (Utils.isEmpty(mode) == false) {
render = _mapping.get(mode);
if (render == null) {
ctx.headerSet("Solon.serialization.mode", "Not supported " + mode);
}
}
if (render == null) {
if (ctx.remoting()) {
render = _mapping.get("@type_json");
}
}
if (render == null) {
render = _mapping.get("@json");
}
return render;
| 1,784
| 218
| 2,002
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/Result.java
|
Result
|
setDescription
|
class Result<T> implements Serializable {
public static int SUCCEED_CODE = 200;
public static int FAILURE_CODE = 400;
/**
* 状态码
*
* 200:成功
* 400:未知失败
* 400xxxx:明确的失败
*/
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
/**
* 状态描述
*/
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {<FILL_FUNCTION_BODY>}
/**
* 数据
*/
private T data;
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
/**
* 此方法仅用于序列化与反序列化
* */
public Result(){
this.code = SUCCEED_CODE;
this.description = "";
}
public Result(T data) {
this.code = SUCCEED_CODE;
this.description = "";
this.data = data;
}
public Result(int code, String description) {
this.code = code;
this.description = description;
}
public Result(int code, String description, T data) {
this.code = code;
this.description = description;
this.data = data;
}
/**
* 成功的空结果
*/
@Note("成功的空结果")
public static <T> Result<T> succeed() {
return new Result(SUCCEED_CODE, "");
}
/**
* 成功的结果
*/
@Note("成功的结果")
public static <T> Result<T> succeed(T data) {
return new Result<>(data);
}
@Note("成功的结果")
public static <T> Result<T> succeed(T data, String description) {
return new Result<>(SUCCEED_CODE, description, data);
}
@Note("成功的结果")
public static <T> Result<T> succeed(T data, int code) {
return new Result<>(code, "", data);
}
/**
* 成功的空结果
*/
@Note("失败的空结果")
public static <T> Result<T> failure() {
return new Result(FAILURE_CODE, "");
}
/**
* 失败的结果
*/
@Note("失败的结果")
public static <T> Result<T> failure(int code) {
return failure(code, "");
}
/**
* 失败的结果
*/
@Note("失败的结果")
public static <T> Result<T> failure(int code, String description) {
return new Result<>(code, description);
}
/**
* 失败的结果
*/
@Note("失败的结果")
public static <T> Result<T> failure(int code, String description, T data) {
return new Result<>(code, description, data);
}
@Note("失败的结果")
public static <T> Result<T> failure(String description) {
return new Result<>(FAILURE_CODE, description);
}
}
|
if (description == null) {
this.description = "";
} else {
this.description = description;
}
| 895
| 35
| 930
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/handle/SessionStateEmpty.java
|
SessionStateEmpty
|
sessionMap
|
class SessionStateEmpty implements SessionState{
private Map<String,Object> sessionMap = null;
public Map<String,Object> sessionMap(){<FILL_FUNCTION_BODY>}
@Override
public String sessionId() {
return null;
}
@Override
public String sessionChangeId() {
return null;
}
@Override
public Collection<String> sessionKeys() {
return sessionMap().keySet();
}
@Override
public <T> T sessionGet(String key, Class<T> clz) {
return (T)sessionMap().get(key);
}
@Override
public void sessionSet(String key, Object val) {
if (val == null) {
sessionRemove(key);
} else {
sessionMap().put(key, val);
}
}
@Override
public void sessionRemove(String key) {
sessionMap().remove(key);
}
@Override
public void sessionClear() {
sessionMap().clear();
}
@Override
public void sessionReset() {
sessionMap().clear();
}
}
|
if(sessionMap == null){
sessionMap = new HashMap<>();
}
return sessionMap;
| 294
| 32
| 326
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/mvc/ActionExecuteHandlerDefault.java
|
ActionExecuteHandlerDefault
|
buildArgs
|
class ActionExecuteHandlerDefault implements ActionExecuteHandler {
/**
* 是否匹配
*
* @param ctx 上下文
* @param ct 内容类型
*/
@Override
public boolean matched(Context ctx, String ct) {
return true;
}
/**
* 执行
*
* @param ctx 上下文
* @param obj 控制器
* @param mWrap 函数包装器
*/
@Override
public Object executeHandle(Context ctx, Object obj, MethodWrap mWrap) throws Throwable {
List<Object> args = buildArgs(ctx, obj, mWrap);
return mWrap.invokeByAspect(obj, args.toArray());
}
/**
* 构建执行参数
*
* @param ctx 上下文
*/
protected List<Object> buildArgs(Context ctx, Object target, MethodWrap mWrap) throws Exception {<FILL_FUNCTION_BODY>}
/**
* 尝试将body转换为特定对象
*/
protected Object changeBody(Context ctx, MethodWrap mWrap) throws Exception {
return ctx.paramMap();
}
/**
* 尝试将值按类型转换
*/
protected Object changeValue(Context ctx, ParamWrap p, int pi, Class<?> pt, Object bodyObj) throws Exception {
String pn = p.getName(); //参数名
String pv = p.getValue(ctx); //参数值
Object tv = null; //目标值
if (pv == null) {
pv = p.getDefaultValue();
}
if (pv == null) {
//
// 没有从 ctx.param 直接找到值
//
if (UploadedFile.class == pt) {
//1.如果是 UploadedFile 类型
tv = ctx.file(pn);
} else if (UploadedFile[].class == pt) {
//2.如果是 UploadedFile[] 类型
tv = Utils.toArray(ctx.files(pn), new UploadedFile[]{});
} else {
//$name 的变量,从attr里找
if (pn.startsWith("$")) {
tv = ctx.attr(pn);
} else {
if (pt.getName().startsWith("java.") || pt.isArray() || pt.isPrimitive()) {
//如果是java基础类型,则为null(后面统一地 isPrimitive 做处理)
//
tv = null;
} else {
//尝试转为实体
tv = changeEntityDo(ctx, p, pn, pt);
}
}
}
} else {
//如果拿到了具体的参数值,则开始转换
tv = changeValueDo(ctx, p, pn, pt, pv);
}
return tv;
}
/**
* 尝试将值转换为目标值
*/
protected Object changeValueDo(Context ctx, ParamWrap p, String name, Class<?> type, String value) {
return ConvertUtil.to(p, value, ctx);
}
/**
* 尝试将值转换为目标实体
*/
protected Object changeEntityDo(Context ctx, ParamWrap p, String name, Class<?> type) throws Exception {
ClassWrap clzW = ClassWrap.get(type);
Map<String, String> map = ctx.paramMap();
return clzW.newBy(map::get, ctx);
}
}
|
ParamWrap[] pSet = mWrap.getParamWraps();
List<Object> args = new ArrayList<>(pSet.length);
Object bodyObj = changeBody(ctx, mWrap);
//p 参数
//pt 参数原类型
for (int i = 0, len = pSet.length; i < len; i++) {
ParamWrap p = pSet[i];
Class<?> pt = p.getType();
if (Context.class.isAssignableFrom(pt)) {
//如果是 Context 类型,直接加入参数
//
args.add(ctx);
} else if (ModelAndView.class.isAssignableFrom(pt)) {
//如果是 ModelAndView 类型,直接加入参数
//
args.add(new ModelAndView());
} else if (Locale.class.isAssignableFrom(pt)) {
//如果是 Locale 类型,直接加入参数
//
args.add(ctx.getLocale());
} else if (UploadedFile.class == pt) {
//如果是 UploadedFile
//
args.add(ctx.file(p.getName()));
} else if (pt.isInstance(ctx.request())) { //getTypeName().equals("javax.servlet.http.HttpServletRequest")
args.add(ctx.request());
} else if (pt.isInstance(ctx.response())) { //getTypeName().equals("javax.servlet.http.HttpServletResponse")
args.add(ctx.response());
} else {
Object tv = null;
if (p.isRequiredBody()) {
//需要 body 数据
if (String.class.equals(pt)) {
tv = ctx.bodyNew();
} else if (InputStream.class.equals(pt)) {
tv = ctx.bodyAsStream();
} else if (Map.class.equals(pt) && bodyObj instanceof NvMap) {
tv = bodyObj;
}
}
if (tv == null) {
//尝试数据转换
try {
tv = changeValue(ctx, p, i, pt, bodyObj);
} catch (Exception e) {
String methodFullName = mWrap.getDeclaringClz().getName() + "::" + mWrap.getName() + "@" + p.getName();
throw new IllegalArgumentException("Action parameter change failed: " + methodFullName, e);
}
}
if (tv == null) {
//
// 如果是基类类型(int,long...),则抛出异常
//
if (pt.isPrimitive()) {
//如果是基本类型,则为给个默认值
//
if (pt == short.class) {
tv = (short) 0;
} else if (pt == int.class) {
tv = 0;
} else if (pt == long.class) {
tv = 0L;
} else if (pt == double.class) {
tv = 0d;
} else if (pt == float.class) {
tv = 0f;
} else if (pt == boolean.class) {
tv = false;
} else {
//
//其它类型不支持
//
throw new IllegalArgumentException("Please enter a valid parameter @" + p.getName());
}
}
}
if (tv == null) {
if (p.isRequiredInput()) {
ctx.status(400);
throw new IllegalArgumentException(p.getRequiredHint());
}
}
args.add(tv);
}
}
return args;
| 900
| 911
| 1,811
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/mvc/ActionParamResolver.java
|
ActionParamResolver
|
resolveParam
|
class ActionParamResolver {
/**
* 分析
*/
public static void resolve(ActionParam vo, AnnotatedElement element) {
// 分析 Body 注解
if (resolveBody(vo, element)) {
return;
}
// 分析 Param 注解
if (resolveParam(vo, element)) {
return;
}
// 分析 PathVar 注解
if (resolvePathVar(vo, element)) {
return;
}
// 分析 Path 注解
if (resolvePath(vo, element)) {
return;
}
// 分析 Header 注解
if (resolveHeader(vo, element)) {
return;
}
// 分析 Cookie 注解
resolveCookie(vo, element);
}
/**
* 分析 body 注解
*/
private static boolean resolveBody(ActionParam vo, AnnotatedElement element) {
Body bodyAnno = element.getAnnotation(Body.class);
if (bodyAnno == null) {
return false;
}
vo.isRequiredBody = true;
return true;
}
/**
* 分析 param 注解
*/
private static boolean resolveParam(ActionParam vo, AnnotatedElement element) {<FILL_FUNCTION_BODY>}
@Deprecated
private static boolean resolvePathVar(ActionParam vo, AnnotatedElement element) {
PathVar paramAnno = element.getAnnotation(PathVar.class);
if (paramAnno == null) {
return false;
}
String name2 = Utils.annoAlias(paramAnno.value(), paramAnno.name());
if (Utils.isNotEmpty(name2)) {
vo.name = name2;
}
vo.isRequiredPath = true;
vo.isRequiredInput = true;
return true;
}
private static boolean resolvePath(ActionParam vo, AnnotatedElement element) {
Path paramAnno = element.getAnnotation(Path.class);
if (paramAnno == null) {
return false;
}
String name2 = Utils.annoAlias(paramAnno.value(), paramAnno.name());
if (Utils.isNotEmpty(name2)) {
vo.name = name2;
}
vo.isRequiredPath = true;
vo.isRequiredInput = true;
return true;
}
/**
* 分析 header 注解
*/
private static boolean resolveHeader(ActionParam vo, AnnotatedElement element) {
Header headerAnno = element.getAnnotation(Header.class);
if (headerAnno == null) {
return false;
}
String name2 = Utils.annoAlias(headerAnno.value(), headerAnno.name());
if (Utils.isNotEmpty(name2)) {
vo.name = name2;
}
if (Constants.PARM_UNDEFINED_VALUE.equals(headerAnno.defaultValue()) == false) {
vo.defaultValue = headerAnno.defaultValue();
}
vo.isRequiredInput = headerAnno.required();
vo.isRequiredHeader = true;
return true;
}
/**
* 分析 cookie 注解
*/
private static boolean resolveCookie(ActionParam vo, AnnotatedElement element) {
Cookie cookieAnno = element.getAnnotation(Cookie.class);
if (cookieAnno == null) {
return false;
}
String name2 = Utils.annoAlias(cookieAnno.value(), cookieAnno.name());
if (Utils.isNotEmpty(name2)) {
vo.name = name2;
}
if (Constants.PARM_UNDEFINED_VALUE.equals(cookieAnno.defaultValue()) == false) {
vo.defaultValue = cookieAnno.defaultValue();
}
vo.isRequiredInput = cookieAnno.required();
vo.isRequiredCookie = true;
return true;
}
}
|
Param paramAnno = element.getAnnotation(Param.class);
if (paramAnno == null) {
return false;
}
String name2 = Utils.annoAlias(paramAnno.value(), paramAnno.name());
if (Utils.isNotEmpty(name2)) {
vo.name = name2;
}
if (Constants.PARM_UNDEFINED_VALUE.equals(paramAnno.defaultValue()) == false) {
vo.defaultValue = paramAnno.defaultValue();
}
vo.isRequiredInput = paramAnno.required();
return true;
| 1,044
| 161
| 1,205
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/mvc/MethodTypeResolver.java
|
MethodTypeResolver
|
findAndFill
|
class MethodTypeResolver {
public static Set<MethodType> findAndFill(Set<MethodType> list, Predicate<Class> checker) {<FILL_FUNCTION_BODY>}
}
|
if (checker.test(Get.class)) {
list.add(MethodType.GET);
}
if (checker.test(Post.class)) {
list.add(MethodType.POST);
}
if (checker.test(Put.class)) {
list.add(MethodType.PUT);
}
if (checker.test(Patch.class)) {
list.add(MethodType.PATCH);
}
if (checker.test(Delete.class)) {
list.add(MethodType.DELETE);
}
if (checker.test(Head.class)) {
list.add(MethodType.HEAD);
}
if (checker.test(Options.class)) {
list.add(MethodType.OPTIONS);
}
if (checker.test(Http.class)) {
list.add(MethodType.HTTP);
}
if (checker.test(Socket.class)) {
list.add(MethodType.SOCKET);
}
return list;
| 50
| 275
| 325
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/route/PathRule.java
|
PathRule
|
exclude
|
class PathRule implements Predicate<String> {
/**
* 拦截规则(包函规则)
*/
private List<PathAnalyzer> includeList = new ArrayList<>();
/**
* 放行规则(排除规则)
*/
private List<PathAnalyzer> excludeList = new ArrayList<>();
public PathRule include(String... patterns) {
for (String p1 : patterns) {
includeList.add(PathAnalyzer.get(p1));
}
return this;
}
public PathRule exclude(String... patterns) {<FILL_FUNCTION_BODY>}
/**
* 是否为空
* */
public boolean isEmpty(){
return includeList.isEmpty() && excludeList.isEmpty();
}
/**
* 规则检测
* */
@Override
public boolean test(String path) {
//1.放行匹配
for (PathAnalyzer pa : excludeList) {
if (pa.matches(path)) {
return false;
}
}
//2.拦截匹配
for (PathAnalyzer pa : includeList) {
if (pa.matches(path)) {
return true;
}
}
//3.无匹配,//如果有排除,又没排除掉;且没有包函;则需要处理
return (excludeList.size() > 0 && includeList.size() == 0);
}
}
|
for (String p1 : patterns) {
excludeList.add(PathAnalyzer.get(p1));
}
return this;
| 378
| 39
| 417
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/route/RouterDefault.java
|
RouterDefault
|
add
|
class RouterDefault implements Router{
//for handler
private final RoutingTable<Handler>[] routesH;
public RouterDefault() {
routesH = new RoutingTableDefault[3];
routesH[0] = new RoutingTableDefault<>();//before:0
routesH[1] = new RoutingTableDefault<>();//main
routesH[2] = new RoutingTableDefault<>();//after:2
}
/**
* 添加路由关系 for Handler
*
* @param path 路径
* @param endpoint 处理点
* @param method 方法
* @param index 顺序位
* @param handler 处理接口
*/
@Override
public void add(String path, Endpoint endpoint, MethodType method, int index, Handler handler) {<FILL_FUNCTION_BODY>}
@Override
public void remove(String pathPrefix) {
routesH[Endpoint.before.code].remove(pathPrefix);
routesH[Endpoint.main.code].remove(pathPrefix);
routesH[Endpoint.after.code].remove(pathPrefix);
}
/**
* 获取某个处理点的所有路由记录
*
* @param endpoint 处理点
* @return 处理点的所有路由记录
* */
@Override
public Collection<Routing<Handler>> getAll(Endpoint endpoint){
return routesH[endpoint.code].getAll();
}
@Override
public Collection<Routing<Handler>> getBy(String path, Endpoint endpoint) {
return routesH[endpoint.code].getBy(path);
}
/**
* 区配一个处理(根据上下文)
*
* @param ctx 上下文
* @param endpoint 处理点
* @return 一个匹配的处理
*/
@Override
public Handler matchOne(Context ctx, Endpoint endpoint) {
String pathNew = ctx.pathNew();
MethodType method = MethodTypeUtil.valueOf(ctx.method());
return routesH[endpoint.code].matchOne(pathNew, method);
}
@Override
public Handler matchMain(Context ctx) {
//不能从缓存里取,不然 pathNew 会有问题
String pathNew = ctx.pathNew();
MethodType method = MethodTypeUtil.valueOf(ctx.method());
Result<Handler> result = routesH[Endpoint.main.code].matchOneAndStatus(pathNew, method);
if (result.getData() != null) {
ctx.attrSet(Constants.mainHandler, result.getData());
} else {
ctx.attrSet(Constants.mainStatus, result.getCode());
}
return result.getData();
}
/**
* 区配多个处理(根据上下文)
*
* @param ctx 上下文
* @param endpoint 处理点
* @return 一批匹配的处理
*/
@Override
public List<Handler> matchMore(Context ctx, Endpoint endpoint) {
String pathNew = ctx.pathNew();
MethodType method = MethodTypeUtil.valueOf(ctx.method());
return routesH[endpoint.code].matchMore(pathNew, method);
}
/**
* 清空路由关系
*/
@Override
public void clear() {
routesH[0].clear();
routesH[1].clear();
routesH[2].clear();
}
}
|
RoutingDefault routing = new RoutingDefault<>(path, method, index, handler);
if (path.contains("*") || path.contains("{")) {
routesH[endpoint.code].add(routing);
} else {
//没有*号的,优先
routesH[endpoint.code].add(0, routing);
}
| 883
| 91
| 974
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/route/RouterHandler.java
|
RouterHandler
|
handleTriggers
|
class RouterHandler implements Handler, RouterInterceptor {
private Router router;
public RouterHandler(Router router) {
this.router = router;
}
//拦截实现
@Override
public void doIntercept(Context ctx, @Nullable Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
handleDo(ctx, mainHandler);
}
/**
* 主处理
*/
protected boolean handleMain(Handler h, Context ctx) throws Throwable {
if (h != null) {
h.handle(ctx);
return ctx.status() != 404;
} else {
return false;
}
}
/**
* 触发器处理(链式拦截)
*/
protected void handleTriggers(Context ctx, Endpoint endpoint) throws Throwable {<FILL_FUNCTION_BODY>}
private void handleDo(Context x, Handler mainHandler) throws Throwable {
//可能上级链已完成处理
if (x.getHandled()) {
return;
}
try {
//前置触发器(支持多处理)
handleTriggers(x, Endpoint.before);
//主体处理
if (x.getHandled() == false) {
//(仅支持唯一代理)
//(设定处理状态,便于 after 获取状态)
x.setHandled(handleMain(mainHandler, x));
}
} catch (Throwable e) {
if (x.errors == null) {
x.errors = e; //如果内部已经做了,就不需要了
}
throw e;
} finally {
//后置触发器(支持多处理)
handleTriggers(x, Endpoint.after); //前后不能反 (后置处理由内部进行状态控制)
}
}
@Override
public void handle(Context x) throws Throwable {
//可能上级链已完成处理
if (x.getHandled()) {
return;
}
//提前获取主处理
Handler mainHandler = router.matchMain(x);
//预处理 action
if (mainHandler instanceof Action) {
x.attrSet(Constants.action, mainHandler);
}
//执行
Solon.app().chainManager().doIntercept(x, mainHandler);
}
}
|
for (Handler h : router.matchMore(ctx, endpoint)) {
h.handle(ctx);
}
| 626
| 31
| 657
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/route/RouterInterceptorLimiter.java
|
RouterInterceptorLimiter
|
postResult
|
class RouterInterceptorLimiter implements RouterInterceptor {
protected final PathRule rule;
private final RouterInterceptor interceptor;
public RouterInterceptorLimiter(RouterInterceptor interceptor, PathRule rule) {
this.rule = rule;
this.interceptor = interceptor;
}
/**
* 是否匹配
*/
protected boolean isMatched(Context ctx) {
return rule == null || rule.isEmpty() || rule.test(ctx.pathNew());
}
/**
* 获取拦截器
* */
public RouterInterceptor getInterceptor() {
return interceptor;
}
/**
* 路径匹配模式
* */
@Override
public PathRule pathPatterns() {
return rule;
}
@Override
public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
if (isMatched(ctx)) {
//执行拦截
interceptor.doIntercept(ctx, mainHandler, chain);
} else {
//原路传递
chain.doIntercept(ctx, mainHandler);
}
}
@Override
public Object postResult(Context ctx, Object result) throws Throwable {<FILL_FUNCTION_BODY>}
}
|
if (isMatched(ctx)) {
return interceptor.postResult(ctx, result);
} else {
return result;
}
| 355
| 41
| 396
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/route/RoutingTableDefault.java
|
RoutingTableDefault
|
matchOne
|
class RoutingTableDefault<T> implements RoutingTable<T> {
private List<Routing<T>> table = new ArrayList<>();
/**
* 添加路由记录
*
* @param routing 路由
*/
@Override
public void add(Routing<T> routing) {
table.add(routing);
}
/**
* 添加路由记录
*
* @param routing 路由
* @param index 索引位置
*/
@Override
public void add(int index, Routing<T> routing) {
table.add(index, routing);
}
@Override
public void remove(String pathPrefix) {
table.removeIf(l -> l.path().startsWith(pathPrefix));
}
@Override
public int count() {
return table.size();
}
@Override
public Collection<Routing<T>> getAll() {
return Collections.unmodifiableList(table);
}
@Override
public Collection<Routing<T>> getBy(String path) {
return table.stream()
.filter(l -> l.test(path))
.sorted(Comparator.comparingInt(l -> l.index()))
.collect(Collectors.toList());
}
/**
* 区配一个目标
*
* @param path 路径
* @param method 方法
* @return 一个区配的目标
*/
public T matchOne(String path, MethodType method) {<FILL_FUNCTION_BODY>}
/**
* 区配一个目标并给出状态
*
* @param path 路径
* @param method 方法
* @return 一个区配的目标
*/
@Override
public Result<T> matchOneAndStatus(String path, MethodType method) {
int degrees = 0;
for (Routing<T> l : table) {
int tmp = l.degrees(method, path);
if (tmp == 2) {
return Result.succeed(l.target());
} else {
if (tmp > degrees) {
degrees = tmp;
}
}
}
if (degrees == 1) {
return Result.failure(405);
} else {
return Result.failure(404);
}
}
/**
* 区配多个目标
*
* @param path 路径
* @param method 方法
* @return 一批区配的目标
*/
public List<T> matchMore(String path, MethodType method) {
return table.stream()
.filter(l -> l.matches(method, path))
.sorted(Comparator.comparingInt(l -> l.index()))
.map(l -> l.target())
.collect(Collectors.toList());
}
@Override
public void clear() {
table.clear();
}
}
|
for (Routing<T> l : table) {
if (l.matches(method, path)) {
return l.target();
}
}
return null;
| 778
| 50
| 828
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/runtime/AotCollector.java
|
AotCollector
|
registerEntityType
|
class AotCollector {
private final Set<Class<?>> entityTypes = new LinkedHashSet<>();
private final Set<Class<?>> jdkProxyTypes = new LinkedHashSet<>();
/**
* 获取实体类型
*/
public Set<Class<?>> getEntityTypes() {
return entityTypes;
}
/**
* 获取Jdk代理类型
*/
public Set<Class<?>> getJdkProxyTypes() {
return jdkProxyTypes;
}
/**
* 注册实体类型
*/
public void registerEntityType(Class<?> type, ParameterizedType genericType) {<FILL_FUNCTION_BODY>}
/**
* 注册jdk代理类型
*/
public void registerJdkProxyType(Class<?> type, Object target) {
if (NativeDetector.isAotRuntime()) {
if (Proxy.isProxyClass(target.getClass())) {
if (type.getName().startsWith("java.") == false) {
jdkProxyTypes.add(type);
}
}
}
}
/**
* 清空
*/
public void clear() {
entityTypes.clear();
jdkProxyTypes.clear();
}
}
|
if (NativeDetector.isAotRuntime()) {
if (type.getName().startsWith("java.") == false) {
entityTypes.add(type);
}
if (genericType != null) {
for (Type type1 : genericType.getActualTypeArguments()) {
if (type1 instanceof Class) {
if (type1.getTypeName().startsWith("java.") == false) {
entityTypes.add((Class<?>) type1);
}
}
}
}
}
| 322
| 137
| 459
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ClassUtil.java
|
ClassUtil
|
hasClass
|
class ClassUtil {
/**
* 是否存在某个类
*
* <pre><code>
* if(ClassUtil.hasClass(()->DemoTestClass.class)){
* ...
* }
* </code></pre>
*
* @param test 检测函数
*/
public static boolean hasClass(SupplierEx<Class<?>> test) {<FILL_FUNCTION_BODY>}
/**
* 根据字符串加载为一个类(如果类不存在返回 null)
*
* @param className 类名称
*/
public static Class<?> loadClass(String className) {
return loadClass(null, className);
}
/**
* 根据字符串加载为一个类(如果类不存在返回 null)
*
* @param classLoader 类加载器
* @param className 类名称
*/
public static Class<?> loadClass(ClassLoader classLoader, String className) {
try {
if (classLoader == null) {
return Class.forName(className);
} else {
return classLoader.loadClass(className);
}
} catch (ClassNotFoundException | NoClassDefFoundError e) {
return null;
}
}
/**
* 尝试根据类名实例化一个对象(如果类不存在返回 null)
*
* @param className 类名称
*/
public static <T> T tryInstance(String className) {
return tryInstance(className, null);
}
/**
* 尝试根据类名实例化一个对象(如果类不存在返回 null)
*
* @param className 类名称
* @param prop 属性
*/
public static <T> T tryInstance(String className, Properties prop) {
return tryInstance(AppClassLoader.global(), className, prop);
}
/**
* 尝试根据类名实例化一个对象(如果类不存在返回 null)
*
* @param classLoader 类加载器
* @param className 类名称
*/
public static <T> T tryInstance(ClassLoader classLoader, String className) {
return tryInstance(classLoader, className, null);
}
/**
* 尝试根据类名实例化一个对象(如果类不存在返回 null)
*
* @param classLoader 类加载器
* @param className 类名称
* @param prop 属性
*/
public static <T> T tryInstance(ClassLoader classLoader, String className, Properties prop) {
Class<?> clz = loadClass(classLoader, className);
return tryInstance(clz, prop);
}
public static <T> T tryInstance(Class<?> clz, Properties prop) {
if (clz == null) {
return null;
} else {
try {
return newInstance(clz, prop);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
/**
* 根据类名实例化一个对象
*
* @param clz 类
*/
public static <T> T newInstance(Class<?> clz) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
return newInstance(clz, null);
}
/**
* 根据类名实例化一个对象
*
* @param clz 类
* @param prop 属性
*/
public static <T> T newInstance(Class<?> clz, Properties prop) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
if (prop == null) {
return (T) clz.getDeclaredConstructor().newInstance();
} else {
return (T) clz.getConstructor(Properties.class).newInstance(prop);
}
}
/////////////////
/**
* @deprecated 2.3
*/
@Deprecated
public static <T> T newInstance(String className) {
return tryInstance(className);
}
/**
* @deprecated 2.3
*/
@Deprecated
public static <T> T newInstance(String className, Properties prop) {
return tryInstance(className, prop);
}
/**
* @deprecated 2.3
*/
@Deprecated
public static <T> T newInstance(ClassLoader classLoader, String className) {
return tryInstance(classLoader, className);
}
/**
* @deprecated 2.3
*/
@Deprecated
public static <T> T newInstance(ClassLoader classLoader, String className, Properties prop) {
return tryInstance(classLoader, className, prop);
}
}
|
try {
test.get();
return true;
} catch (ClassNotFoundException | NoClassDefFoundError e) {
return false;
} catch (Throwable e) {
throw new IllegalStateException(e);
}
| 1,262
| 63
| 1,325
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ConditionUtil.java
|
ConditionUtil
|
test
|
class ConditionUtil {
/**
* 是否有 Missing 条件
* */
public static boolean ifMissing(Condition anno) {
if (anno == null) {
return false;
} else {
try {
return (anno.onMissingBean() != Void.class) || Utils.isNotEmpty(anno.onMissingBeanName());
} catch (Throwable e) {
//如果 onMissingBean 的类是不存在的,会出错
return true;
}
}
}
/**
* 检测条件
* */
public static boolean test(AppContext context, AnnotatedElement element) {
Condition anno = element.getAnnotation(Condition.class);
return test(context, anno);
}
/**
* 检测条件
* */
public static boolean test(AppContext context, Condition anno){<FILL_FUNCTION_BODY>}
private static boolean testNo(AppContext context, Condition anno) {
try {
anno.onClass();
} catch (Throwable e) {
//异常,表示不存在类
return true;
}
if (Utils.isNotEmpty(anno.onClassName())) {
if (ClassUtil.loadClass(context.getClassLoader(), anno.onClassName()) == null) {
//如果null,表示不存在类
return true;
}
}
if (Utils.isNotEmpty(anno.onProperty())) {
String[] kv = anno.onProperty().split("=");
if (kv.length > 1) {
String val = context.cfg().getByExpr(kv[0].trim());
//值要等于kv[1] (val 可能为 null)
if (kv[1].trim().equals(val) == false) {
return true;
}
} else {
String val = context.cfg().getByExpr(anno.onProperty());
//有值就行
if (Utils.isNotEmpty(val) == false) {
return true;
}
}
}
try {
if (anno.onMissingBean() != Void.class) {
if (context.hasWrap(anno.onMissingBean())) {
return true;
}
}
}catch (Throwable e){
//如果 onMissingBean 的类是不存在的,会异常 //异常跳过,不用管
}
if (Utils.isNotEmpty(anno.onMissingBeanName())) {
if (context.hasWrap(anno.onMissingBeanName())) {
return true;
}
}
return false;
}
}
|
if (anno == null) {
return true;
} else {
return testNo(context, anno) == false;
}
| 685
| 40
| 725
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/GenericUtil.java
|
GenericUtil
|
getGenericInfo
|
class GenericUtil {
/**
* 分析类型参数
*
* <pre><code>
* public class DemoEventListener extend EventListener<Demo>{ }
* Class<?>[] tArgs = GenericUtil.resolveTypeArguments(DemoEventListener.class, EventListener.class);
* assert tArgs[0] == Demo.class
* </code></pre>
* @param clazz 类型
* @param genericIfc 泛型接口
* */
public static Class<?>[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc) {
for (Type type0 : clazz.getGenericInterfaces()) {
if (type0 instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) type0;
Class<?> rawType = (Class<?>) type.getRawType();
if (rawType == genericIfc || getGenericInterfaces(rawType).contains(genericIfc)) {
return Arrays.stream(type.getActualTypeArguments())
.map(item -> (Class<?>) item)
.toArray(Class[]::new);
}
}
}
Type type1 = clazz.getGenericSuperclass();
if (type1 instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) type1;
return Arrays.stream(type.getActualTypeArguments())
.map(item -> (Class<?>) item)
.toArray(Class[]::new);
}
return null;
}
/**
* 获取指定类的所有父类
*
* @param clazz 要获取的类
* @return 所有父类
*/
private static List<Class<?>> getGenericInterfaces(Class<?> clazz) {
return getGenericInterfaces(clazz, new ArrayList<>());
}
/**
* 获取指定类的所有父类
*
* @param clazz 要获取的类
* @return 所有父类
*/
private static List<Class<?>> getGenericInterfaces(Class<?> clazz, List<Class<?>> classes) {
Type[] interfaces = clazz.getGenericInterfaces();
for (Type type : interfaces) {
if (type instanceof ParameterizedType) {
Class<?> aClass = (Class<?>) ((ParameterizedType) type).getRawType();
classes.add(aClass);
for (Type type0 : aClass.getGenericInterfaces()) {
if (type0 instanceof ParameterizedType) {
Class<?> clazz0 = (Class<?>) ((ParameterizedType) type0).getRawType();
classes.add(clazz0);
getGenericInterfaces(clazz0, classes);
}
}
}
}
return classes;
}
/**
* 转换为参数化类型
* */
public static ParameterizedType toParameterizedType(Type type) {
ParameterizedType result = null;
if (type instanceof ParameterizedType) {
result = (ParameterizedType) type;
} else if (type instanceof Class) {
final Class<?> clazz = (Class<?>) type;
Type genericSuper = clazz.getGenericSuperclass();
if (null == genericSuper || Object.class.equals(genericSuper)) {
// 如果类没有父类,而是实现一些定义好的泛型接口,则取接口的Type
final Type[] genericInterfaces = clazz.getGenericInterfaces();
if (genericInterfaces != null && genericInterfaces.length > 0) {
// 默认取第一个实现接口的泛型Type
genericSuper = genericInterfaces[0];
}
}
result = toParameterizedType(genericSuper);
}
return result;
}
///////////////////////////
private static final Map<Type, Map<String, Type>> genericInfoCached = new HashMap<>();
/**
* 获取泛型变量和泛型实际类型的对应关系Map
*
* @param type 被解析的包含泛型参数的类
* @return 泛型对应关系Map
*/
public static Map<String, Type> getGenericInfo(Type type) {<FILL_FUNCTION_BODY>}
/**
* 创建类中所有的泛型变量和泛型实际类型的对应关系Map
*
* @param type 被解析的包含泛型参数的类
* @return 泛型对应关系Map
*/
private static Map<String, Type> createTypeGenericMap(Type type) {
final Map<String, Type> typeMap = new HashMap<>();
// 按继承层级寻找泛型变量和实际类型的对应关系
// 在类中,对应关系分为两类:
// 1. 父类定义变量,子类标注实际类型
// 2. 父类定义变量,子类继承这个变量,让子类的子类去标注,以此类推
// 此方法中我们将每一层级的对应关系全部加入到Map中,查找实际类型的时候,根据传入的泛型变量,
// 找到对应关系,如果对应的是继承的泛型变量,则递归继续找,直到找到实际或返回null为止。
// 如果传入的非Class,例如TypeReference,获取到泛型参数中实际的泛型对象类,继续按照类处理
while (null != type) {
final ParameterizedType parameterizedType = toParameterizedType(type);
if(null == parameterizedType){
break;
}
final Type[] typeArguments = parameterizedType.getActualTypeArguments();
final Class<?> rawType = (Class<?>) parameterizedType.getRawType();
final TypeVariable[] typeParameters = rawType.getTypeParameters();
Type value;
for (int i = 0; i < typeParameters.length; i++) {
value = typeArguments[i];
// 跳过泛型变量对应泛型变量的情况
if(false == value instanceof TypeVariable){
typeMap.put(typeParameters[i].getTypeName(), value);
}
}
type = rawType;
}
return typeMap;
}
}
|
Map<String, Type> tmp = genericInfoCached.get(type);
if (tmp == null) {
Utils.locker().lock();
try {
tmp = genericInfoCached.get(type);
if (tmp == null) {
tmp = createTypeGenericMap(type);
genericInfoCached.put(type, tmp);
}
} finally {
Utils.locker().unlock();
}
}
return tmp;
| 1,603
| 123
| 1,726
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/IndexBuilder.java
|
IndexBuilder
|
buildIndexDo
|
class IndexBuilder {
private final Map<String, Integer> map = new HashMap<>();
private final ArrayList<String> classStack = new ArrayList<>();
/**
* 获取bean的初始化index
*
* @param clazz bean类
* @return 顺序index
*/
public int buildIndex(Class<?> clazz) {
return buildIndexDo(clazz, true);
}
/**
* 获取bean的初始化index
*
* @param clazz bean类
* @param stackTop 是否为查找栈顶
* @return 顺序index
*/
private int buildIndexDo(Class<?> clazz, Boolean stackTop) {<FILL_FUNCTION_BODY>}
/**
* 寻找依赖类
*
* @param clazz
* @return 依赖类集合
*/
private List<Class<?>> findRelateClass(Class<?> clazz) {
List<Class<?>> clazzList = new ArrayList<>();
Field[] fields = ReflectUtil.getDeclaredFields(clazz);
for (Field field : fields) {
if (field.isAnnotationPresent(Inject.class)) {
Inject inject = field.getAnnotation(Inject.class);
if (inject.value().contains("${")) {
//注入的是参数, 略过
continue;
}
if (clazz.equals(field.getType())) {
//自己注入自己,略过
continue;
}
clazzList.add(field.getType());
}
}
return clazzList;
}
/**
* 检查是否循环依赖
*
* @param clazz
* @return 是否循环依赖
*/
private boolean isLoopRelate(Class<?> clazz, String topName) {
if (classStack.contains(clazz.getName())) {
return false;
}
classStack.add(clazz.getName()); // 入栈
//寻找依赖类
List<Class<?>> clazzList = findRelateClass(clazz);
for (Class<?> clazzRelate : clazzList) {
if (clazzRelate.getName().equals(topName)) {
classStack.add(clazzRelate.getName()); // 入栈
return true;
}
}
for (Class<?> clazzRelate : clazzList) {
if (isLoopRelate(clazzRelate, topName)) {
return true;
}
}
classStack.remove(clazz.getName()); // 出栈
return false;
}
}
|
if (stackTop) {
classStack.clear();
if (isLoopRelate(clazz, clazz.getName())) {
String link = "";
for (int i = 0; i < classStack.size(); i++) {
link += classStack.get(i);
if (i != classStack.size() - 1) {
link += " -> ";
}
}
throw new IllegalStateException("Lifecycle does not support dependency loops: " + link);
}
}
if (map.get(clazz.getName()) != null) {
return map.get(clazz.getName());
} else {
// 找到他的依赖类
List<Class<?>> clazzList = findRelateClass(clazz);
// 没有依赖类, 直接返回0
if (clazzList.size() == 0) {
map.put(clazz.getName(), 0);
return 0;
}
// 找到依赖类中最大的index
Integer maxIndex = null;
for (Class<?> clazzRelate : clazzList) {
// 避免进入死循环
if (classStack.contains(clazzRelate.getName())) {
continue;
} else {
classStack.add(clazzRelate.getName());
}
int index = buildIndexDo(clazzRelate, false);
if (maxIndex == null) {
maxIndex = index;
} else if (maxIndex < index) {
maxIndex = index;
}
}
if (maxIndex == null) {
maxIndex = 0;
}
// 返回maxIndex + 1
map.put(clazz.getName(), maxIndex + 1);
return maxIndex + 1;
}
| 691
| 473
| 1,164
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/IndexUtil.java
|
IndexUtil
|
buildGatherIndex0
|
class IndexUtil {
/**
* 构建生命周期执行顺序位
*/
public static int buildLifecycleIndex(Class<?> clz) {
return new IndexBuilder().buildIndex(clz);
}
/**
* 构建变量收集器的检查顺序位
*/
public static int buildGatherIndex(InjectGather g1, List<InjectGather> gathers) {
Set<Class<?>> clazzStack = new HashSet<>();
return buildGatherIndex0(g1, gathers, clazzStack);
}
private static int buildGatherIndex0(InjectGather g1, List<InjectGather> gathers, Set<Class<?>> clazzStack) {<FILL_FUNCTION_BODY>}
}
|
if (g1.index > 0) {
return g1.index;
}
for (VarHolder v1 : g1.getVars()) {
if (v1.isDone() == false) {
if (clazzStack.contains(v1.getType())) {
//避免死循环
Optional<InjectGather> tmp = gathers.stream()
.filter(g2 -> g2.getOutType().equals(v1.getType()))
.findFirst();
if(tmp.isPresent()){
int index = tmp.get().index + 1;
if(g1.index < index){
g1.index = index;
}
}
continue;
} else {
clazzStack.add(v1.getType());
}
Optional<InjectGather> tmp = gathers.stream()
.filter(g2 -> g2.getOutType().equals(v1.getType()))
.findFirst();
if (tmp.isPresent()) {
int index = buildGatherIndex0(tmp.get(), gathers, clazzStack) + 1;
if (g1.index < index) {
g1.index = index;
}
}
}
}
return g1.index;
| 201
| 330
| 531
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/IoUtil.java
|
IoUtil
|
transferTo
|
class IoUtil {
public static String transferToString(InputStream ins) throws IOException {
return transferToString(ins, Solon.encoding());
}
/**
* 将输入流转换为字符串
*
* @param ins 输入流
* @param charset 字符集
*/
public static String transferToString(InputStream ins, String charset) throws IOException {
if (ins == null) {
return null;
}
ByteArrayOutputStream outs = transferTo(ins, new ByteArrayOutputStream());
if (Utils.isEmpty(charset)) {
return outs.toString();
} else {
return outs.toString(charset);
}
}
/**
* 将输入流转换为byte数组
*
* @param ins 输入流
*/
public static byte[] transferToBytes(InputStream ins) throws IOException {
if (ins == null) {
return null;
}
return transferTo(ins, new ByteArrayOutputStream()).toByteArray();
}
/**
* 将输入流转换为输出流
*
* @param ins 输入流
* @param out 输出流
*/
public static <T extends OutputStream> T transferTo(InputStream ins, T out) throws IOException {
if (ins == null || out == null) {
return null;
}
int len = 0;
byte[] buf = new byte[512];
while ((len = ins.read(buf)) != -1) {
out.write(buf, 0, len);
}
return out;
}
/**
* 将输入流转换为输出流
*
* @param ins 输入流
* @param out 输出流
* @param start 开始位
* @param length 长度
*/
public static <T extends OutputStream> T transferTo(InputStream ins, T out, long start, long length) throws IOException {<FILL_FUNCTION_BODY>}
}
|
int len = 0;
byte[] buf = new byte[512];
int bufMax = buf.length;
if (length < bufMax) {
bufMax = (int) length;
}
if (start > 0) {
ins.skip(start);
}
while ((len = ins.read(buf, 0, bufMax)) != -1) {
out.write(buf, 0, len);
length -= len;
if (bufMax > length) {
bufMax = (int) length;
if (bufMax == 0) {
break;
}
}
}
return out;
| 509
| 173
| 682
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/IpUtil.java
|
IpUtil
|
getRealIp
|
class IpUtil {
//
// 可以进行替换扩展
//
private static IpUtil global = new IpUtil();
public static IpUtil global() {
return global;
}
public static void globalSet(IpUtil instance) {
if (instance != null) {
global = instance;
}
}
/**
* 获取 Ip
* */
public String getRealIp(Context ctx) {<FILL_FUNCTION_BODY>}
}
|
//客户端ip
String ip = ctx.header("X-Real-IP");
if (Utils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
//包含了客户端和各级代理ip的完整ip链路
ip = ctx.headerOrDefault("X-Forwarded-For", "");
if (ip.contains(",")) {
ip = ip.split(",")[0];
}
}
if (Utils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = ctx.remoteIp();
}
return ip;
| 135
| 154
| 289
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/LogUtil.java
|
LogUtil
|
error
|
class LogUtil {
private static LogUtil global;
static {
//(静态扩展约定:org.noear.solon.extend.impl.XxxxExt)
global = ClassUtil.tryInstance("org.noear.solon.extend.impl.LogUtilExt");
if (global == null) {
global = new LogUtil();
}
}
public static LogUtil global() {
return global;
}
/**
* 框架标题
*/
protected static String title() {
return "[Solon] ";
}
public void trace(String content) {
System.out.print(title());
PrintUtil.purpleln(content);
}
/**
* @deprecated 2.7
*/
@Deprecated
public void debugAsync(String content) {
RunUtil.async(() -> {
debug(content);
});
}
public void debug(String content) {
System.out.print(title());
PrintUtil.blueln(content);
}
/**
* @deprecated 2.7
*/
@Deprecated
public void infoAsync(String content) {
RunUtil.async(() -> {
info(content);
});
}
public void info(String content) {
System.out.print(title());
System.out.println(content);
}
public void warn(String content) {
warn(content, null);
}
public void warn(String content, Throwable throwable) {
System.out.print(title());
PrintUtil.yellowln("WARN: " + content);
if (throwable != null) {
throwable.printStackTrace();
}
}
public void error(String content) {
error(content, null);
}
public void error(String content, Throwable throwable) {<FILL_FUNCTION_BODY>}
}
|
System.out.print(title());
PrintUtil.redln("ERROR: " + content);
if (throwable != null) {
throwable.printStackTrace();
}
| 506
| 51
| 557
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/NamedThreadFactory.java
|
NamedThreadFactory
|
newThread
|
class NamedThreadFactory implements ThreadFactory {
private final String namePrefix;
private final AtomicInteger threadCount = new AtomicInteger(0);
private ThreadGroup group;
private boolean daemon = false;
private int priority = Thread.NORM_PRIORITY;
/**
* @param namePrefix 名字前缀
*/
public NamedThreadFactory(String namePrefix) {
if (Utils.isEmpty(namePrefix)) {
this.namePrefix = this.getClass().getSimpleName() + "-";
} else {
this.namePrefix = namePrefix;
}
}
/**
* 线程组
*/
public NamedThreadFactory group(ThreadGroup group) {
this.group = group;
return this;
}
/**
* 线程守护
*/
public NamedThreadFactory daemon(boolean daemon) {
this.daemon = daemon;
return this;
}
/**
* 优先级
*/
public NamedThreadFactory priority(int priority) {
this.priority = priority;
return this;
}
@Override
public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>}
}
|
Thread t = new Thread(group, r, namePrefix + threadCount.incrementAndGet());
t.setDaemon(daemon);
t.setPriority(priority);
return t;
| 320
| 52
| 372
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ParameterizedTypeImpl.java
|
ParameterizedTypeImpl
|
toString
|
class ParameterizedTypeImpl implements ParameterizedType {
private final Type[] actualTypeArguments;
private final Class<?> rawType;
private final Type ownerType;
public ParameterizedTypeImpl(Class<?> rawType,
Type[] actualTypeArguments,
Type ownerType) {
this.actualTypeArguments = actualTypeArguments;
this.rawType = rawType;
this.ownerType = (ownerType != null) ? ownerType : rawType.getDeclaringClass();
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return ownerType;
}
@Override
public boolean equals(Object o) {
if (o instanceof ParameterizedType) {
ParameterizedType that = (ParameterizedType) o;
if (this == that)
return true;
Type thatOwner = that.getOwnerType();
Type thatRawType = that.getRawType();
return Objects.equals(ownerType, thatOwner) &&
Objects.equals(rawType, thatRawType) &&
Arrays.equals(actualTypeArguments, // avoid clone
that.getActualTypeArguments());
} else
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(actualTypeArguments) ^
Objects.hashCode(ownerType) ^
Objects.hashCode(rawType);
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder();
if (ownerType != null) {
sb.append(ownerType.getTypeName());
sb.append("$");
if (ownerType instanceof ParameterizedTypeImpl) {
// Find simple name of nested type by removing the
// shared prefix with owner.
sb.append(rawType.getName().replace(((ParameterizedTypeImpl) ownerType).rawType.getName() + "$",
""));
} else
sb.append(rawType.getSimpleName());
} else
sb.append(rawType.getName());
if (actualTypeArguments != null) {
StringJoiner sj = new StringJoiner(", ", "<", ">");
sj.setEmptyValue("");
for (Type t : actualTypeArguments) {
sj.add(t.getTypeName());
}
sb.append(sj.toString());
}
return sb.toString();
| 421
| 243
| 664
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/PathAnalyzer.java
|
PathAnalyzer
|
get
|
class PathAnalyzer {
/**
* 区分大小写(默认区分)
*/
private static boolean caseSensitive = true;
/**
* 分析器缓存
*/
private static final Map<String, PathAnalyzer> cached = new LinkedHashMap<>();
public static void setCaseSensitive(boolean caseSensitive) {
PathAnalyzer.caseSensitive = caseSensitive;
}
public static PathAnalyzer get(String expr) {<FILL_FUNCTION_BODY>}
private Pattern pattern;
private Pattern patternNoStart;
private PathAnalyzer(String expr) {
if (caseSensitive) {
pattern = Pattern.compile(exprCompile(expr, true));
if(expr.contains("{")){
patternNoStart = Pattern.compile(exprCompile(expr, false));
}
} else {
pattern = Pattern.compile(exprCompile(expr, true), Pattern.CASE_INSENSITIVE);
if(expr.contains("{")){
patternNoStart = Pattern.compile(exprCompile(expr, false), Pattern.CASE_INSENSITIVE);
}
}
}
/**
* 路径匹配变量
*/
public Matcher matcher(String uri) {
if (patternNoStart != null) {
return patternNoStart.matcher(uri);
} else {
return pattern.matcher(uri);
}
}
/**
* 检测是否匹配
*/
public boolean matches(String uri) {
return pattern.matcher(uri).find();
}
/**
* 将路径表达式编译为正则表达式
*/
private static String exprCompile(String expr, boolean fixedStart) {
//替换特殊符号
String p = expr;
p = p.replace(".", "\\.");
p = p.replace("$", "\\$");
//替换中间的**值
p = p.replace("**", ".[]");
//替换*值
p = p.replace("*", "[^/]*");
//替换{x}值
if (p.indexOf("{") >= 0) {
if (p.indexOf("_}") > 0) {
p = p.replaceAll("\\{[^\\}]+?\\_\\}", "(.+)");
}
p = p.replaceAll("\\{[^\\}]+?\\}", "([^/]+)");//不采用group name,可解决_的问题
}
if (p.startsWith("/") == false) {
p = "/" + p;
}
p = p.replace(".[]", ".*");
//整合并输出
if (fixedStart) {
return "^" + p + "$";
} else {
return p + "$";
}
}
}
|
PathAnalyzer pa = cached.get(expr);
if (pa == null) {
Utils.locker().lock();
try {
pa = cached.get(expr);
if (pa == null) {
pa = new PathAnalyzer(expr);
cached.put(expr, pa);
}
} finally {
Utils.locker().unlock();
}
}
return pa;
| 754
| 110
| 864
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/PathUtil.java
|
PathUtil
|
pathVarMap
|
class PathUtil {
/**
* 合并两个路径
*/
public static String mergePath(String path1, String path2) {
if (Utils.isEmpty(path1) || "**".equals(path1) || "/**".equals(path1)) {
if (path2.startsWith("/")) {
return path2;
} else {
return "/" + path2;
}
}
if (path1.startsWith("/") == false) {
path1 = "/" + path1;
}
if (Utils.isEmpty(path2)) {
if (path1.endsWith("*")) {
//支持多个*情况
int idx = path1.lastIndexOf('/') + 1;
if (idx < 1) {
return "/";
} else {
return path1.substring(0, idx) + path2;
}
}else {
return path1;
}
}
if (path2.startsWith("/")) {
path2 = path2.substring(1);
}
if (path1.endsWith("/")) {
return path1 + path2;
} else {
if (path1.endsWith("*")) {
//支持多个*情况
int idx = path1.lastIndexOf('/') + 1;
if (idx < 1) {
return path2;
} else {
return path1.substring(0, idx) + path2;
}
} else {
return path1 + "/" + path2;
}
}
}
public static final Pattern pathKeyExpr = Pattern.compile("\\{([^\\\\}]+)\\}");
/**
* 将路径根据表达式转成map
* */
public static NvMap pathVarMap(String path, String expr) {<FILL_FUNCTION_BODY>}
}
|
NvMap _map = new NvMap();
//支持path变量
if (expr.indexOf("{") >= 0) {
String path2 = null;
try {
path2 = URLDecoder.decode(path, Solon.encoding());
} catch (Throwable ex) {
path2 = path;
}
Matcher pm = pathKeyExpr.matcher(expr);
List<String> _pks = new ArrayList<>();
while (pm.find()) {
_pks.add(pm.group(1));
}
if (_pks.size() > 0) {
PathAnalyzer _pr = PathAnalyzer.get(expr);
pm = _pr.matcher(path2);
if (pm.find()) {
for (int i = 0, len = _pks.size(); i < len; i++) {
_map.put(_pks.get(i), pm.group(i + 1));//不采用group name,可解决_的问题
}
}
}
}
return _map;
| 483
| 275
| 758
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/PluginUtil.java
|
PluginUtil
|
scanPlugins
|
class PluginUtil {
/**
* 扫描插件
*
* @param classLoader 类加载器
* @param limitFile 限制文件
*/
public static void scanPlugins(ClassLoader classLoader, String limitFile, Consumer<PluginEntity> consumer) {<FILL_FUNCTION_BODY>}
/**
* 查找插件
*/
public static void findPlugins(ClassLoader classLoader, Properties props, Consumer<PluginEntity> consumer) {
String pluginStr = props.getProperty("solon.plugin");
if (Utils.isNotEmpty(pluginStr)) {
int priority = Integer.parseInt(props.getProperty("solon.plugin.priority", "0"));
String[] plugins = pluginStr.trim().split(",");
for (String clzName : plugins) {
if (clzName.length() > 0) {
PluginEntity ent = new PluginEntity(classLoader, clzName.trim(), props);
ent.setPriority(priority);
consumer.accept(ent);
}
}
}
}
}
|
//3.查找插件配置(如果出错,让它抛出异常)
ScanUtil.scan(classLoader, "META-INF/solon", n -> {
return n.endsWith(".properties") || n.endsWith(".yml");
})
.stream()
.map(k -> {
URL resource = ResourceUtil.getResource(classLoader, k);
if (resource == null) {
// native 时,扫描出来的resource可能是不存在的(这种情况就是bug),需要给于用户提示,反馈给社区
LogUtil.global().warn("solon plugin: name=" + k + ", resource is null");
}
return resource;
})
.filter(url -> {
if (url == null) {
return false;
} else {
if (Utils.isNotEmpty(limitFile)) {
return url.toString().contains(limitFile);
}
return true;
}
})
.forEach(url -> {
Properties props = Utils.loadProperties(url);
findPlugins(classLoader, props, consumer);
});
| 283
| 287
| 570
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/PrintUtil.java
|
PrintUtil
|
colorln
|
class PrintUtil {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
public static void blackln(Object txt) {
colorln(ANSI_BLACK, txt);
}
public static void redln(Object txt) {
colorln(ANSI_RED, txt);
}
public static void blueln(Object txt) {
colorln(ANSI_BLUE, txt);
}
public static void greenln(Object txt) {
colorln(ANSI_GREEN, txt);
}
public static void purpleln(Object txt) {
colorln(ANSI_PURPLE, txt);
}
public static void yellowln(Object txt) {
colorln(ANSI_YELLOW, txt);
}
public static void colorln(String color, Object s) {<FILL_FUNCTION_BODY>}
}
|
if (JavaUtil.IS_WINDOWS) {
System.out.println(s);
} else {
System.out.println(color + s);
System.out.print(ANSI_RESET);
}
| 435
| 62
| 497
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ProxyBinder.java
|
ProxyBinder
|
binding
|
class ProxyBinder {
private static ProxyBinder global;
static {
//(静态扩展约定:org.noear.solon.extend.impl.XxxxExt)
global = ClassUtil.tryInstance("org.noear.solon.extend.impl.ProxyBinderExt");
if (global == null) {
global = new ProxyBinder();
}
}
public static ProxyBinder global() {
return global;
}
/**
* 绑定代理
* */
public void binding(BeanWrap bw){<FILL_FUNCTION_BODY>}
}
|
if (NativeDetector.isNotAotRuntime()) {
throw new IllegalStateException("Missing plugin dependency: 'solon.proxy'");
}
| 165
| 40
| 205
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/RankEntity.java
|
RankEntity
|
equals
|
class RankEntity<T> {
public final T target;
public final int index;
public RankEntity(T t, int i) {
target = t;
index = i;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(target);
}
}
|
if (this == o) return true;
if (!(o instanceof RankEntity)) return false;
RankEntity that = (RankEntity) o;
return Objects.equals(target, that.target);
| 106
| 54
| 160
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/RunUtil.java
|
RunUtil
|
runOrThrow
|
class RunUtil {
/**
* 并行执行器(一般用于执行简单的定时任务)
*/
private static ExecutorService parallelExecutor;
/**
* 异步执行器(一般用于执行 @Async 注解任务)
*/
private static ExecutorService asyncExecutor;
/**
* 调度执行器(一般用于延时任务)
*/
private static ScheduledExecutorService scheduledExecutor;
static {
if (Solon.app() != null && Solon.cfg().isEnabledVirtualThreads()) {
parallelExecutor = ThreadsUtil.newVirtualThreadPerTaskExecutor();
asyncExecutor = ThreadsUtil.newVirtualThreadPerTaskExecutor();
} else {
parallelExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("Solon-executor-"));
int asyncPoolSize = Runtime.getRuntime().availableProcessors() * 2;
asyncExecutor = new ThreadPoolExecutor(asyncPoolSize, asyncPoolSize,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
new NamedThreadFactory("Solon-asyncExecutor-"));
}
int scheduledPoolSize = Runtime.getRuntime().availableProcessors() * 2;
scheduledExecutor = new ScheduledThreadPoolExecutor(scheduledPoolSize,
new NamedThreadFactory("Solon-scheduledExecutor-"));
}
public static void setScheduledExecutor(ScheduledExecutorService scheduledExecutor) {
if (scheduledExecutor != null) {
ScheduledExecutorService old = RunUtil.scheduledExecutor;
RunUtil.scheduledExecutor = scheduledExecutor;
old.shutdown();
}
}
/**
* @deprecated 2.5
*/
@Deprecated
public static void setExecutor(ExecutorService executor) {
setParallelExecutor(executor);
}
public static void setParallelExecutor(ExecutorService parallelExecutor) {
if (parallelExecutor != null) {
ExecutorService old = RunUtil.parallelExecutor;
RunUtil.parallelExecutor = parallelExecutor;
old.shutdown();
}
}
public static void setAsyncExecutor(ExecutorService asyncExecutor) {
if (asyncExecutor != null) {
ExecutorService old = RunUtil.asyncExecutor;
RunUtil.asyncExecutor = asyncExecutor;
old.shutdown();
}
}
/**
* 运行或异常
*/
public static void runOrThrow(RunnableEx task) {<FILL_FUNCTION_BODY>}
/**
* 运行并吃掉异常
*/
public static void runAndTry(RunnableEx task) {
try {
task.run();
} catch (Throwable e) {
//略过
}
}
/**
* 并行执行
*/
public static Future<?> parallel(Runnable task) {
return parallelExecutor.submit(task);
}
/**
* 并行执行
*/
public static <T> Future<T> parallel(Callable<T> task) {
return parallelExecutor.submit(task);
}
/**
* 异步执行
*/
public static CompletableFuture<Void> async(Runnable task) {
return CompletableFuture.runAsync(task, asyncExecutor);
}
/**
* 异步执行
*/
public static <U> CompletableFuture<U> async(Supplier<U> task) {
return CompletableFuture.supplyAsync(task, asyncExecutor);
}
public static CompletableFuture<Void> asyncAndTry(RunnableEx task) {
return CompletableFuture.runAsync(()->{
runAndTry(task);
}, asyncExecutor);
}
/**
* 延迟执行
*/
public static ScheduledFuture<?> delay(Runnable task, long millis) {
return scheduledExecutor.schedule(task, millis, TimeUnit.MILLISECONDS);
}
/**
* 延迟执行并重复
*/
public static ScheduledFuture<?> delayAndRepeat(Runnable task, long millis) {
return scheduledExecutor.scheduleWithFixedDelay(task, 1000, millis, TimeUnit.MILLISECONDS);
}
/**
* 定时任务
* */
public static ScheduledFuture<?> scheduleAtFixedRate(Runnable task, long initialDelay, long millisPeriod) {
return scheduledExecutor.scheduleAtFixedRate(task, initialDelay, millisPeriod, TimeUnit.MILLISECONDS);
}
/**
* 定时任务
* */
public static ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long millisDelay) {
return scheduledExecutor.scheduleWithFixedDelay(task, initialDelay, millisDelay, TimeUnit.MILLISECONDS);
}
}
|
try {
task.run();
} catch (Throwable e) {
e = Utils.throwableUnwrap(e);
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
| 1,285
| 76
| 1,361
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ScanUtil.java
|
ScanUtil
|
setScanner
|
class ScanUtil {
static ResourceScanner global;
static {
//(静态扩展约定:org.noear.solon.extend.impl.XxxxExt)
global = ClassUtil.tryInstance("org.noear.solon.extend.impl.ResourceScannerExt");
if (global == null) {
global = new ResourceScanner();
}
}
/**
* 设置扫描器(用户层扩展)
* */
public static void setScanner(ResourceScanner scanner) {<FILL_FUNCTION_BODY>}
/**
* 扫描路径下的的资源(path 扫描路径)
*
* @param path 路径
* @param filter 过滤条件
*/
public static Set<String> scan(String path, Predicate<String> filter) {
return scan(AppClassLoader.global(), path, filter);
}
/**
* 扫描路径下的的资源(path 扫描路径)
*
* @param classLoader 类加载器
* @param path 路径
* @param filter 过滤条件
*/
public static Set<String> scan(ClassLoader classLoader, String path, Predicate<String> filter) {
return global.scan(classLoader, path, filter);
}
}
|
if (scanner != null) {
ScanUtil.global = scanner;
}
| 349
| 27
| 376
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/util/ThreadsUtil.java
|
ThreadsUtil
|
newVirtualThreadPerTaskExecutor
|
class ThreadsUtil {
private static Method method_newVirtualThreadPerTaskExecutor;
public static ExecutorService newVirtualThreadPerTaskExecutor() {<FILL_FUNCTION_BODY>}
}
|
try {
if (method_newVirtualThreadPerTaskExecutor == null) {
method_newVirtualThreadPerTaskExecutor = Executors.class.getDeclaredMethod("newVirtualThreadPerTaskExecutor");
}
return (ExecutorService) method_newVirtualThreadPerTaskExecutor.invoke(Executors.class);
} catch (Exception e) {
throw new IllegalStateException(e);
}
| 50
| 100
| 150
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/wrap/FieldWrap.java
|
FieldWrap
|
doFindSetter
|
class FieldWrap {
/**
* 实体类型
*/
public final Class<?> entityClz;
/**
* 字段
*/
public final Field field;
/**
* 自己申明的注解
*/
public final Annotation[] annoS;
/**
* 字段类型
*/
public final Class<?> type;
/**
* 字段泛型类型(可能为null)
*/
public final @Nullable ParameterizedType genericType;
/**
* 字段是否只读
*/
public final boolean readonly;
/**
* 值设置器
*/
private Method _setter;
/**
* 值获取器
*/
private Method _getter;
protected FieldWrap(Class<?> clz, Field f1, boolean isFinal) {
entityClz = clz;
field = f1;
annoS = f1.getAnnotations();
readonly = isFinal;
Type tmp = f1.getGenericType();
if (tmp instanceof TypeVariable) {
//如果是类型变量,则重新构建类型
Map<String, Type> gMap = GenericUtil.getGenericInfo(clz);
Type typeH = gMap.get(tmp.getTypeName());
if (typeH instanceof ParameterizedType) {
//以防外万一
genericType = (ParameterizedType) typeH;
type = (Class<?>) ((ParameterizedType) typeH).getRawType();
} else {
genericType = null;
type = (Class<?>) typeH;
}
} else {
type = f1.getType();
if (tmp instanceof ParameterizedType) {
ParameterizedType gt0 = (ParameterizedType) tmp;
Map<String, Type> gMap = GenericUtil.getGenericInfo(clz);
Type[] gArgs = gt0.getActualTypeArguments();
boolean gChanged = false;
for (int i = 0; i < gArgs.length; i++) {
Type t1 = gArgs[i];
if (t1 instanceof TypeVariable) {
//尝试转换参数类型
gArgs[i] = gMap.get(t1.getTypeName());
gChanged = true;
}
}
if (gChanged) {
genericType = new ParameterizedTypeImpl((Class<?>) gt0.getRawType(), gArgs, gt0.getOwnerType());
} else {
genericType = gt0;
}
} else {
genericType = null;
}
}
_setter = doFindSetter(clz, f1);
_getter = dofindGetter(clz, f1);
}
private VarDescriptor descriptor;
/**
* 变量申明者
*
* @since 2.3
*/
public VarDescriptor getDescriptor() {
if (descriptor == null) {
//采用懒加载,不浪费
descriptor = new FieldWrapDescriptor(this);
}
return descriptor;
}
public String getName() {
return field.getName();
}
/**
* 获取自身的临时对象
*/
public VarHolder holder(AppContext ctx, Object obj, Runnable onDone) {
return new VarHolderOfField(ctx, this, obj, onDone);
}
/**
* 获取字段的值
*/
public Object getValue(Object tObj) throws ReflectiveOperationException {
if (_getter == null) {
return get(tObj);
} else {
return _getter.invoke(tObj);
}
}
public Object get(Object tObj) throws IllegalAccessException {
if (!field.isAccessible()) {
field.setAccessible(true);
}
return field.get(tObj);
}
/**
* 设置字段的值
*/
public void setValue(Object tObj, Object val) {
setValue(tObj, val, false);
}
public void setValue(Object tObj, Object val, boolean disFun) {
if (readonly) {
return;
}
try {
if (val == null) {
return;
}
if (_setter == null || disFun) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(tObj, val);
} else {
_setter.invoke(tObj, new Object[]{val});
}
} catch (IllegalArgumentException ex) {
if (val == null) {
throw new IllegalArgumentException(field.getName() + "(" + field.getType().getSimpleName() + ") Type receive failur!", ex);
}
throw new IllegalArgumentException(
field.getName() + "(" + field.getType().getSimpleName() +
") Type receive failure :val(" + val.getClass().getSimpleName() + ")", ex);
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static Method dofindGetter(Class<?> tCls, Field field) {
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String setMethodName = "get" + firstLetter + fieldName.substring(1);
try {
Method getFun = tCls.getMethod(setMethodName);
if (getFun != null) {
return getFun;
}
} catch (NoSuchMethodException ex) {
} catch (Throwable ex) {
ex.printStackTrace();
}
return null;
}
/**
* 查找设置器
*/
private static Method doFindSetter(Class<?> tCls, Field field) {<FILL_FUNCTION_BODY>}
}
|
String fieldName = field.getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String setMethodName = "set" + firstLetter + fieldName.substring(1);
try {
Method setFun = tCls.getMethod(setMethodName, new Class[]{field.getType()});
if (setFun != null) {
return setFun;
}
} catch (NoSuchMethodException e) {
//正常情况,不用管
} catch (SecurityException e) {
LogUtil.global().warn("FieldWrap doFindSetter failed!", e);
}
return null;
| 1,545
| 169
| 1,714
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/wrap/MethodWrap.java
|
MethodWrap
|
doInterceptorAdd
|
class MethodWrap implements Interceptor, MethodHolder {
public MethodWrap(AppContext ctx, Method m) {
this(ctx, m, null);
}
public MethodWrap(AppContext ctx, Method m, Map<String,Type> genericInfo) {
context = ctx;
declaringClz = m.getDeclaringClass();
method = m;
parameters = buildParamsWrap(m.getParameters(), genericInfo);
annotations = m.getAnnotations();
interceptors = new ArrayList<>();
interceptorsIdx = new HashSet<>();
//scan method @Around (优先)
for (Annotation anno : annotations) {
if (anno instanceof Around) {
doInterceptorAdd((Around) anno);
} else {
InterceptorEntity ie = context.beanInterceptorGet(anno.annotationType());
if (ie != null) {
doInterceptorAdd(ie);
} else {
doInterceptorAdd(anno.annotationType().getAnnotation(Around.class));
}
}
}
//scan class @Around
for (Annotation anno : declaringClz.getAnnotations()) {
if (anno instanceof Around) {
doInterceptorAdd((Around) anno);
} else {
InterceptorEntity ie = context.beanInterceptorGet(anno.annotationType());
if (ie != null) {
doInterceptorAdd(ie);
} else {
doInterceptorAdd(anno.annotationType().getAnnotation(Around.class));
}
}
}
if (interceptors.size() > 1) {
//排序(顺排)
interceptors.sort(Comparator.comparing(x -> x.getIndex()));
}
interceptors.add(new InterceptorEntity(0, this));
}
private ParamWrap[] buildParamsWrap(Parameter[] pAry, Map<String,Type> genericInfo) {
ParamWrap[] tmp = new ParamWrap[pAry.length];
for (int i = 0, len = pAry.length; i < len; i++) {
tmp[i] = new ParamWrap(pAry[i], method, genericInfo);
if (tmp[i].isRequiredBody()) {
isRequiredBody = true;
bodyParameter = tmp[i];
}
}
return tmp;
}
private void doInterceptorAdd(Around a) {
if (a != null) {
doInterceptorAdd(new InterceptorEntity(a.index(), context.getBeanOrNew(a.value())));
}
}
private void doInterceptorAdd(InterceptorEntity i) {<FILL_FUNCTION_BODY>}
private final AppContext context;
//实体类型
private final Class<?> declaringClz;
//函数
private final Method method;
//函数参数
private final ParamWrap[] parameters;
//函数Body参数(用于 web)
private ParamWrap bodyParameter;
//函数注解
private final Annotation[] annotations;
//函数拦截器列表(扩展切点)
private final List<InterceptorEntity> interceptors;
private final Set<Interceptor> interceptorsIdx;
private boolean isRequiredBody;
/**
* 是否需要 body(用于 web)
*/
public boolean isRequiredBody() {
return isRequiredBody;
}
/**
* 获取函数名
*/
public String getName() {
return method.getName();
}
/**
* 获取申明类
*/
@Override
public Class<?> getDeclaringClz() {
return declaringClz;
}
/**
* 获取函数本身
*/
public Method getMethod() {
return method;
}
/**
* 获取函数反回类型
*/
public Class<?> getReturnType() {
return method.getReturnType();
}
/**
* 获取函数泛型类型
*/
public Type getGenericReturnType() {
return method.getGenericReturnType();
}
/**
* 获取函数参数
*/
public ParamWrap[] getParamWraps() {
return parameters;
}
/**
* 获取函数Body参数
*/
public @Nullable ParamWrap getBodyParamWrap() {
return bodyParameter;
}
/**
* 获取函数所有注解
*/
public Annotation[] getAnnotations() {
return annotations;
}
/**
* 获取函数某种注解
*/
public <T extends Annotation> T getAnnotation(Class<T> type) {
return method.getAnnotation(type);
}
/**
* 检测是否存在注解
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return method.isAnnotationPresent(annotationClass);
}
/**
* 获取包围处理
*
* @deprecated 2.4
*/
@Deprecated
public List<InterceptorEntity> getArounds() {
return getInterceptors();
}
/**
* 获取拦截器
*/
public List<InterceptorEntity> getInterceptors() {
return Collections.unmodifiableList(interceptors);
}
/**
* 拦截处理
*/
@Override
public Object doIntercept(Invocation inv) throws Throwable {
return invoke(inv.target(), inv.args());
}
/**
* 执行(原生处理)
*
* @param obj 目标对象
* @param args 执行参数
*/
public Object invoke(Object obj, Object[] args) throws Throwable {
try {
return method.invoke(obj, args);
} catch (InvocationTargetException e) {
Throwable e2 = e.getTargetException();
throw Utils.throwableUnwrap(e2);
}
}
/**
* 执行切面(即带拦截器的处理)
*
* @param obj 目标对象(要求:未代理对象。避免二次拦截)
* @param args 执行参数
*/
public Object invokeByAspect(Object obj, Object[] args) throws Throwable {
Invocation inv = new Invocation(obj, args, this, interceptors);
return inv.invoke();
}
}
|
if (i != null) {
if (interceptorsIdx.contains(i.getReal())) {
//去重处理
return;
}
interceptorsIdx.add(i.getReal());
interceptors.add(i);
}
| 1,729
| 73
| 1,802
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/wrap/VarDescriptorBase.java
|
VarDescriptorBase
|
getRequiredHint
|
class VarDescriptorBase implements VarDescriptor {
private final AnnotatedElement element;
private final ActionParam vo = new ActionParam();
@Override
public boolean isRequiredBody() {
return vo.isRequiredBody;
}
@Override
public boolean isRequiredHeader() {
return vo.isRequiredHeader;
}
@Override
public boolean isRequiredCookie() {
return vo.isRequiredCookie;
}
@Override
public boolean isRequiredPath() {
return vo.isRequiredPath;
}
@Override
public boolean isRequiredInput() {
return vo.isRequiredInput;
}
@Override
public String getRequiredHint() {<FILL_FUNCTION_BODY>}
@Override
public String getName() {
return vo.name;
}
@Override
public String getDefaultValue() {
return vo.defaultValue;
}
public VarDescriptorBase(AnnotatedElement element, String name) {
this.element = element;
this.vo.name = name;
}
protected void init() {
//没有时,不处理
if (Solon.app().factoryManager().hasMvcFactory()) {
Solon.app().factoryManager().mvcFactory().resolveParam(vo, element);
}
}
/////////////////
}
|
if (vo.isRequiredHeader) {
return "Required header @" + getName();
} else if (vo.isRequiredCookie) {
return "Required cookie @" + getName();
} else {
return "Required parameter @" + getName();
}
| 348
| 69
| 417
|
<no_super_class>
|
noear_solon
|
solon/solon/src/main/java/org/noear/solon/core/wrap/VarHolderOfField.java
|
VarHolderOfField
|
setValue
|
class VarHolderOfField implements VarHolder {
protected final FieldWrap fw;
protected final Object obj;
protected final AppContext ctx;
protected Object val;
protected boolean required = false;
protected boolean done;
protected Runnable onDone;
public VarHolderOfField(AppContext ctx, FieldWrap fw, Object obj, Runnable onDone) {
this.ctx = ctx;
this.fw = fw;
this.obj = obj;
this.onDone = onDone;
}
/**
* 应用上下文
* */
@Override
public AppContext context() {
return ctx;
}
/**
* 泛型(可能为null)
* */
@Override
public @Nullable ParameterizedType getGenericType() {
return fw.genericType;
}
/**
* 是否为字段
* */
@Override
public boolean isField() {
return true;
}
/**
* 获取字段类型
* */
@Override
public Class<?> getType(){
return fw.type;
}
/**
* 获取所有注解
* */
@Override
public Annotation[] getAnnoS(){
return fw.annoS;
}
/**
* 获取完整名字
* */
@Override
public String getFullName() {
return fw.entityClz.getName() + "::" + fw.field.getName();
}
/**
* 设置值
*/
@Override
public void setValue(Object val) {<FILL_FUNCTION_BODY>}
/**
* 获取值
* */
@Override
public Object getValue() {
return val;
}
/**
* 是否为完成的(设置值后即为完成态)
* */
public boolean isDone() {
return done;
}
/**
* 是否必须
* */
@Override
public boolean required() {
return required;
}
/**
* 设定必须
* */
@Override
public void required(boolean required) {
this.required = required;
}
}
|
if(val != null) {
fw.setValue(obj, val, true);
ctx.aot().registerJdkProxyType(getType(), val);
}
this.val = val;
this.done = true;
if (onDone != null) {
onDone.run();
}
| 587
| 88
| 675
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/AgentApplication.java
|
AgentApplication
|
servletContainer
|
class AgentApplication {
@Value("${sonic.agent.port}")
private int port;
public static void main(String[] args) {
SpringApplication.run(AgentApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() {<FILL_FUNCTION_BODY>}
}
|
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(port);
factory.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> connector.setProperty("relaxedQueryChars", "|{}[]\\"));
return factory;
| 89
| 67
| 156
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/aspect/IteratorAspect.java
|
IteratorAspect
|
processInputArg
|
class IteratorAspect {
@Pointcut("@annotation(org.cloud.sonic.agent.aspect.IteratorCheck)")
public void serviceAspect() {
}
@Around(value = "serviceAspect()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Object[] objects = processInputArg(proceedingJoinPoint.getArgs());
return proceedingJoinPoint.proceed(objects);
}
private Object[] processInputArg(Object[] args) {<FILL_FUNCTION_BODY>}
}
|
HandleContext handleContext = null;
for (Object arg : args) {
if (arg instanceof HandleContext) {
handleContext = (HandleContext) arg;
break;
}
}
JSONObject paramStep = null;
for (Object arg : args) {
if (arg instanceof JSONObject) {
paramStep = (JSONObject) arg;
break;
}
}
try {
if (paramStep != null && handleContext != null && handleContext.currentIteratorElement != null) {
String uniquelyIdentifies = handleContext.currentIteratorElement.getUniquelyIdentifies();
JSONObject step = paramStep.getJSONObject("step");
JSONArray eleList = step.getJSONArray("elements");
for (int i = 0; i < eleList.size(); i++) {
JSONObject ele = eleList.getJSONObject(i);
if ("pocoIterator".equals(ele.get("eleType").toString())
|| "androidIterator".equals(ele.get("eleType").toString())
|| "iOSIterator".equals(ele.get("eleType").toString())) {
ele.put("eleValue", uniquelyIdentifies);
}
eleList.set(i, new JSONObject(ele));
}
}
} catch (Throwable e) {
log.info(e.getMessage());
}
return args;
| 142
| 346
| 488
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidDeviceLocalStatus.java
|
AndroidDeviceLocalStatus
|
finish
|
class AndroidDeviceLocalStatus {
/**
* @param udId
* @param status
* @return void
* @author ZhouYiXun
* @des 发送状态变更消息
* @date 2021/8/16 20:56
*/
public static void send(String udId, String status) {
JSONObject deviceDetail = new JSONObject();
deviceDetail.put("msg", "deviceDetail");
deviceDetail.put("udId", udId);
deviceDetail.put("status", status);
TransportWorker.send(deviceDetail);
}
/**
* @param udId
* @return void
* @author ZhouYiXun
* @des 开始测试
* @date 2021/8/16 20:57
*/
public static boolean startTest(String udId) {
synchronized (AndroidDeviceLocalStatus.class) {
if (AndroidDeviceManagerMap.getStatusMap().get(udId) == null) {
send(udId, DeviceStatus.TESTING);
AndroidDeviceManagerMap.getStatusMap().put(udId, DeviceStatus.TESTING);
return true;
} else {
return false;
}
}
}
/**
* @param udId
* @return void
* @author ZhouYiXun
* @des 开始调试
* @date 2021/8/16 20:57
*/
public static void startDebug(String udId) {
send(udId, DeviceStatus.DEBUGGING);
AndroidDeviceManagerMap.getStatusMap().put(udId, DeviceStatus.DEBUGGING);
}
/**
* @param udId
* @return void
* @author ZhouYiXun
* @des 使用完毕
* @date 2021/8/16 19:47
*/
public static void finish(String udId) {<FILL_FUNCTION_BODY>}
/**
* @param udId
* @return void
* @author ZhouYiXun
* @des 使用完毕异常
* @date 2021/8/16 19:47
*/
public static void finishError(String udId) {
if (AndroidDeviceBridgeTool.getIDeviceByUdId(udId) != null
&& AndroidDeviceManagerMap.getStatusMap().get(udId) != null) {
if (AndroidDeviceManagerMap.getStatusMap().get(udId).equals(DeviceStatus.DEBUGGING)
|| AndroidDeviceManagerMap.getStatusMap().get(udId).equals(DeviceStatus.TESTING)) {
send(udId, DeviceStatus.ERROR);
}
}
AndroidDeviceManagerMap.getStatusMap().remove(udId);
}
}
|
if (AndroidDeviceBridgeTool.getIDeviceByUdId(udId) != null
&& AndroidDeviceManagerMap.getStatusMap().get(udId) != null) {
if (AndroidDeviceManagerMap.getStatusMap().get(udId).equals(DeviceStatus.DEBUGGING)
|| AndroidDeviceManagerMap.getStatusMap().get(udId).equals(DeviceStatus.TESTING)) {
send(udId, DeviceStatus.ONLINE);
}
}
AndroidDeviceManagerMap.getStatusMap().remove(udId);
| 745
| 138
| 883
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidDeviceStatusListener.java
|
AndroidDeviceStatusListener
|
send
|
class AndroidDeviceStatusListener implements AndroidDebugBridge.IDeviceChangeListener {
private final Logger logger = LoggerFactory.getLogger(AndroidDeviceStatusListener.class);
/**
* @param device
* @return void
* @author ZhouYiXun
* @des 发送设备状态
* @date 2021/8/16 19:58
*/
private void send(IDevice device) {<FILL_FUNCTION_BODY>}
@Override
public void deviceConnected(IDevice device) {
logger.info("Android device: " + device.getSerialNumber() + " ONLINE!");
AndroidDeviceManagerMap.getStatusMap().remove(device.getSerialNumber());
DevicesBatteryMap.getTempMap().remove(device.getSerialNumber());
send(device);
}
@Override
public void deviceDisconnected(IDevice device) {
logger.info("Android device: " + device.getSerialNumber() + " OFFLINE!");
AndroidDeviceManagerMap.getStatusMap().remove(device.getSerialNumber());
DevicesBatteryMap.getTempMap().remove(device.getSerialNumber());
send(device);
}
@Override
public void deviceChanged(IDevice device, int changeMask) {
IDevice.DeviceState state = device.getState();
if (state == IDevice.DeviceState.OFFLINE) {
return;
}
send(device);
}
}
|
JSONObject deviceDetail = new JSONObject();
deviceDetail.put("msg", "deviceDetail");
deviceDetail.put("udId", device.getSerialNumber());
deviceDetail.put("name", device.getProperty("ro.product.name"));
deviceDetail.put("model", device.getProperty(IDevice.PROP_DEVICE_MODEL));
deviceDetail.put("status", device.getState() == null ? null : device.getState().toString());
deviceDetail.put("platform", PlatformType.ANDROID);
if (device.getProperty("ro.config.ringtone") != null && device.getProperty("ro.config.ringtone").contains("Harmony")) {
deviceDetail.put("version", device.getProperty("hw_sc.build.platform.version"));
deviceDetail.put("isHm", IsHMStatus.IS_HM);
} else {
deviceDetail.put("version", device.getProperty(IDevice.PROP_BUILD_VERSION));
deviceDetail.put("isHm", IsHMStatus.IS_ANDROID);
}
deviceDetail.put("size", AndroidDeviceBridgeTool.getScreenSize(device));
deviceDetail.put("cpu", device.getProperty(IDevice.PROP_DEVICE_CPU_ABI));
deviceDetail.put("manufacturer", device.getProperty(IDevice.PROP_DEVICE_MANUFACTURER));
TransportWorker.send(deviceDetail);
| 375
| 363
| 738
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/android/AndroidSupplyTool.java
|
AndroidSupplyTool
|
startPerfmon
|
class AndroidSupplyTool implements ApplicationListener<ContextRefreshedEvent> {
private static File sasBinary = new File("plugins" + File.separator + "sonic-android-supply");
private static String sas = sasBinary.getAbsolutePath();
@Override
public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
log.info("Enable sonic-android-supply Module");
}
public static void startShare(String udId, Session session) {
JSONObject sasJSON = new JSONObject();
sasJSON.put("msg", "sas");
sasJSON.put("isEnable", true);
stopShare(udId);
String processName = String.format("process-%s-sas", udId);
String commandLine = "%s share -s %s --translate-port %d";
try {
String system = System.getProperty("os.name").toLowerCase();
Process ps = null;
int port = PortTool.getPort();
if (system.contains("win")) {
ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, port)});
} else if (system.contains("linux") || system.contains("mac")) {
ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, port)});
}
GlobalProcessMap.getMap().put(processName, ps);
sasJSON.put("port", port);
} catch (Exception e) {
sasJSON.put("port", 0);
e.printStackTrace();
} finally {
BytesTool.sendText(session, sasJSON.toJSONString());
}
}
public static void startShare(String udId, int port) {
stopShare(udId);
String processName = String.format("process-%s-sas", udId);
String commandLine = "%s share -s %s --translate-port %d";
try {
String system = System.getProperty("os.name").toLowerCase();
Process ps = null;
if (system.contains("win")) {
ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, port)});
} else if (system.contains("linux") || system.contains("mac")) {
ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, port)});
}
GlobalProcessMap.getMap().put(processName, ps);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopShare(String udId) {
String processName = String.format("process-%s-sas", udId);
if (GlobalProcessMap.getMap().get(processName) != null) {
Process ps = GlobalProcessMap.getMap().get(processName);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
}
public static void stopPerfmon(String udId) {
String processName = String.format("process-%s-perfmon", udId);
if (GlobalProcessMap.getMap().get(processName) != null) {
Process ps = GlobalProcessMap.getMap().get(processName);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
}
public static void startPerfmon(String udId, String pkg, Session session, LogUtil logUtil, int interval) {<FILL_FUNCTION_BODY>}
}
|
stopPerfmon(udId);
Process ps = null;
String commandLine = "%s perfmon -s %s -r %d %s -j --sys-cpu --sys-mem --sys-network";
String system = System.getProperty("os.name").toLowerCase();
String tail = pkg.length() == 0 ? "" : (" --proc-cpu --proc-fps --proc-mem --proc-threads -p " + pkg);
try {
if (system.contains("win")) {
ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", String.format(commandLine, sas, udId, interval, tail)});
} else if (system.contains("linux") || system.contains("mac")) {
ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", String.format(commandLine, sas, udId, interval, tail)});
}
} catch (Exception e) {
e.printStackTrace();
}
InputStreamReader inputStreamReader = new InputStreamReader(ps.getInputStream());
BufferedReader stdInput = new BufferedReader(inputStreamReader);
InputStreamReader err = new InputStreamReader(ps.getErrorStream());
BufferedReader stdInputErr = new BufferedReader(err);
Thread psErr = new Thread(() -> {
String s;
while (true) {
try {
if ((s = stdInputErr.readLine()) == null) break;
} catch (IOException e) {
log.info(e.getMessage());
break;
}
log.info(s);
}
try {
stdInputErr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
err.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("perfmon print thread shutdown.");
});
psErr.start();
Thread pro = new Thread(() -> {
String s;
while (true) {
try {
if ((s = stdInput.readLine()) == null) break;
} catch (IOException e) {
log.info(e.getMessage());
break;
}
try {
JSONObject perf = JSON.parseObject(s);
if (session != null) {
JSONObject perfDetail = new JSONObject();
perfDetail.put("msg", "perfDetail");
perfDetail.put("detail", perf);
sendText(session, perfDetail.toJSONString());
}
if (logUtil != null) {
logUtil.sendPerLog(perf.toJSONString());
}
} catch (Exception ignored) {
}
}
try {
stdInput.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("perfmon print thread shutdown.");
});
pro.start();
String processName = String.format("process-%s-perfmon", udId);
GlobalProcessMap.getMap().put(processName, ps);
| 941
| 807
| 1,748
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/bridge/ios/IOSDeviceLocalStatus.java
|
IOSDeviceLocalStatus
|
finishError
|
class IOSDeviceLocalStatus {
public static void send(String udId, String status) {
JSONObject deviceDetail = new JSONObject();
deviceDetail.put("msg", "deviceDetail");
deviceDetail.put("udId", udId);
deviceDetail.put("status", status);
TransportWorker.send(deviceDetail);
}
public static boolean startTest(String udId) {
synchronized (IOSDeviceLocalStatus.class) {
if (IOSDeviceManagerMap.getMap().get(udId) == null) {
send(udId, DeviceStatus.TESTING);
IOSDeviceManagerMap.getMap().put(udId, DeviceStatus.TESTING);
return true;
} else {
return false;
}
}
}
public static void startDebug(String udId) {
send(udId, DeviceStatus.DEBUGGING);
IOSDeviceManagerMap.getMap().put(udId, DeviceStatus.DEBUGGING);
}
public static void finish(String udId) {
if (SibTool.getDeviceList().contains(udId)
&& IOSDeviceManagerMap.getMap().get(udId) != null) {
if (IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.DEBUGGING)
|| IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.TESTING)) {
send(udId, DeviceStatus.ONLINE);
}
}
IOSDeviceManagerMap.getMap().remove(udId);
}
public static void finishError(String udId) {<FILL_FUNCTION_BODY>}
}
|
if (SibTool.getDeviceList().contains(udId)
&& IOSDeviceManagerMap.getMap().get(udId) != null) {
if (IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.DEBUGGING)
|| IOSDeviceManagerMap.getMap().get(udId).equals(DeviceStatus.TESTING)) {
send(udId, DeviceStatus.ERROR);
}
}
IOSDeviceManagerMap.getMap().remove(udId);
| 423
| 128
| 551
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/common/config/ResourceConfig.java
|
ResourceConfig
|
addResourceHandlers
|
class ResourceConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {<FILL_FUNCTION_BODY>}
}
|
registry.addResourceHandler("/static/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/download/**")
.addResourceLocations("file:///" + System.getProperty("user.dir") + "/plugins/");
super.addResourceHandlers(registry);
| 45
| 114
| 159
|
<methods>public void <init>() ,public org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping beanNameHandlerMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.HandlerMapping defaultServletHandlerMapping() ,public org.springframework.web.servlet.FlashMapManager flashMapManager() ,public final org.springframework.context.ApplicationContext getApplicationContext() ,public final jakarta.servlet.ServletContext getServletContext() ,public org.springframework.web.servlet.HandlerExceptionResolver handlerExceptionResolver(org.springframework.web.accept.ContentNegotiationManager) ,public org.springframework.web.servlet.function.support.HandlerFunctionAdapter handlerFunctionAdapter() ,public org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter httpRequestHandlerAdapter() ,public org.springframework.web.servlet.LocaleResolver localeResolver() ,public org.springframework.web.accept.ContentNegotiationManager mvcContentNegotiationManager() ,public org.springframework.format.support.FormattingConversionService mvcConversionService() ,public org.springframework.web.servlet.handler.HandlerMappingIntrospector mvcHandlerMappingIntrospector() ,public org.springframework.util.PathMatcher mvcPathMatcher() ,public org.springframework.web.util.pattern.PathPatternParser mvcPatternParser() ,public org.springframework.web.servlet.resource.ResourceUrlProvider mvcResourceUrlProvider() ,public org.springframework.web.method.support.CompositeUriComponentsContributor mvcUriComponentsContributor(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) ,public org.springframework.web.util.UrlPathHelper mvcUrlPathHelper() ,public org.springframework.validation.Validator mvcValidator() ,public org.springframework.web.servlet.ViewResolver mvcViewResolver(org.springframework.web.accept.ContentNegotiationManager) ,public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter requestMappingHandlerAdapter(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.validation.Validator) ,public org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping requestMappingHandlerMapping(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.HandlerMapping resourceHandlerMapping(org.springframework.web.accept.ContentNegotiationManager, org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.function.support.RouterFunctionMapping routerFunctionMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void setServletContext(jakarta.servlet.ServletContext) ,public org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter simpleControllerHandlerAdapter() ,public org.springframework.web.servlet.ThemeResolver themeResolver() ,public org.springframework.web.servlet.HandlerMapping viewControllerHandlerMapping(org.springframework.format.support.FormattingConversionService, org.springframework.web.servlet.resource.ResourceUrlProvider) ,public org.springframework.web.servlet.RequestToViewNameTranslator viewNameTranslator() <variables>private org.springframework.context.ApplicationContext applicationContext,private List<org.springframework.web.method.support.HandlerMethodArgumentResolver> argumentResolvers,private org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer asyncSupportConfigurer,private org.springframework.web.accept.ContentNegotiationManager contentNegotiationManager,private Map<java.lang.String,org.springframework.web.cors.CorsConfiguration> corsConfigurations,private static final boolean gsonPresent,private List<java.lang.Object> interceptors,private static final boolean jackson2CborPresent,private static final boolean jackson2Present,private static final boolean jackson2SmilePresent,private static final boolean jackson2XmlPresent,private static final boolean jaxb2Present,private static final boolean jsonbPresent,private static final boolean kotlinSerializationCborPresent,private static final boolean kotlinSerializationJsonPresent,private static final boolean kotlinSerializationProtobufPresent,private List<HttpMessageConverter<?>> messageConverters,private org.springframework.web.servlet.config.annotation.PathMatchConfigurer pathMatchConfigurer,private List<org.springframework.web.method.support.HandlerMethodReturnValueHandler> returnValueHandlers,private static final boolean romePresent,private jakarta.servlet.ServletContext servletContext
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/common/config/RestTemplateConfig.java
|
RestTemplateConfig
|
simpleClientHttpRequestFactory
|
class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {<FILL_FUNCTION_BODY>}
}
|
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(120000);
factory.setConnectTimeout(150000);
return factory;
| 71
| 54
| 125
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/common/maps/DevicesLockMap.java
|
DevicesLockMap
|
lockByUdId
|
class DevicesLockMap {
private final static Logger logger = LoggerFactory.getLogger(DevicesLockMap.class);
/**
* key: udId(设备序列号) value: Semaphore
*/
private static Map<String, Semaphore> devicesLockMap = new ConcurrentHashMap<>();
/**
* xxx
* 用设备序列号上锁(无)
*
* @see #lockByUdId(String, Long, TimeUnit)
*/
public static boolean lockByUdId(String udId) throws InterruptedException {
return lockByUdId(udId, null, null);
}
/**
* 用设备序列号上锁(可设置超时)
*
* @param udId 设备序列号
* @param timeOut 获取锁超时时间 此参数必须和 timeUnit 同时存在
* @param timeUnit 时间单位 此参数必须和 timeOut 同时存在
* @return true: 上锁成功 false: 上锁失败
*/
public static boolean lockByUdId(String udId, Long timeOut, TimeUnit timeUnit) throws InterruptedException {<FILL_FUNCTION_BODY>}
/**
* 解锁并从map中移除锁
*
* @param udId 设备序列号
*/
public static void unlockAndRemoveByUdId(String udId) {
Assert.hasText(udId, "udId must not be blank");
Semaphore deviceLock;
synchronized (WebSocketSessionMap.class) {
deviceLock = devicesLockMap.get(udId);
removeLockByUdId(udId);
}
if (deviceLock != null) {
deviceLock.release();
}
}
public static void removeLockByUdId(String udId) {
devicesLockMap.remove(udId);
}
}
|
// 校验参数
Assert.hasText(udId, "udId must not be blank");
if (timeOut != null || timeUnit != null) {
Assert.isTrue(
timeOut != null && timeUnit != null,
"timeOut and timeUnit must not be null at the same time"
);
}
Semaphore deviceLock;
// 原子操作,避免put后被别的线程remove造成当前线程lock失效
synchronized (WebSocketSessionMap.class) {
Semaphore res = devicesLockMap.get(udId);
if (res == null) {
deviceLock = new Semaphore(1);
devicesLockMap.put(udId, deviceLock);
} else {
deviceLock = res;
}
}
// 无超时获取锁逻辑,直接锁并返回true
if (timeOut == null) {
deviceLock.acquire();
return true;
}
// 如果有超时,则成功返回true,超时返回false
try {
return deviceLock.tryAcquire(timeOut, timeUnit);
} catch (InterruptedException e) {
logger.error("获取锁被中断,返回false");
return false;
}
| 504
| 324
| 828
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/common/models/HandleContext.java
|
HandleContext
|
toString
|
class HandleContext {
private String stepDes;
private String detail;
private Throwable e;
public Iterator<BaseElement> iteratorElement;
public BaseElement currentIteratorElement;
public HandleContext() {
this.stepDes = "";
this.detail = "";
this.e = null;
}
public void clear() {
this.stepDes = "";
this.detail = "";
this.e = null;
}
public String getStepDes() {
return stepDes;
}
public void setStepDes(String stepDes) {
this.stepDes = stepDes;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public Throwable getE() {
return e;
}
public void setE(Throwable e) {
this.e = e;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "HandleDes{" +
"stepDes='" + stepDes + '\'' +
", detail='" + detail + '\'' +
", e=" + e +
'}';
| 274
| 51
| 325
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/controller/CertController.java
|
CertController
|
download
|
class CertController {
@Value("${sonic.sgm}")
private String version;
@RequestMapping("/assets/download")
public String download(Model model) {<FILL_FUNCTION_BODY>}
}
|
model.addAttribute("msg", "欢迎来到证书下载页面");
model.addAttribute("pemMsg", "👉 点击下载pem证书");
model.addAttribute("pemName", "sonic-go-mitmproxy-ca-cert.pem");
model.addAttribute("pemUrl", "/download/sonic-go-mitmproxy-ca-cert.pem");
model.addAttribute("tips", "如果pem证书无效,请尝试cer证书");
model.addAttribute("cerMsg", "👉 点击下载cer证书");
model.addAttribute("cerName", "sonic-go-mitmproxy-ca-cert.cer");
model.addAttribute("cerUrl", "/download/sonic-go-mitmproxy-ca-cert.cer");
model.addAttribute("version", "Version: " + version);
return "download";
| 60
| 222
| 282
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/AgentManagerTool.java
|
AgentManagerTool
|
stop
|
class AgentManagerTool {
private final static Logger logger = LoggerFactory.getLogger(AgentManagerTool.class);
private static ConfigurableApplicationContext context;
@Autowired
public void setContext(ConfigurableApplicationContext c) {
AgentManagerTool.context = c;
}
public static void stop() {<FILL_FUNCTION_BODY>}
}
|
try {
context.close();
} catch (Exception e) {
e.printStackTrace();
}
logger.info("Bye!");
System.exit(0);
| 96
| 51
| 147
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/BytesTool.java
|
BytesTool
|
intToByteArray
|
class BytesTool {
public static int agentId = 0;
public static String agentHost = "";
public static int highTemp = 0;
public static int highTempTime = 0;
public static int remoteTimeout = 480;
public static int toInt(byte[] b) {
int res = 0;
for (int i = 0; i < b.length; i++) {
res += (b[i] & 0xff) << (i * 8);
}
return res;
}
public static byte[] intToByteArray(int i) {<FILL_FUNCTION_BODY>}
public static byte[] subByteArray(byte[] byte1, int start, int end) {
byte[] byte2;
byte2 = new byte[end - start];
System.arraycopy(byte1, start, byte2, 0, end - start);
return byte2;
}
public static long bytesToLong(byte[] src, int offset) {
long value;
value = ((src[offset] & 0xFF) | ((src[offset + 1] & 0xFF) << 8) | ((src[offset + 2] & 0xFF) << 16)
| ((src[offset + 3] & 0xFF) << 24));
return value;
}
// java合并两个byte数组
public static byte[] addBytes(byte[] data1, byte[] data2) {
byte[] data3 = new byte[data1.length + data2.length];
System.arraycopy(data1, 0, data3, 0, data1.length);
System.arraycopy(data2, 0, data3, data1.length, data2.length);
return data3;
}
public static void sendByte(Session session, byte[] message) {
if (session == null || !session.isOpen()) {
return;
}
synchronized (session) {
try {
session.getBasicRemote().sendBinary(ByteBuffer.wrap(message));
} catch (IllegalStateException | IOException e) {
log.error("WebSocket send msg error...connection has been closed.");
}
}
}
public static void sendByte(Session session, ByteBuffer message) {
if (session == null || !session.isOpen()) {
return;
}
synchronized (session) {
try {
session.getBasicRemote().sendBinary(message);
} catch (IllegalStateException | IOException e) {
log.error("WebSocket send msg error...connection has been closed.");
}
}
}
public static void sendText(Session session, String message) {
if (session == null || !session.isOpen()) {
return;
}
synchronized (session) {
try {
session.getBasicRemote().sendText(message);
} catch (IllegalStateException | IOException e) {
log.error("WebSocket send msg error...connection has been closed.");
}
}
}
public static boolean isInt(String s) {
return s.matches("[0-9]+");
}
public static int getInt(String a) {
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(a);
return Integer.parseInt(m.replaceAll("").trim());
}
public static boolean versionCheck(String target, String local) {
int[] targetParse = parseVersion(target);
int[] localParse = parseVersion(local);
if (targetParse[0] < localParse[0]) {
return true;
}
if (targetParse[0] == localParse[0]) {
if (targetParse[1] < localParse[1]) {
return true;
}
if (targetParse[1] == localParse[1]) {
if (targetParse[2] <= localParse[2]) {
return true;
}
}
}
return false;
}
public static int[] parseVersion(String s) {
return Arrays.stream(s.split("\\.")).mapToInt(Integer::parseInt).toArray();
}
}
|
byte[] result = new byte[4];
result[0] = (byte) (i & 0xff);
result[1] = (byte) (i >> 8 & 0xff);
result[2] = (byte) (i >> 16 & 0xff);
result[3] = (byte) (i >> 24 & 0xff);
return result;
| 1,068
| 102
| 1,170
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/LaunchTool.java
|
LaunchTool
|
destroy
|
class LaunchTool implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
File testFile = new File("test-output");
if (!testFile.exists()) {
testFile.mkdirs();
}
ScheduleTool.scheduleAtFixedRate(
new TransportConnectionThread(),
TransportConnectionThread.DELAY,
TransportConnectionThread.DELAY,
TransportConnectionThread.TIME_UNIT
);
TransportWorker.readQueue();
new Thread(() -> {
File file = new File("plugins/sonic-go-mitmproxy-ca-cert.pem");
if (!file.exists()) {
log.info("Generating ca file...");
SGMTool.startProxy("init", SGMTool.getCommand());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 仅生成证书
SGMTool.stopProxy("init");
file = new File("plugins/sonic-go-mitmproxy-ca-cert.pem");
if (!file.exists()) {
log.info("init sonic-go-mitmproxy-ca failed!");
} else {
log.info("init sonic-go-mitmproxy-ca Successful!");
}
}
}).start();
}
@PreDestroy
public void destroy() {<FILL_FUNCTION_BODY>}
}
|
for (String key : GlobalProcessMap.getMap().keySet()) {
Process ps = GlobalProcessMap.getMap().get(key);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
for (String key : IOSProcessMap.getMap().keySet()) {
List<Process> ps = IOSProcessMap.getMap().get(key);
for (Process p : ps) {
p.children().forEach(ProcessHandle::destroy);
p.destroy();
}
}
log.info("Release done!");
| 373
| 143
| 516
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/PHCTool.java
|
PHCTool
|
setPosition
|
class PHCTool {
private static String baseUrl = "http://127.0.0.1:7531";
private static RestTemplate restTemplate;
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
PHCTool.restTemplate = restTemplate;
}
public static void setPosition(int position, String type) {<FILL_FUNCTION_BODY>}
public static boolean isSupport() {
try {
ResponseEntity<String> responseEntity =
restTemplate.getForEntity(baseUrl + "/ping", String.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
if ("pong".equals(responseEntity.getBody())) {
log.info("hub is ready.");
return true;
}
}
log.info("hub is not ready.");
return false;
} catch (Exception e) {
log.info("hub is not ready. ignore...");
return false;
}
}
}
|
if (!isSupport()) return;
log.info("set hub position: {} {}", position, type);
JSONObject re = new JSONObject();
re.put("position", position);
re.put("type", type);
restTemplate.postForEntity(baseUrl + "/control", re, String.class);
| 258
| 80
| 338
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/PortTool.java
|
PortTool
|
getBindSocket
|
class PortTool {
public static Integer getPort() {
ServerSocket serverSocket;
int port = 0;
try {
serverSocket = new ServerSocket(0);
port = serverSocket.getLocalPort();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return port;
}
public static Socket getBindSocket() {<FILL_FUNCTION_BODY>}
public static int releaseAndGetPort(Socket socket) {
int port = socket.getLocalPort();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
return port;
}
}
|
Socket socket = new Socket();
InetSocketAddress inetAddress = new InetSocketAddress(0);
try {
socket.bind(inetAddress);
} catch (IOException e) {
e.printStackTrace();
}
return socket;
| 179
| 68
| 247
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/ProcessCommandTool.java
|
ProcessCommandTool
|
getProcessLocalCommand
|
class ProcessCommandTool {
public static String getProcessLocalCommandStr(String commandLine) {
List<String> processLocalCommand = getProcessLocalCommand(commandLine);
StringBuilder stringBuilder = new StringBuilder("");
for (String s : processLocalCommand) {
stringBuilder.append(s);
}
return stringBuilder.toString();
}
public static List<String> getProcessLocalCommand(String commandLine) {<FILL_FUNCTION_BODY>}
}
|
Process process = null;
InputStreamReader inputStreamReader = null;
InputStreamReader errorStreamReader;
LineNumberReader consoleInput = null;
LineNumberReader consoleError = null;
String consoleInputLine;
String consoleErrorLine;
List<String> sdrResult = new ArrayList<String>();
List<String> sdrErrorResult = new ArrayList<String>();
try {
String system = System.getProperty("os.name").toLowerCase();
if (system.contains("win")) {
process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", commandLine});
} else {
process = Runtime.getRuntime().exec(new String[]{"sh", "-c", commandLine});
}
inputStreamReader = new InputStreamReader(process.getInputStream());
consoleInput = new LineNumberReader(inputStreamReader);
while ((consoleInputLine = consoleInput.readLine()) != null) {
sdrResult.add(consoleInputLine);
}
errorStreamReader = new InputStreamReader(process.getErrorStream());
consoleError = new LineNumberReader(errorStreamReader);
while ((consoleErrorLine = consoleError.readLine()) != null) {
sdrErrorResult.add(consoleErrorLine);
}
int resultCode = process.waitFor();
if (resultCode > 0 && sdrErrorResult.size() > 0) {
return sdrErrorResult;
} else {
return sdrResult;
}
} catch (Exception e) {
return new ArrayList<String>();
} finally {
try {
if (null != consoleInput) {
consoleInput.close();
}
if (null != consoleError) {
consoleError.close();
}
if (null != inputStreamReader) {
inputStreamReader.close();
}
if (null != process) {
process.destroy();
}
} catch (Exception e) {
}
}
| 121
| 495
| 616
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/SGMTool.java
|
SGMTool
|
startProxy
|
class SGMTool {
private static final String pFile = new File("plugins").getAbsolutePath();
private static final File sgmBinary = new File(pFile + File.separator + "sonic-go-mitmproxy");
private static final String sgm = sgmBinary.getAbsolutePath();
public static String getCommand(int pPort, int webPort) {
return String.format(
"%s -cert_path %s -addr :%d -web_addr :%d", sgm, pFile, pPort, webPort);
}
public static String getCommand() {
return String.format(
"%s -cert_path %s", sgm, pFile);
}
public static void startProxy(String udId, String command) {<FILL_FUNCTION_BODY>}
public static void stopProxy(String udId) {
String processName = String.format("process-%s-proxy", udId);
if (GlobalProcessMap.getMap().get(processName) != null) {
Process ps = GlobalProcessMap.getMap().get(processName);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
}
}
|
String processName = String.format("process-%s-proxy", udId);
if (GlobalProcessMap.getMap().get(processName) != null) {
Process ps = GlobalProcessMap.getMap().get(processName);
ps.children().forEach(ProcessHandle::destroy);
ps.destroy();
}
String system = System.getProperty("os.name").toLowerCase();
Process ps = null;
try {
if (system.contains("win")) {
ps = Runtime.getRuntime().exec(new String[]{"cmd", "/c", command});
} else if (system.contains("linux") || system.contains("mac")) {
ps = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
}
InputStreamReader inputStreamReader = new InputStreamReader(ps.getInputStream());
BufferedReader stdInput = new BufferedReader(inputStreamReader);
Semaphore isFinish = new Semaphore(0);
new Thread(() -> {
String s;
while (true) {
try {
if ((s = stdInput.readLine()) == null) break;
} catch (IOException e) {
log.info(e.getMessage());
break;
}
if (s.contains("Proxy start listen")) {
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
}
isFinish.release();
}
}
try {
stdInput.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("{} web proxy done.", udId);
}).start();
int wait = 0;
while (!isFinish.tryAcquire()) {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
wait++;
if (wait >= 120) {
log.info("{} web proxy start timeout!", udId);
return;
}
}
GlobalProcessMap.getMap().put(processName, ps);
} catch (Exception e) {
e.printStackTrace();
}
| 311
| 585
| 896
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/SpringTool.java
|
SpringTool
|
getPropertiesValue
|
class SpringTool implements ApplicationContextAware, EmbeddedValueResolverAware {
private static ApplicationContext applicationContext = null;
private static StringValueResolver stringValueResolver = null;
@Override
public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
if (SpringTool.applicationContext == null) {
SpringTool.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static String getPropertiesValue(String name) {<FILL_FUNCTION_BODY>}
@Override
public void setEmbeddedValueResolver(@NonNull StringValueResolver resolver) {
stringValueResolver = resolver;
}
}
|
try {
name = "${" + name + "}";
return stringValueResolver.resolveStringValue(name);
} catch (Exception e) {
log.error("{%s} is not found.".formatted(name));
return null;
}
| 249
| 69
| 318
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/DownloadTool.java
|
DownloadTool
|
download
|
class DownloadTool {
public static File download(String urlString) throws IOException {<FILL_FUNCTION_BODY>}
}
|
URL url = new URL(urlString);
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
byte[] bs = new byte[1024];
int len;
long time = Calendar.getInstance().getTimeInMillis();
String tail = "";
if (urlString.lastIndexOf(".") != -1) {
tail = urlString.substring(urlString.lastIndexOf(".") + 1);
}
String filename = "test-output" + File.separator + "download-" + time + "." + tail;
File file = new File(filename);
FileOutputStream os;
os = new FileOutputStream(file, true);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
is.close();
return file;
| 33
| 226
| 259
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/FileTool.java
|
FileTool
|
unZipChromeDriver
|
class FileTool {
public static void zip(File result, File inputFile) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
result.getAbsoluteFile()));
zip(out, inputFile, "");
out.close();
}
public static void zip(ZipOutputStream out, File f, String base) throws IOException {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i]);
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
/**
* 解压缩下载完成的chromeDriver.zip文件
*
* @param source 原始的下载临时文件
* @param version 完整的chrome版本
* @param greaterThen114 是否>=115(大于115的场景下,使用的是google官方Chrome for Testing (CfT)下载路径)
* @param systemName 系统类型(大于115的场景下,判断产物文件会使用到)
* @return chromeDriver文件
*/
public static File unZipChromeDriver(File source, String version, boolean greaterThen114, String systemName) {<FILL_FUNCTION_BODY>}
public static void deleteDir(File file) {
if (!file.exists()) {
return;
}
File[] files = file.listFiles();
for (File f : files) {
if (f.isDirectory()) {
deleteDir(f);
} else {
f.delete();
}
}
file.delete();
}
}
|
int BUFFER = 2048;
File webview = new File("webview");
if (!webview.exists()) {
webview.mkdirs();
}
String system = System.getProperty("os.name").toLowerCase();
String tail = "chromedriver";
if (system.contains("win")) {
tail += ".exe";
}
File driver = null;
try {
ZipFile zipFile = new ZipFile(source);
Enumeration emu = zipFile.entries();
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
// >=115之后的版本,entry.name字段有变更,带上了系统类型
final String targetFileName = greaterThen114 ?
String.format("chromedriver-%s/%s", systemName, tail)
: tail;
if (entry.getName().equals(targetFileName)) {
String fileName = version + "_" + tail;
File file = new File(webview + File.separator + fileName);
File parent = file.getParentFile();
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close();
driver = file;
}
bis.close();
if (driver != null) {
break;
}
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
if (driver != null) {
driver.setExecutable(true);
driver.setWritable(true);
source.delete();
}
return driver;
| 530
| 541
| 1,071
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/tools/file/UploadTools.java
|
UploadTools
|
uploadPatchRecord
|
class UploadTools {
private final static Logger logger = LoggerFactory.getLogger(UploadTools.class);
@Value("${sonic.server.host}")
private String host;
@Value("${sonic.server.port}")
private String port;
private static String baseUrl;
private static RestTemplate restTemplate;
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
UploadTools.restTemplate = restTemplate;
baseUrl = ("http://" + host + ":" + port + "/server/api/folder").replace(":80/", "/");
}
public static String upload(File uploadFile, String type) {
File folder = new File("test-output");
if (!folder.exists()) {//判断文件目录是否存在
folder.mkdirs();
}
File transfer;
if (type.equals("keepFiles") || type.equals("imageFiles")) {
long timeMillis = Calendar.getInstance().getTimeInMillis();
try {
Thumbnails.of(uploadFile)
.scale(1f)
.outputQuality(0.25f).toFile(folder + File.separator + timeMillis + "transfer.jpg");
} catch (IOException e) {
logger.error(e.getMessage());
}
transfer = new File(folder + File.separator + timeMillis + "transfer.jpg");
} else {
transfer = uploadFile;
}
FileSystemResource resource = new FileSystemResource(transfer);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
param.add("type", type);
ResponseEntity<JSONObject> responseEntity =
restTemplate.postForEntity(baseUrl + "/upload/v2", param, JSONObject.class);
if (responseEntity.getBody().getInteger("code") == 2000) {
if (uploadFile.exists()) {
uploadFile.delete();
}
if (transfer.exists()) {
transfer.delete();
}
} else {
logger.info("发送失败!" + responseEntity.getBody());
}
return baseUrl + "/" + responseEntity.getBody().getString("data");
}
public static String uploadPatchRecord(File uploadFile) {<FILL_FUNCTION_BODY>}
}
|
if (uploadFile.length() == 0) {
uploadFile.delete();
return null;
}
String url = "";
long size = 1024 * 1024;
int num = (int) (Math.ceil(uploadFile.length() * 1.0 / size));
String uuid = UUID.randomUUID().toString();
File file = new File("test-output/record" + File.separator + uuid);
if (!file.exists()) {
file.mkdirs();
}
try {
RandomAccessFile before = new RandomAccessFile(uploadFile, "r");
long beforeSize = uploadFile.length();
byte[] bytes = new byte[1024];
int len;
int successNum = 0;
for (int i = 0; i < num; i++) {
File branchFile = new File(file.getPath() + File.separator + uploadFile.getName());
RandomAccessFile branch = new RandomAccessFile(branchFile, "rw");
while ((len = before.read(bytes)) != -1) {
if (beforeSize > len) {
branch.write(bytes, 0, len);
beforeSize -= len;
} else {
branch.write(bytes, 0, (int) beforeSize);
}
if (branch.length() >= size)
break;
}
branch.close();
FileSystemResource resource = new FileSystemResource(branchFile);
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", resource);
param.add("uuid", uuid);
param.add("index", i + "");
param.add("total", num + "");
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(baseUrl + "/upload/recordFiles", param, JSONObject.class);
if (responseEntity.getBody().getInteger("code") == 2000) {
successNum++;
}
if (responseEntity.getBody().getString("data") != null) {
url = responseEntity.getBody().getString("data");
}
branchFile.delete();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
before.close();
file.delete();
if (successNum == num) {
uploadFile.delete();
} else {
logger.info("上传缺失!");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return url;
| 600
| 673
| 1,273
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/RoutingDelegate.java
|
RoutingDelegate
|
createRequestEntity
|
class RoutingDelegate {
public ResponseEntity<String> redirect(HttpServletRequest request, HttpServletResponse response, String routeUrl, String prefix) {
try {
String redirectUrl = createPredictUrl(request, routeUrl, prefix);
RequestEntity requestEntity = createRequestEntity(request, redirectUrl);
return route(requestEntity);
} catch (Exception e) {
if (e.getMessage().contains("{") && e.getMessage().contains("}")) {
return new ResponseEntity(JSON.parseObject(e.getMessage().substring(e.getMessage().indexOf("{"), e.getMessage().lastIndexOf("}") + 1)).toJSONString(), HttpStatus.INTERNAL_SERVER_ERROR);
} else {
JSONObject err = new JSONObject();
err.put("error", "-1");
err.put("message", "REDIRECT ERROR");
err.put("traceback", "REDIRECT ERROR");
JSONObject base = new JSONObject();
base.put("value", err);
base.put("sessionId", "");
return new ResponseEntity(base.toJSONString(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
private String createPredictUrl(HttpServletRequest request, String routeUrl, String prefix) {
String queryString = request.getQueryString();
return routeUrl + request.getRequestURI().replace(prefix, "") +
(queryString != null ? "?" + queryString : "");
}
private RequestEntity createRequestEntity(HttpServletRequest request, String url) throws URISyntaxException, IOException {<FILL_FUNCTION_BODY>}
private ResponseEntity<String> route(RequestEntity requestEntity) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.exchange(requestEntity, String.class);
}
private byte[] parseRequestBody(HttpServletRequest request) throws IOException {
InputStream inputStream = request.getInputStream();
return StreamUtils.copyToByteArray(inputStream);
}
private MultiValueMap<String, String> parseRequestHeader(HttpServletRequest request) {
HttpHeaders headers = new HttpHeaders();
List<String> headerNames = Collections.list(request.getHeaderNames());
for (String headerName : headerNames) {
List<String> headerValues = Collections.list(request.getHeaders(headerName));
for (String headerValue : headerValues) {
headers.add(headerName, headerValue);
}
}
return headers;
}
}
|
String method = request.getMethod();
HttpMethod httpMethod = HttpMethod.valueOf(method);
MultiValueMap<String, String> headers = parseRequestHeader(request);
byte[] body = parseRequestBody(request);
return new RequestEntity<>(body, headers, httpMethod, new URI(url));
| 621
| 78
| 699
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportConnectionThread.java
|
TransportConnectionThread
|
run
|
class TransportConnectionThread implements Runnable {
/**
* second
*/
public static final long DELAY = 10;
public static final String THREAD_NAME = "transport-connection-thread";
public static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
String serverHost = String.valueOf(SpringTool.getPropertiesValue("sonic.server.host"));
Integer serverPort = Integer.valueOf(SpringTool.getPropertiesValue("sonic.server.port"));
String key = String.valueOf(SpringTool.getPropertiesValue("sonic.agent.key"));
@Override
public void run() {<FILL_FUNCTION_BODY>}
}
|
Thread.currentThread().setName(THREAD_NAME);
if (TransportWorker.client == null) {
if (!TransportWorker.isKeyAuth) {
return;
}
String url = String.format("ws://%s:%d/server/websockets/agent/%s",
serverHost, serverPort, key).replace(":80/", "/");
URI uri = URI.create(url);
TransportClient transportClient = new TransportClient(uri);
transportClient.connect();
} else {
JSONObject ping = new JSONObject();
ping.put("msg", "ping");
TransportWorker.send(ping);
}
| 176
| 168
| 344
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportController.java
|
TransportController
|
catchAll
|
class TransportController {
public final static String DELEGATE_PREFIX = "/uia";
@Autowired
private RoutingDelegate routingDelegate;
@RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = MediaType.ALL_VALUE)
public ResponseEntity catchAll(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>}
}
|
System.out.println(request.getRequestURI());
return routingDelegate.redirect(request, response, "http://localhost:" + request.getRequestURI().replace(DELEGATE_PREFIX + "/", ""), request.getRequestURI());
| 118
| 62
| 180
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/transport/TransportWorker.java
|
TransportWorker
|
readQueue
|
class TransportWorker {
private static LinkedBlockingQueue<JSONObject> dataQueue = new LinkedBlockingQueue<>();
public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static TransportClient client = null;
public static Boolean isKeyAuth = true;
public static void send(JSONObject jsonObject) {
dataQueue.offer(jsonObject);
}
public static void readQueue() {<FILL_FUNCTION_BODY>}
}
|
cachedThreadPool.execute(() -> {
while (isKeyAuth) {
try {
if (client != null && client.isOpen()) {
if (!dataQueue.isEmpty()) {
JSONObject m = dataQueue.poll();
m.put("agentId", BytesTool.agentId);
client.send(m.toJSONString());
} else {
Thread.sleep(1000);
}
} else {
Thread.sleep(5000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
| 121
| 156
| 277
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AndroidScreenWSServer.java
|
AndroidScreenWSServer
|
startScreen
|
class AndroidScreenWSServer implements IAndroidWSServer {
@Value("${sonic.agent.key}")
private String key;
private Map<String, String> typeMap = new ConcurrentHashMap<>();
private Map<String, String> picMap = new ConcurrentHashMap<>();
private AndroidMonitorHandler androidMonitorHandler = new AndroidMonitorHandler();
@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey,
@PathParam("udId") String udId, @PathParam("token") String token) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) {
log.info("Auth Failed!");
return;
}
IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId);
if (iDevice == null) {
log.info("Target device is not connecting, please check the connection.");
return;
}
AndroidDeviceBridgeTool.screen(iDevice, "abort");
session.getUserProperties().put("udId", udId);
session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId));
WebSocketSessionMap.addSession(session);
saveUdIdMapAndSet(session, iDevice);
int wait = 0;
boolean isInstall = true;
while (AndroidAPKMap.getMap().get(udId) == null || (!AndroidAPKMap.getMap().get(udId))) {
Thread.sleep(500);
wait++;
if (wait >= 40) {
isInstall = false;
break;
}
}
if (!isInstall) {
log.info("Waiting for apk install timeout!");
exit(session);
}
session.getUserProperties().put("schedule",ScheduleTool.schedule(() -> {
log.info("time up!");
if (session.isOpen()) {
JSONObject errMsg = new JSONObject();
errMsg.put("msg", "error");
BytesTool.sendText(session, errMsg.toJSONString());
exit(session);
}
}, BytesTool.remoteTimeout));
}
@OnClose
public void onClose(Session session) {
exit(session);
}
@OnError
public void onError(Session session, Throwable error) {
log.error(error.getMessage());
error.printStackTrace();
JSONObject errMsg = new JSONObject();
errMsg.put("msg", "error");
BytesTool.sendText(session, errMsg.toJSONString());
}
@OnMessage
public void onMessage(String message, Session session) {
JSONObject msg = JSON.parseObject(message);
log.info("{} send: {}", session.getUserProperties().get("id").toString(), msg);
String udId = session.getUserProperties().get("udId").toString();
switch (msg.getString("type")) {
case "switch" -> {
typeMap.put(udId, msg.getString("detail"));
IDevice iDevice = udIdMap.get(session);
if (!androidMonitorHandler.isMonitorRunning(iDevice)) {
androidMonitorHandler.startMonitor(iDevice, res -> {
JSONObject rotationJson = new JSONObject();
rotationJson.put("msg", "rotation");
rotationJson.put("value", Integer.parseInt(res) * 90);
BytesTool.sendText(session, rotationJson.toJSONString());
startScreen(session);
});
} else {
startScreen(session);
}
}
case "pic" -> {
picMap.put(udId, msg.getString("detail"));
startScreen(session);
}
}
}
private void startScreen(Session session) {<FILL_FUNCTION_BODY>}
private void exit(Session session) {
synchronized (session) {
ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule");
future.cancel(true);
String udId = session.getUserProperties().get("udId").toString();
androidMonitorHandler.stopMonitor(udIdMap.get(session));
WebSocketSessionMap.removeSession(session);
removeUdIdMapAndSet(session);
AndroidDeviceManagerMap.getRotationMap().remove(udId);
if (ScreenMap.getMap().get(session) != null) {
ScreenMap.getMap().get(session).interrupt();
}
typeMap.remove(udId);
picMap.remove(udId);
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("{} : quit.", session.getUserProperties().get("id").toString());
}
}
}
|
IDevice iDevice = udIdMap.get(session);
if (iDevice != null) {
Thread old = ScreenMap.getMap().get(session);
if (old != null) {
old.interrupt();
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (ScreenMap.getMap().get(session) != null);
}
typeMap.putIfAbsent(iDevice.getSerialNumber(), "scrcpy");
switch (typeMap.get(iDevice.getSerialNumber())) {
case "scrcpy" -> {
ScrcpyServerUtil scrcpyServerUtil = new ScrcpyServerUtil();
Thread scrcpyThread = scrcpyServerUtil.start(iDevice.getSerialNumber(), AndroidDeviceManagerMap.getRotationMap().get(iDevice.getSerialNumber()), session);
ScreenMap.getMap().put(session, scrcpyThread);
}
case "minicap" -> {
MiniCapUtil miniCapUtil = new MiniCapUtil();
AtomicReference<String[]> banner = new AtomicReference<>(new String[24]);
Thread miniCapThread = miniCapUtil.start(
iDevice.getSerialNumber(), banner, null,
picMap.get(iDevice.getSerialNumber()) == null ? "high" : picMap.get(iDevice.getSerialNumber()),
AndroidDeviceManagerMap.getRotationMap().get(iDevice.getSerialNumber()), session
);
ScreenMap.getMap().put(session, miniCapThread);
}
}
JSONObject picFinish = new JSONObject();
picFinish.put("msg", "picFinish");
BytesTool.sendText(session, picFinish.toJSONString());
}
| 1,257
| 467
| 1,724
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/AudioWSServer.java
|
AudioWSServer
|
startAudio
|
class AudioWSServer implements IAndroidWSServer {
@Value("${sonic.agent.key}")
private String key;
private Map<Session, Thread> audioMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("udId") String udId) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key))) {
log.info("Auth Failed!");
return;
}
IDevice iDevice = AndroidDeviceBridgeTool.getIDeviceByUdId(udId);
session.getUserProperties().put("udId", udId);
session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId));
WebSocketSessionMap.addSession(session);
saveUdIdMapAndSet(session, iDevice);
int wait = 0;
boolean isInstall = true;
while (AndroidAPKMap.getMap().get(udId) == null || (!AndroidAPKMap.getMap().get(udId))) {
Thread.sleep(500);
wait++;
if (wait >= 40) {
isInstall = false;
break;
}
}
if (!isInstall) {
log.info("Waiting for apk install timeout!");
} else {
startAudio(session);
}
}
private void startAudio(Session session) {<FILL_FUNCTION_BODY>}
private void stopAudio(Session session) {
if (audioMap.get(session) != null) {
audioMap.get(session).interrupt();
int wait = 0;
while (!audioMap.get(session).isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
wait++;
if (wait >= 3) {
break;
}
}
}
audioMap.remove(session);
}
// @OnMessage
// public void onMessage(String message, Session session) {
// JSONObject msg = JSON.parseObject(message);
// log.info("{} send: {}",session.getUserProperties().get("id").toString(), msg);
// switch (msg.getString("type")) {
// case "start":
// startAudio(session);
// break;
// case "stop":
// stopAudio(session);
// break;
// }
// }
@OnClose
public void onClose(Session session) {
exit(session);
}
@OnError
public void onError(Session session, Throwable error) {
log.info("Audio socket error, cause: {}, ignore...", error.getMessage());
}
private void exit(Session session) {
stopAudio(session);
WebSocketSessionMap.removeSession(session);
removeUdIdMapAndSet(session);
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("{} : quit.", session.getUserProperties().get("id").toString());
}
}
|
stopAudio(session);
IDevice iDevice = udIdMap.get(session);
AndroidDeviceBridgeTool.executeCommand(iDevice, "appops set org.cloud.sonic.android PROJECT_MEDIA allow");
AndroidDeviceBridgeTool.executeCommand(iDevice, "appops set org.cloud.sonic.android RECORD_AUDIO allow");
AndroidDeviceBridgeTool.executeCommand(iDevice, "am start -n org.cloud.sonic.android/.plugin.audioPlugin.AudioActivity");
int wait = 0;
String has = AndroidDeviceBridgeTool.executeCommand(iDevice, "cat /proc/net/unix");
while (!has.contains("sonicaudioservice")) {
wait++;
if (wait > 8) {
return;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
has = AndroidDeviceBridgeTool.executeCommand(iDevice, "cat /proc/net/unix");
}
int appAudioPort = PortTool.getPort();
Thread audio = new Thread(() -> {
try {
AndroidDeviceBridgeTool.forward(iDevice, appAudioPort, "sonicaudioservice");
Socket audioSocket = null;
InputStream inputStream = null;
try {
audioSocket = new Socket("localhost", appAudioPort);
inputStream = audioSocket.getInputStream();
while (audioSocket.isConnected() && !Thread.interrupted()) {
byte[] lengthBytes = inputStream.readNBytes(32);
if (Thread.interrupted() || lengthBytes.length == 0) {
break;
}
StringBuilder binStr = new StringBuilder();
for (byte lengthByte : lengthBytes) {
binStr.append(lengthByte);
}
Integer readLen = Integer.valueOf(binStr.toString(), 2);
byte[] dataBytes = inputStream.readNBytes(readLen);
ByteBuffer byteBuffer = ByteBuffer.allocate(dataBytes.length);
byteBuffer.put(dataBytes);
byteBuffer.flip();
BytesTool.sendByte(session, byteBuffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (audioSocket != null && audioSocket.isConnected()) {
try {
audioSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception ignored) {
}
AndroidDeviceBridgeTool.removeForward(iDevice, appAudioPort, "sonicaudioservice");
});
audio.start();
audioMap.put(session, audio);
| 826
| 733
| 1,559
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSScreenWSServer.java
|
IOSScreenWSServer
|
onOpen
|
class IOSScreenWSServer implements IIOSWSServer {
@Value("${sonic.agent.key}")
private String key;
@Value("${sonic.agent.port}")
private int port;
@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey,
@PathParam("udId") String udId, @PathParam("token") String token) throws InterruptedException {<FILL_FUNCTION_BODY>}
@OnClose
public void onClose(Session session) {
exit(session);
}
@OnError
public void onError(Session session, Throwable error) {
log.error(error.getMessage());
}
private void exit(Session session) {
synchronized (session) {
ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule");
future.cancel(true);
WebSocketSessionMap.removeSession(session);
removeUdIdMapAndSet(session);
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("{} : quit.", session.getUserProperties().get("id").toString());
}
}
}
|
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) {
log.info("Auth Failed!");
return;
}
if (!SibTool.getDeviceList().contains(udId)) {
log.info("Target device is not connecting, please check the connection.");
return;
}
session.getUserProperties().put("udId", udId);
session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId));
WebSocketSessionMap.addSession(session);
saveUdIdMapAndSet(session, udId);
int screenPort = 0;
int wait = 0;
while (wait < 120) {
Integer p = IOSWSServer.screenMap.get(udId);
if (p != null) {
screenPort = p;
break;
}
Thread.sleep(500);
wait++;
}
if (screenPort == 0) {
return;
}
int finalScreenPort = screenPort;
new Thread(() -> {
URL url;
try {
url = new URL("http://localhost:" + finalScreenPort);
} catch (MalformedURLException e) {
return;
}
MjpegInputStream mjpegInputStream = null;
int waitMjpeg = 0;
while (mjpegInputStream == null) {
try {
mjpegInputStream = new MjpegInputStream(url.openStream());
} catch (IOException e) {
log.info(e.getMessage());
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.info(e.getMessage());
return;
}
waitMjpeg++;
if (waitMjpeg >= 20) {
log.info("mjpeg server connect fail");
return;
}
}
ByteBuffer bufferedImage;
int i = 0;
while (true) {
try {
if ((bufferedImage = mjpegInputStream.readFrameForByteBuffer()) == null) break;
} catch (IOException e) {
log.info(e.getMessage());
break;
}
i++;
if (i % 3 != 0) {
sendByte(session, bufferedImage);
} else {
i = 0;
}
}
try {
mjpegInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("screen done.");
}).start();
session.getUserProperties().put("schedule", ScheduleTool.schedule(() -> {
log.info("time up!");
if (session.isOpen()) {
JSONObject errMsg = new JSONObject();
errMsg.put("msg", "error");
BytesTool.sendText(session, errMsg.toJSONString());
exit(session);
}
}, BytesTool.remoteTimeout));
| 325
| 780
| 1,105
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/IOSTerminalWSServer.java
|
IOSTerminalWSServer
|
onOpen
|
class IOSTerminalWSServer implements IIOSWSServer {
@Value("${sonic.agent.key}")
private String key;
@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey,
@PathParam("udId") String udId, @PathParam("token") String token) throws Exception {<FILL_FUNCTION_BODY>}
@OnMessage
public void onMessage(String message, Session session) throws InterruptedException {
JSONObject msg = JSON.parseObject(message);
log.info("{} send: {}", session.getUserProperties().get("id").toString(), msg);
String udId = udIdMap.get(session);
switch (msg.getString("type")) {
case "processList" -> SibTool.getProcessList(udId, session);
case "appList" -> SibTool.getAppList(udId, session);
case "syslog" -> SibTool.getSysLog(udId, msg.getString("filter"), session);
case "stopSyslog" -> SibTool.stopSysLog(udId);
}
}
@OnClose
public void onClose(Session session) {
exit(session);
}
@OnError
public void onError(Session session, Throwable error) {
log.error(error.getMessage());
JSONObject errMsg = new JSONObject();
errMsg.put("msg", "error");
sendText(session, errMsg.toJSONString());
}
private void exit(Session session) {
synchronized (session) {
ScheduledFuture<?> future = (ScheduledFuture<?>) session.getUserProperties().get("schedule");
future.cancel(true);
if (udIdMap.get(session) != null) {
SibTool.stopSysLog(udIdMap.get(session));
}
WebSocketSessionMap.removeSession(session);
removeUdIdMapAndSet(session);
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("{} : quit.", session.getUserProperties().get("id").toString());
}
}
}
|
if (secretKey.length() == 0 || (!secretKey.equals(key)) || token.length() == 0) {
log.info("Auth Failed!");
return;
}
if (!SibTool.getDeviceList().contains(udId)) {
log.info("Target device is not connecting, please check the connection.");
return;
}
session.getUserProperties().put("udId", udId);
session.getUserProperties().put("id", String.format("%s-%s", this.getClass().getSimpleName(), udId));
WebSocketSessionMap.addSession(session);
saveUdIdMapAndSet(session, udId);
JSONObject ter = new JSONObject();
ter.put("msg", "terminal");
sendText(session, ter.toJSONString());
session.getUserProperties().put("schedule", ScheduleTool.schedule(() -> {
log.info("time up!");
if (session.isOpen()) {
JSONObject errMsg = new JSONObject();
errMsg.put("msg", "error");
BytesTool.sendText(session, errMsg.toJSONString());
exit(session);
}
}, BytesTool.remoteTimeout));
| 570
| 311
| 881
|
<no_super_class>
|
SonicCloudOrg_sonic-agent
|
sonic-agent/src/main/java/org/cloud/sonic/agent/websockets/WebViewWSServer.java
|
WebViewWSServer
|
onMessage
|
class WebViewWSServer {
private final Logger logger = LoggerFactory.getLogger(WebViewWSServer.class);
@Value("${sonic.agent.key}")
private String key;
private Map<Session, WebSocketClient> sessionWebSocketClientMap = new HashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("key") String secretKey, @PathParam("port") int port, @PathParam("id") String id) throws Exception {
if (secretKey.length() == 0 || (!secretKey.equals(key))) {
logger.info("Auth Failed!");
return;
}
URI uri = new URI("ws://localhost:" + port + "/devtools/page/" + id);
WebSocketClient webSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
logger.info("Connected!");
}
@Override
public void onMessage(String s) {
BytesTool.sendText(session, s);
}
@Override
public void onClose(int i, String s, boolean b) {
logger.info("Disconnected!");
}
@Override
public void onError(Exception e) {
}
};
webSocketClient.connect();
sessionWebSocketClientMap.put(session, webSocketClient);
}
@OnMessage
public void onMessage(String message, Session session) throws InterruptedException {<FILL_FUNCTION_BODY>}
@OnClose
public void onClose(Session session) {
sessionWebSocketClientMap.get(session).close();
sessionWebSocketClientMap.remove(session);
}
@OnError
public void onError(Session session, Throwable error) {
logger.error(error.getMessage());
}
}
|
if (sessionWebSocketClientMap.get(session) != null) {
try {
sessionWebSocketClientMap.get(session).send(message);
} catch (Exception e) {
}
}
| 470
| 58
| 528
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/config/CommonResultControllerAdvice.java
|
CommonResultControllerAdvice
|
beforeBodyWrite
|
class CommonResultControllerAdvice implements ResponseBodyAdvice<Object> {
@Resource
private MessageSource messageSource;
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {<FILL_FUNCTION_BODY>}
public static RespModel process(String l, RespModel respModel, MessageSource messageSource) {
String language = "en_US";
if (l != null) {
language = l;
}
String[] split = language.split("_");
Locale locale;
if (split.length >= 2) {
locale = new Locale(split[0], split[1]);
} else {
locale = new Locale("en", "US");
}
respModel.setMessage(messageSource.getMessage(respModel.getMessage(), new Object[]{}, locale));
return respModel;
}
private MappingJacksonValue getOrCreateContainer(Object body) {
return (body instanceof MappingJacksonValue ? (MappingJacksonValue) body : new MappingJacksonValue(body));
}
}
|
MappingJacksonValue container = getOrCreateContainer(body);
String l = request.getHeaders().getFirst("Accept-Language");
// Get return body
Object returnBody = container.getValue();
if (returnBody instanceof RespModel) {
RespModel<?> baseResponse = (RespModel) returnBody;
process(l, baseResponse, messageSource);
}
return container;
| 353
| 105
| 458
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/config/GlobalWebException.java
|
GlobalWebException
|
ErrHandler
|
class GlobalWebException {
private final Logger logger = LoggerFactory.getLogger(GlobalWebException.class);
@ExceptionHandler(Exception.class)
public RespModel ErrHandler(Exception exception) {<FILL_FUNCTION_BODY>}
}
|
logger.error(exception.getMessage());
if (exception instanceof MissingServletRequestParameterException) {
return new RespModel(RespEnum.PARAMS_MISSING_ERROR);
} else if (exception instanceof ConstraintViolationException) {
return new RespModel(RespEnum.PARAMS_VIOLATE_ERROR);
} else if (exception instanceof MethodArgumentNotValidException) {
return new RespModel(RespEnum.PARAMS_NOT_VALID);
} else if (exception instanceof HttpMessageNotReadableException) {
return new RespModel(RespEnum.PARAMS_NOT_READABLE);
} else if (exception instanceof SonicException) {
return new RespModel(4006, exception.getMessage());
} else {
exception.printStackTrace();
return new RespModel(RespEnum.UNKNOWN_ERROR);
}
| 65
| 220
| 285
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/config/I18nConfig.java
|
I18nConfig
|
messageSource
|
class I18nConfig {
@Bean
public MessageSource messageSource() {<FILL_FUNCTION_BODY>}
}
|
ReloadableResourceBundleMessageSource messageSource
= new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:i18n/sonic");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
| 36
| 65
| 101
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/config/WebAspectConfig.java
|
WebAspectConfig
|
deBefore
|
class WebAspectConfig {
private final Logger logger = LoggerFactory.getLogger(WebAspectConfig.class);
/**
* @return void
* @author ZhouYiXun
* @des 定义切点,注解类webAspect
* @date 2021/8/15 23:08
*/
@Pointcut("@annotation(WebAspect)")
public void webAspect() {
}
/**
* @param joinPoint
* @return void
* @author ZhouYiXun
* @des 请求前获取所有信息
* @date 2021/8/15 23:08
*/
@Before("webAspect()")
public void deBefore(JoinPoint joinPoint) throws Throwable {<FILL_FUNCTION_BODY>}
/**
* @param ret
* @return void
* @author ZhouYiXun
* @des 请求完毕后打印结果
* @date 2021/8/15 23:10
*/
@AfterReturning(returning = "ret", pointcut = "webAspect()")
public void doAfterReturning(Object ret) throws Throwable {
JSONObject jsonObject = new JSONObject();
jsonObject.put("response", ret);
logger.info(jsonObject.toJSONString());
}
/**
* @param joinPoint
* @param ex
* @return void
* @author ZhouYiXun
* @des 报错的话打印错误信息
* @date 2021/8/15 23:11
*/
@AfterThrowing(throwing = "ex", pointcut = "webAspect()")
public void error(JoinPoint joinPoint, Exception ex) {
logger.info("error : " + ex.getMessage());
}
}
|
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//默认打印为json格式,接入elasticsearch等会方便查看
JSONObject jsonObject = new JSONObject();
jsonObject.put("url", request.getRequestURL().toString());
jsonObject.put("method", request.getMethod());
jsonObject.put("auth", request.getHeader("SonicToken"));
jsonObject.put("class", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
jsonObject.put("request", Arrays.toString(joinPoint.getArgs()));
logger.info(jsonObject.toJSONString());
| 488
| 182
| 670
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/http/RespModel.java
|
RespModel
|
toString
|
class RespModel<T> {
@Schema(description = "状态码")
private int code;
@Schema(description = "状态描述")
private String message;
@Schema(description = "响应详情")
private T data;
public RespModel() {
}
public RespModel(int code, String message) {
this(code, message, null);
}
public RespModel(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public RespModel(RespEnum respEnum) {
this.code = respEnum.getCode();
this.message = respEnum.getMessage();
}
public RespModel(RespEnum respEnum, T data) {
this.code = respEnum.getCode();
this.message = respEnum.getMessage();
this.data = data;
}
public static RespModel result(RespEnum respEnum) {
return new RespModel(respEnum);
}
public static <T> RespModel<T> result(RespEnum respEnum, T data) {
return new RespModel<T>(respEnum, data);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public RespModel<T> setMessage(String msg) {
this.message = msg;
return this;
}
public T getData() {
return data;
}
public RespModel<T> setData(T data) {
this.data = data;
return this;
}
@Override
public String toString() {<FILL_FUNCTION_BODY>}
}
|
return "RespModel{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
| 484
| 47
| 531
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/BeanTool.java
|
BeanTool
|
transformFrom
|
class BeanTool {
private BeanTool() {
}
/**
* Transforms from the source object. (copy same properties only)
*
* @param source source data
* @param targetClass target class must not be null
* @param <T> target class type
* @return instance with specified type copying from source data; or null if source data is null
* @throws BeanToolException if newing target instance failed or copying failed
*/
@Nullable
public static <T> T transformFrom(@Nullable Object source, @NonNull Class<T> targetClass) {<FILL_FUNCTION_BODY>}
/**
* Transforms from source data collection in batch.
*
* @param sources source data collection
* @param targetClass target class must not be null
* @param <T> target class type
* @return target collection transforming from source data collection.
* @throws BeanToolException if newing target instance failed or copying failed
*/
@NonNull
public static <T> List<T> transformFromInBatch(Collection<?> sources, @NonNull Class<T> targetClass) {
if (CollectionUtils.isEmpty(sources)) {
return Collections.emptyList();
}
// Transform in batch
return sources.stream()
.map(source -> transformFrom(source, targetClass))
.collect(Collectors.toList());
}
/**
* Update properties (non null).
*
* @param source source data must not be null
* @param target target data must not be null
* @throws BeanToolException if copying failed
*/
public static void updateProperties(@NonNull Object source, @NonNull Object target) {
Assert.notNull(source, "source object must not be null");
Assert.notNull(target, "target object must not be null");
// Set non null properties from source properties to target properties
try {
org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
} catch (BeansException e) {
throw new BeanToolException("Failed to copy properties", e);
}
}
/**
* Gets null names array of property.
*
* @param source object data must not be null
* @return null name array of property
*/
@NonNull
private static String[] getNullPropertyNames(@NonNull Object source) {
return getNullPropertyNameSet(source).toArray(new String[0]);
}
/**
* Gets null names set of property.
*
* @param source object data must not be null
* @return null name set of property
*/
@NonNull
private static Set<String> getNullPropertyNameSet(@NonNull Object source) {
Assert.notNull(source, "source object must not be null");
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
String propertyName = propertyDescriptor.getName();
Object propertyValue = beanWrapper.getPropertyValue(propertyName);
// if property value is equal to null, add it to empty name set
if (propertyValue == null) {
emptyNames.add(propertyName);
}
}
return emptyNames;
}
@NonNull
public static <T> T toBean(Object source, Class<T> clazz) {
Assert.notNull(source, "object must not be null");
Assert.notNull(clazz, "clazz must not be null");
return BeanTool.toBean(source, clazz);
}
}
|
Assert.notNull(targetClass, "Target class must not be null");
if (source == null) {
return null;
}
// Init the instance
try {
// New instance for the target class
T targetInstance = targetClass.getDeclaredConstructor().newInstance();
// Copy properties
org.springframework.beans.BeanUtils.copyProperties(source, targetInstance, getNullPropertyNames(source));
// Return the target instance
return targetInstance;
} catch (Exception e) {
throw new BeanToolException("Failed to new " + targetClass.getName() + " instance or copy properties", e);
}
| 942
| 160
| 1,102
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/JWTTokenTool.java
|
JWTTokenTool
|
verify
|
class JWTTokenTool {
@Value("${sonic.token.secret}")
private String TOKEN_SECRET;
@Value("${sonic.token.expireDay}")
private int EXPIRE_DAY;
/**
* @param username
* @return java.lang.String
* @author ZhouYiXun
* @des 通过用户名生成token
* @date 2021/8/15 23:05
*/
public String getToken(String username) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, EXPIRE_DAY);
Date nowTime = now.getTime();
return JWT.create().withAudience(username, UUID.randomUUID().toString())
.withExpiresAt(nowTime)
.sign(Algorithm.HMAC256(TOKEN_SECRET));
}
public String getToken(String username, int day) {
Calendar now = Calendar.getInstance();
now.add(Calendar.DATE, day);
Date nowTime = now.getTime();
return JWT.create().withAudience(username, UUID.randomUUID().toString())
.withExpiresAt(nowTime)
.sign(Algorithm.HMAC256(TOKEN_SECRET));
}
/**
* @param token
* @return java.lang.String
* @author ZhouYiXun
* @des 由token获取生成时的用户信息
* @date 2021/8/15 23:05
*/
public String getUserName(String token) {
try {
return JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException e) {
return null;
}
}
/**
* @param token
* @return boolean
* @author ZhouYiXun
* @des 校验token的签名是否合法
* @date 2021/8/15 23:05
*/
public boolean verify(String token) {<FILL_FUNCTION_BODY>}
}
|
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
try {
jwtVerifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
| 562
| 78
| 640
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-common/src/main/java/org/cloud/sonic/common/tools/ReflectionTool.java
|
ReflectionTool
|
getParameterizedType
|
class ReflectionTool {
private ReflectionTool() {
}
/**
* Gets parameterized type.
*
* @param superType super type must not be null (super class or super interface)
* @param genericTypes generic type array
* @return parameterized type of the interface or null if it is mismatch
*/
@Nullable
public static ParameterizedType getParameterizedType(@NonNull Class<?> superType, Type... genericTypes) {
Assert.notNull(superType, "Interface or super type must not be null");
ParameterizedType currentType = null;
for (Type genericType : genericTypes) {
if (genericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericType;
if (parameterizedType.getRawType().getTypeName().equals(superType.getTypeName())) {
currentType = parameterizedType;
break;
}
}
}
return currentType;
}
/**
* Gets parameterized type.
*
* @param interfaceType interface type must not be null
* @param implementationClass implementation class of the interface must not be null
* @return parameterized type of the interface or null if it is mismatch
*/
@Nullable
public static ParameterizedType getParameterizedType(@NonNull Class<?> interfaceType, Class<?> implementationClass) {<FILL_FUNCTION_BODY>}
/**
* Gets parameterized type by super class.
*
* @param superClassType super class type must not be null
* @param extensionClass extension class
* @return parameterized type or null
*/
@Nullable
public static ParameterizedType getParameterizedTypeBySuperClass(@NonNull Class<?> superClassType, Class<?> extensionClass) {
if (extensionClass == null) {
return null;
}
return getParameterizedType(superClassType, extensionClass.getGenericSuperclass());
}
}
|
Assert.notNull(interfaceType, "Interface type must not be null");
Assert.isTrue(interfaceType.isInterface(), "The give type must be an interface");
if (implementationClass == null) {
// If the super class is Object parent then return null
return null;
}
// Get parameterized type
ParameterizedType currentType = getParameterizedType(interfaceType, implementationClass.getGenericInterfaces());
if (currentType != null) {
// return the current type
return currentType;
}
Class<?> superclass = implementationClass.getSuperclass();
return getParameterizedType(interfaceType, superclass);
| 501
| 169
| 670
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/PermissionFilter.java
|
PermissionFilter
|
doFilterInternal
|
class PermissionFilter extends OncePerRequestFilter {
/**
* 是否开启权限管理
*/
@Value("${sonic.permission.enable}")
private boolean permissionEnable;
/**
* 内置超管账号
*/
@Value("${sonic.permission.superAdmin}")
private String superAdmin;
@Autowired
private JWTTokenTool jwtTokenTool;
@Autowired
private RolesServices rolesServices;
@Autowired
private ResourcesService resourcesService;
public static final String TOKEN = "SonicToken";
@Resource
private MessageSource messageSource;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {<FILL_FUNCTION_BODY>}
private RespModel process(HttpServletRequest request, RespModel respModel) {
String l = request.getHeader("Accept-Language");
CommonResultControllerAdvice.process(l, respModel, messageSource);
return respModel;
}
}
|
if (request.getRequestURL().toString().contains("swagger")) {
filterChain.doFilter(request, response);
return;
}
String token = request.getHeader(TOKEN);
if (permissionEnable && token != null && !request.getMethod().equalsIgnoreCase("options")) {
String userName = jwtTokenTool.getUserName(token);
if (Objects.equals(superAdmin, userName)) {
filterChain.doFilter(request, response);
return;
}
String resourceName = request.getServletPath();
String method = request.getMethod();
log.info("PermissionFilter: {}", resourceName);
Resources resources = resourcesService.search(resourceName, method);
if (resources == null) {
response.setContentType("text/plain;charset=UTF-8");
JSONObject re = (JSONObject) JSONObject.toJSON(process(request, new RespModel(RespEnum.RESOURCE_NOT_FOUND)));
response.getWriter().write(re.toJSONString());
return;
}
if (resources.getWhite() == UrlType.WHITE || resources.getNeedAuth() == UrlType.WHITE) {
filterChain.doFilter(request, response);
return;
}
if (!rolesServices.checkUserHasResourceAuthorize(userName, resourceName, method)) {
response.setContentType("text/plain;charset=UTF-8");
JSONObject re = (JSONObject) JSONObject.toJSON(process(request, new RespModel(RespEnum.PERMISSION_DENIED)));
response.getWriter().write(re.toJSONString());
return;
}
}
filterChain.doFilter(request, response);
| 283
| 447
| 730
|
<methods>public void <init>() ,public final void doFilter(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, jakarta.servlet.FilterChain) throws jakarta.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/RestTempConfig.java
|
RestTempConfig
|
simpleClientHttpRequestFactory
|
class RestTempConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {<FILL_FUNCTION_BODY>}
}
|
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);
factory.setConnectTimeout(5000);
return factory;
| 71
| 50
| 121
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/SonicRunner.java
|
SonicRunner
|
idleInit
|
class SonicRunner implements ApplicationRunner {
@Autowired
private ResourcesService resourcesService;
@Autowired
private ConfListService confListService;
@Value("${spring.version}")
private String version;
@Override
public void run(ApplicationArguments args) throws Exception {
resourceInit();
remoteInit();
idleInit();
}
/**
* 每次启动对信息进行版本对比,不一致进行一起更新
*/
private void resourceInit() {
try {
ConfList conf = confListService.searchByKey(ConfType.RESOURCE);
if (conf != null && Objects.equals(conf.getContent(), version)) {
log.info("version: {}, resource has been init...", version);
return;
}
resourcesService.init();
log.info("version: {}, resource init finish!", version);
confListService.save(ConfType.RESOURCE, version, null);
} catch (Exception e) {
log.error("init resource error", e);
}
}
private void remoteInit() {
try {
ConfList conf = confListService.searchByKey(ConfType.REMOTE_DEBUG_TIMEOUT);
if (conf != null) {
log.info("remote conf has been init...");
return;
}
confListService.save(ConfType.REMOTE_DEBUG_TIMEOUT, "480", null);
log.info("remote conf init finish!");
} catch (Exception e) {
log.error("init remote conf error", e);
}
}
private void idleInit() {<FILL_FUNCTION_BODY>}
}
|
try {
ConfList conf = confListService.searchByKey(ConfType.IDEL_DEBUG_TIMEOUT);
if (conf != null) {
log.info("idle conf has been init...");
return;
}
confListService.save(ConfType.IDEL_DEBUG_TIMEOUT, "480", null);
log.info("idle conf init finish!");
} catch (Exception e) {
log.error("init idle conf error", e);
}
| 434
| 129
| 563
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/SpringDocConfig.java
|
SpringDocConfig
|
springDocOpenAPI
|
class SpringDocConfig {
@Value("${spring.version}")
private String version;
@Bean
public OpenAPI springDocOpenAPI() {<FILL_FUNCTION_BODY>}
}
|
return new OpenAPI()
.info(new Info().title("Controller REST API")
.version(version)
.contact(new Contact().name("SonicCloudOrg")
.email("soniccloudorg@163.com"))
.description("Controller of Sonic Cloud Real Machine Platform")
.termsOfService("https://github.com/SonicCloudOrg/sonic-server/blob/main/LICENSE")
.license(new License().name("AGPL v3")
.url("https://github.com/SonicCloudOrg/sonic-server/blob/main/LICENSE")));
| 55
| 154
| 209
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyBatisPlusConfig.java
|
MyBatisPlusConfig
|
mybatisPlusInterceptor
|
class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {<FILL_FUNCTION_BODY>}
}
|
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
| 47
| 59
| 106
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/config/mybatis/MyMetaObjectHandler.java
|
MyMetaObjectHandler
|
updateFill
|
class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.debug("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
this.strictInsertFill(metaObject, "time", Date.class, new Date());
this.strictInsertFill(metaObject, "editTime", Date.class, new Date());
}
@Override
public void updateFill(MetaObject metaObject) {<FILL_FUNCTION_BODY>}
}
|
log.debug("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
this.strictUpdateFill(metaObject, "editTime", Date.class, new Date());
| 163
| 58
| 221
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AgentsController.java
|
AgentsController
|
hubControl
|
class AgentsController {
@Autowired
private AgentsService agentsService;
@WebAspect
@GetMapping("/hubControl")
public RespModel<?> hubControl(@RequestParam(name = "id") int id, @RequestParam(name = "position") int position,
@RequestParam(name = "type") String type) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "查询所有Agent端", description = "获取所有Agent端以及详细信息")
@GetMapping("/list")
public RespModel<List<AgentsDTO>> findAgents() {
return new RespModel<>(
RespEnum.SEARCH_OK,
agentsService.findAgents().stream().map(TypeConverter::convertTo).collect(Collectors.toList())
);
}
@WebAspect
@Operation(summary = "修改agent信息", description = "修改agent信息")
@PutMapping("/update")
public RespModel<String> update(@RequestBody AgentsDTO jsonObject) {
agentsService.update(jsonObject.getId(),
jsonObject.getName(), jsonObject.getHighTemp(),
jsonObject.getHighTempTime(), jsonObject.getRobotType(),
jsonObject.getRobotToken(), jsonObject.getRobotToken(),
jsonObject.getAlertRobotIds());
return new RespModel<>(RespEnum.HANDLE_OK);
}
@WebAspect
@Operation(summary = "查询Agent端信息", description = "获取对应id的Agent信息")
@GetMapping
public RespModel<?> findOne(@RequestParam(name = "id") int id) {
Agents agents = agentsService.findById(id);
if (agents != null) {
return new RespModel<>(RespEnum.SEARCH_OK, agents);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
}
|
JSONObject result = new JSONObject();
result.put("msg", "hub");
result.put("position", position);
result.put("type", type);
TransportWorker.send(id, result);
return new RespModel<>(RespEnum.HANDLE_OK);
| 505
| 76
| 581
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AlertRobotsAdminController.java
|
AlertRobotsAdminController
|
delete
|
class AlertRobotsAdminController {
@Autowired
private AlertRobotsService alertRobotsService;
@WebAspect
@Operation(summary = "更新机器人参数", description = "新增或更新对应的机器人")
@PutMapping
public RespModel<String> save(@Validated @RequestBody AlertRobotsDTO alertRobotsDTO) {
alertRobotsService.saveOrUpdate(alertRobotsDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查找机器人参数", description = "查找所有机器人参数列表")
@GetMapping("/list")
@Parameters(value = {
@Parameter(name = "scene", allowEmptyValue = true, description = "使用场景"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页尺寸")
})
public RespModel<CommentPage<AlertRobots>> listAll(
@RequestParam(name = "scene", required = false) String scene,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize", defaultValue = "20") int pageSize
) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.findRobots(new Page<>(page, pageSize), null, scene));
}
@WebAspect
@Operation(summary = "查找机器人参数", description = "查找所有机器人参数列表")
@GetMapping("/listAll")
@Parameters(value = {
@Parameter(name = "scene", allowEmptyValue = true, description = "使用场景")
})
public RespModel<List<AlertRobots>> listAll(
@RequestParam(name = "scene", required = false) String scene
) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.findAllRobots(null, scene));
}
@WebAspect
@Operation(summary = "删除机器人参数", description = "删除对应id的机器人参数")
@Parameter(name = "id", description = "id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "获取机器人对类型机器人在相应使用场景下的默认模板", description = "获取机器人对类型机器人在相应使用场景下的默认模板")
@Parameter(name = "type", description = "type")
@Parameter(name = "scene", description = "scene")
@GetMapping("/findDefaultTemplate")
@WhiteUrl
public RespModel<String> getDefaultNoticeTemplate(@RequestParam(name = "type") int type, @RequestParam(name = "scene") String scene) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.getDefaultNoticeTemplate(type, scene));
}
}
|
if (alertRobotsService.removeById(id)) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
| 765
| 63
| 828
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/AlertRobotsController.java
|
AlertRobotsController
|
delete
|
class AlertRobotsController {
@Autowired
private AlertRobotsService alertRobotsService;
@WebAspect
@Operation(summary = "更新机器人参数", description = "新增或更新对应的机器人")
@PutMapping
public RespModel<String> save(@Validated @RequestBody AlertRobotsDTO alertRobotsDTO) {
alertRobotsService.saveOrUpdate(alertRobotsDTO.convertTo());
return new RespModel<>(RespEnum.UPDATE_OK);
}
@WebAspect
@Operation(summary = "查找项目机器人参数", description = "查找对应项目id的机器人参数列表")
@GetMapping("/list")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "scene", allowEmptyValue = true, description = "使用场景"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页尺寸")
})
public RespModel<CommentPage<AlertRobots>> list(
@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "scene", required = false) String scene,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize", defaultValue = "20") int pageSize
) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.findRobots(new Page<>(page, pageSize), projectId, scene));
}
@WebAspect
@Operation(summary = "查找项目机器人参数", description = "查找对应项目id的机器人参数列表")
@GetMapping("/listAll")
@Parameters(value = {
@Parameter(name = "projectId", allowEmptyValue = true, description = "项目id"),
@Parameter(name = "scene", allowEmptyValue = true, description = "使用场景")
})
public RespModel<List<AlertRobots>> listAll(
@RequestParam(name = "projectId", required = false, defaultValue = "-1") int projectId,
@RequestParam(name = "scene", required = false) String scene
) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.findAllRobots(projectId, scene));
}
@WebAspect
@Operation(summary = "删除机器人参数", description = "删除对应id的机器人参数")
@Parameter(name = "id", description = "id")
@DeleteMapping
public RespModel<String> delete(
@Parameter(name = "projectId", description = "项目id") int projectId,
@RequestParam(name = "id") int id
) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "获取机器人对类型机器人在相应使用场景下的默认模板", description = "获取机器人对类型机器人在相应使用场景下的默认模板")
@Parameter(name = "type", description = "type")
@Parameter(name = "scene", description = "scene")
@GetMapping("/findDefaultTemplate")
@WhiteUrl
public RespModel<String> getDefaultNoticeTemplate(@RequestParam(name = "type") int type, @RequestParam(name = "scene") String scene) {
return new RespModel<>(RespEnum.SEARCH_OK, alertRobotsService.getDefaultNoticeTemplate(type, scene));
}
}
|
if (alertRobotsService.remove(Wrappers.lambdaQuery(AlertRobots.class).eq(AlertRobots::getId, id).eq(AlertRobots::getProjectId, projectId))) {
return new RespModel<>(RespEnum.DELETE_OK);
} else {
return new RespModel<>(RespEnum.DELETE_FAIL);
}
| 883
| 99
| 982
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ConfListController.java
|
ConfListController
|
setRemoteTimeout
|
class ConfListController {
@Autowired
private ConfListService confListService;
@Autowired
private AgentsService agentsService;
@WebAspect
@Operation(summary = "获取远控超时时间", description = "获取远控超时时间")
@GetMapping("/getRemoteTimeout")
public RespModel getRemoteTimeout() {
return new RespModel<>(RespEnum.SEARCH_OK,
Integer.parseInt(confListService.searchByKey(ConfType.REMOTE_DEBUG_TIMEOUT).getContent()));
}
@WebAspect
@Operation(summary = "设置远控超时时间", description = "设置远控超时时间")
@GetMapping("/setRemoteTimeout")
public RespModel setRemoteTimeout(@RequestParam(name = "timeout") int timeout) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "获取闲置超时时间", description = "获取闲置超时时间")
@GetMapping("/getIdleTimeout")
public RespModel getIdleTimeout() {
return new RespModel<>(RespEnum.SEARCH_OK,
Integer.parseInt(confListService.searchByKey(ConfType.IDEL_DEBUG_TIMEOUT).getContent()));
}
@WebAspect
@Operation(summary = "设置闲置超时时间", description = "设置闲置超时时间")
@GetMapping("/setIdleTimeout")
public RespModel setIdleTimeout(@RequestParam(name = "timeout") int timeout) {
confListService.save(ConfType.IDEL_DEBUG_TIMEOUT, timeout + "", null);
return new RespModel<>(RespEnum.HANDLE_OK);
}
}
|
confListService.save(ConfType.REMOTE_DEBUG_TIMEOUT, timeout + "", null);
List<Agents> agentsList = agentsService.findAgents();
for (Agents agents : agentsList) {
JSONObject result = new JSONObject();
result.put("msg", "settings");
result.put("remoteTimeout", timeout);
TransportWorker.send(agents.getId(), result);
}
return new RespModel<>(RespEnum.HANDLE_OK);
| 436
| 127
| 563
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ElementsController.java
|
ElementsController
|
save
|
class ElementsController {
@Autowired
private ElementsService elementsService;
@WebAspect
@Operation(summary = "查找控件元素列表1", description = "查找对应项目id的控件元素列表")
@Parameters(value = {
@Parameter(name = "projectId", description = "项目id"),
@Parameter(name = "eleTypes[]", description = "类型(多个)"),
@Parameter(name = "name", description = "控件名称"),
@Parameter(name = "value", description = "控件值"),
@Parameter(name = "type", description = "类型"),
@Parameter(name = "moduleIds", description = "模块ID"),
@Parameter(name = "page", description = "页码"),
@Parameter(name = "pageSize", description = "页数据大小")
})
@GetMapping("/list")
public RespModel<CommentPage<ElementsDTO>> findAll(@RequestParam(name = "projectId") int projectId,
@RequestParam(name = "type", required = false) String type,
@RequestParam(name = "eleTypes[]", required = false) List<String> eleTypes,
@RequestParam(name = "name", required = false) String name,
@RequestParam(name = "value", required = false) String value,
@RequestParam(name = "moduleIds[]", required = false) List<Integer> moduleIds,
@RequestParam(name = "page") int page,
@RequestParam(name = "pageSize") int pageSize) {
Page<Elements> pageable = new Page<>(page, pageSize);
return new RespModel<>(
RespEnum.SEARCH_OK,
elementsService.findAll(projectId, type, eleTypes, name, value, moduleIds, pageable)
);
}
@WebAspect
@Operation(summary = "查找控件元素详情", description = "查找对应id的对应控件元素详细信息")
@Parameter(name = "id", description = "控件元素id")
@GetMapping
public RespModel<Elements> findById(@RequestParam(name = "id") int id) {
Elements elements = elementsService.findById(id);
if (elements != null) {
return new RespModel<>(RespEnum.SEARCH_OK, elements);
} else {
return new RespModel<>(RespEnum.ID_NOT_FOUND);
}
}
@WebAspect
@Operation(summary = "删除控件元素", description = "删除对应id的控件元素,当控件元素存在于用例或id不存在时,删除失败")
@Parameter(name = "id", description = "元素id")
@DeleteMapping
public RespModel<String> delete(@RequestParam(name = "id") int id) {
return elementsService.delete(id);
}
@WebAspect
@Operation(summary = "删除控件元素前检验", description = "返回引用控件的步骤")
@Parameter(name = "id", description = "元素id")
@GetMapping("/deleteCheck")
public RespModel<List<StepsDTO>> deleteCheck(@RequestParam(name = "id") int id) {
return new RespModel<>(RespEnum.SEARCH_OK, elementsService.findAllStepsByElementsId(id));
}
@WebAspect
@Operation(summary = "更新控件元素", description = "新增或更新控件元素信息,id为0时新增,否则为更新对应id的信息")
@PutMapping
public RespModel<String> save(@Validated @RequestBody ElementsDTO elementsDTO) {<FILL_FUNCTION_BODY>}
@WebAspect
@Operation(summary = "复制控件元素", description = "复制控件元素,按照元素ID")
@Parameter(name = "id", description = "元素id")
@GetMapping("/copyEle")
public RespModel<String> copy(@RequestParam(name = "id") int id) {
return elementsService.copy(id);
}
}
|
if (elementsService.save(elementsDTO.convertTo())) {
return new RespModel<>(RespEnum.UPDATE_OK);
} else {
return new RespModel<>(RespEnum.UPDATE_FAIL);
}
| 1,041
| 63
| 1,104
|
<no_super_class>
|
SonicCloudOrg_sonic-server
|
sonic-server/sonic-server-controller/src/main/java/org/cloud/sonic/controller/controller/ExchangeController.java
|
ExchangeController
|
stop
|
class ExchangeController {
@Autowired
private AgentsService agentsService;
@Autowired
private DevicesService devicesService;
@WebAspect
@Operation(summary = "重启设备", description = "根据 id 重启特定设备")
@GetMapping("/reboot")
public RespModel<String> reboot(@RequestParam(name = "id") int id) {
Devices devices = devicesService.findById(id);
Agents agents = agentsService.findById(devices.getAgentId());
if (ObjectUtils.isEmpty(agents)) {
return new RespModel<>(RespEnum.AGENT_NOT_ONLINE);
}
if (ObjectUtils.isEmpty(devices)) {
return new RespModel<>(RespEnum.DEVICE_NOT_FOUND);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "reboot");
jsonObject.put("udId", devices.getUdId());
jsonObject.put("platform", devices.getPlatform());
TransportWorker.send(agents.getId(), jsonObject);
return new RespModel<>(RespEnum.HANDLE_OK);
}
@WebAspect
@Operation(summary = "下线agent", description = "下线指定的 agent")
@GetMapping("/stop")
public RespModel<String> stop(@RequestParam(name = "id") int id) {<FILL_FUNCTION_BODY>}
//eureka调度用
@WebAspect
@WhiteUrl
@PostMapping("/send")
public RespModel<String> send(@RequestParam(name = "id") int id, @RequestBody JSONObject jsonObject) {
Session agentSession = BytesTool.agentSessionMap.get(id);
if (agentSession != null) {
BytesTool.sendText(agentSession, jsonObject.toJSONString());
}
return new RespModel<>(RespEnum.SEND_OK);
}
}
|
Agents agents = agentsService.findById(id);
if (agents.getStatus() != AgentStatus.ONLINE) {
return new RespModel<>(2000, "stop.agent.not.online");
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "shutdown");
TransportWorker.send(agents.getId(), jsonObject);
return new RespModel<>(RespEnum.HANDLE_OK);
| 501
| 121
| 622
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.