This commit is contained in:
wentch
2015-12-15 16:24:06 +08:00
parent 7daa5f629e
commit 89edaea575
86 changed files with 1604 additions and 100 deletions

View File

@@ -0,0 +1,132 @@
/*
* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package javax.annotation;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
/**
* The Resource annotation marks a resource that is needed
* by the application. This annotation may be applied to an
* application component class, or to fields or methods of the
* component class. When the annotation is applied to a
* field or method, the container will inject an instance
* of the requested resource into the application component
* when the component is initialized. If the annotation is
* applied to the component class, the annotation declares a
* resource that the application will look up at runtime. <p>
*
* Even though this annotation is not marked Inherited, deployment
* tools are required to examine all superclasses of any component
* class to discover all uses of this annotation in all superclasses.
* All such annotation instances specify resources that are needed
* by the application component. Note that this annotation may
* appear on private fields and methods of superclasses; the container
* is required to perform injection in these cases as well.
*
* @since Common Annotations 1.0
*/
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
/**
* The JNDI name of the resource. For field annotations,
* the default is the field name. For method annotations,
* the default is the JavaBeans property name corresponding
* to the method. For class annotations, there is no default
* and this must be specified.
*/
String name() default "";
/**
* The name of the resource that the reference points to. It can
* link to any compatible resource using the global JNDI names.
*
* @since Common Annotations 1.1
*/
String lookup() default "";
/**
* The Java type of the resource. For field annotations,
* the default is the type of the field. For method annotations,
* the default is the type of the JavaBeans property.
* For class annotations, there is no default and this must be
* specified.
*/
Class<?> type() default java.lang.Object.class;
/**
* The two possible authentication types for a resource.
*/
enum AuthenticationType {
CONTAINER,
APPLICATION
}
/**
* The authentication type to use for this resource.
* This may be specified for resources representing a
* connection factory of any supported type, and must
* not be specified for resources of other types.
*/
AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
/**
* Indicates whether this resource can be shared between
* this component and other components.
* This may be specified for resources representing a
* connection factory of any supported type, and must
* not be specified for resources of other types.
*/
boolean shareable() default true;
/**
* A product specific name that this resource should be mapped to.
* The name of this resource, as defined by the <code>name</code>
* element or defaulted, is a name that is local to the application
* component using the resource. (It's a name in the JNDI
* <code>java:comp/env</code> namespace.) Many application servers
* provide a way to map these local names to names of resources
* known to the application server. This mapped name is often a
* <i>global</i> JNDI name, but may be a name of any form. <p>
*
* Application servers are not required to support any particular
* form or type of mapped name, nor the ability to use mapped names.
* The mapped name is product-dependent and often installation-dependent.
* No use of a mapped name is portable.
*/
String mappedName() default "";
/**
* Description of this resource. The description is expected
* to be in the default language of the system on which the
* application is deployed. The description can be presented
* to the Deployer to help in choosing the correct resource.
*/
String description() default "";
}

View File

@@ -10,6 +10,7 @@ import java.lang.reflect.Type;
/** /**
* 对不明类型的对象进行序列化; BSON序列化时将对象的类名写入WriterJSON则不写入。 * 对不明类型的对象进行序列化; BSON序列化时将对象的类名写入WriterJSON则不写入。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -13,6 +13,7 @@ import java.util.*;
* 数组长度不能超过 32767。 在BSON中数组长度设定的是short对于大于32767长度的数组传输会影响性能所以没有采用int存储。 * 数组长度不能超过 32767。 在BSON中数组长度设定的是short对于大于32767长度的数组传输会影响性能所以没有采用int存储。
* 支持一定程度的泛型。 * 支持一定程度的泛型。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -9,9 +9,10 @@ import java.lang.reflect.*;
/** /**
* 对象数组的反序列化不包含int[]、long[]这样的primitive class数组. * 对象数组的反序列化不包含int[]、long[]这样的primitive class数组.
* 数组长度不能超过 32767。 在BSON中数组长度设定的是short对于大于32767长度的数组传输会影响性能所以没有采用int存储。 * 数组长度不能超过 32767。 在BSON中数组长度设定的是short对于大于32767长度的数组传输会影响性能所以没有必要采用int存储。
* 支持一定程度的泛型。 * 支持一定程度的泛型。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -15,6 +15,7 @@ import java.util.Collection;
* 集合大小不能超过 32767。 在BSON中集合大小设定的是short对于大于32767长度的集合传输会影响性能所以没有采用int存储。 * 集合大小不能超过 32767。 在BSON中集合大小设定的是short对于大于32767长度的集合传输会影响性能所以没有采用int存储。
* 支持一定程度的泛型。 * 支持一定程度的泛型。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -13,6 +13,7 @@ import java.util.Collection;
* 集合大小不能超过 32767。 在BSON中集合大小设定的是short对于大于32767长度的集合传输会影响性能所以没有采用int存储。 * 集合大小不能超过 32767。 在BSON中集合大小设定的是short对于大于32767长度的集合传输会影响性能所以没有采用int存储。
* 支持一定程度的泛型。 * 支持一定程度的泛型。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -8,6 +8,7 @@ package org.redkale.convert;
/** /**
* 序列化操作类 * 序列化操作类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -12,6 +12,7 @@ import static java.lang.annotation.RetentionPolicy.*;
/** /**
* 依附在setter、getter方法、字段进行简单的配置 * 依附在setter、getter方法、字段进行简单的配置
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
@Inherited @Inherited

View File

@@ -8,6 +8,7 @@ package org.redkale.convert;
/** /**
* ConvertColumn 对应的实体类 * ConvertColumn 对应的实体类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class ConvertColumnEntry { public final class ConvertColumnEntry {

View File

@@ -12,6 +12,7 @@ import static java.lang.annotation.RetentionPolicy.*;
/** /**
* ConvertColumn 的多用类 * ConvertColumn 的多用类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
@Inherited @Inherited

View File

@@ -13,6 +13,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
* 用于类名的别名, 类似javax.persistence.Table * 用于类名的别名, 类似javax.persistence.Table
* 该值必须是全局唯一 * 该值必须是全局唯一
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
@Inherited @Inherited

View File

@@ -6,6 +6,7 @@ package org.redkale.convert;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class ConvertException extends RuntimeException { public class ConvertException extends RuntimeException {

View File

@@ -7,6 +7,7 @@ package org.redkale.convert;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public enum ConvertType { public enum ConvertType {

View File

@@ -9,6 +9,7 @@ import org.redkale.util.Attribute;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <T> * @param <T>

View File

@@ -9,6 +9,7 @@ import java.lang.reflect.Type;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <T> * @param <T>

View File

@@ -9,6 +9,7 @@ import org.redkale.util.Attribute;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <W> * @param <W>
* @param <T> * @param <T>

View File

@@ -9,6 +9,7 @@ import java.lang.reflect.Type;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <W> * @param <W>
* @param <T> * @param <T>

View File

@@ -12,15 +12,16 @@ import java.lang.reflect.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.*; import java.net.*;
import static org.redkale.convert.ext.InetAddressSimpledCoder.*; import static org.redkale.convert.ext.InetAddressSimpledCoder.*;
import org.redkale.util.Creator.Creators;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.regex.*; import java.util.regex.*;
import org.redkale.convert.ext.*; import org.redkale.convert.ext.*;
import org.redkale.util.*; import org.redkale.util.*;
import org.redkale.util.Creator.Creators;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -9,6 +9,7 @@ import java.lang.reflect.*;
/** /**
* 只增不减的伪Map类 * 只增不减的伪Map类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <K> * @param <K>
* @param <V> * @param <V>
@@ -44,8 +45,9 @@ public final class HashedMap<K extends Type, V> {
Entry<K, V> entry = data[index]; Entry<K, V> entry = data[index];
while (entry != null) { while (entry != null) {
if (k == entry.key) { if (k == entry.key) {
V old = entry.value;
entry.value = value; entry.value = value;
return entry.value; return old;
} }
entry = entry.next; entry = entry.next;
} }

View File

@@ -12,6 +12,7 @@ import java.util.Map;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <K> * @param <K>
* @param <V> * @param <V>

View File

@@ -11,6 +11,7 @@ import java.util.Map;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <K> * @param <K>
* @param <V> * @param <V>

View File

@@ -15,6 +15,7 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <T> * @param <T>

View File

@@ -6,12 +6,13 @@
package org.redkale.convert; package org.redkale.convert;
import org.redkale.util.Attribute; import org.redkale.util.Attribute;
import org.redkale.util.Attribute.Attributes;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.*; import java.util.*;
import org.redkale.util.Attribute.Attributes;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <W> * @param <W>
* @param <T> * @param <T>

View File

@@ -9,6 +9,7 @@ import java.util.concurrent.atomic.AtomicInteger;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public interface Reader { public interface Reader {

View File

@@ -10,6 +10,7 @@ import java.lang.reflect.Type;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -9,6 +9,7 @@ import org.redkale.util.Attribute;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public interface Writer { public interface Writer {

View File

@@ -10,6 +10,7 @@ import java.util.function.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class BsonByteBufferWriter extends BsonWriter { public final class BsonByteBufferWriter extends BsonWriter {

View File

@@ -29,6 +29,7 @@ import org.redkale.util.*;
* 5. SIGN_NONEXT 标记位值固定为0 (byte) * 5. SIGN_NONEXT 标记位值固定为0 (byte)
* 6. SIGN_OBJECTE 标记位值固定为0xEE (short) * 6. SIGN_OBJECTE 标记位值固定为0xEE (short)
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class BsonConvert extends Convert<BsonReader, BsonWriter> { public final class BsonConvert extends Convert<BsonReader, BsonWriter> {

View File

@@ -10,6 +10,7 @@ import org.redkale.convert.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class BsonFactory extends Factory<BsonReader, BsonWriter> { public final class BsonFactory extends Factory<BsonReader, BsonWriter> {

View File

@@ -14,6 +14,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class BsonReader implements Reader { public final class BsonReader implements Reader {

View File

@@ -9,6 +9,7 @@ import org.redkale.convert.SimpledCoder;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -12,6 +12,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class BsonWriter implements Writer { public class BsonWriter implements Writer {

View File

@@ -12,6 +12,7 @@ import java.math.BigInteger;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class BoolArraySimpledCoder<R extends Reader, W extends Writer> ext
@Override @Override
public boolean[] convertFrom(R in) { public boolean[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
boolean[] data = new boolean[8]; boolean[] data = new boolean[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class ByteArraySimpledCoder<R extends Reader, W extends Writer> ext
@Override @Override
public byte[] convertFrom(R in) { public byte[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
byte[] data = new byte[8]; byte[] data = new byte[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class CharArraySimpledCoder<R extends Reader, W extends Writer> ext
@Override @Override
public char[] convertFrom(R in) { public char[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
char[] data = new char[8]; char[] data = new char[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -12,6 +12,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -8,16 +8,19 @@ package org.redkale.convert.ext;
import org.redkale.convert.Reader; import org.redkale.convert.Reader;
import org.redkale.convert.Writer; import org.redkale.convert.Writer;
import org.redkale.convert.SimpledCoder; import org.redkale.convert.SimpledCoder;
import org.redkale.util.DLong; import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
*/ */
public final class DLongSimpledCoder<R extends Reader, W extends Writer> extends SimpledCoder<R, W, DLong> { public final class DLongSimpledCoder<R extends Reader, W extends Writer> extends SimpledCoder<R, W, DLong> {
private static final ByteArraySimpledCoder bsSimpledCoder = ByteArraySimpledCoder.instance;
public static final DLongSimpledCoder instance = new DLongSimpledCoder(); public static final DLongSimpledCoder instance = new DLongSimpledCoder();
@Override @Override
@@ -25,16 +28,15 @@ public final class DLongSimpledCoder<R extends Reader, W extends Writer> extends
if (value == null) { if (value == null) {
out.writeNull(); out.writeNull();
} else { } else {
out.writeSmallString(value.getFirst() + "_" + value.getSecond()); bsSimpledCoder.convertTo(out, value.directBytes());
} }
} }
@Override @Override
public DLong convertFrom(R in) { public DLong convertFrom(R in) {
String str = in.readString(); byte[] bs = bsSimpledCoder.convertFrom(in);
if (str == null) return null; if (bs == null) return null;
int pos = str.indexOf('_'); return new DLong(bs);
return new DLong(Long.parseLong(str.substring(0, pos)), Long.parseLong(str.substring(pos + 1)));
} }
} }

View File

@@ -12,6 +12,7 @@ import java.util.Date;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class DoubleArraySimpledCoder<R extends Reader, W extends Writer> e
@Override @Override
public double[] convertFrom(R in) { public double[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
double[] data = new double[8]; double[] data = new double[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class FloatArraySimpledCoder<R extends Reader, W extends Writer> ex
@Override @Override
public float[] convertFrom(R in) { public float[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
float[] data = new float[8]; float[] data = new float[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -12,6 +12,7 @@ import java.net.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class IntArraySimpledCoder<R extends Reader, W extends Writer> exte
@Override @Override
public int[] convertFrom(R in) { public int[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
int[] data = new int[8]; int[] data = new int[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class LongArraySimpledCoder<R extends Reader, W extends Writer> ext
@Override @Override
public long[] convertFrom(R in) { public long[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
long[] data = new long[8]; long[] data = new long[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -12,6 +12,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -10,6 +10,7 @@ import org.redkale.convert.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class ShortArraySimpledCoder<R extends Reader, W extends Writer> ex
@Override @Override
public short[] convertFrom(R in) { public short[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
short[] data = new short[8]; short[] data = new short[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>
@@ -38,9 +39,8 @@ public final class StringArraySimpledCoder<R extends Reader, W extends Writer> e
@Override @Override
public String[] convertFrom(R in) { public String[] convertFrom(R in) {
int len = in.readArrayB(); int len = in.readArrayB();
if (len == Reader.SIGN_NULL) { if (len == Reader.SIGN_NULL) return null;
return null; if (len == Reader.SIGN_NOLENGTH) {
} else if (len == Reader.SIGN_NOLENGTH) {
int size = 0; int size = 0;
String[] data = new String[8]; String[] data = new String[8];
while (in.hasNext()) { while (in.hasNext()) {

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.Writer;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.SimpledCoder;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -0,0 +1,34 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.convert.json;
import org.redkale.util.*;
/**
*
* @see http://www.redkale.org
* @author zhangjx
*/
public class DLongJsonSimpledCoder extends JsonSimpledCoder<DLong> {
public static final DLongJsonSimpledCoder instance = new DLongJsonSimpledCoder();
@Override
public void convertTo(final JsonWriter out, final DLong value) {
if (value == null) {
out.writeNull();
} else {
out.writeSmallString(value.toString());
}
}
@Override
public DLong convertFrom(JsonReader in) {
final String str = in.readString();
if (str == null) return null;
return new DLong(Utility.hexToBin(str));
}
}

View File

@@ -11,6 +11,7 @@ import org.redkale.convert.ext.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <R> * @param <R>
* @param <W> * @param <W>

View File

@@ -13,6 +13,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class JsonByteBufferWriter extends JsonWriter { public final class JsonByteBufferWriter extends JsonWriter {

View File

@@ -14,6 +14,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View File

@@ -9,9 +9,11 @@ import org.redkale.convert.ConvertType;
import org.redkale.convert.Factory; import org.redkale.convert.Factory;
import java.io.Serializable; import java.io.Serializable;
import java.net.*; import java.net.*;
import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class JsonFactory extends Factory<JsonReader, JsonWriter> { public final class JsonFactory extends Factory<JsonReader, JsonWriter> {
@@ -21,6 +23,7 @@ public final class JsonFactory extends Factory<JsonReader, JsonWriter> {
static { static {
instance.register(InetAddress.class, InetAddressJsonSimpledCoder.instance); instance.register(InetAddress.class, InetAddressJsonSimpledCoder.instance);
instance.register(InetSocketAddress.class, InetAddressJsonSimpledCoder.InetSocketAddressJsonSimpledCoder.instance); instance.register(InetSocketAddress.class, InetAddressJsonSimpledCoder.InetSocketAddressJsonSimpledCoder.instance);
instance.register(DLong.class, DLongJsonSimpledCoder.instance);
instance.register(Serializable.class, instance.loadEncoder(Object.class)); instance.register(Serializable.class, instance.loadEncoder(Object.class));
} }

View File

@@ -13,6 +13,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class JsonReader implements Reader { public final class JsonReader implements Reader {

View File

@@ -9,6 +9,7 @@ import org.redkale.convert.SimpledCoder;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -14,6 +14,7 @@ import org.redkale.util.*;
* *
* writeTo系列的方法输出的字符不能含特殊字符 * writeTo系列的方法输出的字符不能含特殊字符
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class JsonWriter implements Writer { public class JsonWriter implements Writer {

View File

@@ -10,6 +10,7 @@ import java.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class HttpClient { public final class HttpClient {

View File

@@ -11,6 +11,7 @@ import java.util.concurrent.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class HttpFactory { public class HttpFactory {

View File

@@ -14,6 +14,7 @@ import org.redkale.util.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class WebSocketClient { public class WebSocketClient {

View File

@@ -0,0 +1,446 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.lang.reflect.Array;
import java.util.*;
import java.util.function.BiPredicate;
/**
* 该类提供类似JSONObject的数据结构主要用于读取xml配置文件和http-header存储
*
* @see http://www.redkale.org
* @author zhangjx
*/
@SuppressWarnings("unchecked")
public abstract class AnyValue {
/**
* 可读写的AnyValue默认实现类
*
* @see http://www.redkale.org
* @author zhangjx
*/
@SuppressWarnings("unchecked")
public static final class DefaultAnyValue extends AnyValue {
public static final BiPredicate<String, String> EQUALS = new BiPredicate<String, String>() {
@Override
public boolean test(String name1, String name2) {
return name1.equals(name2);
}
};
public static final BiPredicate<String, String> EQUALSIGNORE = new BiPredicate<String, String>() {
@Override
public boolean test(String name1, String name2) {
return name1.equalsIgnoreCase(name2);
}
};
private final BiPredicate<String, String> predicate;
private Entry<String>[] stringValues = new Entry[0];
private Entry<AnyValue>[] entityValues = new Entry[0];
public static final DefaultAnyValue create() {
return new DefaultAnyValue();
}
public static final DefaultAnyValue create(String name, String value) {
DefaultAnyValue conf = new DefaultAnyValue();
conf.addValue(name, value);
return conf;
}
public static final DefaultAnyValue create(String name, AnyValue value) {
DefaultAnyValue conf = new DefaultAnyValue();
conf.addValue(name, value);
return conf;
}
public DefaultAnyValue() {
this(false);
}
public DefaultAnyValue(boolean ignoreCase) {
this.predicate = ignoreCase ? EQUALSIGNORE : EQUALS;
}
public DefaultAnyValue(BiPredicate<String, String> predicate) {
this.predicate = predicate;
}
public DefaultAnyValue duplicate() {
DefaultAnyValue rs = new DefaultAnyValue(this.predicate);
rs.stringValues = this.stringValues;
rs.entityValues = this.entityValues;
return rs;
}
public DefaultAnyValue addAll(final AnyValue av) {
if (av == null) return this;
if (av instanceof DefaultAnyValue) {
final DefaultAnyValue adv = (DefaultAnyValue) av;
if (adv.stringValues != null) {
for (Entry<String> en : adv.stringValues) {
this.addValue(en.name, en.value);
}
}
if (adv.entityValues != null) {
for (Entry<AnyValue> en : adv.entityValues) {
this.addValue(en.name, en.value);
}
}
} else {
final Entry<String>[] strings = av.getStringEntrys();
if (strings != null) {
for (Entry<String> en : strings) {
this.addValue(en.name, en.value);
}
}
final Entry<AnyValue>[] anys = av.getAnyEntrys();
if (anys != null) {
for (Entry<AnyValue> en : anys) {
this.addValue(en.name, en.value);
}
}
}
return this;
}
public DefaultAnyValue setAll(final AnyValue av) {
if (av == null) return this;
if (av instanceof DefaultAnyValue) {
final DefaultAnyValue adv = (DefaultAnyValue) av;
if (adv.stringValues != null) {
for (Entry<String> en : adv.stringValues) {
this.setValue(en.name, en.value);
}
}
if (adv.entityValues != null) {
for (Entry<AnyValue> en : adv.entityValues) {
this.setValue(en.name, en.value);
}
}
} else {
final Entry<String>[] strings = av.getStringEntrys();
if (strings != null) {
for (Entry<String> en : strings) {
this.setValue(en.name, en.value);
}
}
final Entry<AnyValue>[] anys = av.getAnyEntrys();
if (anys != null) {
for (Entry<AnyValue> en : anys) {
this.setValue(en.name, en.value);
}
}
}
return this;
}
@Override
public Entry<String>[] getStringEntrys() {
return stringValues;
}
@Override
public Entry<AnyValue>[] getAnyEntrys() {
return entityValues;
}
@Override
public String[] getNames() {
Set<String> set = new LinkedHashSet();
for (Entry en : this.stringValues) {
set.add(en.name);
}
for (Entry en : this.entityValues) {
set.add(en.name);
}
return set.toArray(new String[set.size()]);
}
@Override
public String[] getValues(String... names) {
return Entry.getValues(this.predicate, String.class, this.stringValues, names);
}
@Override
public AnyValue[] getAnyValues(String... names) {
return Entry.getValues(this.predicate, AnyValue.class, this.entityValues, names);
}
@Override
public String toString() {
return toString(0);
}
public DefaultAnyValue clear() {
this.stringValues = new Entry[0];
this.entityValues = new Entry[0];
return this;
}
public DefaultAnyValue setValue(String name, String value) {
if (name == null) return this;
if (getValue(name) == null) {
this.addValue(name, value);
} else {
for (Entry<String> en : this.stringValues) {
if (predicate.test(en.name, name)) {
en.value = value;
return this;
}
}
}
return this;
}
public DefaultAnyValue setValue(String name, AnyValue value) {
if (name == null) return this;
if (getValue(name) == null) {
this.addValue(name, value);
} else {
for (Entry<AnyValue> en : this.entityValues) {
if (predicate.test(en.name, name)) {
en.value = value;
return this;
}
}
}
return this;
}
public DefaultAnyValue addValue(String name, String value) {
if (name == null) return this;
int len = this.stringValues.length;
Entry[] news = new Entry[len + 1];
System.arraycopy(this.stringValues, 0, news, 0, len);
news[len] = new Entry(name, value);
this.stringValues = news;
return this;
}
public DefaultAnyValue addValue(String name, AnyValue value) {
if (name == null || value == null) return this;
int len = this.entityValues.length;
Entry[] news = new Entry[len + 1];
System.arraycopy(this.entityValues, 0, news, 0, len);
news[len] = new Entry(name, value);
this.entityValues = news;
return this;
}
@Override
public AnyValue getAnyValue(String name) {
for (Entry<AnyValue> en : this.entityValues) {
if (predicate.test(en.name, name)) {
return en.value;
}
}
return null;
}
@Override
public String getValue(String name) {
for (Entry<String> en : this.stringValues) {
if (predicate.test(en.name, name)) {
return en.value;
}
}
return null;
}
@Override
public String[] getValues(String name) {
return Entry.getValues(this.predicate, String.class, this.stringValues, name);
}
@Override
public AnyValue[] getAnyValues(String name) {
return Entry.getValues(this.predicate, AnyValue.class, this.entityValues, name);
}
}
public static final class Entry<T> {
public final String name;
T value;
public Entry(String name0, T value0) {
this.name = name0;
this.value = value0;
}
public T getValue() {
return value;
}
static <T> T[] getValues(BiPredicate<String, String> comparison, Class<T> clazz, Entry<T>[] entitys, String name) {
int len = 0;
for (Entry en : entitys) {
if (comparison.test(en.name, name)) {
++len;
}
}
if (len == 0) return (T[]) Array.newInstance(clazz, len);
T[] rs = (T[]) Array.newInstance(clazz, len);
int i = 0;
for (Entry<T> en : entitys) {
if (comparison.test(en.name, name)) {
rs[i++] = en.value;
}
}
return rs;
}
static <T> T[] getValues(BiPredicate<String, String> comparison, Class<T> clazz, Entry<T>[] entitys, String... names) {
int len = 0;
for (Entry en : entitys) {
for (String name : names) {
if (comparison.test(en.name, name)) {
++len;
break;
}
}
}
if (len == 0) return (T[]) Array.newInstance(clazz, len);
T[] rs = (T[]) Array.newInstance(clazz, len);
int i = 0;
for (Entry<T> en : entitys) {
for (String name : names) {
if (comparison.test(en.name, name)) {
rs[i++] = en.value;
break;
}
}
}
return rs;
}
}
public static AnyValue create() {
return new DefaultAnyValue();
}
protected String toString(int len) {
if (len < 0) len = 0;
char[] chars = new char[len];
Arrays.fill(chars, ' ');
final String space = new String(chars);
StringBuilder sb = new StringBuilder();
sb.append("{\r\n");
for (Entry<String> en : getStringEntrys()) {
sb.append(space).append(" '").append(en.name).append("': '").append(en.value).append("',\r\n");
}
for (Entry<AnyValue> en : getAnyEntrys()) {
sb.append(space).append(" '").append(en.name).append("': '").append(en.value.toString(len + 4)).append("',\r\n");
}
sb.append(space).append('}');
return sb.toString();
}
public abstract Entry<String>[] getStringEntrys();
public abstract Entry<AnyValue>[] getAnyEntrys();
public abstract String[] getNames();
public abstract String[] getValues(String name);
public abstract String[] getValues(String... names);
public abstract AnyValue[] getAnyValues(String name);
public abstract AnyValue[] getAnyValues(String... names);
public abstract AnyValue getAnyValue(String name);
public abstract String getValue(String name);
public boolean getBoolValue(String name) {
return Boolean.parseBoolean(getValue(name));
}
public boolean getBoolValue(String name, boolean defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Boolean.parseBoolean(value);
}
public byte getByteValue(String name) {
return Byte.parseByte(getValue(name));
}
public byte getByteValue(String name, byte defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Byte.decode(value);
}
public char getCharValue(String name) {
return getValue(name).charAt(0);
}
public char getCharValue(String name, char defaultValue) {
String value = getValue(name);
return value == null || value.length() == 0 ? defaultValue : value.charAt(0);
}
public short getShortValue(String name) {
return Short.decode(getValue(name));
}
public short getShortValue(String name, short defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Short.decode(value);
}
public int getIntValue(String name) {
return Integer.decode(getValue(name));
}
public int getIntValue(String name, int defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Integer.decode(value);
}
public long getLongValue(String name) {
return Long.decode(getValue(name));
}
public long getLongValue(String name, long defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Long.decode(value);
}
public float getFloatValue(String name) {
return Float.parseFloat(getValue(name));
}
public float getFloatValue(String name, float defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Float.parseFloat(value);
}
public double getDoubleValue(String name) {
return Double.parseDouble(getValue(name));
}
public double getDoubleValue(String name, double defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : Double.parseDouble(value);
}
public String getValue(String name, String defaultValue) {
String value = getValue(name);
return value == null ? defaultValue : value;
}
}

View File

@@ -10,6 +10,7 @@ import org.objectweb.asm.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public class AsmMethodVisitor { public class AsmMethodVisitor {
@@ -18,8 +19,9 @@ public class AsmMethodVisitor {
private boolean debug = false; private boolean debug = false;
public void setDebug(boolean d) { public AsmMethodVisitor setDebug(boolean d) {
debug = d; debug = d;
return this;
} }
private final Map<Label, Integer> labels = new LinkedHashMap(); private final Map<Label, Integer> labels = new LinkedHashMap();
@@ -49,6 +51,12 @@ public class AsmMethodVisitor {
this.visitor = visitor; this.visitor = visitor;
} }
public AnnotationVisitor visitParameterAnnotation(int i, String string, boolean bln) {
AnnotationVisitor av = visitor.visitParameterAnnotation(i, string, bln);
if (debug) System.out.println("mv.visitParameterAnnotation(" + i + ", \"" + string + "\", " + bln + ");");
return av;
}
public AnnotationVisitor visitAnnotation(String desc, boolean flag) { public AnnotationVisitor visitAnnotation(String desc, boolean flag) {
AnnotationVisitor av = visitor.visitAnnotation(desc, flag); AnnotationVisitor av = visitor.visitAnnotation(desc, flag);
if (debug) System.out.println("mv.visitAnnotation(\"" + desc + "\", " + flag + ");"); if (debug) System.out.println("mv.visitAnnotation(\"" + desc + "\", " + flag + ");");

View File

@@ -11,17 +11,22 @@ import org.objectweb.asm.Type;
/** /**
* 该类功能是动态映射一个Data类中成员对应的getter、setter方法 代替低效的反射实现方式。 * 该类功能是动态映射一个Data类中成员对应的getter、setter方法 代替低效的反射实现方式。
* 映射Field时field要么是public非final要么存在对应的getter、setter方法。 * 映射Field时field必须满足以下条件之一:
* 1、field属性是public且非final
* 2、至少存在对应的getter、setter方法中的一个
* 当不存在getter方法时get操作规定返回null
* 当不存在setter方法时set操作为空方法
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
* @param <F> * @param <F>
*/ */
public interface Attribute<T, F> { public interface Attribute<T, F> {
public Class type(); public Class<? extends F> type();
public Class declaringClass(); public Class<T> declaringClass();
public String field(); public String field();
@@ -29,23 +34,49 @@ public interface Attribute<T, F> {
public void set(T obj, F value); public void set(T obj, F value);
public static final class Attributes { public static abstract class Attributes {
/**
* 根据一个Field生成 Attribute 对象。
*
* @param <T>
* @param <F>
* @param field
* @return
*/
public static <T, F> Attribute<T, F> create(final Field field) { public static <T, F> Attribute<T, F> create(final Field field) {
return create((Class<T>) field.getDeclaringClass(), field.getName(), field, null, null); return create((Class<T>) field.getDeclaringClass(), field.getName(), field, null, null);
} }
/**
* 根据一个Field和field的别名生成 Attribute 对象。
*
* @param <T>
* @param <F>
* @param fieldname 别名
* @param field
* @return
*/
public static <T, F> Attribute<T, F> create(String fieldname, final Field field) { public static <T, F> Attribute<T, F> create(String fieldname, final Field field) {
return create((Class<T>) field.getDeclaringClass(), fieldname, field, null, null); return create((Class<T>) field.getDeclaringClass(), fieldname, field, null, null);
} }
/**
* 根据一个Class和field名生成 Attribute 对象。
*
* @param <T>
* @param <F>
* @param clazz
* @param fieldname 字段名, 如果该字段不存在则抛异常
* @return
*/
public static <T, F> Attribute<T, F> create(Class<T> clazz, final String fieldname) { public static <T, F> Attribute<T, F> create(Class<T> clazz, final String fieldname) {
try { try {
return create(clazz, fieldname, clazz.getDeclaredField(fieldname), null, null); return create(clazz, fieldname, clazz.getDeclaredField(fieldname), null, null);
} catch (NoSuchFieldException ex) { } catch (NoSuchFieldException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);
} catch (SecurityException ex2) { } catch (SecurityException ex) {
throw new RuntimeException(ex2); throw new RuntimeException(ex);
} }
} }
@@ -57,18 +88,60 @@ public interface Attribute<T, F> {
return create(clazz, fieldname, field, null, null); return create(clazz, fieldname, field, null, null);
} }
/**
* getter、setter不能全为null
*
* @param <T>
* @param <F>
* @param getter
* @param setter
* @return
*/
public static <T, F> Attribute<T, F> create(final Method getter, final Method setter) { public static <T, F> Attribute<T, F> create(final Method getter, final Method setter) {
return create((Class) (getter == null ? setter.getDeclaringClass() : getter.getDeclaringClass()), null, null, getter, setter); return create((Class) (getter == null ? setter.getDeclaringClass() : getter.getDeclaringClass()), null, null, getter, setter);
} }
/**
* getter、setter不能全为null
*
* @param <T>
* @param <F>
* @param clazz
* @param getter
* @param setter
* @return
*/
public static <T, F> Attribute<T, F> create(Class<T> clazz, final Method getter, final Method setter) { public static <T, F> Attribute<T, F> create(Class<T> clazz, final Method getter, final Method setter) {
return create(clazz, null, null, getter, setter); return create(clazz, null, null, getter, setter);
} }
/**
* getter、setter不能全为null
*
* @param <T>
* @param <F>
* @param clazz
* @param fieldalias
* @param getter
* @param setter
* @return
*/
public static <T, F> Attribute<T, F> create(Class<T> clazz, final String fieldalias, final Method getter, final Method setter) { public static <T, F> Attribute<T, F> create(Class<T> clazz, final String fieldalias, final Method getter, final Method setter) {
return create(clazz, fieldalias, null, getter, setter); return create(clazz, fieldalias, null, getter, setter);
} }
/**
* field、getter、setter不能全为null
*
* @param <T>
* @param <F>
* @param clazz
* @param fieldalias0
* @param field0
* @param getter0
* @param setter0
* @return
*/
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T, F> Attribute<T, F> create(final Class<T> clazz, String fieldalias0, final Field field0, Method getter0, Method setter0) { public static <T, F> Attribute<T, F> create(final Class<T> clazz, String fieldalias0, final Field field0, Method getter0, Method setter0) {
if (fieldalias0 != null && fieldalias0.isEmpty()) fieldalias0 = null; if (fieldalias0 != null && fieldalias0.isEmpty()) fieldalias0 = null;
@@ -145,10 +218,10 @@ public interface Attribute<T, F> {
} catch (Exception ex) { } catch (Exception ex) {
} }
//--------------------------------------------------- //---------------------------------------------------
final org.objectweb.asm.ClassWriter cw = new org.objectweb.asm.ClassWriter(0); final jdk.internal.org.objectweb.asm.ClassWriter cw = new jdk.internal.org.objectweb.asm.ClassWriter(0);
org.objectweb.asm.MethodVisitor mv; jdk.internal.org.objectweb.asm.MethodVisitor mv;
cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, "Ljava/lang/Object;L" + supDynName + "<" + interDesc + columnDesc + ">;", "java/lang/Object", new String[]{supDynName}); cw.visit(V1_8, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, "Ljava/lang/Object;L" + supDynName + "<" + interDesc + columnDesc + ">;", "java/lang/Object", new String[]{supDynName});
{ //构造方法 { //构造方法
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
@@ -209,6 +282,7 @@ public interface Attribute<T, F> {
mv.visitFieldInsn(GETFIELD, interName, field.getName(), Type.getDescriptor(pcolumn)); mv.visitFieldInsn(GETFIELD, interName, field.getName(), Type.getDescriptor(pcolumn));
if (pcolumn != column) { if (pcolumn != column) {
mv.visitMethodInsn(INVOKESTATIC, columnName, "valueOf", "(" + Type.getDescriptor(pcolumn) + ")" + columnDesc, false); mv.visitMethodInsn(INVOKESTATIC, columnName, "valueOf", "(" + Type.getDescriptor(pcolumn) + ")" + columnDesc, false);
m = 2;
} }
} }
} else { } else {
@@ -236,6 +310,7 @@ public interface Attribute<T, F> {
try { try {
java.lang.reflect.Method pm = column.getMethod(pcolumn.getSimpleName() + "Value"); java.lang.reflect.Method pm = column.getMethod(pcolumn.getSimpleName() + "Value");
mv.visitMethodInsn(INVOKEVIRTUAL, columnName, pm.getName(), Type.getMethodDescriptor(pm), false); mv.visitMethodInsn(INVOKEVIRTUAL, columnName, pm.getName(), Type.getMethodDescriptor(pm), false);
m = 3;
} catch (Exception ex) { } catch (Exception ex) {
throw new RuntimeException(ex); //不可能会发生 throw new RuntimeException(ex); //不可能会发生
} }

View File

@@ -0,0 +1,28 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 自动加载。 使用场景:
* 1、被标记为@AutoLoad(false)的Service类不会被自动加载
* 2、被标记为@AutoLoad(false)的Servlet类不会被自动加载
* 3、被标记为@AutoLoad且同时被标记为@javax.persistence.Cacheable的Entity类在被DataSource初始化时需要将Entity类对应的表数据全量加载进缓存中。
*
* @see http://www.redkale.org
* @author zhangjx
*/
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface AutoLoad {
boolean value() default true;
}

View File

@@ -9,7 +9,9 @@ import java.nio.*;
import java.nio.charset.*; import java.nio.charset.*;
/** /**
* 简单的byte[]操作类。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class ByteArray { public final class ByteArray {
@@ -134,12 +136,16 @@ public final class ByteArray {
public String toDecodeString(final int offset, int len, final Charset charset) { public String toDecodeString(final int offset, int len, final Charset charset) {
int index = offset; int index = offset;
for (int i = offset; i < (offset + len); i++) { for (int i = offset; i < (offset + len); i++) {
if (content[i] == '+') { switch (content[i]) {
content[index] = ' '; case '+':
} else if (content[i] == '%') { content[index] = ' ';
content[index] = (byte) ((hexBit(content[++i]) * 16 + hexBit(content[++i]))); break;
} else { case '%':
content[index] = content[i]; content[index] = (byte) ((hexBit(content[++i]) * 16 + hexBit(content[++i])));
break;
default:
content[index] = content[i];
break;
} }
index++; index++;
} }

View File

@@ -4,16 +4,17 @@
*/ */
package org.redkale.util; package org.redkale.util;
import java.beans.*; import java.beans.ConstructorProperties;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.*; import java.util.*;
import org.objectweb.asm.*; import jdk.internal.org.objectweb.asm.*;
import static org.objectweb.asm.Opcodes.*; import static jdk.internal.org.objectweb.asm.Opcodes.*;
import org.objectweb.asm.Type; import jdk.internal.org.objectweb.asm.Type;
/** /**
* 实现一个类的构造方法。 代替低效的反射实现方式。 * 实现一个类的构造方法。 代替低效的反射实现方式。 不支持数组类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */
@@ -21,7 +22,7 @@ public interface Creator<T> {
public T create(Object... params); public T create(Object... params);
public static final class Creators { public static abstract class Creators {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> Creator<T> create(Class<T> clazz) { public static <T> Creator<T> create(Class<T> clazz) {
@@ -50,7 +51,7 @@ public interface Creator<T> {
} }
Constructor<T> constructor = null; Constructor<T> constructor = null;
for (Constructor c : clazz.getConstructors()) { for (Constructor c : clazz.getConstructors()) {
if (c.getParameterTypes().length == 0) { if (c.getParameterCount() == 0) {
constructor = c; constructor = c;
break; break;
} }
@@ -69,13 +70,13 @@ public interface Creator<T> {
FieldVisitor fv; FieldVisitor fv;
MethodVisitor mv; MethodVisitor mv;
AnnotationVisitor av0; AnnotationVisitor av0;
cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, "Ljava/lang/Object;L" + supDynName + "<" + interDesc + ">;", "java/lang/Object", new String[]{supDynName}); cw.visit(V1_8, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, "Ljava/lang/Object;L" + supDynName + "<" + interDesc + ">;", "java/lang/Object", new String[]{supDynName});
{//构造方法 {//构造方法
mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
ConstructorProperties cps = constructor.getAnnotation(ConstructorProperties.class); ConstructorProperties cps = constructor.getAnnotation(ConstructorProperties.class);
if (cps != null) { if (cps != null) {
av0 = mv.visitAnnotation("Ljava/beans/ConstructorProperties;", true); av0 = mv.visitAnnotation(Type.getDescriptor(ConstructorProperties.class), true);
AnnotationVisitor av1 = av0.visitArray("value"); AnnotationVisitor av1 = av0.visitArray("value");
for (String n : cps.value()) { for (String n : cps.value()) {
av1.visit(null, n); av1.visit(null, n);
@@ -94,9 +95,8 @@ public interface Creator<T> {
mv.visitTypeInsn(NEW, interName); mv.visitTypeInsn(NEW, interName);
mv.visitInsn(DUP); mv.visitInsn(DUP);
//--------------------------------------- //---------------------------------------
final Class[] params = constructor.getParameterTypes();
{ {
Parameter[] params = constructor.getParameters();
final int[] iconsts = {ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5}; final int[] iconsts = {ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5};
for (int i = 0; i < params.length; i++) { for (int i = 0; i < params.length; i++) {
mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 1);
@@ -106,7 +106,7 @@ public interface Creator<T> {
mv.visitIntInsn(BIPUSH, i); mv.visitIntInsn(BIPUSH, i);
} }
mv.visitInsn(AALOAD); mv.visitInsn(AALOAD);
Class ct = params[i]; Class ct = params[i].getType();
mv.visitTypeInsn(CHECKCAST, Type.getInternalName(ct)); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(ct));
if (ct.isPrimitive()) { if (ct.isPrimitive()) {
Class fct = Array.get(Array.newInstance(ct, 1), 0).getClass(); Class fct = Array.get(Array.newInstance(ct, 1), 0).getClass();
@@ -122,7 +122,7 @@ public interface Creator<T> {
//--------------------------------------- //---------------------------------------
mv.visitMethodInsn(INVOKESPECIAL, interName, "<init>", Type.getConstructorDescriptor(constructor), false); mv.visitMethodInsn(INVOKESPECIAL, interName, "<init>", Type.getConstructorDescriptor(constructor), false);
mv.visitInsn(ARETURN); mv.visitInsn(ARETURN);
mv.visitMaxs((params.length > 0 ? (params.length + 3) : 2), 2); mv.visitMaxs((constructor.getParameterCount() > 0 ? (constructor.getParameterCount() + 3) : 2), 2);
mv.visitEnd(); mv.visitEnd();
} }
{ //虚拟 create 方法 { //虚拟 create 方法

View File

@@ -5,31 +5,46 @@
*/ */
package org.redkale.util; package org.redkale.util;
import java.nio.*;
import java.util.*;
/** /**
* 16bytes数据结构
* 注意: 为了提高性能, DLong中的bytes是直接返回 不得对bytes的内容进行修改。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class DLong extends Number implements Comparable<DLong> { public final class DLong extends Number implements Comparable<DLong> {
private final long first; private final byte[] bytes;
private final long second; public DLong(long v1, long v2) {
this.bytes = new byte[]{(byte) (v1 >> 56), (byte) (v1 >> 48), (byte) (v1 >> 40), (byte) (v1 >> 32),
public DLong(long one, long two) { (byte) (v1 >> 24), (byte) (v1 >> 16), (byte) (v1 >> 8), (byte) v1, (byte) (v2 >> 56), (byte) (v2 >> 48), (byte) (v2 >> 40), (byte) (v2 >> 32),
this.first = one; (byte) (v2 >> 24), (byte) (v2 >> 16), (byte) (v2 >> 8), (byte) v2};
this.second = two;
} }
public long getFirst() { public DLong(byte[] bytes) {
return first; if (bytes == null || bytes.length != 16) throw new NumberFormatException("Not 16 length bytes");
this.bytes = bytes;
} }
public long getSecond() { public byte[] getBytes() {
return second; return Arrays.copyOf(bytes, bytes.length);
} }
public boolean equals(long one, long two) { public byte[] directBytes() {
return this.first == one && this.second == two; return bytes;
}
public ByteBuffer putTo(ByteBuffer buffer) {
buffer.put(bytes);
return buffer;
}
public boolean equals(byte[] bytes) {
return Arrays.equals(this.bytes, bytes);
} }
@Override @Override
@@ -37,30 +52,34 @@ public final class DLong extends Number implements Comparable<DLong> {
if (obj == null) return false; if (obj == null) return false;
if (getClass() != obj.getClass()) return false; if (getClass() != obj.getClass()) return false;
final DLong other = (DLong) obj; final DLong other = (DLong) obj;
return (this.first == other.first && this.second == other.second); return Arrays.equals(this.bytes, other.bytes);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int hash = 7; return Arrays.hashCode(bytes);
hash = 89 * hash + (int) (this.first ^ (this.first >>> 32));
hash = 89 * hash + (int) (this.second ^ (this.second >>> 32));
return hash;
} }
@Override @Override
public String toString() { public String toString() {
return this.first + "_" + this.second; return new String(Utility.binToHex(bytes));
} }
@Override @Override
public int intValue() { public int intValue() {
return (int) longValue(); return ((bytes[12] & 0xff) << 24) | ((bytes[113] & 0xff) << 16) | ((bytes[14] & 0xff) << 8) | (bytes[15] & 0xff);
} }
@Override @Override
public long longValue() { public long longValue() {
return first ^ second; return ((((long) bytes[8] & 0xff) << 56)
| (((long) bytes[9] & 0xff) << 48)
| (((long) bytes[10] & 0xff) << 40)
| (((long) bytes[11] & 0xff) << 32)
| (((long) bytes[12] & 0xff) << 24)
| (((long) bytes[13] & 0xff) << 16)
| (((long) bytes[14] & 0xff) << 8)
| (((long) bytes[15] & 0xff)));
} }
@Override @Override
@@ -75,7 +94,11 @@ public final class DLong extends Number implements Comparable<DLong> {
@Override @Override
public int compareTo(DLong o) { public int compareTo(DLong o) {
return (int) (first == o.first ? (second - o.second) : (first - o.first)); if (o == null) return 1;
for (int i = 0; i < bytes.length; i++) {
if (this.bytes[i] != o.bytes[i]) return this.bytes[i] - o.bytes[i];
}
return 0;
} }
} }

View File

@@ -0,0 +1,28 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 用于忽略字段、方法或类。使用场景:
* 1、convert功能中被标记为@Ignore的字段或方法会被忽略
* 2、FilterBean中的被标记为@Ignore的字段会被忽略
* 3、被标记为@Ignore的Service类不会被自动加载
* 4、被标记为@Ignore的Servlet类不会被自动加载
*
* @see http://www.redkale.org
* @author zhangjx
*/
@Inherited
@Documented
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Ignore {
}

View File

@@ -0,0 +1,25 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* 被标记的日志级别以上的才会被记录
*
* @see http://www.redkale.org
* @author zhangjx
*/
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface LogLevel {
String value();
}

View File

@@ -0,0 +1,16 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
/**
*
* @see http://www.redkale.org
* @author zhangjx
*/
public interface Nameable {
String name();
}

View File

@@ -4,15 +4,16 @@
*/ */
package org.redkale.util; package org.redkale.util;
import org.redkale.util.Creator.Creators;
import java.util.*; import java.util.*;
import java.util.concurrent.*; import java.util.concurrent.*;
import java.util.concurrent.atomic.*; import java.util.concurrent.atomic.*;
import java.util.function.*; import java.util.function.*;
import java.util.logging.*; import java.util.logging.*;
import org.redkale.util.Creator.Creators;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */
@@ -56,7 +57,7 @@ public final class ObjectPool<T> implements Supplier<T> {
this.creator = creator; this.creator = creator;
this.prepare = prepare; this.prepare = prepare;
this.recycler = recycler; this.recycler = recycler;
this.queue = new ArrayBlockingQueue(Math.max(Runtime.getRuntime().availableProcessors() * 2, max)); this.queue = new LinkedBlockingQueue(Math.max(Runtime.getRuntime().availableProcessors() * 2, max));
this.debug = logger.isLoggable(Level.FINER); this.debug = logger.isLoggable(Level.FINER);
} }

View File

@@ -0,0 +1,135 @@
package org.redkale.util;
import java.lang.reflect.Modifier;
import java.util.function.Predicate;
import static org.objectweb.asm.Opcodes.*;
import org.objectweb.asm.*;
public interface Reproduce<D, S> {
public D copy(D dest, S src);
public static abstract class Reproduces {
public static <D, S> Reproduce<D, S> create(final Class<D> destClass, final Class<S> srcClass) {
return create(destClass, srcClass, null);
}
@SuppressWarnings("unchecked")
public static <D, S> Reproduce<D, S> create(final Class<D> destClass, final Class<S> srcClass, final Predicate<String> columnPredicate) {
// ------------------------------------------------------------------------------
final String supDynName = Reproduce.class.getName().replace('.', '/');
final String destName = destClass.getName().replace('.', '/');
final String srcName = srcClass.getName().replace('.', '/');
final String destDesc = Type.getDescriptor(destClass);
final String srcDesc = Type.getDescriptor(srcClass);
String newDynName = supDynName + "Dyn_" + destClass.getSimpleName() + "_" + srcClass.getSimpleName();
ClassLoader loader = Reproduce.class.getClassLoader();
if (String.class.getClassLoader() != destClass.getClassLoader()) {
loader = destClass.getClassLoader();
newDynName = destName + "_Dyn" + Reproduce.class.getSimpleName() + "_" + srcClass.getSimpleName();
}
try {
return (Reproduce) Class.forName(newDynName.replace('/', '.')).newInstance();
} catch (Exception ex) {
}
// ------------------------------------------------------------------------------
ClassWriter cw = new ClassWriter(0);
FieldVisitor fv;
MethodVisitor mv;
AnnotationVisitor av0;
cw.visit(V1_8, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, "Ljava/lang/Object;L" + supDynName + "<" + destDesc + srcDesc + ">;", "java/lang/Object", new String[]{supDynName});
{ // 构造函数
mv = (cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null));
//mv.setDebug(true);
mv.visitVarInsn(ALOAD, 0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 1);
mv.visitEnd();
}
{
mv = (cw.visitMethod(ACC_PUBLIC, "copy", "(" + destDesc + srcDesc + ")" + destDesc, null, null));
//mv.setDebug(true);
for (java.lang.reflect.Field field : srcClass.getFields()) {
if (Modifier.isStatic(field.getModifiers())) continue;
if (Modifier.isFinal(field.getModifiers())) continue;
if (!Modifier.isPublic(field.getModifiers())) continue;
final String fname = field.getName();
try {
if (!field.getType().equals(destClass.getField(fname).getType())) continue;
if (!columnPredicate.test(fname)) continue;
} catch (Exception e) {
continue;
}
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
String td = Type.getDescriptor(field.getType());
mv.visitFieldInsn(GETFIELD, srcName, fname, td);
mv.visitFieldInsn(PUTFIELD, destName, fname, td);
}
for (java.lang.reflect.Method getter : srcClass.getMethods()) {
if (Modifier.isStatic(getter.getModifiers())) continue;
if (getter.getParameterCount() > 0) continue;
if ("getClass".equals(getter.getName())) continue;
if (!getter.getName().startsWith("get") && !getter.getName().startsWith("is")) continue;
java.lang.reflect.Method setter;
boolean is = getter.getName().startsWith("is");
try {
setter = destClass.getMethod(getter.getName().replaceFirst(is ? "is" : "get", "set"), getter.getReturnType());
if (columnPredicate != null) {
String col = setter.getName().substring(3);
if (col.length() < 2 || Character.isLowerCase(col.charAt(1))) {
char[] cs = col.toCharArray();
cs[0] = Character.toLowerCase(cs[0]);
col = new String(cs);
}
if (!columnPredicate.test(col)) continue;
}
} catch (Exception e) {
continue;
}
mv.visitVarInsn(ALOAD, 1);
mv.visitVarInsn(ALOAD, 2);
mv.visitMethodInsn(INVOKEVIRTUAL, srcName, getter.getName(), Type.getMethodDescriptor(getter), false);
mv.visitMethodInsn(INVOKEVIRTUAL, destName, setter.getName(), Type.getMethodDescriptor(setter), false);
}
mv.visitVarInsn(ALOAD, 1);
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
{
mv = (cw.visitMethod(ACC_PUBLIC + ACC_BRIDGE + ACC_SYNTHETIC, "copy", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", null, null));
//mv.setDebug(true);
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ALOAD, 1);
mv.visitTypeInsn(CHECKCAST, destName);
mv.visitVarInsn(ALOAD, 2);
mv.visitTypeInsn(CHECKCAST, srcName);
mv.visitMethodInsn(INVOKEVIRTUAL, newDynName, "copy", "(" + destDesc + srcDesc + ")" + destDesc, false);
mv.visitInsn(ARETURN);
mv.visitMaxs(3, 3);
mv.visitEnd();
}
cw.visitEnd();
// ------------------------------------------------------------------------------
byte[] bytes = cw.toByteArray();
Class<?> creatorClazz = new ClassLoader(loader) {
public final Class<?> loadClass(String name, byte[] b) {
return defineClass(name, b, 0, b.length);
}
}.loadClass(newDynName.replace('/', '.'), bytes);
try {
return (Reproduce) creatorClazz.newInstance();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
}

View File

@@ -0,0 +1,245 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import java.util.regex.*;
import javax.annotation.*;
/**
* 如果Resource(name = "$") 表示资源name采用所属对象的name
*
* @see http://www.redkale.org
* @author zhangjx
*/
@SuppressWarnings("unchecked")
public final class ResourceFactory {
public static final String RESOURCE_PARENT_NAME = "$";
private static final Logger logger = Logger.getLogger(ResourceFactory.class.getSimpleName());
private final ResourceFactory parent;
private static final ResourceFactory instance = new ResourceFactory(null);
private final ConcurrentHashMap<Type, Intercepter> interceptmap = new ConcurrentHashMap();
private final ConcurrentHashMap<Class<?>, ConcurrentHashMap<String, ?>> store = new ConcurrentHashMap();
private final ConcurrentHashMap<Type, ConcurrentHashMap<String, ?>> gencstore = new ConcurrentHashMap();
private ResourceFactory(ResourceFactory parent) {
this.parent = parent;
}
public static ResourceFactory root() {
return instance;
}
public ResourceFactory createChild() {
return new ResourceFactory(this);
}
public void release() {
this.store.clear();
}
public void register(final Class clazz, final Object rs) {
register("", clazz, rs);
}
public void register(final Object rs) {
if (rs != null) register("", rs.getClass(), rs);
}
public void add(final Type clazz, final Intercepter rs) {
if (clazz == null || rs == null) return;
interceptmap.put(clazz, rs);
}
public void register(final String name, final Object rs) {
register(name, rs.getClass(), rs);
}
public <A> void register(final String name, final Class<? extends A> clazz, final A rs) {
ConcurrentHashMap map = this.store.get(clazz);
if (map == null) {
ConcurrentHashMap<String, A> sub = new ConcurrentHashMap();
sub.put(name, rs);
store.put(clazz, sub);
} else {
map.put(name, rs);
}
}
public <A> void register(final String name, final Type clazz, final A rs) {
if (clazz instanceof Class) {
register(name, (Class) clazz, rs);
return;
}
ConcurrentHashMap map = this.gencstore.get(clazz);
if (map == null) {
ConcurrentHashMap<String, A> sub = new ConcurrentHashMap();
sub.put(name, rs);
gencstore.put(clazz, sub);
} else {
map.put(name, rs);
}
}
public <A> A find(Class<? extends A> clazz) {
return find("", clazz);
}
public <A> A find(String name, Type clazz) {
Map<String, ?> map = this.gencstore.get(clazz);
if (map != null) {
A rs = (A) map.get(name);
if (rs != null) return rs;
}
if (parent != null) return parent.find(name, clazz);
return null;
}
public <A> A find(String name, Class<? extends A> clazz) {
Map<String, ?> map = this.store.get(clazz);
if (map != null) {
A rs = (A) map.get(name);
if (rs != null) return rs;
}
if (parent != null) return parent.find(name, clazz);
return null;
}
public <A> A findChild(final String name, final Class<? extends A> clazz) {
A rs = find(name, clazz);
if (rs != null) return rs;
for (Map.Entry<Class<?>, ConcurrentHashMap<String, ?>> en : this.store.entrySet()) { //不用forEach为兼容JDK 6
if (!clazz.isAssignableFrom(en.getKey())) continue;
Object v = en.getValue().get(name);
if (v != null) return (A) v;
}
return null;
}
public <A> Map<String, A> find(final Pattern reg, Class<? extends A> clazz, A exclude) {
Map<String, A> result = new LinkedHashMap();
load(reg, clazz, exclude, result);
return result;
}
private <A> void load(final Pattern reg, Class<? extends A> clazz, final A exclude, final Map<String, A> result) {
ConcurrentHashMap<String, ?> map = this.store.get(clazz);
if (map != null) {
for (Map.Entry<String, ?> en : map.entrySet()) { // 不用forEach为兼容JDK 6
String x = en.getKey();
Object y = en.getValue();
if (y != exclude && reg.matcher(x).find() && result.get(x) == null) result.put(x, (A) y);
}
}
if (parent != null) parent.load(reg, clazz, exclude, result);
}
public <T> boolean inject(final Object src) {
return inject(src, null);
}
public <T> boolean inject(final Object src, final T attachment) {
return inject(src, attachment, new ArrayList());
}
private <T> boolean inject(final Object src, final T attachment, final List<Object> list) {
if (src == null) return false;
try {
list.add(src);
Class clazz = src.getClass();
do {
for (Field field : clazz.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) continue;
field.setAccessible(true);
final Class classtype = field.getType();
final Type genctype = field.getGenericType();
Resource rc = field.getAnnotation(Resource.class);
if (rc == null) {
boolean flag = true;
Object ns = field.get(src);
for (Object o : list) {
if (o == ns) {
flag = false;
break;
}
}
if (ns == null) continue;
if (ns.getClass().isPrimitive() || ns.getClass().isArray() || ns.getClass().getName().startsWith("java")) continue;
if (flag) this.inject(ns, attachment, list);
continue;
}
if (Modifier.isFinal(field.getModifiers())) continue;
final String rcname = (rc.name().contains(RESOURCE_PARENT_NAME) && src instanceof Nameable) ? rc.name().replace(RESOURCE_PARENT_NAME, ((Nameable) src).name()) : rc.name();
Object rs = genctype == classtype ? null : find(rcname, genctype);
if (rs == null) {
if (Map.class.isAssignableFrom(classtype)) {
rs = find(Pattern.compile(rcname.isEmpty() ? ".*" : rcname), (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[1], src);
} else if (rcname.startsWith("property.")) {
rs = find(rcname, String.class);
} else {
rs = find(rcname, classtype);
}
}
if (rs == null) {
Intercepter it = findIntercepter(field.getGenericType(), field);
if (it != null) it.invoke(this, src, field, attachment);
continue;
}
if (!rs.getClass().isPrimitive() && classtype.isPrimitive()) {
if (classtype == int.class) {
rs = Integer.decode(rs.toString());
} else if (classtype == long.class) {
rs = Long.decode(rs.toString());
} else if (classtype == short.class) {
rs = Short.decode(rs.toString());
} else if (classtype == boolean.class) {
rs = "true".equalsIgnoreCase(rs.toString());
} else if (classtype == byte.class) {
rs = Byte.decode(rs.toString());
} else if (classtype == float.class) {
rs = Float.parseFloat(rs.toString());
} else if (classtype == double.class) {
rs = Double.parseDouble(rs.toString());
}
}
field.set(src, rs);
}
} while ((clazz = clazz.getSuperclass()) != Object.class);
return true;
} catch (Exception ex) {
logger.log(Level.FINER, "inject " + src + " error", ex);
return false;
}
}
private Intercepter findIntercepter(Type ft, Field field) {
Intercepter it = this.interceptmap.get(ft);
if (it != null) return it;
Class c = field.getType();
for (Map.Entry<Type, Intercepter> en : this.interceptmap.entrySet()) {
Type t = en.getKey();
if (t == ft) return en.getValue();
if (t instanceof Class && (((Class) t)).isAssignableFrom(c)) return en.getValue();
}
return parent == null ? null : parent.findIntercepter(ft, field);
}
public static interface Intercepter {
public void invoke(ResourceFactory factory, Object src, Field field, Object attachment);
}
}

View File

@@ -0,0 +1,137 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.util.*;
import java.util.function.*;
import java.util.regex.*;
/**
*
* @see http://www.redkale.org
* @author zhangjx
*/
public class SelectColumn implements Predicate<String> {
private Pattern[] patterns;
private String[] columns;
private boolean excludable; //是否排除
public SelectColumn() {
}
protected SelectColumn(final String[] columns0, final boolean excludable) {
this.excludable = excludable;
final int len = columns0.length;
if (len < 1) return;
Pattern[] regs = null;
String[] cols = null;
int regcount = 0;
int colcount = 0;
for (String col : columns0) {
boolean reg = false;
for (int i = 0; i < col.length(); i++) {
char ch = col.charAt(i);
if (ch == '^' || ch == '$' || ch == '*' || ch == '?' || ch == '+' || ch == '[' || ch == '(') {
reg = true;
break;
}
}
if (reg) {
if (regs == null) regs = new Pattern[len];
regs[regcount++] = Pattern.compile(col);
} else {
if (cols == null) cols = new String[len];
cols[colcount++] = col;
}
}
if (regs != null) {
if (regcount == len) {
this.patterns = regs;
} else {
this.patterns = Arrays.copyOf(regs, regcount);
}
}
if (cols != null) {
if (colcount == len) {
this.columns = cols;
} else {
this.columns = Arrays.copyOf(cols, colcount);
}
}
}
/**
* class中的字段名
*
* @param columns
* @return
*/
public static SelectColumn createIncludes(String... columns) {
return new SelectColumn(columns, false);
}
/**
* class中的字段名
*
* @param columns
* @return
*/
public static SelectColumn createExcludes(String... columns) {
return new SelectColumn(columns, true);
}
@Override
public boolean test(final String column) {
if (this.columns != null) {
for (String col : this.columns) {
if (col.equalsIgnoreCase(column)) return !excludable;
}
}
if (this.patterns != null) {
for (Pattern reg : this.patterns) {
if (reg.matcher(column).find()) return !excludable;
}
}
return excludable;
}
public String[] getColumns() {
return columns;
}
public void setColumns(String[] columns) {
this.columns = columns;
}
public boolean isExcludable() {
return excludable;
}
public void setExcludable(boolean excludable) {
this.excludable = excludable;
}
public Pattern[] getPatterns() {
return patterns;
}
public void setPatterns(Pattern[] patterns) {
this.patterns = patterns;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append("{excludable=").append(excludable);
if (columns != null) sb.append(", columns=").append(Arrays.toString(columns));
if (patterns != null) sb.append(", patterns=").append(Arrays.toString(patterns));
return sb.append('}').toString();
}
}

View File

@@ -8,7 +8,9 @@ package org.redkale.util;
import java.util.*; import java.util.*;
/** /**
* 页集合。 结构由一个total总数和一个List列表组合而成。
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */
@@ -36,14 +38,15 @@ public class Sheet<T> implements java.io.Serializable {
return data == null ? new Sheet() : new Sheet(data.size(), data); return data == null ? new Sheet() : new Sheet(data.size(), data);
} }
public void copyTo(Sheet<T> copy) { public Sheet<T> copyTo(Sheet<T> copy) {
if (copy == null) return; if (copy == null) return copy;
copy.total = this.total; copy.total = this.total;
if (this.getRows() != null) { if (this.getRows() != null) {
copy.setRows(new ArrayList(this.getRows())); copy.setRows(new ArrayList(this.getRows()));
} else { } else {
copy.rows = null; copy.rows = null;
} }
return copy;
} }
/** /**

View File

@@ -8,7 +8,10 @@ import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
/** /**
*
* 获取泛型的Type类
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
* @param <T> * @param <T>
*/ */

View File

@@ -5,27 +5,53 @@
package org.redkale.util; package org.redkale.util;
import java.io.*; import java.io.*;
import java.lang.reflect.Field;
import java.net.*; import java.net.*;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.*; import java.nio.charset.*;
import java.time.*;
import java.util.*; import java.util.*;
import javax.net.ssl.*; import javax.net.ssl.*;
/** /**
* *
* @see http://www.redkale.org
* @author zhangjx * @author zhangjx
*/ */
public final class Utility { public final class Utility {
private static final int zoneRawOffset = TimeZone.getDefault().getRawOffset();
private static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL"; private static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL";
private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final sun.misc.Unsafe UNSAFE;
private static final long strvaloffset;
private static final long sbvaloffset;
private static final javax.net.ssl.SSLContext DEFAULTSSL_CONTEXT; private static final javax.net.ssl.SSLContext DEFAULTSSL_CONTEXT;
static { static {
sun.misc.Unsafe usafe = null;
long fd1 = 0L;
long fd2 = 0L;
try {
Field safeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
safeField.setAccessible(true);
usafe = (sun.misc.Unsafe) safeField.get(null);
fd1 = usafe.objectFieldOffset(String.class.getDeclaredField("value"));
fd2 = usafe.objectFieldOffset(StringBuilder.class.getSuperclass().getDeclaredField("value"));
} catch (Exception e) {
throw new RuntimeException(e); //不可能会发生
}
UNSAFE = usafe;
strvaloffset = fd1;
sbvaloffset = fd2;
try { try {
DEFAULTSSL_CONTEXT = javax.net.ssl.SSLContext.getInstance("SSL"); DEFAULTSSL_CONTEXT = javax.net.ssl.SSLContext.getInstance("SSL");
@@ -105,6 +131,76 @@ public final class Utility {
return back; return back;
} }
/**
* 获取当天凌晨零点的格林时间
*
* @return
*/
public static long midnight() {
return midnight(System.currentTimeMillis());
}
/**
* 获取指定时间当天凌晨零点的格林时间
*
* @param time
* @return
*/
public static long midnight(long time) {
return (time + zoneRawOffset) / 86400000 * 86400000 - zoneRawOffset;
}
/**
* 获取当天20151231格式的int值
*
* @return
*/
public static int today() {
java.time.LocalDate today = java.time.LocalDate.now();
return today.getYear() * 10000 + today.getMonthValue() * 100 + today.getDayOfMonth();
}
/**
* 获取时间点所在星期的周一
*
* @param time
* @return
*/
public static long monday(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate();
ld = ld.minusDays(ld.getDayOfWeek().getValue() - 1);
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
* 获取时间点所在星期的周日
*
* @param time
* @return
*/
public static long sunday(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate();
ld = ld.plusDays(7 - ld.getDayOfWeek().getValue());
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
* 获取时间点所在月份的1号
*
* @param time
* @return
*/
public static long monthFirstDay(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate().withDayOfMonth(1);
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
public static String binToHexString(byte[] bytes) { public static String binToHexString(byte[] bytes) {
return new String(binToHex(bytes)); return new String(binToHex(bytes));
} }
@@ -153,6 +249,10 @@ public final class Utility {
return bytes; return bytes;
} }
public static byte[] hexToBin(String str) {
return hexToBin(charArray(str));
}
public static byte[] hexToBin(char[] src) { public static byte[] hexToBin(char[] src) {
return hexToBin(src, 0, src.length); return hexToBin(src, 0, src.length);
} }
@@ -211,7 +311,7 @@ public final class Utility {
public static byte[] encodeUTF8(final String value) { public static byte[] encodeUTF8(final String value) {
if (value == null) return new byte[0]; if (value == null) return new byte[0];
return encodeUTF8(value.toCharArray()); return encodeUTF8((char[]) UNSAFE.getObject(value, strvaloffset));
} }
public static byte[] encodeUTF8(final char[] array) { public static byte[] encodeUTF8(final char[] array) {
@@ -252,14 +352,11 @@ public final class Utility {
} }
public static char[] charArray(String value) { public static char[] charArray(String value) {
return value == null ? null : value.toCharArray(); return value == null ? null : (char[]) UNSAFE.getObject(value, strvaloffset);
} }
public static char[] charArray(StringBuilder value) { public static char[] charArray(StringBuilder value) {
if (value == null) return null; return value == null ? null : (char[]) UNSAFE.getObject(value, sbvaloffset);
char[] chs = new char[value.length()];
value.getChars(0, value.length(), chs, 0);
return chs;
} }
public static ByteBuffer encodeUTF8(final ByteBuffer buffer, final char[] array) { public static ByteBuffer encodeUTF8(final ByteBuffer buffer, final char[] array) {
@@ -272,7 +369,7 @@ public final class Utility {
public static int encodeUTF8Length(String value) { public static int encodeUTF8Length(String value) {
if (value == null) return -1; if (value == null) return -1;
return encodeUTF8Length(value.toCharArray()); return encodeUTF8Length((char[]) UNSAFE.getObject(value, strvaloffset));
} }
public static int encodeUTF8Length(final char[] text) { public static int encodeUTF8Length(final char[] text) {
@@ -427,7 +524,7 @@ public final class Utility {
if (conn instanceof HttpsURLConnection) ((HttpsURLConnection) conn).setSSLSocketFactory((ctx == null ? DEFAULTSSL_CONTEXT : ctx).getSocketFactory()); if (conn instanceof HttpsURLConnection) ((HttpsURLConnection) conn).setSSLSocketFactory((ctx == null ? DEFAULTSSL_CONTEXT : ctx).getSocketFactory());
conn.setRequestMethod(method); conn.setRequestMethod(method);
if (headers != null) { if (headers != null) {
for (Map.Entry<String, String> en : headers.entrySet()) { for (Map.Entry<String, String> en : headers.entrySet()) { //不用forEach是为了兼容JDK 6
conn.setRequestProperty(en.getKey(), en.getValue()); conn.setRequestProperty(en.getKey(), en.getValue());
} }
} }