com.jstarcraft.core.common.reflection.TypeUtility Java Examples

The following examples show how to use com.jstarcraft.core.common.reflection.TypeUtility. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public Object readValueFrom(CsvReader context, Type type) throws Exception {
    // TODO 处理null
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int length = Integer.valueOf(check);
    // 处理对象类型
    Class<?> clazz = TypeUtility.getRawType(type, null);
    ClassDefinition definition = context.getClassDefinition(clazz);
    Object instance = definition.getInstance();
    for (PropertyDefinition property : definition.getProperties()) {
        CsvConverter converter = context.getCsvConverter(property.getSpecification());
        Object value = converter.readValueFrom(context, property.getType());
        property.setValue(instance, value);
    }
    return instance;
}
 
Example #2
Source File: ObjectStoreConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public NavigableMap<String, IndexableField> encode(LuceneContext context, String path, Field field, LuceneStore annotation, Type type, Object instance) {
    NavigableMap<String, IndexableField> indexables = new TreeMap<>();
    Class<?> clazz = TypeUtility.getRawType(type, null);

    try {
        // TODO 此处需要代码重构
        for (Entry<Field, StoreConverter> keyValue : context.getStoreKeyValues(clazz).entrySet()) {
            // TODO 此处代码可以优反射次数.
            field = keyValue.getKey();
            StoreConverter converter = keyValue.getValue();
            annotation = field.getAnnotation(LuceneStore.class);
            String name = field.getName();
            type = field.getGenericType();
            Object data = field.get(instance);
            for (IndexableField indexable : converter.encode(context, path + "." + name, field, annotation, type, data).values()) {
                indexables.put(path + "." + name, indexable);
            }
        }
        return indexables;
    } catch (Exception exception) {
        // TODO
        throw new StorageException(exception);
    }
}
 
Example #3
Source File: ArrayStoreConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public NavigableMap<String, IndexableField> encode(LuceneContext context, String path, Field field, LuceneStore annotation, Type type, Object instance) {
    NavigableMap<String, IndexableField> indexables = new TreeMap<>();
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    Specification specification = Specification.getSpecification(componentClass);
    StoreConverter converter = context.getStoreConverter(specification);
    int size = Array.getLength(instance);
    IndexableField indexable = new StoredField(path + ".size", size);
    indexables.put(path + ".size", indexable);
    for (int index = 0; index < size; index++) {
        Object element = Array.get(instance, index);
        indexables.putAll(converter.encode(context, path + "[" + index + "]", field, annotation, componentType, element));
    }
    return indexables;
}
 
Example #4
Source File: MapConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Map<Object, Object> value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 兼容UniMi
    type = TypeUtility.refineType(type, Map.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    Map<Object, Object> map = Map.class.cast(value);
    out.print(map.size());
    Class<?> keyClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter keyConverter = context.getCsvConverter(Specification.getSpecification(keyClazz));
    Class<?> valueClazz = TypeUtility.getRawType(types[1], null);
    CsvConverter valueConverter = context.getCsvConverter(Specification.getSpecification(valueClazz));
    for (Entry<Object, Object> keyValue : map.entrySet()) {
        Object key = keyValue.getKey();
        keyConverter.writeValueTo(context, types[0], key);
        Object element = keyValue.getValue();
        valueConverter.writeValueTo(context, types[1], element);
    }
    return;
}
 
Example #5
Source File: CollectionConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Collection<Object> value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 兼容UniMi
    type = TypeUtility.refineType(type, Collection.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    Collection<?> collection = Collection.class.cast(value);
    out.print(collection.size());
    Class<?> elementClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter converter = context.getCsvConverter(Specification.getSpecification(elementClazz));
    for (Object element : collection) {
        converter.writeValueTo(context, types[0], element);
    }
    return;
}
 
Example #6
Source File: CollectionConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Object> readValueFrom(CsvReader context, Type type) throws Exception {
    // TODO 处理null
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int length = Integer.valueOf(check);
    Class<?> clazz = TypeUtility.getRawType(type, null);
    // 兼容UniMi
    type = TypeUtility.refineType(type, Collection.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    ClassDefinition definition = context.getClassDefinition(clazz);
    Collection<Object> collection = (Collection) definition.getInstance();
    Class<?> elementClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter converter = context.getCsvConverter(Specification.getSpecification(elementClazz));
    for (int index = 0; index < length; index++) {
        Object element = converter.readValueFrom(context, types[0]);
        collection.add(element);
    }
    return collection;
}
 
Example #7
Source File: InstantConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 处理日期类型
    if (TypeUtility.isAssignable(type, Date.class)) {
        value = Date.class.cast(value).getTime();
        out.print(value);
        return;
    } else {
        value = Instant.class.cast(value).toEpochMilli();
        out.print(value);
        return;
    }
}
 
Example #8
Source File: ObjectIndexConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<IndexableField> convert(LuceneContext context, String path, Field field, LuceneIndex annotation, Type type, Object data) {
    Collection<IndexableField> indexables = new LinkedList<>();
    Class<?> clazz = TypeUtility.getRawType(type, null);

    try {
        // TODO 此处需要代码重构
        for (Entry<Field, IndexConverter> keyValue : context.getIndexKeyValues(clazz).entrySet()) {
            // TODO 此处代码可以优反射次数.
            field = keyValue.getKey();
            IndexConverter converter = keyValue.getValue();
            annotation = field.getAnnotation(LuceneIndex.class);
            String name = field.getName();
            for (IndexableField indexable : converter.convert(context, path + "." + name, field, annotation, field.getGenericType(), field.get(data))) {
                indexables.add(indexable);
            }
        }
        return indexables;
    } catch (Exception exception) {
        // TODO
        throw new StorageException(exception);
    }
}
 
Example #9
Source File: ObjectConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object instance) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (instance == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    // 处理对象类型
    Class<?> clazz = TypeUtility.getRawType(type, null);
    ClassDefinition definition = context.getClassDefinition(clazz);
    int length = definition.getProperties().length;
    out.print(length);
    for (PropertyDefinition property : definition.getProperties()) {
        CsvConverter converter = context.getCsvConverter(property.getSpecification());
        Object value = property.getValue(instance);
        converter.writeValueTo(context, property.getType(), value);
    }
}
 
Example #10
Source File: ObjectSortConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<IndexableField> convert(LuceneContext context, String path, Field field, LuceneSort annotation, Type type, Object data) {
    Collection<IndexableField> indexables = new LinkedList<>();
    Class<?> clazz = TypeUtility.getRawType(type, null);

    try {
        // TODO 此处需要代码重构
        for (Entry<Field, SortConverter> keyValue : context.getSortKeyValues(clazz).entrySet()) {
            // TODO 此处代码可以优反射次数.
            field = keyValue.getKey();
            SortConverter converter = keyValue.getValue();
            annotation = field.getAnnotation(LuceneSort.class);
            String name = field.getName();
            for (IndexableField indexable : converter.convert(context, path + "." + name, field, annotation, field.getGenericType(), field.get(data))) {
                indexables.add(indexable);
            }
        }
        return indexables;
    } catch (Exception exception) {
        // TODO
        throw new StorageException(exception);
    }
}
 
Example #11
Source File: DetectionPattern.java    From jstarcraft-nlp with Apache License 2.0 6 votes vote down vote up
public static final Map<String, DetectionPattern> loadPatterns(InputStream stream) {
    try (DataInputStream buffer = new DataInputStream(stream)) {
        Map<String, DetectionPattern> detections = new HashMap<>();
        byte[] data = new byte[buffer.available()];
        buffer.readFully(data);
        String json = new String(data, StringUtility.CHARSET);
        // 兼容\x转义ASCII字符
        json = StringUtility.unescapeJava(json);
        Type type = TypeUtility.parameterize(LinkedHashMap.class, String.class, String.class);
        LinkedHashMap<String, String> regulations = JsonUtility.string2Object(json, type);

        for (Entry<String, String> scriptTerm : regulations.entrySet()) {
            String script = scriptTerm.getKey();
            String regulation = scriptTerm.getValue();
            Pattern pattern = Pattern.compile(regulation, Pattern.MULTILINE);
            DetectionPattern detection = new DetectionPattern(script, pattern);
            detections.put(script, detection);
        }
        return Collections.unmodifiableMap(detections);
    } catch (Exception exception) {
        throw new IllegalArgumentException(exception);
    }
}
 
Example #12
Source File: ArraySortConverter.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<IndexableField> convert(LuceneContext context, String path, Field field, LuceneSort annotation, Type type, Object data) {
    Collection<IndexableField> indexables = new LinkedList<>();
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    throw new StorageException();
}
 
Example #13
Source File: JsonUtility.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
public static Type java2Type(JavaType java) {
    Type type = null;
    if (java.isArrayType()) {
        // 数组类型
        type = java.getRawClass();
    } else if (java.hasGenericTypes()) {
        // 泛型类型
        List<JavaType> javas = java.getBindings().getTypeParameters();
        Type[] generics = new Type[javas.size()];
        int index = 0;
        for (JavaType term : javas) {
            generics[index++] = java2Type(term);
        }
        Class<?> clazz = java.getRawClass();
        type = TypeUtility.parameterize(clazz, generics);
    } else {
        type = java.getRawClass();
    }
    return type;
}
 
Example #14
Source File: ClassUtilityTestCase.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    // 模拟类不在ClassLoader的情况
    String name = "com.jstarcraft.core.common.compilation.MockTask";
    String path = "MockTask.clazz";
    Map<String, byte[]> bytes = new HashMap<>();
    try (InputStream stream = ClassUtilityTestCase.class.getResourceAsStream(path); DataInputStream buffer = new DataInputStream(stream)) {
        byte[] data = new byte[buffer.available()];
        buffer.readFully(data);
        bytes.put(name, data);
        Class<?>[] classes = ClassUtility.bytes2Classes(bytes);
        Type type = TypeUtility.parameterize(classes[0], String.class);
        Callable<String> task = JsonUtility.string2Object("{\"value\":\"birdy\"}", type);
        Assert.assertEquals("birdy", task.call());
        Assert.assertEquals(bytes, ClassUtility.classes2Bytes(classes));
    }
}
 
Example #15
Source File: VariableDefinition.java    From jstarcraft-core with Apache License 2.0 6 votes vote down vote up
static VariableDefinition instanceOf(Type type, CommandVariable variable, Integer index) {
    Class<?> clazz = TypeUtility.getRawType(type, null);
    int modifier = clazz.getModifiers();
    if (!clazz.isPrimitive() && Modifier.isAbstract(modifier)) {
        throw new CommunicationDefinitionException("指令的参数与返回不能为抽象");
    }
    if (Modifier.isInterface(modifier)) {
        throw new CommunicationDefinitionException("指令的参数与返回不能为接口");
    }

    VariableDefinition instance = new VariableDefinition();
    instance.variable = variable;
    instance.position = index;
    instance.type = type;
    return instance;
}
 
Example #16
Source File: KryoContentCodec.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
private Type readValueFrom(Iterator<Integer> iterator) {
    Integer code = iterator.next();
    ClassDefinition definition = codecDefinition.getClassDefinition(code);
    if (definition.getType() == Class.class) {
        code = iterator.next();
        definition = codecDefinition.getClassDefinition(code);
        return definition.getType();
    } else if (definition.getType() == GenericArrayType.class) {
        Type type = currentTypes.get();
        if (type == Class.class) {
            type = readValueFrom(iterator);
            Class<?> clazz = Class.class.cast(type);
            return Array.newInstance(clazz, 0).getClass();
        } else {
            type = readValueFrom(iterator);
            return TypeUtility.genericArrayType(type);
        }
    } else if (definition.getType() == ParameterizedType.class) {
        code = iterator.next();
        definition = codecDefinition.getClassDefinition(code);
        Integer length = iterator.next();
        Type[] types = new Type[length];
        for (int index = 0; index < length; index++) {
            types[index] = readValueFrom(iterator);
        }
        return TypeUtility.parameterize(definition.getType(), types);
    } else {
        throw new CodecConvertionException();
    }
}
 
Example #17
Source File: KryoContentCodec.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Type type, InputStream stream) {
    try (Input byteBufferInput = new Input(stream)) {
        if (stream.available() == 0) {
            return null;
        }
        Specification specification = Specification.getSpecification(type);
        if (specification == Specification.TYPE) {
            currentTypes.set(type);
            LinkedList<Integer> list = kryo.readObject(byteBufferInput, LinkedList.class);
            Type value = readValueFrom(list.iterator());
            currentTypes.remove();
            return value;
        } else {
            if (kryo.isRegistrationRequired()) {
                // Registration registration =
                // kryo.readClass(byteBufferInput);
                return kryo.readObject(byteBufferInput, TypeUtility.getRawType(type, null));
            } else {
                return kryo.readClassAndObject(byteBufferInput);
            }
        }
    } catch (Exception exception) {
        String message = "Kryo解码异常";
        LOGGER.error(message, exception);
        throw new CodecException(message, exception);
    }
}
 
Example #18
Source File: KryoContentCodec.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Type type, byte[] content) {
    if (content.length == 0) {
        return null;
    }
    try (Input byteBufferInput = new Input(content)) {
        Specification specification = Specification.getSpecification(type);
        if (specification == Specification.TYPE) {
            currentTypes.set(type);
            LinkedList<Integer> list = kryo.readObject(byteBufferInput, LinkedList.class);
            Type value = readValueFrom(list.iterator());
            currentTypes.remove();
            return value;
        } else {
            if (kryo.isRegistrationRequired()) {
                // Registration registration =
                // kryo.readClass(byteBufferInput);
                return kryo.readObject(byteBufferInput, TypeUtility.getRawType(type, null));
            } else {
                return kryo.readClassAndObject(byteBufferInput);
            }
        }
    } catch (Exception exception) {
        String message = "Kryo解码异常";
        LOGGER.error(message, exception);
        throw new CodecException(message, exception);
    }
}
 
Example #19
Source File: ProtocolContentCodec.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Type type, InputStream stream) {
    try {
        ProtocolReader context = new ProtocolReader(stream, codecDefinition);
        ProtocolConverter converter = context.getProtocolConverter(Specification.getSpecification(type));
        ClassDefinition classDefinition = codecDefinition.getClassDefinition(TypeUtility.getRawType(type, null));
        return converter.readValueFrom(context, type, classDefinition);
    } catch (Exception exception) {
        String message = "Protocol解码失败:" + exception.getMessage();
        LOGGER.error(message, exception);
        throw new CodecException(message, exception);
    }
}
 
Example #20
Source File: TypeConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Type readValueFrom(CsvReader context, Type type) throws Exception {
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int code = Integer.valueOf(check);
    ClassDefinition definition = context.getClassDefinition(code);
    if (definition.getType() == Class.class) {
        code = Integer.valueOf(in.next());
        definition = context.getClassDefinition(code);
        return definition.getType();
    } else if (definition.getType() == GenericArrayType.class) {
        if (type == Class.class) {
            type = readValueFrom(context, type);
            Class<?> clazz = Class.class.cast(type);
            return Array.newInstance(clazz, 0).getClass();
        } else {
            type = readValueFrom(context, type);
            return TypeUtility.genericArrayType(type);
        }
    } else if (definition.getType() == ParameterizedType.class) {
        code = Integer.valueOf(in.next());
        definition = context.getClassDefinition(code);
        Integer length = Integer.valueOf(in.next());
        Type[] types = new Type[length];
        for (int index = 0; index < length; index++) {
            types[index] = readValueFrom(context, type);
        }
        return TypeUtility.parameterize(definition.getType(), types);
    } else {
        throw new CodecConvertionException();
    }
}
 
Example #21
Source File: NumberConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Number readValueFrom(CsvReader context, Type type) throws Exception {
    // TODO 处理null
    Iterator<String> in = context.getInputStream();
    String element = in.next();
    if (StringUtility.isEmpty(element)) {
        return null;
    }
    Class<Number> clazz = (Class<Number>) TypeUtility.getRawType(type, null);
    return NumberUtility.convert(element, clazz);
}
 
Example #22
Source File: MapConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Map<Object, Object> readValueFrom(CsvReader context, Type type) throws Exception {
    // TODO 处理null
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int length = Integer.valueOf(check);
    Class<?> clazz = TypeUtility.getRawType(type, null);
    // 兼容UniMi
    type = TypeUtility.refineType(type, Map.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    ClassDefinition definition = context.getClassDefinition(clazz);
    Map<Object, Object> map = (Map) definition.getInstance();
    Class<?> keyClazz = TypeUtility.getRawType(types[0], null);
    CsvConverter keyConverter = context.getCsvConverter(Specification.getSpecification(keyClazz));
    Class<?> valueClazz = TypeUtility.getRawType(types[1], null);
    CsvConverter valueConverter = context.getCsvConverter(Specification.getSpecification(valueClazz));
    for (int index = 0; index < length; index++) {
        Object key = keyConverter.readValueFrom(context, types[0]);
        Object element = valueConverter.readValueFrom(context, types[1]);
        map.put(key, element);
    }
    return map;
}
 
Example #23
Source File: EnumerationConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object readValueFrom(CsvReader context, Type type) throws Exception {
    Iterator<String> in = context.getInputStream();
    String element = in.next();
    if (StringUtility.isEmpty(element)) {
        return null;
    }
    int index = Integer.valueOf(element);
    Class<?> clazz = TypeUtility.getRawType(type, null);
    return clazz.getEnumConstants()[index];
}
 
Example #24
Source File: ArrayConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object readValueFrom(CsvReader context, Type type) throws Exception {
    // TODO 处理null
    Iterator<String> in = context.getInputStream();
    String check = in.next();
    if (StringUtility.isEmpty(check)) {
        return null;
    }
    int length = Integer.valueOf(check);
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    Object array = Array.newInstance(componentClass, length);
    Specification specification = Specification.getSpecification(componentClass);
    CsvConverter converter = context.getCsvConverter(specification);
    for (int index = 0; index < length; index++) {
        Object element = converter.readValueFrom(context, componentType);
        Array.set(array, index, element);
    }
    return array;
}
 
Example #25
Source File: ArrayConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public void writeValueTo(CsvWriter context, Type type, Object value) throws Exception {
    // TODO 处理null
    CSVPrinter out = context.getOutputStream();
    if (value == null) {
        out.print(StringUtility.EMPTY);
        return;
    }
    Class<?> componentClass = null;
    Type componentType = null;
    if (type instanceof GenericArrayType) {
        GenericArrayType genericArrayType = GenericArrayType.class.cast(type);
        componentType = genericArrayType.getGenericComponentType();
        componentClass = TypeUtility.getRawType(componentType, null);
    } else {
        Class<?> clazz = TypeUtility.getRawType(type, null);
        componentType = clazz.getComponentType();
        componentClass = clazz.getComponentType();
    }
    int length = Array.getLength(value);
    out.print(length);
    Specification specification = Specification.getSpecification(componentClass);
    CsvConverter converter = context.getCsvConverter(specification);
    for (int index = 0; index < length; index++) {
        Object element = Array.get(value, index);
        converter.writeValueTo(context, componentType, element);
    }
}
 
Example #26
Source File: ContentCodecTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testNull() throws Exception {
    // 基于Null的协议测试
    // 基于对象的协议测试
    MockComplexObject object = MockComplexObject.instanceOf(0, "birdy", null, 10, Instant.now(), MockEnumeration.TERRAN);
    testConvert(MockComplexObject.class, null);
    testConvert(MockComplexObject.class, object);

    // 基于枚举的协议测试
    testConvert(MockEnumeration.class, null);

    // 基于数组的协议测试
    Integer[] integerArray = new Integer[] { 0, null };
    testConvert(Integer[].class, integerArray);
    MockComplexObject[] objectArray = new MockComplexObject[] { object, null };
    testConvert(MockComplexObject[].class, objectArray);

    // 基于集合的协议测试
    List<MockComplexObject> objectList = new ArrayList<>(objectArray.length);
    Collections.addAll(objectList, objectArray);
    testConvert(TypeUtility.parameterize(ArrayList.class, MockComplexObject.class), objectList);
    // testConvert(ArrayList.class, objectList);
    Set<MockComplexObject> objectSet = new HashSet<>(objectList);
    testConvert(TypeUtility.parameterize(HashSet.class, MockComplexObject.class), objectSet);
    // testConvert(HashSet.class, objectSet);

    // 基于映射的协议测试
    Map<String, MockComplexObject> map = new HashMap<>();
    map.put(object.getFirstName(), object);
    map.put("null", null);
    testConvert(TypeUtility.parameterize(HashMap.class, String.class, MockComplexObject.class), map);
    // testConvert(HashMap.class, map);
}
 
Example #27
Source File: JsonUtilityTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertType() {
    // 基于对象类型测试
    convertType(MockComplexObject.class);
    convertType(MockMatrix.class);

    // 基于枚举类型测试
    convertType(MockEnumeration.class);

    // 基于数组类型测试
    convertType(MockEnumeration[].class);
    convertType(Integer[].class);
    convertType(int[].class);
    convertType(MockComplexObject[].class);
    convertType(Byte[].class);
    convertType(byte[].class);

    // 基于集合类型测试
    convertType(TypeUtility.parameterize(ArrayList.class, MockEnumeration.class));
    convertType(TypeUtility.parameterize(HashSet.class, MockEnumeration.class));

    convertType(TypeUtility.parameterize(ArrayList.class, Integer.class));
    convertType(TypeUtility.parameterize(TreeSet.class, Integer.class));

    convertType(TypeUtility.parameterize(ArrayList.class, MockComplexObject.class));
    convertType(TypeUtility.parameterize(HashSet.class, MockComplexObject.class));

    // 基于映射类型测试
    convertType(TypeUtility.parameterize(HashMap.class, String.class, MockComplexObject.class));

    // 基于原始与包装类型测试
    convertType(AtomicBoolean.class);
    convertType(Boolean.class);
    convertType(boolean.class);
}
 
Example #28
Source File: CsvUtilityTestCase.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testConvert() {
    CsvObject object = CsvObject.instanceOf(0, "birdy", "hong", 1, Instant.now(), CsvEnumeration.TERRAN);
    String csv = CsvUtility.object2String(object, CsvObject.class);
    Object intance = CsvUtility.string2Object(csv, CsvObject.class);
    Assert.assertThat(intance, CoreMatchers.equalTo(object));

    Object[] array = new CsvObject[] { object };
    csv = CsvUtility.object2String(array, CsvObject[].class);
    intance = CsvUtility.string2Object(csv, CsvObject[].class);
    Assert.assertThat(intance, CoreMatchers.equalTo(array));

    Type collectionType = TypeUtility.parameterize(HashSet.class, CsvObject.class);
    HashSet<CsvObject> collection = new HashSet<>();
    collection.add(object);
    csv = CsvUtility.object2String(collection, collectionType);
    intance = CsvUtility.string2Object(csv, collectionType);
    Assert.assertThat(intance, CoreMatchers.equalTo(collection));

    Type mapType = TypeUtility.parameterize(HashMap.class, CsvObject.class, CsvObject.class);
    HashMap<CsvObject, CsvObject> map = new HashMap<>();
    map.put(object, object);
    csv = CsvUtility.object2String(map, mapType);
    intance = CsvUtility.string2Object(csv, mapType);
    Assert.assertThat(intance, CoreMatchers.equalTo(map));

    Type keyValueType = TypeUtility.parameterize(KeyValue.class, Integer.class, CsvObject.class);
    KeyValue<Integer, CsvObject> keyValue = new KeyValue<>(0, object);
    csv = CsvUtility.object2String(keyValue, keyValueType);
    intance = CsvUtility.string2Object(csv, keyValueType);
    Assert.assertThat(intance, CoreMatchers.equalTo(keyValue));

    // 测试区分对象为null与属性为null的情况.
    Type arrayType = TypeUtility.genericArrayType(keyValueType);
    array = new KeyValue[] { null, new KeyValue<>(null, null), keyValue };
    csv = CsvUtility.object2String(array, arrayType);
    intance = CsvUtility.string2Object(csv, arrayType);
    Assert.assertThat(intance, CoreMatchers.equalTo(array));
}
 
Example #29
Source File: MapStoreConverter.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(LuceneContext context, String path, Field field, LuceneStore annotation, Type type, NavigableMap<String, IndexableField> indexables) {
    String from = path;
    char character = path.charAt(path.length() - 1);
    character++;
    String to = path.substring(0, path.length() - 1) + character;
    indexables = indexables.subMap(from, true, to, false);
    Class<?> clazz = TypeUtility.getRawType(type, null);
    // 兼容UniMi
    type = TypeUtility.refineType(type, Map.class);
    ParameterizedType parameterizedType = ParameterizedType.class.cast(type);
    Type[] types = parameterizedType.getActualTypeArguments();
    Type keyType = types[0];
    Class<?> keyClazz = TypeUtility.getRawType(keyType, null);
    Type valueType = types[1];
    Class<?> valueClazz = TypeUtility.getRawType(valueType, null);

    try {
        // TODO 此处需要代码重构
        Map<Object, Object> map = (Map) context.getInstance(clazz);
        Specification keySpecification = Specification.getSpecification(keyClazz);
        StoreConverter keyConverter = context.getStoreConverter(keySpecification);
        Specification valueSpecification = Specification.getSpecification(valueClazz);
        StoreConverter valueConverter = context.getStoreConverter(valueSpecification);

        IndexableField indexable = indexables.get(path + ".size");
        int size = indexable.numericValue().intValue();
        for (int index = 0; index < size; index++) {
            Object key = keyConverter.decode(context, path + "[" + index + "_key]", field, annotation, keyType, indexables);
            Object value = valueConverter.decode(context, path + "[" + index + "_value]", field, annotation, valueType, indexables);
            map.put(key, value);
        }
        return map;
    } catch (Exception exception) {
        // TODO
        throw new StorageException(exception);
    }
}
 
Example #30
Source File: DetectionTrie.java    From jstarcraft-nlp with Apache License 2.0 5 votes vote down vote up
public static final Map<String, Set<DetectionTrie>> loadTries(InputStream stream) {
    try (DataInputStream buffer = new DataInputStream(stream)) {
        Map<String, Set<DetectionTrie>> detections = new HashMap<>();
        byte[] data = new byte[buffer.available()];
        buffer.readFully(data);
        String json = new String(data, StringUtility.CHARSET);
        // 兼容\x转义ASCII字符
        json = StringUtility.unescapeJava(json);
        Type type = TypeUtility.parameterize(LinkedHashMap.class, String.class, String.class);
        type = TypeUtility.parameterize(LinkedHashMap.class, String.class, LinkedHashMap.class);
        LinkedHashMap<String, LinkedHashMap<String, String>> dictionaries = JsonUtility.string2Object(json, type);

        for (Entry<String, LinkedHashMap<String, String>> scriptTerm : dictionaries.entrySet()) {
            Set<DetectionTrie> tries = new HashSet<>();
            String script = scriptTerm.getKey();
            LinkedHashMap<String, String> languages = scriptTerm.getValue();
            for (Entry<String, String> languageTerm : languages.entrySet()) {
                String language = languageTerm.getKey();
                String[] dictionary = languageTerm.getValue().split("\\|");
                int weight = 0;
                TreeMap<String, Integer> tree = new TreeMap<>();
                for (String word : dictionary) {
                    tree.put(word, weight++);
                }
                DoubleArrayTrie<Integer> trie = new DoubleArrayTrie<>(tree);
                DetectionTrie detection = new DetectionTrie(language, trie);
                tries.add(detection);
            }
            detections.put(script, Collections.unmodifiableSet(tries));
        }
        return Collections.unmodifiableMap(detections);
    } catch (Exception exception) {
        throw new IllegalArgumentException(exception);
    }
}