Java Code Examples for com.jstarcraft.core.common.reflection.TypeUtility#parameterize()

The following examples show how to use com.jstarcraft.core.common.reflection.TypeUtility#parameterize() . 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: 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 2
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 3
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 4
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);
    }
}
 
Example 5
Source File: ConfigurationTestCase.java    From jstarcraft-rns with Apache License 2.0 5 votes vote down vote up
@Test
public void testConfigurationJson() {
    LinkedList<KeyValue<String, Class<?>>> left = new LinkedList<>();
    left.add(new KeyValue<>("user", String.class));
    left.add(new KeyValue<>("item", int.class));
    left.add(new KeyValue<>("score", double.class));
    left.add(new KeyValue<>("word", String.class));
    String json = JsonUtility.object2String(left);
    Type type = TypeUtility.parameterize(KeyValue.class, String.class, Class.class);
    type = TypeUtility.parameterize(LinkedList.class, type);
    LinkedList<KeyValue<String, Class<?>>> right = JsonUtility.string2Object(json, type);
    assertEquals(left, right);
}
 
Example 6
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 7
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 8
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 9
Source File: ContentCodecTestCase.java    From jstarcraft-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testPerformance() {
    Collection<Type> protocolClasses = new LinkedList<>();
    protocolClasses.add(MockComplexObject.class);
    protocolClasses.add(MockEnumeration.class);
    protocolClasses.add(MockSimpleObject.class);

    protocolClasses.add(ArrayList.class);
    protocolClasses.add(HashSet.class);
    protocolClasses.add(TreeSet.class);
    CodecDefinition definition = CodecDefinition.instanceOf(protocolClasses);
    ContentCodec contentCodec = this.getContentCodec(definition);

    String message = StringUtility.format("[{}]编解码性能测试", contentCodec.getClass().getName());
    logger.debug(message);

    int size = 100;

    Type type = MockComplexObject.class;
    Object instance = MockComplexObject.instanceOf(Integer.MAX_VALUE, "birdy", "hong", size, Instant.now(), MockEnumeration.TERRAN);
    testPerformance(contentCodec, type, instance);

    type = MockSimpleObject.class;
    instance = MockSimpleObject.instanceOf(0, "birdy");
    testPerformance(contentCodec, type, instance);

    String[] stringArray = new String[size];
    for (int index = 0; index < size; index++) {
        stringArray[index] = "mickey" + index;
    }
    type = String[].class;
    instance = stringArray;
    testPerformance(contentCodec, type, instance);

    ArrayList<String> stringList = new ArrayList<>(size);
    Collections.addAll(stringList, stringArray);
    type = TypeUtility.parameterize(ArrayList.class, String.class);
    instance = stringList;
    testPerformance(contentCodec, type, instance);

    HashSet<String> stringSet = new HashSet<>(size);
    Collections.addAll(stringSet, stringArray);
    type = TypeUtility.parameterize(HashSet.class, String.class);
    instance = stringSet;
    testPerformance(contentCodec, type, instance);
}