Code format (#2662)

* NullPointerException

* code rule
This commit is contained in:
Wang jie 2018-10-23 12:35:49 +08:00 committed by Ian Luo
parent dd950acaeb
commit 6938d487a3
64 changed files with 1569 additions and 937 deletions

View File

@ -26,10 +26,10 @@ import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.LoadBalance;
import org.apache.dubbo.rpc.support.RpcUtils;
@ -138,10 +138,12 @@ public abstract class AbstractClusterInvoker<T> implements Invoker<T> {
}
private Invoker<T> doSelect(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
if (invokers == null || invokers.isEmpty())
if (invokers == null || invokers.isEmpty()) {
return null;
if (invokers.size() == 1)
}
if (invokers.size() == 1) {
return invokers.get(0);
}
Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation);
//If the `invoker` is in the `selected` or invoker is unavailable && availablecheck is true, reselect.

View File

@ -206,14 +206,18 @@ public /**final**/ class URL implements Serializable {
}
i = url.indexOf("://");
if (i >= 0) {
if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\"");
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 3);
} else {
// case: file:/path/to/file.txt
i = url.indexOf(":/");
if (i >= 0) {
if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\"");
if (i == 0) {
throw new IllegalStateException("url missing protocol: \"" + url + "\"");
}
protocol = url.substring(0, i);
url = url.substring(i + 1);
}
@ -246,7 +250,9 @@ public /**final**/ class URL implements Serializable {
url = url.substring(0, i);
}
}
if (url.length() > 0) host = url;
if (url.length() > 0) {
host = url;
}
return new URL(protocol, username, password, host, port, path, parameters);
}
@ -915,17 +921,23 @@ public /**final**/ class URL implements Serializable {
}
public URL addParameter(String key, Enum<?> value) {
if (value == null) return this;
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URL addParameter(String key, Number value) {
if (value == null) return this;
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URL addParameter(String key, CharSequence value) {
if (value == null || value.length() == 0) return this;
if (value == null || value.length() == 0) {
return this;
}
return addParameter(key, String.valueOf(value));
}
@ -984,7 +996,9 @@ public /**final**/ class URL implements Serializable {
}
}
// return immediately if there's no change
if (hasAndEqual) return this;
if (hasAndEqual) {
return this;
}
Map<String, String> map = new HashMap<String, String>(getParameters());
map.putAll(parameters);
@ -1055,35 +1069,47 @@ public /**final**/ class URL implements Serializable {
}
public String getRawParameter(String key) {
if ("protocol".equals(key))
if ("protocol".equals(key)) {
return protocol;
if ("username".equals(key))
}
if ("username".equals(key)) {
return username;
if ("password".equals(key))
}
if ("password".equals(key)) {
return password;
if ("host".equals(key))
}
if ("host".equals(key)) {
return host;
if ("port".equals(key))
}
if ("port".equals(key)) {
return String.valueOf(port);
if ("path".equals(key))
}
if ("path".equals(key)) {
return path;
}
return getParameter(key);
}
public Map<String, String> toMap() {
Map<String, String> map = new HashMap<String, String>(parameters);
if (protocol != null)
if (protocol != null) {
map.put("protocol", protocol);
if (username != null)
}
if (username != null) {
map.put("username", username);
if (password != null)
}
if (password != null) {
map.put("password", password);
if (host != null)
}
if (host != null) {
map.put("host", host);
if (port > 0)
}
if (port > 0) {
map.put("port", String.valueOf(port));
if (path != null)
}
if (path != null) {
map.put("path", path);
}
return map;
}
@ -1218,7 +1244,9 @@ public /**final**/ class URL implements Serializable {
public String getServiceKey() {
String inf = getServiceInterface();
if (inf == null) return null;
if (inf == null) {
return null;
}
StringBuilder buf = new StringBuilder();
String group = getParameter(Constants.GROUP_KEY);
if (group != null && group.length() > 0) {
@ -1359,45 +1387,61 @@ public /**final**/ class URL implements Serializable {
@Override
public boolean equals(Object obj) {
if (this == obj)
if (this == obj) {
return true;
if (obj == null)
}
if (obj == null) {
return false;
if (getClass() != obj.getClass())
}
if (getClass() != obj.getClass()) {
return false;
}
URL other = (URL) obj;
if (host == null) {
if (other.host != null)
if (other.host != null) {
return false;
} else if (!host.equals(other.host))
}
} else if (!host.equals(other.host)) {
return false;
}
if (parameters == null) {
if (other.parameters != null)
if (other.parameters != null) {
return false;
} else if (!parameters.equals(other.parameters))
}
} else if (!parameters.equals(other.parameters)) {
return false;
}
if (password == null) {
if (other.password != null)
if (other.password != null) {
return false;
} else if (!password.equals(other.password))
}
} else if (!password.equals(other.password)) {
return false;
}
if (path == null) {
if (other.path != null)
if (other.path != null) {
return false;
} else if (!path.equals(other.path))
}
} else if (!path.equals(other.path)) {
return false;
if (port != other.port)
}
if (port != other.port) {
return false;
}
if (protocol == null) {
if (other.protocol != null)
if (other.protocol != null) {
return false;
} else if (!protocol.equals(other.protocol))
}
} else if (!protocol.equals(other.protocol)) {
return false;
}
if (username == null) {
if (other.username != null)
if (other.username != null) {
return false;
} else if (!username.equals(other.username))
}
} else if (!username.equals(other.username)) {
return false;
}
return true;
}

View File

@ -399,14 +399,16 @@ public final class JavaBeanSerializeUtil {
}
result = Array.newInstance(componentType, beanDescriptor.propertySize());
cache.put(beanDescriptor, result);
} else try {
Class<?> cl = name2Class(loader, beanDescriptor.getClassName());
result = instantiate(cl);
cache.put(beanDescriptor, result);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} else {
try {
Class<?> cl = name2Class(loader, beanDescriptor.getClassName());
result = instantiate(cl);
cache.put(beanDescriptor, result);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
return result;

View File

@ -1,391 +1,391 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.bytecode;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* ClassGenerator
*/
public final class ClassGenerator {
private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0);
private static final String SIMPLE_NAME_TAG = "<init>";
private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<ClassLoader, ClassPool>(); //ClassLoader - ClassPool
private ClassPool mPool;
private CtClass mCtc;
private String mClassName;
private String mSuperClass;
private Set<String> mInterfaces;
private List<String> mFields;
private List<String> mConstructors;
private List<String> mMethods;
private Map<String, Method> mCopyMethods; // <method desc,method instance>
private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance>
private boolean mDefaultConstructor = false;
private ClassGenerator() {
}
private ClassGenerator(ClassPool pool) {
mPool = pool;
}
public static ClassGenerator newInstance() {
return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader()));
}
public static ClassGenerator newInstance(ClassLoader loader) {
return new ClassGenerator(getClassPool(loader));
}
public static boolean isDynamicClass(Class<?> cl) {
return ClassGenerator.DC.class.isAssignableFrom(cl);
}
public static ClassPool getClassPool(ClassLoader loader) {
if (loader == null) {
return ClassPool.getDefault();
}
ClassPool pool = POOL_MAP.get(loader);
if (pool == null) {
pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
POOL_MAP.put(loader, pool);
}
return pool;
}
private static String modifier(int mod) {
StringBuilder modifier = new StringBuilder();
if (Modifier.isPublic(mod)) {
modifier.append("public");
}
if (Modifier.isProtected(mod)) {
modifier.append("protected");
}
if (Modifier.isPrivate(mod)) {
modifier.append("private");
}
if (Modifier.isStatic(mod)) {
modifier.append(" static");
}
if (Modifier.isVolatile(mod)) {
modifier.append(" volatile");
}
return modifier.toString();
}
public String getClassName() {
return mClassName;
}
public ClassGenerator setClassName(String name) {
mClassName = name;
return this;
}
public ClassGenerator addInterface(String cn) {
if (mInterfaces == null) {
mInterfaces = new HashSet<String>();
}
mInterfaces.add(cn);
return this;
}
public ClassGenerator addInterface(Class<?> cl) {
return addInterface(cl.getName());
}
public ClassGenerator setSuperClass(String cn) {
mSuperClass = cn;
return this;
}
public ClassGenerator setSuperClass(Class<?> cl) {
mSuperClass = cl.getName();
return this;
}
public ClassGenerator addField(String code) {
if (mFields == null) {
mFields = new ArrayList<String>();
}
mFields.add(code);
return this;
}
public ClassGenerator addField(String name, int mod, Class<?> type) {
return addField(name, mod, type, null);
}
public ClassGenerator addField(String name, int mod, Class<?> type, String def) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' ');
sb.append(name);
if (def != null && def.length() > 0) {
sb.append('=');
sb.append(def);
}
sb.append(';');
return addField(sb.toString());
}
public ClassGenerator addMethod(String code) {
if (mMethods == null) {
mMethods = new ArrayList<String>();
}
mMethods.add(code);
return this;
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) {
return addMethod(name, mod, rt, pts, null, body);
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets,
String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addMethod(sb.toString());
}
public ClassGenerator addMethod(Method m) {
addMethod(m.getName(), m);
return this;
}
public ClassGenerator addMethod(String name, Method m) {
String desc = name + ReflectUtils.getDescWithoutMethodName(m);
addMethod(':' + desc);
if (mCopyMethods == null) {
mCopyMethods = new ConcurrentHashMap<String, Method>(8);
}
mCopyMethods.put(desc, m);
return this;
}
public ClassGenerator addConstructor(String code) {
if (mConstructors == null) {
mConstructors = new LinkedList<String>();
}
mConstructors.add(code);
return this;
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) {
return addConstructor(mod, pts, null, body);
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addConstructor(sb.toString());
}
public ClassGenerator addConstructor(Constructor<?> c) {
String desc = ReflectUtils.getDesc(c);
addConstructor(":" + desc);
if (mCopyConstructors == null) {
mCopyConstructors = new ConcurrentHashMap<String, Constructor<?>>(4);
}
mCopyConstructors.put(desc, c);
return this;
}
public ClassGenerator addDefaultConstructor() {
mDefaultConstructor = true;
return this;
}
public ClassPool getClassPool() {
return mPool;
}
public Class<?> toClass() {
return toClass(ClassHelper.getClassLoader(ClassGenerator.class),
getClass().getProtectionDomain());
}
public Class<?> toClass(ClassLoader loader, ProtectionDomain pd) {
if (mCtc != null) {
mCtc.detach();
}
long id = CLASS_NAME_COUNTER.getAndIncrement();
try {
CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass);
if (mClassName == null) {
mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers())
? ClassGenerator.class.getName() : mSuperClass + "$sc") + id;
}
mCtc = mPool.makeClass(mClassName);
if (mSuperClass != null) {
mCtc.setSuperclass(ctcs);
}
mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag.
if (mInterfaces != null) {
for (String cl : mInterfaces) {
mCtc.addInterface(mPool.get(cl));
}
}
if (mFields != null) {
for (String code : mFields) {
mCtc.addField(CtField.make(code, mCtc));
}
}
if (mMethods != null) {
for (String code : mMethods) {
if (code.charAt(0) == ':') {
mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))),
code.substring(1, code.indexOf('(')), mCtc, null));
} else {
mCtc.addMethod(CtNewMethod.make(code, mCtc));
}
}
}
if (mDefaultConstructor) {
mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));
}
if (mConstructors != null) {
for (String code : mConstructors) {
if (code.charAt(0) == ':') {
mCtc.addConstructor(CtNewConstructor
.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null));
} else {
String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $.
mCtc.addConstructor(
CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc));
}
}
}
return mCtc.toClass(loader, pd);
} catch (RuntimeException e) {
throw e;
} catch (NotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (CannotCompileException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public void release() {
if (mCtc != null) {
mCtc.detach();
}
if (mInterfaces != null) {
mInterfaces.clear();
}
if (mFields != null) {
mFields.clear();
}
if (mMethods != null) {
mMethods.clear();
}
if (mConstructors != null) {
mConstructors.clear();
}
if (mCopyMethods != null) {
mCopyMethods.clear();
}
if (mCopyConstructors != null) {
mCopyConstructors.clear();
}
}
private CtClass getCtClass(Class<?> c) throws NotFoundException {
return mPool.get(c.getName());
}
private CtMethod getCtMethod(Method m) throws NotFoundException {
return getCtClass(m.getDeclaringClass())
.getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m));
}
private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException {
return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c));
}
public static interface DC {
} // dynamic class tag interface.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.common.bytecode;
import org.apache.dubbo.common.utils.ClassHelper;
import org.apache.dubbo.common.utils.ReflectUtils;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.NotFoundException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* ClassGenerator
*/
public final class ClassGenerator {
private static final AtomicLong CLASS_NAME_COUNTER = new AtomicLong(0);
private static final String SIMPLE_NAME_TAG = "<init>";
private static final Map<ClassLoader, ClassPool> POOL_MAP = new ConcurrentHashMap<ClassLoader, ClassPool>(); //ClassLoader - ClassPool
private ClassPool mPool;
private CtClass mCtc;
private String mClassName;
private String mSuperClass;
private Set<String> mInterfaces;
private List<String> mFields;
private List<String> mConstructors;
private List<String> mMethods;
private Map<String, Method> mCopyMethods; // <method desc,method instance>
private Map<String, Constructor<?>> mCopyConstructors; // <constructor desc,constructor instance>
private boolean mDefaultConstructor = false;
private ClassGenerator() {
}
private ClassGenerator(ClassPool pool) {
mPool = pool;
}
public static ClassGenerator newInstance() {
return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader()));
}
public static ClassGenerator newInstance(ClassLoader loader) {
return new ClassGenerator(getClassPool(loader));
}
public static boolean isDynamicClass(Class<?> cl) {
return ClassGenerator.DC.class.isAssignableFrom(cl);
}
public static ClassPool getClassPool(ClassLoader loader) {
if (loader == null) {
return ClassPool.getDefault();
}
ClassPool pool = POOL_MAP.get(loader);
if (pool == null) {
pool = new ClassPool(true);
pool.appendClassPath(new LoaderClassPath(loader));
POOL_MAP.put(loader, pool);
}
return pool;
}
private static String modifier(int mod) {
StringBuilder modifier = new StringBuilder();
if (Modifier.isPublic(mod)) {
modifier.append("public");
}
if (Modifier.isProtected(mod)) {
modifier.append("protected");
}
if (Modifier.isPrivate(mod)) {
modifier.append("private");
}
if (Modifier.isStatic(mod)) {
modifier.append(" static");
}
if (Modifier.isVolatile(mod)) {
modifier.append(" volatile");
}
return modifier.toString();
}
public String getClassName() {
return mClassName;
}
public ClassGenerator setClassName(String name) {
mClassName = name;
return this;
}
public ClassGenerator addInterface(String cn) {
if (mInterfaces == null) {
mInterfaces = new HashSet<String>();
}
mInterfaces.add(cn);
return this;
}
public ClassGenerator addInterface(Class<?> cl) {
return addInterface(cl.getName());
}
public ClassGenerator setSuperClass(String cn) {
mSuperClass = cn;
return this;
}
public ClassGenerator setSuperClass(Class<?> cl) {
mSuperClass = cl.getName();
return this;
}
public ClassGenerator addField(String code) {
if (mFields == null) {
mFields = new ArrayList<String>();
}
mFields.add(code);
return this;
}
public ClassGenerator addField(String name, int mod, Class<?> type) {
return addField(name, mod, type, null);
}
public ClassGenerator addField(String name, int mod, Class<?> type, String def) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(type)).append(' ');
sb.append(name);
if (def != null && def.length() > 0) {
sb.append('=');
sb.append(def);
}
sb.append(';');
return addField(sb.toString());
}
public ClassGenerator addMethod(String code) {
if (mMethods == null) {
mMethods = new ArrayList<String>();
}
mMethods.add(code);
return this;
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, String body) {
return addMethod(name, mod, rt, pts, null, body);
}
public ClassGenerator addMethod(String name, int mod, Class<?> rt, Class<?>[] pts, Class<?>[] ets,
String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(ReflectUtils.getName(rt)).append(' ').append(name);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addMethod(sb.toString());
}
public ClassGenerator addMethod(Method m) {
addMethod(m.getName(), m);
return this;
}
public ClassGenerator addMethod(String name, Method m) {
String desc = name + ReflectUtils.getDescWithoutMethodName(m);
addMethod(':' + desc);
if (mCopyMethods == null) {
mCopyMethods = new ConcurrentHashMap<String, Method>(8);
}
mCopyMethods.put(desc, m);
return this;
}
public ClassGenerator addConstructor(String code) {
if (mConstructors == null) {
mConstructors = new LinkedList<String>();
}
mConstructors.add(code);
return this;
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, String body) {
return addConstructor(mod, pts, null, body);
}
public ClassGenerator addConstructor(int mod, Class<?>[] pts, Class<?>[] ets, String body) {
StringBuilder sb = new StringBuilder();
sb.append(modifier(mod)).append(' ').append(SIMPLE_NAME_TAG);
sb.append('(');
for (int i = 0; i < pts.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(pts[i]));
sb.append(" arg").append(i);
}
sb.append(')');
if (ets != null && ets.length > 0) {
sb.append(" throws ");
for (int i = 0; i < ets.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(ReflectUtils.getName(ets[i]));
}
}
sb.append('{').append(body).append('}');
return addConstructor(sb.toString());
}
public ClassGenerator addConstructor(Constructor<?> c) {
String desc = ReflectUtils.getDesc(c);
addConstructor(":" + desc);
if (mCopyConstructors == null) {
mCopyConstructors = new ConcurrentHashMap<String, Constructor<?>>(4);
}
mCopyConstructors.put(desc, c);
return this;
}
public ClassGenerator addDefaultConstructor() {
mDefaultConstructor = true;
return this;
}
public ClassPool getClassPool() {
return mPool;
}
public Class<?> toClass() {
return toClass(ClassHelper.getClassLoader(ClassGenerator.class),
getClass().getProtectionDomain());
}
public Class<?> toClass(ClassLoader loader, ProtectionDomain pd) {
if (mCtc != null) {
mCtc.detach();
}
long id = CLASS_NAME_COUNTER.getAndIncrement();
try {
CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass);
if (mClassName == null) {
mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers())
? ClassGenerator.class.getName() : mSuperClass + "$sc") + id;
}
mCtc = mPool.makeClass(mClassName);
if (mSuperClass != null) {
mCtc.setSuperclass(ctcs);
}
mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag.
if (mInterfaces != null) {
for (String cl : mInterfaces) {
mCtc.addInterface(mPool.get(cl));
}
}
if (mFields != null) {
for (String code : mFields) {
mCtc.addField(CtField.make(code, mCtc));
}
}
if (mMethods != null) {
for (String code : mMethods) {
if (code.charAt(0) == ':') {
mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))),
code.substring(1, code.indexOf('(')), mCtc, null));
} else {
mCtc.addMethod(CtNewMethod.make(code, mCtc));
}
}
}
if (mDefaultConstructor) {
mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));
}
if (mConstructors != null) {
for (String code : mConstructors) {
if (code.charAt(0) == ':') {
mCtc.addConstructor(CtNewConstructor
.copy(getCtConstructor(mCopyConstructors.get(code.substring(1))), mCtc, null));
} else {
String[] sn = mCtc.getSimpleName().split("\\$+"); // inner class name include $.
mCtc.addConstructor(
CtNewConstructor.make(code.replaceFirst(SIMPLE_NAME_TAG, sn[sn.length - 1]), mCtc));
}
}
}
return mCtc.toClass(loader, pd);
} catch (RuntimeException e) {
throw e;
} catch (NotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (CannotCompileException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
public void release() {
if (mCtc != null) {
mCtc.detach();
}
if (mInterfaces != null) {
mInterfaces.clear();
}
if (mFields != null) {
mFields.clear();
}
if (mMethods != null) {
mMethods.clear();
}
if (mConstructors != null) {
mConstructors.clear();
}
if (mCopyMethods != null) {
mCopyMethods.clear();
}
if (mCopyConstructors != null) {
mCopyConstructors.clear();
}
}
private CtClass getCtClass(Class<?> c) throws NotFoundException {
return mPool.get(c.getName());
}
private CtMethod getCtMethod(Method m) throws NotFoundException {
return getCtClass(m.getDeclaringClass())
.getMethod(m.getName(), ReflectUtils.getDescWithoutMethodName(m));
}
private CtConstructor getCtConstructor(Constructor<?> c) throws NotFoundException {
return getCtClass(c.getDeclaringClass()).getConstructor(ReflectUtils.getDesc(c));
}
public static interface DC {
} // dynamic class tag interface.
}

View File

@ -98,16 +98,18 @@ public abstract class Mixin {
if (pkg == null) {
pkg = npkg;
} else {
if (!pkg.equals(npkg))
if (!pkg.equals(npkg)) {
throw new IllegalArgumentException("non-public interfaces class from different packages");
}
}
}
ccp.addField("private " + dcs[i].getName() + " d" + i + ";");
code.append("d").append(i).append(" = (").append(dcs[i].getName()).append(")$1[").append(i).append("];\n");
if (MixinAware.class.isAssignableFrom(dcs[i]))
if (MixinAware.class.isAssignableFrom(dcs[i])) {
code.append("d").append(i).append(".setMixinInstance(this);\n");
}
}
ccp.addConstructor(Modifier.PUBLIC, new Class<?>[]{Object[].class}, code.toString());
@ -119,39 +121,45 @@ public abstract class Mixin {
if (pkg == null) {
pkg = npkg;
} else {
if (!pkg.equals(npkg))
if (!pkg.equals(npkg)) {
throw new IllegalArgumentException("non-public delegate class from different packages");
}
}
}
ccp.addInterface(ics[i]);
for (Method method : ics[i].getMethods()) {
if ("java.lang.Object".equals(method.getDeclaringClass().getName()))
if ("java.lang.Object".equals(method.getDeclaringClass().getName())) {
continue;
}
String desc = ReflectUtils.getDesc(method);
if (worked.contains(desc))
if (worked.contains(desc)) {
continue;
}
worked.add(desc);
int ix = findMethod(dcs, desc);
if (ix < 0)
if (ix < 0) {
throw new RuntimeException("Missing method [" + desc + "] implement.");
}
Class<?> rt = method.getReturnType();
String mn = method.getName();
if (Void.TYPE.equals(rt))
if (Void.TYPE.equals(rt)) {
ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(),
"d" + ix + "." + mn + "($$);");
else
} else {
ccp.addMethod(mn, method.getModifiers(), rt, method.getParameterTypes(), method.getExceptionTypes(),
"return ($r)d" + ix + "." + mn + "($$);");
}
}
}
if (pkg == null)
if (pkg == null) {
pkg = PACKAGE_NAME;
}
// create MixinInstance class.
String micn = pkg + ".mixin" + id;
@ -173,10 +181,12 @@ public abstract class Mixin {
throw new RuntimeException(e.getMessage(), e);
} finally {
// release ClassGenerator
if (ccp != null)
if (ccp != null) {
ccp.release();
if (ccm != null)
}
if (ccm != null) {
ccm.release();
}
}
}
@ -187,17 +197,20 @@ public abstract class Mixin {
cl = dcs[i];
methods = cl.getMethods();
for (Method method : methods) {
if (desc.equals(ReflectUtils.getDesc(method)))
if (desc.equals(ReflectUtils.getDesc(method))) {
return i;
}
}
}
return -1;
}
private static void assertInterfaceArray(Class<?>[] ics) {
for (int i = 0; i < ics.length; i++)
if (!ics[i].isInterface())
for (int i = 0; i < ics.length; i++) {
if (!ics[i].isInterface()) {
throw new RuntimeException("Class " + ics[i].getName() + " is not a interface.");
}
}
}
/**

View File

@ -77,14 +77,16 @@ public abstract class Proxy {
* @return Proxy instance.
*/
public static Proxy getProxy(ClassLoader cl, Class<?>... ics) {
if (ics.length > 65535)
if (ics.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ics.length; i++) {
String itf = ics[i].getName();
if (!ics[i].isInterface())
if (!ics[i].isInterface()) {
throw new RuntimeException(itf + " is not a interface.");
}
Class<?> tmp = null;
try {
@ -92,8 +94,9 @@ public abstract class Proxy {
} catch (ClassNotFoundException e) {
}
if (tmp != ics[i])
if (tmp != ics[i]) {
throw new IllegalArgumentException(ics[i] + " is not visible from class loader");
}
sb.append(itf).append(';');
}
@ -117,8 +120,9 @@ public abstract class Proxy {
Object value = cache.get(key);
if (value instanceof Reference<?>) {
proxy = (Proxy) ((Reference<?>) value).get();
if (proxy != null)
if (proxy != null) {
return proxy;
}
}
if (value == PendingGenerationMarker) {
@ -149,16 +153,18 @@ public abstract class Proxy {
if (pkg == null) {
pkg = npkg;
} else {
if (!pkg.equals(npkg))
if (!pkg.equals(npkg)) {
throw new IllegalArgumentException("non-public interfaces from different packages");
}
}
}
ccp.addInterface(ics[i]);
for (Method method : ics[i].getMethods()) {
String desc = ReflectUtils.getDesc(method);
if (worked.contains(desc))
if (worked.contains(desc)) {
continue;
}
worked.add(desc);
int ix = methods.size();
@ -166,19 +172,22 @@ public abstract class Proxy {
Class<?>[] pts = method.getParameterTypes();
StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];");
for (int j = 0; j < pts.length; j++)
for (int j = 0; j < pts.length; j++) {
code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";");
}
code.append(" Object ret = handler.invoke(this, methods[" + ix + "], args);");
if (!Void.TYPE.equals(rt))
if (!Void.TYPE.equals(rt)) {
code.append(" return ").append(asArgument(rt, "ret")).append(";");
}
methods.add(method);
ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString());
}
}
if (pkg == null)
if (pkg == null) {
pkg = PACKAGE_NAME;
}
// create ProxyInstance class.
String pcn = pkg + ".proxy" + id;
@ -205,15 +214,18 @@ public abstract class Proxy {
throw new RuntimeException(e.getMessage(), e);
} finally {
// release ClassGenerator
if (ccp != null)
if (ccp != null) {
ccp.release();
if (ccm != null)
}
if (ccm != null) {
ccm.release();
}
synchronized (cache) {
if (proxy == null)
if (proxy == null) {
cache.remove(key);
else
} else {
cache.put(key, new WeakReference<Proxy>(proxy));
}
cache.notifyAll();
}
}
@ -222,22 +234,30 @@ public abstract class Proxy {
private static String asArgument(Class<?> cl, String name) {
if (cl.isPrimitive()) {
if (Boolean.TYPE == cl)
if (Boolean.TYPE == cl) {
return name + "==null?false:((Boolean)" + name + ").booleanValue()";
if (Byte.TYPE == cl)
}
if (Byte.TYPE == cl) {
return name + "==null?(byte)0:((Byte)" + name + ").byteValue()";
if (Character.TYPE == cl)
}
if (Character.TYPE == cl) {
return name + "==null?(char)0:((Character)" + name + ").charValue()";
if (Double.TYPE == cl)
}
if (Double.TYPE == cl) {
return name + "==null?(double)0:((Double)" + name + ").doubleValue()";
if (Float.TYPE == cl)
}
if (Float.TYPE == cl) {
return name + "==null?(float)0:((Float)" + name + ").floatValue()";
if (Integer.TYPE == cl)
}
if (Integer.TYPE == cl) {
return name + "==null?(int)0:((Integer)" + name + ").intValue()";
if (Long.TYPE == cl)
}
if (Long.TYPE == cl) {
return name + "==null?(long)0:((Long)" + name + ").longValue()";
if (Short.TYPE == cl)
}
if (Short.TYPE == cl) {
return name + "==null?(short)0:((Short)" + name + ").shortValue()";
}
throw new RuntimeException(name + " is unknown primitive type.");
}
return "(" + ReflectUtils.getName(cl) + ")" + name;

View File

@ -77,11 +77,19 @@ public abstract class Wrapper {
@Override
public Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args) throws NoSuchMethodException {
if ("getClass".equals(mn)) return instance.getClass();
if ("hashCode".equals(mn)) return instance.hashCode();
if ("toString".equals(mn)) return instance.toString();
if ("getClass".equals(mn)) {
return instance.getClass();
}
if ("hashCode".equals(mn)) {
return instance.hashCode();
}
if ("toString".equals(mn)) {
return instance.toString();
}
if ("equals".equals(mn)) {
if (args.length == 1) return instance.equals(args[0]);
if (args.length == 1) {
return instance.equals(args[0]);
}
throw new IllegalArgumentException("Invoke method [" + mn + "] argument number error.");
}
throw new NoSuchMethodException("Method [" + mn + "] not found.");
@ -97,10 +105,13 @@ public abstract class Wrapper {
*/
public static Wrapper getWrapper(Class<?> c) {
while (ClassGenerator.isDynamicClass(c)) // can not wrapper on dynamic class.
{
c = c.getSuperclass();
}
if (c == Object.class)
if (c == Object.class) {
return OBJECT_WRAPPER;
}
Wrapper ret = WRAPPER_MAP.get(c);
if (ret == null) {
@ -111,8 +122,9 @@ public abstract class Wrapper {
}
private static Wrapper makeWrapper(Class<?> c) {
if (c.isPrimitive())
if (c.isPrimitive()) {
throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c);
}
String name = c.getName();
ClassLoader cl = ClassHelper.getClassLoader(c);
@ -134,8 +146,9 @@ public abstract class Wrapper {
for (Field f : c.getFields()) {
String fn = f.getName();
Class<?> ft = f.getType();
if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers()))
if (Modifier.isStatic(f.getModifiers()) || Modifier.isTransient(f.getModifiers())) {
continue;
}
c1.append(" if( $2.equals(\"").append(fn).append("\") ){ w.").append(fn).append("=").append(arg(ft, "$3")).append("; return; }");
c2.append(" if( $2.equals(\"").append(fn).append("\") ){ return ($w)w.").append(fn).append("; }");
@ -150,7 +163,9 @@ public abstract class Wrapper {
}
for (Method m : methods) {
if (m.getDeclaringClass() == Object.class) //ignore Object's method.
{
continue;
}
String mn = m.getName();
c3.append(" if( \"").append(mn).append("\".equals( $2 ) ");
@ -175,16 +190,18 @@ public abstract class Wrapper {
c3.append(" ) { ");
if (m.getReturnType() == Void.TYPE)
if (m.getReturnType() == Void.TYPE) {
c3.append(" w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");").append(" return null;");
else
} else {
c3.append(" return ($w)w.").append(mn).append('(').append(args(m.getParameterTypes(), "$4")).append(");");
}
c3.append(" }");
mns.add(mn);
if (m.getDeclaringClass() == c)
if (m.getDeclaringClass() == c) {
dmns.add(mn);
}
ms.put(ReflectUtils.getDesc(m), m);
}
if (hasMethod) {
@ -229,8 +246,9 @@ public abstract class Wrapper {
cc.addField("public static " + Map.class.getName() + " pts;"); // property type map.
cc.addField("public static String[] mns;"); // all method name array.
cc.addField("public static String[] dmns;"); // declared method name array.
for (int i = 0, len = ms.size(); i < len; i++)
for (int i = 0, len = ms.size(); i < len; i++) {
cc.addField("public static Class[] mts" + i + ";");
}
cc.addMethod("public String[] getPropertyNames(){ return pns; }");
cc.addMethod("public boolean hasProperty(String n){ return pts.containsKey($1); }");
@ -249,8 +267,9 @@ public abstract class Wrapper {
wc.getField("mns").set(null, mns.toArray(new String[0]));
wc.getField("dmns").set(null, dmns.toArray(new String[0]));
int ix = 0;
for (Method m : ms.values())
for (Method m : ms.values()) {
wc.getField("mts" + ix++).set(null, m.getParameterTypes());
}
return (Wrapper) wc.newInstance();
} catch (RuntimeException e) {
throw e;
@ -266,22 +285,30 @@ public abstract class Wrapper {
private static String arg(Class<?> cl, String name) {
if (cl.isPrimitive()) {
if (cl == Boolean.TYPE)
if (cl == Boolean.TYPE) {
return "((Boolean)" + name + ").booleanValue()";
if (cl == Byte.TYPE)
}
if (cl == Byte.TYPE) {
return "((Byte)" + name + ").byteValue()";
if (cl == Character.TYPE)
}
if (cl == Character.TYPE) {
return "((Character)" + name + ").charValue()";
if (cl == Double.TYPE)
}
if (cl == Double.TYPE) {
return "((Number)" + name + ").doubleValue()";
if (cl == Float.TYPE)
}
if (cl == Float.TYPE) {
return "((Number)" + name + ").floatValue()";
if (cl == Integer.TYPE)
}
if (cl == Integer.TYPE) {
return "((Number)" + name + ").intValue()";
if (cl == Long.TYPE)
}
if (cl == Long.TYPE) {
return "((Number)" + name + ").longValue()";
if (cl == Short.TYPE)
}
if (cl == Short.TYPE) {
return "((Number)" + name + ").shortValue()";
}
throw new RuntimeException("Unknown primitive type: " + cl.getName());
}
return "(" + ReflectUtils.getName(cl) + ")" + name;
@ -289,11 +316,14 @@ public abstract class Wrapper {
private static String args(Class<?>[] cs, String name) {
int len = cs.length;
if (len == 0) return "";
if (len == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
if (i > 0)
if (i > 0) {
sb.append(',');
}
sb.append(arg(cs[i], name + "[" + i + "]"));
}
return sb.toString();
@ -365,8 +395,9 @@ public abstract class Wrapper {
*/
public Object[] getPropertyValues(Object instance, String[] pns) throws NoSuchPropertyException, IllegalArgumentException {
Object[] ret = new Object[pns.length];
for (int i = 0; i < ret.length; i++)
for (int i = 0; i < ret.length; i++) {
ret[i] = getPropertyValue(instance, pns[i]);
}
return ret;
}
@ -378,11 +409,13 @@ public abstract class Wrapper {
* @param pvs property value array.
*/
public void setPropertyValues(Object instance, String[] pns, Object[] pvs) throws NoSuchPropertyException, IllegalArgumentException {
if (pns.length != pvs.length)
if (pns.length != pvs.length) {
throw new IllegalArgumentException("pns.length != pvs.length");
}
for (int i = 0; i < pns.length; i++)
for (int i = 0; i < pns.length; i++) {
setPropertyValue(instance, pns[i], pvs[i]);
}
}
/**
@ -406,8 +439,11 @@ public abstract class Wrapper {
* @return has or has not.
*/
public boolean hasMethod(String name) {
for (String mn : getMethodNames())
if (mn.equals(name)) return true;
for (String mn : getMethodNames()) {
if (mn.equals(name)) {
return true;
}
}
return false;
}

View File

@ -168,8 +168,9 @@ public class JdkCompiler extends AbstractCompiler {
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
FileObject o = fileObjects.get(uri(location, packageName, relativeName));
if (o != null)
if (o != null) {
return o;
}
return super.getFileForInput(location, packageName, relativeName);
}
@ -196,8 +197,9 @@ public class JdkCompiler extends AbstractCompiler {
@Override
public String inferBinaryName(Location loc, JavaFileObject file) {
if (file instanceof JavaFileObjectImpl)
if (file instanceof JavaFileObjectImpl) {
return file.getName();
}
return super.inferBinaryName(loc, file);
}

View File

@ -105,8 +105,9 @@ public class ExtensionLoader<T> {
@SuppressWarnings("unchecked")
public static <T> ExtensionLoader<T> getExtensionLoader(Class<T> type) {
if (type == null)
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
}
if (!type.isInterface()) {
throw new IllegalArgumentException("Extension type(" + type + ") is not interface!");
}
@ -277,8 +278,9 @@ public class ExtensionLoader<T> {
*/
@SuppressWarnings("unchecked")
public T getLoadedExtension(String name) {
if (name == null || name.length() == 0)
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Extension name == null");
}
Holder<Object> holder = cachedInstances.get(name);
if (holder == null) {
cachedInstances.putIfAbsent(name, new Holder<Object>());
@ -304,8 +306,9 @@ public class ExtensionLoader<T> {
*/
@SuppressWarnings("unchecked")
public T getExtension(String name) {
if (name == null || name.length() == 0)
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Extension name == null");
}
if ("true".equals(name)) {
return getDefaultExtension();
}
@ -340,8 +343,9 @@ public class ExtensionLoader<T> {
}
public boolean hasExtension(String name) {
if (name == null || name.length() == 0)
if (name == null || name.length() == 0) {
throw new IllegalArgumentException("Extension name == null");
}
try {
this.getExtensionClass(name);
return true;
@ -549,13 +553,16 @@ public class ExtensionLoader<T> {
}
private Class<?> getExtensionClass(String name) {
if (type == null)
if (type == null) {
throw new IllegalArgumentException("Extension type == null");
if (name == null)
}
if (name == null) {
throw new IllegalArgumentException("Extension name == null");
}
Class<?> clazz = getExtensionClasses().get(name);
if (clazz == null)
if (clazz == null) {
throw new IllegalStateException("No such extension \"" + name + "\" for " + type.getName() + "!");
}
return clazz;
}
@ -584,7 +591,9 @@ public class ExtensionLoader<T> {
throw new IllegalStateException("more than 1 default extension name on extension " + type.getName()
+ ": " + Arrays.toString(names));
}
if (names.length == 1) cachedDefaultName = names[0];
if (names.length == 1) {
cachedDefaultName = names[0];
}
}
}
@ -627,7 +636,9 @@ public class ExtensionLoader<T> {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) line = line.substring(0, ci);
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
try {
@ -768,8 +779,9 @@ public class ExtensionLoader<T> {
}
}
// no need to generate adaptive class since there's no adaptive method found.
if (!hasAdaptiveAnnotation)
if (!hasAdaptiveAnnotation) {
throw new IllegalStateException("No adaptive method on extension " + type.getName() + ", refuse to create the adaptive class!");
}
codeBuilder.append("package ").append(type.getPackage().getName()).append(";");
codeBuilder.append("\nimport ").append(ExtensionLoader.class.getName()).append(";");
@ -865,7 +877,7 @@ public class ExtensionLoader<T> {
boolean hasInvocation = false;
for (int i = 0; i < pts.length; ++i) {
if (pts[i].getName().equals("org.apache.dubbo.rpc.Invocation")) {
if (("org.apache.dubbo.rpc.Invocation").equals(pts[i].getName())) {
// Null Point check
String s = String.format("\nif (arg%d == null) throw new IllegalArgumentException(\"invocation == null\");", i);
code.append(s);
@ -881,30 +893,36 @@ public class ExtensionLoader<T> {
for (int i = value.length - 1; i >= 0; --i) {
if (i == value.length - 1) {
if (null != defaultExtName) {
if (!"protocol".equals(value[i]))
if (hasInvocation)
if (!"protocol".equals(value[i])) {
if (hasInvocation) {
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
} else {
getNameCode = String.format("url.getParameter(\"%s\", \"%s\")", value[i], defaultExtName);
else
}
} else {
getNameCode = String.format("( url.getProtocol() == null ? \"%s\" : url.getProtocol() )", defaultExtName);
}
} else {
if (!"protocol".equals(value[i]))
if (hasInvocation)
if (!"protocol".equals(value[i])) {
if (hasInvocation) {
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
} else {
getNameCode = String.format("url.getParameter(\"%s\")", value[i]);
else
}
} else {
getNameCode = "url.getProtocol()";
}
}
} else {
if (!"protocol".equals(value[i]))
if (hasInvocation)
if (!"protocol".equals(value[i])) {
if (hasInvocation) {
getNameCode = String.format("url.getMethodParameter(methodName, \"%s\", \"%s\")", value[i], defaultExtName);
else
} else {
getNameCode = String.format("url.getParameter(\"%s\", %s)", value[i], getNameCode);
else
}
} else {
getNameCode = String.format("url.getProtocol() == null ? (%s) : url.getProtocol()", getNameCode);
}
}
}
code.append("\nString extName = ").append(getNameCode).append(";");
@ -929,8 +947,9 @@ public class ExtensionLoader<T> {
s = String.format("extension.%s(", method.getName());
code.append(s);
for (int i = 0; i < pts.length; i++) {
if (i != 0)
if (i != 0) {
code.append(", ");
}
code.append("arg").append(i);
}
code.append(");");

View File

@ -395,12 +395,15 @@ public class Bytes {
* @return hex string.
*/
public static String bytes2hex(byte[] bs, int off, int len) {
if (off < 0)
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2hex: offset < 0, offset is " + off);
if (len < 0)
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2hex: length < 0, length is " + len);
if (off + len > bs.length)
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2hex: offset + length > array length.");
}
byte b;
int r = off, w = 0;
@ -432,20 +435,25 @@ public class Bytes {
* @return byte array.
*/
public static byte[] hex2bytes(final String str, final int off, int len) {
if ((len & 1) == 1)
if ((len & 1) == 1) {
throw new IllegalArgumentException("hex2bytes: ( len & 1 ) == 1.");
}
if (off < 0)
if (off < 0) {
throw new IndexOutOfBoundsException("hex2bytes: offset < 0, offset is " + off);
if (len < 0)
}
if (len < 0) {
throw new IndexOutOfBoundsException("hex2bytes: length < 0, length is " + len);
if (off + len > str.length())
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("hex2bytes: offset + length > array length.");
}
int num = len / 2, r = off, w = 0;
byte[] b = new byte[num];
for (int i = 0; i < num; i++)
for (int i = 0; i < num; i++) {
b[w++] = (byte) (hex(str.charAt(r++)) << 4 | hex(str.charAt(r++)));
}
return b;
}
@ -488,8 +496,9 @@ public class Bytes {
* @return base64 string.
*/
public static String bytes2base64(byte[] b, int offset, int length, String code) {
if (code.length() < 64)
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
return bytes2base64(b, offset, length, code.toCharArray());
}
@ -515,15 +524,19 @@ public class Bytes {
* @return base64 string.
*/
public static String bytes2base64(final byte[] bs, final int off, final int len, final char[] code) {
if (off < 0)
if (off < 0) {
throw new IndexOutOfBoundsException("bytes2base64: offset < 0, offset is " + off);
if (len < 0)
}
if (len < 0) {
throw new IndexOutOfBoundsException("bytes2base64: length < 0, length is " + len);
if (off + len > bs.length)
}
if (off + len > bs.length) {
throw new IndexOutOfBoundsException("bytes2base64: offset + length > array length.");
}
if (code.length < 64)
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
boolean pad = code.length > 64; // has pad char.
int num = len / 3, rem = len % 3, r = off, w = 0;
@ -551,8 +564,9 @@ public class Bytes {
cs[w++] = code[b1 >> 2];
cs[w++] = code[(b1 << 4) & MASK6 | (b2 >> 4)];
cs[w++] = code[(b2 << 2) & MASK6];
if (pad)
if (pad) {
cs[w++] = code[64];
}
}
return new String(cs);
}
@ -600,24 +614,30 @@ public class Bytes {
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final String code) {
if (off < 0)
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
if (len < 0)
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
if (off + len > str.length())
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length() < 64)
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1)
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length() > 64) {
if (rem != 0)
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code.charAt(64);
if (str.charAt(off + len - 2) == pc) {
@ -630,10 +650,11 @@ public class Bytes {
rem = 3;
}
} else {
if (rem == 2)
if (rem == 2) {
size++;
else if (rem == 3)
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
@ -681,35 +702,43 @@ public class Bytes {
* @return byte array.
*/
public static byte[] base642bytes(final String str, final int off, final int len, final char[] code) {
if (off < 0)
if (off < 0) {
throw new IndexOutOfBoundsException("base642bytes: offset < 0, offset is " + off);
if (len < 0)
}
if (len < 0) {
throw new IndexOutOfBoundsException("base642bytes: length < 0, length is " + len);
if (off + len > str.length())
}
if (off + len > str.length()) {
throw new IndexOutOfBoundsException("base642bytes: offset + length > string length.");
}
if (code.length < 64)
if (code.length < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
int rem = len % 4;
if (rem == 1)
if (rem == 1) {
throw new IllegalArgumentException("base642bytes: base64 string length % 4 == 1.");
}
int num = len / 4, size = num * 3;
if (code.length > 64) {
if (rem != 0)
if (rem != 0) {
throw new IllegalArgumentException("base642bytes: base64 string length error.");
}
char pc = code[64];
if (str.charAt(off + len - 2) == pc)
if (str.charAt(off + len - 2) == pc) {
size -= 2;
else if (str.charAt(off + len - 1) == pc)
} else if (str.charAt(off + len - 1) == pc) {
size--;
}
} else {
if (rem == 2)
if (rem == 2) {
size++;
else if (rem == 3)
} else if (rem == 3) {
size += 2;
}
}
int r = off, w = 0;
@ -823,15 +852,24 @@ public class Bytes {
}
private static byte hex(char c) {
if (c <= '9') return (byte) (c - '0');
if (c >= 'a' && c <= 'f') return (byte) (c - 'a' + 10);
if (c >= 'A' && c <= 'F') return (byte) (c - 'A' + 10);
if (c <= '9') {
return (byte) (c - '0');
}
if (c >= 'a' && c <= 'f') {
return (byte) (c - 'a' + 10);
}
if (c >= 'A' && c <= 'F') {
return (byte) (c - 'A' + 10);
}
throw new IllegalArgumentException("hex string format error [" + c + "].");
}
private static int indexOf(char[] cs, char c) {
for (int i = 0, len = cs.length; i < len; i++)
if (cs[i] == c) return i;
for (int i = 0, len = cs.length; i < len; i++) {
if (cs[i] == c) {
return i;
}
}
return -1;
}
@ -839,14 +877,18 @@ public class Bytes {
int hash = code.hashCode();
byte[] ret = DECODE_TABLE_MAP.get(hash);
if (ret == null) {
if (code.length() < 64)
if (code.length() < 64) {
throw new IllegalArgumentException("Base64 code length < 64.");
}
// create new decode table.
ret = new byte[128];
for (int i = 0; i < 128; i++) // init table.
{
ret[i] = -1;
for (int i = 0; i < 64; i++)
}
for (int i = 0; i < 64; i++) {
ret[code.charAt(i)] = (byte) i;
}
DECODE_TABLE_MAP.put(hash, ret);
}
return ret;
@ -858,8 +900,9 @@ public class Bytes {
while (is.available() > 0) {
int read, total = 0;
do {
if ((read = is.read(buf, total, bs - total)) <= 0)
if ((read = is.read(buf, total, bs - total)) <= 0) {
break;
}
total += read;
}
while (total < bs);

View File

@ -41,20 +41,25 @@ public class StreamUtils {
@Override
public int read(byte b[], int off, int len) throws IOException {
if (b == null)
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off)
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit)
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit)
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0)
if (len <= 0) {
return 0;
}
is.read(b, off, len);
mPosition += len;
@ -63,11 +68,13 @@ public class StreamUtils {
@Override
public long skip(long len) throws IOException {
if (mPosition + len > mLimit)
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0)
if (len <= 0) {
return 0;
}
is.skip(len);
mPosition += len;
@ -128,7 +135,9 @@ public class StreamUtils {
}
if (!mInReset) {
if (mDry) return -1;
if (mDry) {
return -1;
}
if (null == mMarkBuffer) {
mMarkBuffer = new byte[markBufferSize];
@ -196,7 +205,9 @@ public class StreamUtils {
public int available() throws IOException {
int available = is.available();
if (mInMarked && mInReset) available += mCount - mPosition;
if (mInMarked && mInReset) {
available += mCount - mPosition;
}
return available;
}

View File

@ -48,16 +48,21 @@ public class UnsafeByteArrayInputStream extends InputStream {
@Override
public int read(byte b[], int off, int len) {
if (b == null)
if (b == null) {
throw new NullPointerException();
if (off < 0 || len < 0 || len > b.length - off)
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
if (mPosition >= mLimit)
}
if (mPosition >= mLimit) {
return -1;
if (mPosition + len > mLimit)
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
if (len <= 0)
}
if (len <= 0) {
return 0;
}
System.arraycopy(mData, mPosition, b, off, len);
mPosition += len;
return len;
@ -65,10 +70,12 @@ public class UnsafeByteArrayInputStream extends InputStream {
@Override
public long skip(long len) {
if (mPosition + len > mLimit)
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
if (len <= 0)
}
if (len <= 0) {
return 0;
}
mPosition += len;
return len;
}

View File

@ -34,29 +34,34 @@ public class UnsafeByteArrayOutputStream extends OutputStream {
}
public UnsafeByteArrayOutputStream(int size) {
if (size < 0)
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: " + size);
}
mBuffer = new byte[size];
}
@Override
public void write(int b) {
int newcount = mCount + 1;
if (newcount > mBuffer.length)
if (newcount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount));
}
mBuffer[mCount] = (byte) b;
mCount = newcount;
}
@Override
public void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0))
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
if (len == 0)
}
if (len == 0) {
return;
}
int newcount = mCount + len;
if (newcount > mBuffer.length)
if (newcount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount));
}
System.arraycopy(b, off, mBuffer, mCount, len);
mCount = newcount;
}

View File

@ -36,8 +36,9 @@ public class UnsafeStringReader extends Reader {
@Override
public int read() throws IOException {
ensureOpen();
if (mPosition >= mLimit)
if (mPosition >= mLimit) {
return -1;
}
return mString.charAt(mPosition++);
}
@ -46,14 +47,17 @@ public class UnsafeStringReader extends Reader {
public int read(char[] cs, int off, int len) throws IOException {
ensureOpen();
if ((off < 0) || (off > cs.length) || (len < 0) ||
((off + len) > cs.length) || ((off + len) < 0))
((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0)
if (len == 0) {
return 0;
}
if (mPosition >= mLimit)
if (mPosition >= mLimit) {
return -1;
}
int n = Math.min(mLimit - mPosition, len);
mString.getChars(mPosition, mPosition + n, cs, off);
@ -64,8 +68,9 @@ public class UnsafeStringReader extends Reader {
@Override
public long skip(long ns) throws IOException {
ensureOpen();
if (mPosition >= mLimit)
if (mPosition >= mLimit) {
return 0;
}
long n = Math.min(mLimit - mPosition, ns);
n = Math.max(-mPosition, n);
@ -86,8 +91,9 @@ public class UnsafeStringReader extends Reader {
@Override
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0)
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
ensureOpen();
mMark = mPosition;
@ -105,7 +111,8 @@ public class UnsafeStringReader extends Reader {
}
private void ensureOpen() throws IOException {
if (mString == null)
if (mString == null) {
throw new IOException("Stream closed");
}
}
}

View File

@ -30,8 +30,9 @@ public class UnsafeStringWriter extends Writer {
}
public UnsafeStringWriter(int size) {
if (size < 0)
if (size < 0) {
throw new IllegalArgumentException("Negative buffer size");
}
lock = mBuffer = new StringBuilder();
}
@ -49,11 +50,13 @@ public class UnsafeStringWriter extends Writer {
@Override
public void write(char[] cs, int off, int len) throws IOException {
if ((off < 0) || (off > cs.length) || (len < 0) ||
((off + len) > cs.length) || ((off + len) < 0))
((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len > 0)
if (len > 0) {
mBuffer.append(cs, off, len);
}
}
@Override
@ -68,10 +71,11 @@ public class UnsafeStringWriter extends Writer {
@Override
public Writer append(CharSequence csq) {
if (csq == null)
if (csq == null) {
write("null");
else
} else {
write(csq.toString());
}
return this;
}

View File

@ -141,7 +141,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Boolean) return ((Boolean) jv).booleanValue();
if (jv instanceof Boolean) {
return ((Boolean) jv).booleanValue();
}
return false;
}
};
@ -150,7 +152,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Boolean) return (Boolean) jv;
if (jv instanceof Boolean) {
return (Boolean) jv;
}
return (Boolean) null;
}
};
@ -159,7 +163,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof String && ((String) jv).length() > 0) return ((String) jv).charAt(0);
if (jv instanceof String && ((String) jv).length() > 0) {
return ((String) jv).charAt(0);
}
return (char) 0;
}
};
@ -168,7 +174,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof String && ((String) jv).length() > 0) return ((String) jv).charAt(0);
if (jv instanceof String && ((String) jv).length() > 0) {
return ((String) jv).charAt(0);
}
return (Character) null;
}
};
@ -177,7 +185,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).intValue();
if (jv instanceof Number) {
return ((Number) jv).intValue();
}
return 0;
}
};
@ -186,7 +196,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return Integer.valueOf(((Number) jv).intValue());
if (jv instanceof Number) {
return Integer.valueOf(((Number) jv).intValue());
}
return (Integer) null;
}
};
@ -195,7 +207,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).shortValue();
if (jv instanceof Number) {
return ((Number) jv).shortValue();
}
return (short) 0;
}
};
@ -204,7 +218,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return Short.valueOf(((Number) jv).shortValue());
if (jv instanceof Number) {
return Short.valueOf(((Number) jv).shortValue());
}
return (Short) null;
}
};
@ -213,7 +229,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).longValue();
if (jv instanceof Number) {
return ((Number) jv).longValue();
}
return (long) 0;
}
};
@ -222,7 +240,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return Long.valueOf(((Number) jv).longValue());
if (jv instanceof Number) {
return Long.valueOf(((Number) jv).longValue());
}
return (Long) null;
}
};
@ -231,7 +251,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).floatValue();
if (jv instanceof Number) {
return ((Number) jv).floatValue();
}
return (float) 0;
}
};
@ -240,7 +262,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return new Float(((Number) jv).floatValue());
if (jv instanceof Number) {
return new Float(((Number) jv).floatValue());
}
return (Float) null;
}
};
@ -249,7 +273,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).doubleValue();
if (jv instanceof Number) {
return ((Number) jv).doubleValue();
}
return (double) 0;
}
};
@ -258,7 +284,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return new Double(((Number) jv).doubleValue());
if (jv instanceof Number) {
return new Double(((Number) jv).doubleValue());
}
return (Double) null;
}
};
@ -267,7 +295,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return ((Number) jv).byteValue();
if (jv instanceof Number) {
return ((Number) jv).byteValue();
}
return (byte) 0;
}
};
@ -276,7 +306,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) {
if (jv instanceof Number) return Byte.valueOf(((Number) jv).byteValue());
if (jv instanceof Number) {
return Byte.valueOf(((Number) jv).byteValue());
}
return (Byte) null;
}
};
@ -285,7 +317,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) throws IOException {
if (jv instanceof String) return Bytes.base642bytes((String) jv);
if (jv instanceof String) {
return Bytes.base642bytes((String) jv);
}
return (byte[]) null;
}
};
@ -310,7 +344,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) throws IOException {
if (jv instanceof Number) return BigInteger.valueOf(((Number) jv).longValue());
if (jv instanceof Number) {
return BigInteger.valueOf(((Number) jv).longValue());
}
return (BigInteger) null;
}
};
@ -319,7 +355,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) throws IOException {
if (jv instanceof Number) return BigDecimal.valueOf(((Number) jv).doubleValue());
if (jv instanceof Number) {
return BigDecimal.valueOf(((Number) jv).doubleValue());
}
return (BigDecimal) null;
}
};
@ -328,7 +366,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) throws IOException {
if (jv instanceof Number) return new AtomicInteger(((Number) jv).intValue());
if (jv instanceof Number) {
return new AtomicInteger(((Number) jv).intValue());
}
return (AtomicInteger) null;
}
};
@ -337,7 +377,9 @@ public class GenericJSONConverter implements JSONConverter {
d = new Decoder() {
@Override
public Object decode(Object jv) throws IOException {
if (jv instanceof Number) return new AtomicLong(((Number) jv).longValue());
if (jv instanceof Number) {
return new AtomicLong(((Number) jv).longValue());
}
return (AtomicLong) null;
}
};
@ -353,8 +395,9 @@ public class GenericJSONConverter implements JSONConverter {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
if (jv instanceof Number)
if (jv instanceof Number) {
return new Date(((Number) jv).longValue());
}
return (Date) null;
}
};
@ -398,32 +441,36 @@ public class GenericJSONConverter implements JSONConverter {
} else if (c.isArray()) {
int len = Array.getLength(obj);
jb.arrayBegin();
for (int i = 0; i < len; i++)
for (int i = 0; i < len; i++) {
writeValue(Array.get(obj, i), jb, writeClass);
}
jb.arrayEnd();
} else if (Map.class.isAssignableFrom(c)) {
Object key, value;
jb.objectBegin();
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) obj).entrySet()) {
key = entry.getKey();
if (key == null)
if (key == null) {
continue;
}
jb.objectItem(key.toString());
value = entry.getValue();
if (value == null)
if (value == null) {
jb.valueNull();
else
} else {
writeValue(value, jb, writeClass);
}
}
jb.objectEnd();
} else if (Collection.class.isAssignableFrom(c)) {
jb.arrayBegin();
for (Object item : (Collection<Object>) obj) {
if (item == null)
if (item == null) {
jb.valueNull();
else
} else {
writeValue(item, jb, writeClass);
}
}
jb.arrayEnd();
} else if(obj instanceof Locale) {
@ -446,10 +493,11 @@ public class GenericJSONConverter implements JSONConverter {
jb.objectItem(pn);
Object value = w.getPropertyValue(obj, pn);
if (value == null || value == obj)
if (value == null || value == obj) {
jb.valueNull();
else
} else {
writeValue(value, jb, writeClass);
}
}
if (writeClass) {
jb.objectItem(JSONVisitor.CLASS_PROPERTY);

View File

@ -92,105 +92,131 @@ class J2oVisitor implements JSONVisitor {
}
}
if (c == boolean.class) {
if (len == 0) return EMPTY_BOOL_ARRAY;
if (len == 0) {
return EMPTY_BOOL_ARRAY;
}
Object o;
boolean[] ret = new boolean[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Boolean)
if (o instanceof Boolean) {
ret[i] = ((Boolean) o).booleanValue();
}
}
return ret;
}
if (c == int.class) {
if (len == 0) return EMPTY_INT_ARRAY;
if (len == 0) {
return EMPTY_INT_ARRAY;
}
Object o;
int[] ret = new int[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).intValue();
}
}
return ret;
}
if (c == long.class) {
if (len == 0) return EMPTY_LONG_ARRAY;
if (len == 0) {
return EMPTY_LONG_ARRAY;
}
Object o;
long[] ret = new long[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).longValue();
}
}
return ret;
}
if (c == float.class) {
if (len == 0) return EMPTY_FLOAT_ARRAY;
if (len == 0) {
return EMPTY_FLOAT_ARRAY;
}
Object o;
float[] ret = new float[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).floatValue();
}
}
return ret;
}
if (c == double.class) {
if (len == 0) return EMPTY_DOUBLE_ARRAY;
if (len == 0) {
return EMPTY_DOUBLE_ARRAY;
}
Object o;
double[] ret = new double[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).doubleValue();
}
}
return ret;
}
if (c == byte.class) {
if (len == 0) return EMPTY_BYTE_ARRAY;
if (len == 0) {
return EMPTY_BYTE_ARRAY;
}
Object o;
byte[] ret = new byte[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).byteValue();
}
}
return ret;
}
if (c == char.class) {
if (len == 0) return EMPTY_CHAR_ARRAY;
if (len == 0) {
return EMPTY_CHAR_ARRAY;
}
Object o;
char[] ret = new char[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Character)
if (o instanceof Character) {
ret[i] = ((Character) o).charValue();
}
}
return ret;
}
if (c == short.class) {
if (len == 0) return EMPTY_SHORT_ARRAY;
if (len == 0) {
return EMPTY_SHORT_ARRAY;
}
Object o;
short[] ret = new short[len];
for (int i = len - 1; i >= 0; i--) {
o = list.pop();
if (o instanceof Number)
if (o instanceof Number) {
ret[i] = ((Number) o).shortValue();
}
}
return ret;
}
Object ret = Array.newInstance(c, len);
for (int i = len - 1; i >= 0; i--)
for (int i = len - 1; i >= 0; i--) {
Array.set(ret, i, list.pop());
}
return ret;
}
private static String name(Class<?>[] types) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < types.length; i++) {
if (i > 0)
if (i > 0) {
sb.append(", ");
}
sb.append(types[i].getName());
}
return sb.toString();
@ -294,12 +320,13 @@ class J2oVisitor implements JSONVisitor {
public void arrayBegin() throws ParseException {
mStack.push(mType);
if (mType.isArray())
if (mType.isArray()) {
mType = mType.getComponentType();
else if (mType == Object.class || Collection.class.isAssignableFrom(mType))
} else if (mType == Object.class || Collection.class.isAssignableFrom(mType)) {
mType = Object.class;
else
} else {
throw new ParseException("Convert error, can not load json array data into class [" + mType.getName() + "].");
}
}
@Override
@ -331,8 +358,9 @@ class J2oVisitor implements JSONVisitor {
} else {
throw new ParseException("Convert error, can not load json array data into class [" + mType.getName() + "].");
}
for (int i = 0; i < count; i++)
for (int i = 0; i < count; i++) {
items.add(mStack.remove(i - count));
}
ret = items;
}
mStack.pop();
@ -342,10 +370,11 @@ class J2oVisitor implements JSONVisitor {
@Override
public void arrayItem(int index) throws ParseException {
if (mTypes != null && mStack.size() == index + 1) {
if (index < mTypes.length)
if (index < mTypes.length) {
mType = mTypes[index];
else
} else {
throw new ParseException("Can not load json array data into [" + name(mTypes) + "].");
}
}
}

View File

@ -52,7 +52,9 @@ public class JSON {
* @throws IOException
*/
public static String json(Object obj) throws IOException {
if (obj == null) return NULL;
if (obj == null) {
return NULL;
}
StringWriter sw = new StringWriter();
try {
json(obj, sw);
@ -74,10 +76,11 @@ public class JSON {
}
public static void json(Object obj, Writer writer, boolean writeClass) throws IOException {
if (obj == null)
if (obj == null) {
writer.write(NULL);
else
} else {
json(obj, new JSONWriter(writer), writeClass);
}
}
/**
@ -89,7 +92,9 @@ public class JSON {
* @throws IOException
*/
public static String json(Object obj, String[] properties) throws IOException {
if (obj == null) return NULL;
if (obj == null) {
return NULL;
}
StringWriter sw = new StringWriter();
try {
json(obj, properties, sw);
@ -112,17 +117,19 @@ public class JSON {
* @throws IOException
*/
public static void json(Object obj, final String[] properties, Writer writer, boolean writeClass) throws IOException {
if (obj == null)
if (obj == null) {
writer.write(NULL);
else
} else {
json(obj, properties, new JSONWriter(writer), writeClass);
}
}
private static void json(Object obj, JSONWriter jb, boolean writeClass) throws IOException {
if (obj == null)
if (obj == null) {
jb.valueNull();
else
} else {
DEFAULT_CONVERTER.writeValue(obj, jb, writeClass);
}
}
private static void json(Object obj, String[] properties, JSONWriter jb, boolean writeClass) throws IOException {
@ -136,10 +143,11 @@ public class JSON {
for (String prop : properties) {
jb.objectItem(prop);
value = wrapper.getPropertyValue(obj, prop);
if (value == null)
if (value == null) {
jb.valueNull();
else
} else {
DEFAULT_CONVERTER.writeValue(value, jb, writeClass);
}
}
jb.objectEnd();
}

View File

@ -151,8 +151,9 @@ public class JSONArray implements JSONNode {
* add items.
*/
public void addAll(Object[] eles) {
for (Object ele : eles)
for (Object ele : eles) {
mArray.add(ele);
}
}
/**
@ -172,10 +173,11 @@ public class JSONArray implements JSONNode {
public void writeJSON(JSONConverter jc, JSONWriter jb, boolean writeClass) throws IOException {
jb.arrayBegin();
for (Object item : mArray) {
if (item == null)
if (item == null) {
jb.valueNull();
else
} else {
jc.writeValue(item, jb, writeClass);
}
}
jb.arrayEnd();
}

View File

@ -167,8 +167,9 @@ public class JSONObject implements JSONNode {
* @param values value array.
*/
public void putAll(String[] names, Object[] values) {
for (int i = 0, len = Math.min(names.length, values.length); i < len; i++)
for (int i = 0, len = Math.min(names.length, values.length); i < len; i++) {
mMap.put(names[i], values[i]);
}
}
/**
@ -177,8 +178,9 @@ public class JSONObject implements JSONNode {
* @param map map.
*/
public void putAll(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet())
for (Map.Entry<String, Object> entry : map.entrySet()) {
mMap.put(entry.getKey(), entry.getValue());
}
}
/**
@ -196,10 +198,11 @@ public class JSONObject implements JSONNode {
key = entry.getKey();
jb.objectItem(key);
value = entry.getValue();
if (value == null)
if (value == null) {
jb.valueNull();
else
} else {
jc.writeValue(value, jb, writeClass);
}
}
jb.objectEnd();
}

View File

@ -57,10 +57,12 @@ public class JSONReader {
public JSONToken nextToken(int expect) throws IOException, ParseException {
JSONToken ret = mLex.yylex();
if (ret == null)
if (ret == null) {
throw new ParseException("EOF error.");
if (expect != JSONToken.ANY && expect != ret.type)
}
if (expect != JSONToken.ANY && expect != ret.type) {
throw new ParseException("Unexpected token.");
}
return ret;
}
}

View File

@ -53,11 +53,13 @@ public class JSONWriter {
}
private static String escape(String str) {
if (str == null)
if (str == null) {
return str;
}
int len = str.length();
if (len == 0)
if (len == 0) {
return str;
}
char c;
StringBuilder sb = null;
@ -82,8 +84,9 @@ public class JSONWriter {
sb.append('\\').append(c);
break;
default:
if (sb != null)
if (sb != null) {
sb.append(c);
}
}
}
}
@ -263,8 +266,9 @@ public class JSONWriter {
private void beforeValue() throws IOException {
switch (mState.type) {
case ARRAY:
if (mState.itemCount++ > 0)
if (mState.itemCount++ > 0) {
mWriter.write(JSON.COMMA);
}
return;
case OBJECT:
throw new IOException("Must call objectItem first.");
@ -280,8 +284,9 @@ public class JSONWriter {
mWriter.write(JSON.NULL);
case OBJECT:
mState.type = OBJECT_VALUE;
if (mState.itemCount++ > 0)
if (mState.itemCount++ > 0) {
mWriter.write(JSON.COMMA);
}
return;
default:
throw new IOException("Must call objectBegin first.");

View File

@ -340,7 +340,9 @@ public class Yylex {
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
do {
result[j++] = value;
} while (--count > 0);
}
return j;
}
@ -393,7 +395,9 @@ public class Yylex {
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
do {
result[j++] = value;
} while (--count > 0);
}
return j;
}
@ -411,7 +415,9 @@ public class Yylex {
while (i < 122) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
do {
map[j++] = value;
} while (--count > 0);
}
return map;
}
@ -477,8 +483,9 @@ public class Yylex {
zzAtEOF = true; /* indicate end of file */
zzEndRead = zzStartRead; /* invalidate buffer */
if (zzReader != null)
if (zzReader != null) {
zzReader.close();
}
}
@ -588,8 +595,9 @@ public class Yylex {
* This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if (number > yylength())
if (number > yylength()) {
zzScanError(ZZ_PUSHBACK_2BIG);
}
zzMarkedPos -= number;
}
@ -631,9 +639,9 @@ public class Yylex {
{
while (true) {
if (zzCurrentPosL < zzEndReadL)
if (zzCurrentPosL < zzEndReadL) {
zzInput = zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
} else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
} else {
@ -654,14 +662,18 @@ public class Yylex {
}
}
int zzNext = zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) break zzForAction;
if (zzNext == -1) {
break zzForAction;
}
zzState = zzNext;
int zzAttributes = zzAttrL[zzState];
if ((zzAttributes & 1) == 1) {
zzAction = zzState;
zzMarkedPosL = zzCurrentPosL;
if ((zzAttributes & 8) == 8) break zzForAction;
if ((zzAttributes & 8) == 8) {
break zzForAction;
}
}
}

View File

@ -61,35 +61,47 @@ public class JdkLoggerAdapter implements LoggerAdapter {
}
private static java.util.logging.Level toJdkLevel(Level level) {
if (level == Level.ALL)
if (level == Level.ALL) {
return java.util.logging.Level.ALL;
if (level == Level.TRACE)
}
if (level == Level.TRACE) {
return java.util.logging.Level.FINER;
if (level == Level.DEBUG)
}
if (level == Level.DEBUG) {
return java.util.logging.Level.FINE;
if (level == Level.INFO)
}
if (level == Level.INFO) {
return java.util.logging.Level.INFO;
if (level == Level.WARN)
}
if (level == Level.WARN) {
return java.util.logging.Level.WARNING;
if (level == Level.ERROR)
}
if (level == Level.ERROR) {
return java.util.logging.Level.SEVERE;
}
// if (level == Level.OFF)
return java.util.logging.Level.OFF;
}
private static Level fromJdkLevel(java.util.logging.Level level) {
if (level == java.util.logging.Level.ALL)
if (level == java.util.logging.Level.ALL) {
return Level.ALL;
if (level == java.util.logging.Level.FINER)
}
if (level == java.util.logging.Level.FINER) {
return Level.TRACE;
if (level == java.util.logging.Level.FINE)
}
if (level == java.util.logging.Level.FINE) {
return Level.DEBUG;
if (level == java.util.logging.Level.INFO)
}
if (level == java.util.logging.Level.INFO) {
return Level.INFO;
if (level == java.util.logging.Level.WARNING)
}
if (level == java.util.logging.Level.WARNING) {
return Level.WARN;
if (level == java.util.logging.Level.SEVERE)
}
if (level == java.util.logging.Level.SEVERE) {
return Level.ERROR;
}
// if (level == java.util.logging.Level.OFF)
return Level.OFF;
}

View File

@ -54,35 +54,47 @@ public class Log4jLoggerAdapter implements LoggerAdapter {
}
private static org.apache.log4j.Level toLog4jLevel(Level level) {
if (level == Level.ALL)
if (level == Level.ALL) {
return org.apache.log4j.Level.ALL;
if (level == Level.TRACE)
}
if (level == Level.TRACE) {
return org.apache.log4j.Level.TRACE;
if (level == Level.DEBUG)
}
if (level == Level.DEBUG) {
return org.apache.log4j.Level.DEBUG;
if (level == Level.INFO)
}
if (level == Level.INFO) {
return org.apache.log4j.Level.INFO;
if (level == Level.WARN)
}
if (level == Level.WARN) {
return org.apache.log4j.Level.WARN;
if (level == Level.ERROR)
}
if (level == Level.ERROR) {
return org.apache.log4j.Level.ERROR;
}
// if (level == Level.OFF)
return org.apache.log4j.Level.OFF;
}
private static Level fromLog4jLevel(org.apache.log4j.Level level) {
if (level == org.apache.log4j.Level.ALL)
if (level == org.apache.log4j.Level.ALL) {
return Level.ALL;
if (level == org.apache.log4j.Level.TRACE)
}
if (level == org.apache.log4j.Level.TRACE) {
return Level.TRACE;
if (level == org.apache.log4j.Level.DEBUG)
}
if (level == org.apache.log4j.Level.DEBUG) {
return Level.DEBUG;
if (level == org.apache.log4j.Level.INFO)
}
if (level == org.apache.log4j.Level.INFO) {
return Level.INFO;
if (level == org.apache.log4j.Level.WARN)
}
if (level == org.apache.log4j.Level.WARN) {
return Level.WARN;
if (level == org.apache.log4j.Level.ERROR)
}
if (level == org.apache.log4j.Level.ERROR) {
return Level.ERROR;
}
// if (level == org.apache.log4j.Level.OFF)
return Level.OFF;
}

View File

@ -33,7 +33,9 @@ public class SimpleDataStore implements DataStore {
@Override
public Map<String, Object> get(String componentName) {
ConcurrentMap<String, Object> value = data.get(componentName);
if (value == null) return new HashMap<String, Object>();
if (value == null) {
return new HashMap<String, Object>();
}
return new HashMap<String, Object>(value);
}

View File

@ -142,8 +142,12 @@ public class AtomicPositiveInteger extends Number {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof AtomicPositiveInteger)) return false;
if (this == obj) {
return true;
}
if (!(obj instanceof AtomicPositiveInteger)) {
return false;
}
AtomicPositiveInteger other = (AtomicPositiveInteger) obj;
return intValue() == other.intValue();
}

View File

@ -187,7 +187,9 @@ public class CollectionUtils {
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> toMap(Object... pairs) {
Map<K, V> ret = new HashMap<K, V>();
if (pairs == null || pairs.length == 0) return ret;
if (pairs == null || pairs.length == 0) {
return ret;
}
if (pairs.length % 2 != 0) {
throw new IllegalArgumentException("Map pairs can not be odd number.");

View File

@ -147,8 +147,9 @@ public class IOUtils {
* @throws IOException
*/
public static String[] readLines(File file) throws IOException {
if (file == null || !file.exists() || !file.canRead())
if (file == null || !file.exists() || !file.canRead()) {
return new String[0];
}
return readLines(new FileInputStream(file));
}
@ -165,8 +166,9 @@ public class IOUtils {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
while ((line = reader.readLine()) != null)
while ((line = reader.readLine()) != null) {
lines.add(line);
}
return lines.toArray(new String[0]);
} finally {
reader.close();
@ -183,8 +185,9 @@ public class IOUtils {
public static void writeLines(OutputStream os, String[] lines) throws IOException {
PrintWriter writer = new PrintWriter(new OutputStreamWriter(os));
try {
for (String line : lines)
for (String line : lines) {
writer.println(line);
}
writer.flush();
} finally {
writer.close();
@ -199,8 +202,9 @@ public class IOUtils {
* @throws IOException
*/
public static void writeLines(File file, String[] lines) throws IOException {
if (file == null)
if (file == null) {
throw new IOException("File is null.");
}
writeLines(new FileOutputStream(file), lines);
}
@ -212,8 +216,9 @@ public class IOUtils {
* @throws IOException
*/
public static void appendLines(File file, String[] lines) throws IOException {
if (file == null)
if (file == null) {
throw new IOException("File is null.");
}
writeLines(new FileOutputStream(file, true), lines);
}

View File

@ -72,22 +72,44 @@ public class Log implements Serializable {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Log other = (Log) obj;
if (logLevel == null) {
if (other.logLevel != null) return false;
} else if (!logLevel.equals(other.logLevel)) return false;
if (other.logLevel != null) {
return false;
}
} else if (!logLevel.equals(other.logLevel)) {
return false;
}
if (logMessage == null) {
if (other.logMessage != null) return false;
} else if (!logMessage.equals(other.logMessage)) return false;
if (other.logMessage != null) {
return false;
}
} else if (!logMessage.equals(other.logMessage)) {
return false;
}
if (logName == null) {
if (other.logName != null) return false;
} else if (!logName.equals(other.logName)) return false;
if (other.logName != null) {
return false;
}
} else if (!logName.equals(other.logName)) {
return false;
}
if (logThread == null) {
if (other.logThread != null) return false;
} else if (!logThread.equals(other.logThread)) return false;
if (other.logThread != null) {
return false;
}
} else if (!logThread.equals(other.logThread)) {
return false;
}
return true;
}

View File

@ -50,7 +50,9 @@ public class LogUtil {
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
String logName = logList.get(i).getLogName();
if (logName.contains(expectedLogName)) count++;
if (logName.contains(expectedLogName)) {
count++;
}
}
return count;
}
@ -60,7 +62,9 @@ public class LogUtil {
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
Level logLevel = logList.get(i).getLogLevel();
if (logLevel.equals(expectedLevel)) count++;
if (logLevel.equals(expectedLevel)) {
count++;
}
}
return count;
}
@ -70,8 +74,9 @@ public class LogUtil {
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
Log log = logList.get(i);
if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName))
if (log.getLogLevel().equals(expectedLevel) && log.getLogThread().equals(threadName)) {
count++;
}
}
return count;
}
@ -81,7 +86,9 @@ public class LogUtil {
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
String logThread = logList.get(i).getLogThread();
if (logThread.contains(expectedThread)) count++;
if (logThread.contains(expectedThread)) {
count++;
}
}
return count;
}
@ -91,7 +98,9 @@ public class LogUtil {
List<Log> logList = DubboAppender.logList;
for (int i = 0; i < logList.size(); i++) {
String logMessage = logList.get(i).getLogMessage();
if (logMessage.contains(expectedMessage)) count++;
if (logMessage.contains(expectedMessage)) {
count++;
}
}
return count;
}
@ -103,7 +112,9 @@ public class LogUtil {
Level logLevel = logList.get(i).getLogLevel();
if (logLevel.equals(expectedLevel)) {
String logMessage = logList.get(i).getLogMessage();
if (logMessage.contains(expectedMessage)) count++;
if (logMessage.contains(expectedMessage)) {
count++;
}
}
}
return count;

View File

@ -134,8 +134,9 @@ public class NetUtils {
}
static boolean isValidAddress(InetAddress address) {
if (address == null || address.isLoopbackAddress())
if (address == null || address.isLoopbackAddress()) {
return false;
}
String name = address.getHostAddress();
return (name != null
&& !ANYHOST.equals(name)
@ -221,8 +222,9 @@ public class NetUtils {
* @return first valid local IP
*/
public static InetAddress getLocalAddress() {
if (LOCAL_ADDRESS != null)
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddress0();
LOCAL_ADDRESS = localAddress;
return localAddress;
@ -333,8 +335,9 @@ public class NetUtils {
StringBuilder sb = new StringBuilder();
sb.append(protocol).append("://");
sb.append(host).append(':').append(port);
if (path.charAt(0) != '/')
if (path.charAt(0) != '/') {
sb.append('/');
}
sb.append(path);
return sb.toString();
}

View File

@ -82,8 +82,9 @@ public class PojoUtils {
}
public static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes) {
if (objs.length != types.length || objs.length != gtypes.length)
if (objs.length != types.length || objs.length != gtypes.length) {
throw new IllegalArgumentException("args.length != types.length");
}
Object[] dests = new Object[objs.length];
for (int i = 0; i < objs.length; i++) {
dests[i] = realize(objs[i], types[i], gtypes[i]);
@ -448,8 +449,9 @@ public class PojoUtils {
Method method = getSetterMethod(dest.getClass(), name, value.getClass());
Field field = getField(dest.getClass(), name);
if (method != null) {
if (!method.isAccessible())
if (!method.isAccessible()) {
method.setAccessible(true);
}
Type ptype = method.getGenericParameterTypes()[0];
value = realize0(value, method.getParameterTypes()[0], ptype, history);
try {

View File

@ -138,22 +138,23 @@ public final class ReflectUtils {
}
public static Class<?> getBoxedClass(Class<?> c) {
if (c == int.class)
if (c == int.class) {
c = Integer.class;
else if (c == boolean.class)
} else if (c == boolean.class) {
c = Boolean.class;
else if (c == long.class)
} else if (c == long.class) {
c = Long.class;
else if (c == float.class)
} else if (c == float.class) {
c = Float.class;
else if (c == double.class)
} else if (c == double.class) {
c = Double.class;
else if (c == char.class)
} else if (c == char.class) {
c = Character.class;
else if (c == byte.class)
} else if (c == byte.class) {
c = Byte.class;
else if (c == short.class)
} else if (c == short.class) {
c = Short.class;
}
return c;
}
@ -186,25 +187,36 @@ public final class ReflectUtils {
*/
public static boolean isCompatible(Class<?>[] cs, Object[] os) {
int len = cs.length;
if (len != os.length) return false;
if (len == 0) return true;
for (int i = 0; i < len; i++)
if (!isCompatible(cs[i], os[i])) return false;
if (len != os.length) {
return false;
}
if (len == 0) {
return true;
}
for (int i = 0; i < len; i++) {
if (!isCompatible(cs[i], os[i])) {
return false;
}
}
return true;
}
public static String getCodeBase(Class<?> cls) {
if (cls == null)
if (cls == null) {
return null;
}
ProtectionDomain domain = cls.getProtectionDomain();
if (domain == null)
if (domain == null) {
return null;
}
CodeSource source = domain.getCodeSource();
if (source == null)
if (source == null) {
return null;
}
URL location = source.getLocation();
if (location == null)
if (location == null) {
return null;
}
return location.getFile();
}
@ -266,8 +278,9 @@ public final class ReflectUtils {
ret.append(m.getName()).append('(');
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0)
if (i > 0) {
ret.append(',');
}
ret.append(getName(parameterTypes[i]));
}
ret.append(')');
@ -303,8 +316,9 @@ public final class ReflectUtils {
StringBuilder ret = new StringBuilder("(");
Class<?>[] parameterTypes = c.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++) {
if (i > 0)
if (i > 0) {
ret.append(',');
}
ret.append(getName(parameterTypes[i]));
}
ret.append(')');
@ -330,15 +344,25 @@ public final class ReflectUtils {
if (c.isPrimitive()) {
String t = c.getName();
if ("void".equals(t)) ret.append(JVM_VOID);
else if ("boolean".equals(t)) ret.append(JVM_BOOLEAN);
else if ("byte".equals(t)) ret.append(JVM_BYTE);
else if ("char".equals(t)) ret.append(JVM_CHAR);
else if ("double".equals(t)) ret.append(JVM_DOUBLE);
else if ("float".equals(t)) ret.append(JVM_FLOAT);
else if ("int".equals(t)) ret.append(JVM_INT);
else if ("long".equals(t)) ret.append(JVM_LONG);
else if ("short".equals(t)) ret.append(JVM_SHORT);
if ("void".equals(t)) {
ret.append(JVM_VOID);
} else if ("boolean".equals(t)) {
ret.append(JVM_BOOLEAN);
} else if ("byte".equals(t)) {
ret.append(JVM_BYTE);
} else if ("char".equals(t)) {
ret.append(JVM_CHAR);
} else if ("double".equals(t)) {
ret.append(JVM_DOUBLE);
} else if ("float".equals(t)) {
ret.append(JVM_FLOAT);
} else if ("int".equals(t)) {
ret.append(JVM_INT);
} else if ("long".equals(t)) {
ret.append(JVM_LONG);
} else if ("short".equals(t)) {
ret.append(JVM_SHORT);
}
} else {
ret.append('L');
ret.append(c.getName().replace('.', '/'));
@ -356,12 +380,14 @@ public final class ReflectUtils {
* @throws NotFoundException
*/
public static String getDesc(final Class<?>[] cs) {
if (cs.length == 0)
if (cs.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder(64);
for (Class<?> c : cs)
for (Class<?> c : cs) {
sb.append(getDesc(c));
}
return sb.toString();
}
@ -376,8 +402,9 @@ public final class ReflectUtils {
public static String getDesc(final Method m) {
StringBuilder ret = new StringBuilder(m.getName()).append('(');
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append(getDesc(m.getReturnType()));
return ret.toString();
}
@ -392,8 +419,9 @@ public final class ReflectUtils {
public static String getDesc(final Constructor<?> c) {
StringBuilder ret = new StringBuilder("(");
Class<?>[] parameterTypes = c.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append('V');
return ret.toString();
}
@ -409,8 +437,9 @@ public final class ReflectUtils {
StringBuilder ret = new StringBuilder();
ret.append('(');
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append(getDesc(m.getReturnType()));
return ret.toString();
}
@ -431,15 +460,25 @@ public final class ReflectUtils {
ret.append(getDesc(c.getComponentType()));
} else if (c.isPrimitive()) {
String t = c.getName();
if ("void".equals(t)) ret.append(JVM_VOID);
else if ("boolean".equals(t)) ret.append(JVM_BOOLEAN);
else if ("byte".equals(t)) ret.append(JVM_BYTE);
else if ("char".equals(t)) ret.append(JVM_CHAR);
else if ("double".equals(t)) ret.append(JVM_DOUBLE);
else if ("float".equals(t)) ret.append(JVM_FLOAT);
else if ("int".equals(t)) ret.append(JVM_INT);
else if ("long".equals(t)) ret.append(JVM_LONG);
else if ("short".equals(t)) ret.append(JVM_SHORT);
if ("void".equals(t)) {
ret.append(JVM_VOID);
} else if ("boolean".equals(t)) {
ret.append(JVM_BOOLEAN);
} else if ("byte".equals(t)) {
ret.append(JVM_BYTE);
} else if ("char".equals(t)) {
ret.append(JVM_CHAR);
} else if ("double".equals(t)) {
ret.append(JVM_DOUBLE);
} else if ("float".equals(t)) {
ret.append(JVM_FLOAT);
} else if ("int".equals(t)) {
ret.append(JVM_INT);
} else if ("long".equals(t)) {
ret.append(JVM_LONG);
} else if ("short".equals(t)) {
ret.append(JVM_SHORT);
}
} else {
ret.append('L');
ret.append(c.getName().replace('.', '/'));
@ -458,8 +497,9 @@ public final class ReflectUtils {
public static String getDesc(final CtMethod m) throws NotFoundException {
StringBuilder ret = new StringBuilder(m.getName()).append('(');
CtClass[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append(getDesc(m.getReturnType()));
return ret.toString();
}
@ -474,8 +514,9 @@ public final class ReflectUtils {
public static String getDesc(final CtConstructor c) throws NotFoundException {
StringBuilder ret = new StringBuilder("(");
CtClass[] parameterTypes = c.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append('V');
return ret.toString();
}
@ -491,8 +532,9 @@ public final class ReflectUtils {
StringBuilder ret = new StringBuilder();
ret.append('(');
CtClass[] parameterTypes = m.getParameterTypes();
for (int i = 0; i < parameterTypes.length; i++)
for (int i = 0; i < parameterTypes.length; i++) {
ret.append(getDesc(parameterTypes[i]));
}
ret.append(')').append(getDesc(m.getReturnType()));
return ret.toString();
}
@ -511,17 +553,30 @@ public final class ReflectUtils {
c = (name.length() - index) / 2;
name = name.substring(0, index);
}
while (c-- > 0) sb.append("[");
if ("void".equals(name)) sb.append(JVM_VOID);
else if ("boolean".equals(name)) sb.append(JVM_BOOLEAN);
else if ("byte".equals(name)) sb.append(JVM_BYTE);
else if ("char".equals(name)) sb.append(JVM_CHAR);
else if ("double".equals(name)) sb.append(JVM_DOUBLE);
else if ("float".equals(name)) sb.append(JVM_FLOAT);
else if ("int".equals(name)) sb.append(JVM_INT);
else if ("long".equals(name)) sb.append(JVM_LONG);
else if ("short".equals(name)) sb.append(JVM_SHORT);
else sb.append('L').append(name.replace('.', '/')).append(';');
while (c-- > 0) {
sb.append("[");
}
if ("void".equals(name)) {
sb.append(JVM_VOID);
} else if ("boolean".equals(name)) {
sb.append(JVM_BOOLEAN);
} else if ("byte".equals(name)) {
sb.append(JVM_BYTE);
} else if ("char".equals(name)) {
sb.append(JVM_CHAR);
} else if ("double".equals(name)) {
sb.append(JVM_DOUBLE);
} else if ("float".equals(name)) {
sb.append(JVM_FLOAT);
} else if ("int".equals(name)) {
sb.append(JVM_INT);
} else if ("long".equals(name)) {
sb.append(JVM_LONG);
} else if ("short".equals(name)) {
sb.append(JVM_SHORT);
} else {
sb.append('L').append(name.replace('.', '/')).append(';');
}
return sb.toString();
}
@ -579,7 +634,9 @@ public final class ReflectUtils {
} else {
sb.append(desc.substring(c + 1, desc.length() - 1).replace('/', '.'));
}
while (c-- > 0) sb.append("[]");
while (c-- > 0) {
sb.append("[]");
}
return sb.toString();
}
@ -628,34 +685,57 @@ public final class ReflectUtils {
}
if (c > 0) {
StringBuilder sb = new StringBuilder();
while (c-- > 0)
while (c-- > 0) {
sb.append("[");
}
if ("void".equals(name)) sb.append(JVM_VOID);
else if ("boolean".equals(name)) sb.append(JVM_BOOLEAN);
else if ("byte".equals(name)) sb.append(JVM_BYTE);
else if ("char".equals(name)) sb.append(JVM_CHAR);
else if ("double".equals(name)) sb.append(JVM_DOUBLE);
else if ("float".equals(name)) sb.append(JVM_FLOAT);
else if ("int".equals(name)) sb.append(JVM_INT);
else if ("long".equals(name)) sb.append(JVM_LONG);
else if ("short".equals(name)) sb.append(JVM_SHORT);
else sb.append('L').append(name).append(';'); // "java.lang.Object" ==> "Ljava.lang.Object;"
if ("void".equals(name)) {
sb.append(JVM_VOID);
} else if ("boolean".equals(name)) {
sb.append(JVM_BOOLEAN);
} else if ("byte".equals(name)) {
sb.append(JVM_BYTE);
} else if ("char".equals(name)) {
sb.append(JVM_CHAR);
} else if ("double".equals(name)) {
sb.append(JVM_DOUBLE);
} else if ("float".equals(name)) {
sb.append(JVM_FLOAT);
} else if ("int".equals(name)) {
sb.append(JVM_INT);
} else if ("long".equals(name)) {
sb.append(JVM_LONG);
} else if ("short".equals(name)) {
sb.append(JVM_SHORT);
} else {
sb.append('L').append(name).append(';'); // "java.lang.Object" ==> "Ljava.lang.Object;"
}
name = sb.toString();
} else {
if ("void".equals(name)) return void.class;
else if ("boolean".equals(name)) return boolean.class;
else if ("byte".equals(name)) return byte.class;
else if ("char".equals(name)) return char.class;
else if ("double".equals(name)) return double.class;
else if ("float".equals(name)) return float.class;
else if ("int".equals(name)) return int.class;
else if ("long".equals(name)) return long.class;
else if ("short".equals(name)) return short.class;
if ("void".equals(name)) {
return void.class;
} else if ("boolean".equals(name)) {
return boolean.class;
} else if ("byte".equals(name)) {
return byte.class;
} else if ("char".equals(name)) {
return char.class;
} else if ("double".equals(name)) {
return double.class;
} else if ("float".equals(name)) {
return float.class;
} else if ("int".equals(name)) {
return int.class;
} else if ("long".equals(name)) {
return long.class;
} else if ("short".equals(name)) {
return short.class;
}
}
if (cl == null)
if (cl == null) {
cl = ClassHelper.getClassLoader();
}
Class<?> clazz = NAME_CLASS_CACHE.get(name);
if (clazz == null) {
clazz = Class.forName(name, true, cl);
@ -717,8 +797,9 @@ public final class ReflectUtils {
throw new ClassNotFoundException("Class not found: " + desc);
}
if (cl == null)
if (cl == null) {
cl = ClassHelper.getClassLoader();
}
Class<?> clazz = DESC_CLASS_CACHE.get(desc);
if (clazz == null) {
clazz = Class.forName(desc, true, cl);
@ -748,13 +829,15 @@ public final class ReflectUtils {
* @throws ClassNotFoundException
*/
private static Class<?>[] desc2classArray(ClassLoader cl, String desc) throws ClassNotFoundException {
if (desc.length() == 0)
if (desc.length() == 0) {
return EMPTY_CLASS_ARRAY;
}
List<Class<?>> cs = new ArrayList<Class<?>>();
Matcher m = DESC_PATTERN.matcher(desc);
while (m.find())
while (m.find()) {
cs.add(desc2class(cl, m.group()));
}
return cs.toArray(EMPTY_CLASS_ARRAY);
}
@ -862,8 +945,9 @@ public final class ReflectUtils {
}
private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) {
if (level > 2)
if (level > 2) {
return null;
}
if (returnType == null) {
return null;
} else if (returnType == boolean.class || returnType == Boolean.class) {

View File

@ -38,10 +38,11 @@ public class Stack<E> {
* @param ele
*/
public void push(E ele) {
if (mElements.size() > mSize)
if (mElements.size() > mSize) {
mElements.set(mSize, ele);
else
} else {
mElements.add(ele);
}
mSize++;
}
@ -51,8 +52,9 @@ public class Stack<E> {
* @return the last element.
*/
public E pop() {
if (mSize == 0)
if (mSize == 0) {
throw new EmptyStackException();
}
return mElements.set(--mSize, null);
}
@ -62,8 +64,9 @@ public class Stack<E> {
* @return the last element.
*/
public E peek() {
if (mSize == 0)
if (mSize == 0) {
throw new EmptyStackException();
}
return mElements.get(mSize - 1);
}
@ -74,8 +77,9 @@ public class Stack<E> {
* @return element.
*/
public E get(int index) {
if (index >= mSize)
if (index >= mSize) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize);
}
return index < 0 ? mElements.get(index + mSize) : mElements.get(index);
}
@ -88,8 +92,9 @@ public class Stack<E> {
* @return old element.
*/
public E set(int index, E value) {
if (index >= mSize)
if (index >= mSize) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize);
}
return mElements.set(index < 0 ? index + mSize : index, value);
}
@ -101,8 +106,9 @@ public class Stack<E> {
* @return element
*/
public E remove(int index) {
if (index >= mSize)
if (index >= mSize) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + mSize);
}
E ret = mElements.remove(index < 0 ? index + mSize : index);
mSize--;

View File

@ -18,10 +18,11 @@ package org.apache.dubbo.common.utils;
import org.apache.dubbo.common.Constants;
import org.apache.dubbo.common.io.UnsafeStringWriter;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import com.alibaba.fastjson.JSON;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
@ -339,8 +340,9 @@ public final class StringUtils {
}
public static boolean isBlank(String str) {
if (str == null || str.length() == 0)
if (str == null || str.length() == 0) {
return true;
}
return false;
}
@ -351,8 +353,9 @@ public final class StringUtils {
* @return is empty.
*/
public static boolean isEmpty(String str) {
if (str == null || str.length() == 0)
if (str == null || str.length() == 0) {
return true;
}
return false;
}
@ -372,10 +375,12 @@ public final class StringUtils {
* @return equals
*/
public static boolean isEquals(String s1, String s2) {
if (s1 == null && s2 == null)
if (s1 == null && s2 == null) {
return true;
if (s1 == null || s2 == null)
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
@ -386,14 +391,16 @@ public final class StringUtils {
* @return is integer
*/
public static boolean isInteger(String str) {
if (str == null || str.length() == 0)
if (str == null || str.length() == 0) {
return false;
}
return INT_PATTERN.matcher(str).matches();
}
public static int parseInteger(String str) {
if (!isInteger(str))
if (!isInteger(str)) {
return 0;
}
return Integer.parseInt(str);
}
@ -495,7 +502,9 @@ public final class StringUtils {
* @return String.
*/
public static String translat(String src, String from, String to) {
if (isEmpty(src)) return src;
if (isEmpty(src)) {
return src;
}
StringBuilder sb = null;
int ix;
char c;
@ -503,15 +512,17 @@ public final class StringUtils {
c = src.charAt(i);
ix = from.indexOf(c);
if (ix == -1) {
if (sb != null)
if (sb != null) {
sb.append(c);
}
} else {
if (sb == null) {
sb = new StringBuilder(len);
sb.append(src, 0, i);
}
if (ix < to.length())
if (ix < to.length()) {
sb.append(to.charAt(ix));
}
}
}
return sb == null ? src : sb.toString();
@ -530,14 +541,16 @@ public final class StringUtils {
for (int i = 0; i < len; i++) {
c = str.charAt(i);
if (c == ch) {
if (list == null)
if (list == null) {
list = new ArrayList<String>();
}
list.add(str.substring(ix, i));
ix = i + 1;
}
}
if (ix > 0)
if (ix > 0) {
list.add(str.substring(ix));
}
return list == null ? EMPTY_STRING_ARRAY : (String[]) list.toArray(EMPTY_STRING_ARRAY);
}
@ -548,10 +561,13 @@ public final class StringUtils {
* @return String.
*/
public static String join(String[] array) {
if (array.length == 0) return "";
if (array.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (String s : array)
for (String s : array) {
sb.append(s);
}
return sb.toString();
}
@ -563,11 +579,14 @@ public final class StringUtils {
* @return String.
*/
public static String join(String[] array, char split) {
if (array.length == 0) return "";
if (array.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
if (i > 0) {
sb.append(split);
}
sb.append(array[i]);
}
return sb.toString();
@ -581,24 +600,32 @@ public final class StringUtils {
* @return String.
*/
public static String join(String[] array, String split) {
if (array.length == 0) return "";
if (array.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
if (i > 0) {
sb.append(split);
}
sb.append(array[i]);
}
return sb.toString();
}
public static String join(Collection<String> coll, String split) {
if (coll.isEmpty()) return "";
if (coll.isEmpty()) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String s : coll) {
if (isFirst) isFirst = false;
else sb.append(split);
if (isFirst) {
isFirst = false;
} else {
sb.append(split);
}
sb.append(s);
}
return sb.toString();
@ -616,8 +643,9 @@ public final class StringUtils {
Map<String, String> map = new HashMap<String, String>(tmp.length);
for (int i = 0; i < tmp.length; i++) {
Matcher matcher = KVP_PATTERN.matcher(tmp[i]);
if (matcher.matches() == false)
if (matcher.matches() == false) {
continue;
}
map.put(matcher.group(1), matcher.group(2));
}
return map;
@ -635,8 +663,9 @@ public final class StringUtils {
* @return Parameters instance.
*/
public static Map<String, String> parseQueryString(String qs) {
if (qs == null || qs.length() == 0)
if (qs == null || qs.length() == 0) {
return new HashMap<String, String>();
}
return parseKeyValuePair(qs, "\\&");
}

View File

@ -361,8 +361,9 @@ public class UrlUtils {
public static boolean isMatch(URL consumerUrl, URL providerUrl) {
String consumerInterface = consumerUrl.getServiceInterface();
String providerInterface = providerUrl.getServiceInterface();
if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface)))
if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) {
return false;
}
if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY),
consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) {
@ -393,14 +394,17 @@ public class UrlUtils {
}
public static boolean isMatchGlobPattern(String pattern, String value) {
if ("*".equals(pattern))
if ("*".equals(pattern)) {
return true;
}
if ((pattern == null || pattern.length() == 0)
&& (value == null || value.length() == 0))
&& (value == null || value.length() == 0)) {
return true;
}
if ((pattern == null || pattern.length() == 0)
|| (value == null || value.length() == 0))
|| (value == null || value.length() == 0)) {
return false;
}
int i = pattern.lastIndexOf('*');
// doesn't find "*"

View File

@ -378,17 +378,23 @@ public class URL extends org.apache.dubbo.common.URL {
}
public URL addParameter(String key, Enum<?> value) {
if (value == null) return this;
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URL addParameter(String key, Number value) {
if (value == null) return this;
if (value == null) {
return this;
}
return addParameter(key, String.valueOf(value));
}
public URL addParameter(String key, CharSequence value) {
if (value == null || value.length() == 0) return this;
if (value == null || value.length() == 0) {
return this;
}
return addParameter(key, String.valueOf(value));
}

View File

@ -257,8 +257,9 @@ public abstract class AbstractConfig implements Serializable {
&& method.getParameterTypes().length == 0
&& isPrimitive(method.getReturnType())) {
Parameter parameter = method.getAnnotation(Parameter.class);
if (parameter == null || !parameter.attribute())
if (parameter == null || !parameter.attribute()) {
continue;
}
String key;
if (parameter.key().length() > 0) {
key = parameter.key();

View File

@ -229,7 +229,9 @@ public class ReferenceConfig<T> extends AbstractReferenceConfig {
throw new IllegalStateException("Unload " + resolveFile + ", cause: " + e.getMessage(), e);
} finally {
try {
if (null != fis) fis.close();
if (null != fis) {
fis.close();
}
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
@ -440,9 +442,13 @@ public class ReferenceConfig<T> extends AbstractReferenceConfig {
private void resolveAsyncInterface(Class<?> interfaceClass, Map<String, String> map) {
AsyncFor annotation = interfaceClass.getAnnotation(AsyncFor.class);
if (annotation == null) return;
if (annotation == null) {
return;
}
Class<?> target = annotation.value();
if (!target.isAssignableFrom(interfaceClass)) return;
if (!target.isAssignableFrom(interfaceClass)) {
return;
}
this.asyncInterfaceClass = interfaceClass;
this.interfaceClass = target;
setInterface(this.interfaceClass.getName());

View File

@ -162,8 +162,9 @@ public class RegistryConfig extends AbstractConfig {
@Deprecated
public void setWait(Integer wait) {
this.wait = wait;
if (wait != null && wait > 0)
if (wait != null && wait > 0) {
System.setProperty(Constants.SHUTDOWN_WAIT_KEY, String.valueOf(wait));
}
}
public Boolean isCheck() {

View File

@ -117,7 +117,9 @@ public class ReferenceConfigCache {
void destroyKey(String key) {
ReferenceConfig<?> config = cache.remove(key);
if (config == null) return;
if (config == null) {
return;
}
config.destroy();
}

View File

@ -200,11 +200,13 @@ public class ExchangeCodec extends TelnetCodec {
protected Object getRequestData(long id) {
DefaultFuture future = DefaultFuture.getFuture(id);
if (future == null)
if (future == null) {
return null;
}
Request req = future.getRequest();
if (req == null)
if (req == null) {
return null;
}
return req.getData();
}
@ -218,8 +220,12 @@ public class ExchangeCodec extends TelnetCodec {
// set request and serialization flag.
header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId());
if (req.isTwoWay()) header[2] |= FLAG_TWOWAY;
if (req.isEvent()) header[2] |= FLAG_EVENT;
if (req.isTwoWay()) {
header[2] |= FLAG_TWOWAY;
}
if (req.isEvent()) {
header[2] |= FLAG_EVENT;
}
// set request id.
Bytes.long2bytes(req.getId(), header, 4);
@ -260,7 +266,9 @@ public class ExchangeCodec extends TelnetCodec {
Bytes.short2bytes(MAGIC, header);
// set request and serialization flag.
header[2] = serialization.getContentTypeId();
if (res.isHeartbeat()) header[2] |= FLAG_EVENT;
if (res.isHeartbeat()) {
header[2] |= FLAG_EVENT;
}
// set response status.
byte status = res.getStatus();
header[3] = status;
@ -277,7 +285,9 @@ public class ExchangeCodec extends TelnetCodec {
} else {
encodeResponseData(channel, out, res.getResult(), res.getVersion());
}
} else out.writeUTF(res.getErrorMessage());
} else {
out.writeUTF(res.getErrorMessage());
}
out.flushBuffer();
if (out instanceof Cleanable) {
((Cleanable) out).cleanup();

View File

@ -83,9 +83,13 @@ public class HeaderExchangeHandler implements ChannelHandlerDelegate {
Object data = req.getData();
String msg;
if (data == null) msg = null;
else if (data instanceof Throwable) msg = StringUtils.toString((Throwable) data);
else msg = data.toString();
if (data == null) {
msg = null;
} else if (data instanceof Throwable) {
msg = StringUtils.toString((Throwable) data);
} else {
msg = data.toString();
}
res.setErrorMessage("Fail to decode request due to: " + msg);
res.setStatus(Response.BAD_REQUEST);

View File

@ -199,56 +199,63 @@ public abstract class AbstractClient extends AbstractEndpoint implements Client
@Override
public InetSocketAddress getRemoteAddress() {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return getUrl().toInetSocketAddress();
}
return channel.getRemoteAddress();
}
@Override
public InetSocketAddress getLocalAddress() {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0);
}
return channel.getLocalAddress();
}
@Override
public boolean isConnected() {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return false;
}
return channel.isConnected();
}
@Override
public Object getAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return null;
}
return channel.getAttribute(key);
}
@Override
public void setAttribute(String key, Object value) {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return;
}
channel.setAttribute(key, value);
}
@Override
public void removeAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return;
}
channel.removeAttribute(key);
}
@Override
public boolean hasAttribute(String key) {
Channel channel = getChannel();
if (channel == null)
if (channel == null) {
return false;
}
return channel.hasAttribute(key);
}

View File

@ -168,13 +168,23 @@ final class GrizzlyChannel extends AbstractChannel {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
GrizzlyChannel other = (GrizzlyChannel) obj;
if (connection == null) {
if (other.connection != null) return false;
} else if (!connection.equals(other.connection)) return false;
if (other.connection != null) {
return false;
}
} else if (!connection.equals(other.connection)) {
return false;
}
return true;
}

View File

@ -161,13 +161,23 @@ final class MinaChannel extends AbstractChannel {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MinaChannel other = (MinaChannel) obj;
if (session == null) {
if (other.session != null) return false;
} else if (!session.equals(other.session)) return false;
if (other.session != null) {
return false;
}
} else if (!session.equals(other.session)) {
return false;
}
return true;
}

View File

@ -95,7 +95,9 @@ final class MinaCodecAdapter implements ProtocolCodecFactory {
@Override
public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception {
int readable = in.limit();
if (readable <= 0) return;
if (readable <= 0) {
return;
}
ChannelBuffer frame;

View File

@ -177,13 +177,23 @@ final class NettyChannel extends AbstractChannel {
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
NettyChannel other = (NettyChannel) obj;
if (channel == null) {
if (other.channel != null) return false;
} else if (!channel.equals(other.channel)) return false;
if (other.channel != null) {
return false;
}
} else if (!channel.equals(other.channel)) {
return false;
}
return true;
}

View File

@ -157,8 +157,9 @@ public class NettyClient extends AbstractClient {
@Override
protected org.apache.dubbo.remoting.Channel getChannel() {
Channel c = channel;
if (c == null || !c.isConnected())
if (c == null || !c.isConnected()) {
return null;
}
return NettyChannel.getOrAddChannel(c, getUrl(), this);
}

View File

@ -156,8 +156,9 @@ public class NettyClient extends AbstractClient {
@Override
protected org.apache.dubbo.remoting.Channel getChannel() {
Channel c = channel;
if (c == null || !c.isActive())
if (c == null || !c.isActive()) {
return null;
}
return NettyChannel.getOrAddChannel(c, getUrl(), this);
}

View File

@ -33,8 +33,9 @@ public class EchoFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1)
if (inv.getMethodName().equals(Constants.$ECHO) && inv.getArguments() != null && inv.getArguments().length == 1) {
return new RpcResult(inv.getArguments()[0]);
}
return invoker.invoke(inv);
}

View File

@ -33,12 +33,15 @@ public abstract class AbstractExporter<T> implements Exporter<T> {
private volatile boolean unexported = false;
public AbstractExporter(Invoker<T> invoker) {
if (invoker == null)
if (invoker == null) {
throw new IllegalStateException("service invoker == null");
if (invoker.getInterface() == null)
}
if (invoker.getInterface() == null) {
throw new IllegalStateException("service type == null");
if (invoker.getUrl() == null)
}
if (invoker.getUrl() == null) {
throw new IllegalStateException("service url == null");
}
this.invoker = invoker;
}

View File

@ -63,10 +63,12 @@ public abstract class AbstractInvoker<T> implements Invoker<T> {
}
public AbstractInvoker(Class<T> type, URL url, Map<String, String> attachment) {
if (type == null)
if (type == null) {
throw new IllegalArgumentException("service type == null");
if (url == null)
}
if (url == null) {
throw new IllegalArgumentException("service url == null");
}
this.type = type;
this.url = url;
this.attachment = attachment == null ? null : Collections.unmodifiableMap(attachment);

View File

@ -91,8 +91,9 @@ public class DecodeableRpcResult extends RpcResult implements Codec, Decodeable
case DubboCodec.RESPONSE_WITH_EXCEPTION:
try {
Object obj = in.readObject();
if (obj instanceof Throwable == false)
if (obj instanceof Throwable == false) {
throw new IOException("Response data error, expect Throwable, but get " + obj);
}
setException((Throwable) obj);
} catch (ClassNotFoundException e) {
throw new IOException(StringUtils.toString("Read response data failed.", e));
@ -119,8 +120,9 @@ public class DecodeableRpcResult extends RpcResult implements Codec, Decodeable
case DubboCodec.RESPONSE_WITH_EXCEPTION_WITH_ATTACHMENTS:
try {
Object obj = in.readObject();
if (obj instanceof Throwable == false)
if (obj instanceof Throwable == false) {
throw new IOException("Response data error, expect Throwable, but get " + obj);
}
setException((Throwable) obj);
setAttachments((Map<String, String>) in.readObject(Map.class));
} catch (ClassNotFoundException e) {

View File

@ -179,10 +179,11 @@ public class DubboCodec extends ExchangeCodec implements Codec2 {
out.writeUTF(inv.getMethodName());
out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes()));
Object[] args = inv.getArguments();
if (args != null)
if (args != null) {
for (int i = 0; i < args.length; i++) {
out.writeObject(encodeInvocationArgument(channel, inv, i));
}
}
out.writeObject(RpcUtils.getNecessaryAttachments(inv));
}

View File

@ -116,8 +116,9 @@ public class DubboInvoker<T> extends AbstractInvoker<T> {
@Override
public boolean isAvailable() {
if (!super.isAvailable())
if (!super.isAvailable()) {
return false;
}
for (ExchangeClient client : clients) {
if (client.isConnected() && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)) {
//cannot write == not Available ?

View File

@ -225,8 +225,9 @@ public class DubboProtocol extends AbstractProtocol {
DubboExporter<?> exporter = (DubboExporter<?>) exporterMap.get(serviceKey);
if (exporter == null)
if (exporter == null) {
throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv);
}
return exporter.getInvoker();
}
@ -297,8 +298,9 @@ public class DubboProtocol extends AbstractProtocol {
url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT));
String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER);
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str))
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
throw new RpcException("Unsupported server type: " + str + ", url: " + url);
}
url = url.addParameter(Constants.CODEC_KEY, DubboCodec.NAME);
ExchangeServer server;

View File

@ -62,15 +62,17 @@ final class LazyConnectExchangeClient implements ExchangeClient {
private void initClient() throws RemotingException {
if (client != null)
if (client != null) {
return;
}
if (logger.isInfoEnabled()) {
logger.info("Lazy connect to " + url);
}
connectLock.lock();
try {
if (client != null)
if (client != null) {
return;
}
this.client = Exchangers.connect(url, requestHandler);
} finally {
connectLock.unlock();
@ -162,22 +164,25 @@ final class LazyConnectExchangeClient implements ExchangeClient {
@Override
public boolean isClosed() {
if (client != null)
if (client != null) {
return client.isClosed();
else
} else {
return true;
}
}
@Override
public void close() {
if (client != null)
if (client != null) {
client.close();
}
}
@Override
public void close(int timeout) {
if (client != null)
if (client != null) {
client.close(timeout);
}
}
@Override

View File

@ -74,22 +74,30 @@ public class RedisProtocol extends AbstractProtocol {
config.setTestOnBorrow(url.getParameter("test.on.borrow", true));
config.setTestOnReturn(url.getParameter("test.on.return", false));
config.setTestWhileIdle(url.getParameter("test.while.idle", false));
if (url.getParameter("max.idle", 0) > 0)
if (url.getParameter("max.idle", 0) > 0) {
config.setMaxIdle(url.getParameter("max.idle", 0));
if (url.getParameter("min.idle", 0) > 0)
}
if (url.getParameter("min.idle", 0) > 0) {
config.setMinIdle(url.getParameter("min.idle", 0));
if (url.getParameter("max.active", 0) > 0)
}
if (url.getParameter("max.active", 0) > 0) {
config.setMaxTotal(url.getParameter("max.active", 0));
if (url.getParameter("max.total", 0) > 0)
}
if (url.getParameter("max.total", 0) > 0) {
config.setMaxTotal(url.getParameter("max.total", 0));
if (url.getParameter("max.wait", 0) > 0)
}
if (url.getParameter("max.wait", 0) > 0) {
config.setMaxWaitMillis(url.getParameter("max.wait", 0));
if (url.getParameter("num.tests.per.eviction.run", 0) > 0)
}
if (url.getParameter("num.tests.per.eviction.run", 0) > 0) {
config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0));
if (url.getParameter("time.between.eviction.runs.millis", 0) > 0)
}
if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) {
config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0));
if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
}
if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) {
config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0));
}
final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT),
url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT),
StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(),

View File

@ -201,8 +201,9 @@ public class ThriftProtocol extends AbstractProtocol {
url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString());
String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER);
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str))
if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
throw new RpcException("Unsupported server type: " + str + ", url: " + url);
}
ExchangeServer server;
try {

View File

@ -36,8 +36,9 @@ public class RandomAccessByteArrayOutputStream extends OutputStream {
public RandomAccessByteArrayOutputStream(int size) {
if (size < 0)
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: " + size);
}
buffer = new byte[size];
}
@ -45,8 +46,9 @@ public class RandomAccessByteArrayOutputStream extends OutputStream {
public void write(int b) {
int newcount = count + 1;
if (newcount > buffer.length)
if (newcount > buffer.length) {
buffer = Bytes.copyOf(buffer, Math.max(buffer.length << 1, newcount));
}
buffer[count] = (byte) b;
count = newcount;
}
@ -54,13 +56,16 @@ public class RandomAccessByteArrayOutputStream extends OutputStream {
@Override
public void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0))
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
if (len == 0)
}
if (len == 0) {
return;
}
int newcount = count + len;
if (newcount > buffer.length)
if (newcount > buffer.length) {
buffer = Bytes.copyOf(buffer, Math.max(buffer.length << 1, newcount));
}
System.arraycopy(b, off, buffer, count, len);
count = newcount;
}

View File

@ -18,6 +18,7 @@ package org.apache.dubbo.common.serialize.fastjson;
import org.apache.dubbo.common.serialize.ObjectInput;
import org.apache.dubbo.common.utils.PojoUtils;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
@ -105,7 +106,9 @@ public class FastJsonObjectInput implements ObjectInput {
private String readLine() throws IOException, EOFException {
String line = reader.readLine();
if (line == null || line.trim().length() == 0) throw new EOFException();
if (line == null || line.trim().length() == 0) {
throw new EOFException();
}
return line;
}

View File

@ -40,12 +40,15 @@ public class JavaObjectInput extends NativeJavaObjectInput {
@Override
public byte[] readBytes() throws IOException {
int len = getObjectInputStream().readInt();
if (len < 0)
if (len < 0) {
return null;
if (len == 0)
}
if (len == 0) {
return new byte[0];
if (len > MAX_BYTE_ARRAY_LENGTH)
}
if (len > MAX_BYTE_ARRAY_LENGTH) {
throw new IOException("Byte array length too large. " + len);
}
byte[] b = new byte[len];
getObjectInputStream().readFully(b);
@ -55,8 +58,9 @@ public class JavaObjectInput extends NativeJavaObjectInput {
@Override
public String readUTF() throws IOException {
int len = getObjectInputStream().readInt();
if (len < 0)
if (len < 0) {
return null;
}
return getObjectInputStream().readUTF();
}
@ -64,8 +68,9 @@ public class JavaObjectInput extends NativeJavaObjectInput {
@Override
public Object readObject() throws IOException, ClassNotFoundException {
byte b = getObjectInputStream().readByte();
if (b == 0)
if (b == 0) {
return null;
}
return getObjectInputStream().readObject();
}