Search in sources :

Example 56 with Resource

use of javax.annotation.Resource in project redkale by redkale.

the class Sncp method createRemoteService.

/**
 * <blockquote><pre>
 * &#64;Resource(name = "")
 * &#64;SncpDyn(remote = true)
 * &#64;ResourceType(TestService.class)
 * public final class _DynRemoteTestService extends TestService{
 *
 *      private AnyValue _redkale_conf;
 *
 *      private SncpClient _redkale_client;
 *
 *      &#64;Override
 *      public void createSomeThing(TestBean bean){
 *          _redkale_client.remote(0, bean);
 *      }
 *
 *      &#64;Override
 *      public String findSomeThing(){
 *          return _redkale_client.remote(1);
 *      }
 *
 *      &#64;Override
 *      public String updateSomeThing(String id){
 *          return  _redkale_client.remote(2, id);
 *      }
 * }
 * </pre></blockquote>
 *
 * 创建远程模式的Service实例
 *
 * @param <T>                    Service泛型
 * @param classLoader            ClassLoader
 * @param name                   资源名
 * @param serviceTypeOrImplClass Service类
 * @param messageAgent           MQ管理器
 * @param transportFactory       TransportFactory
 * @param clientAddress          本地IP地址
 * @param groups0                所有的组节点,包含自身
 * @param conf                   启动配置项
 *
 * @return Service的远程模式实例
 */
@SuppressWarnings("unchecked")
public static <T extends Service> T createRemoteService(final ClassLoader classLoader, final String name, final Class<T> serviceTypeOrImplClass, final MessageAgent messageAgent, final TransportFactory transportFactory, final InetSocketAddress clientAddress, final Set<String> groups0, final AnyValue conf) {
    if (serviceTypeOrImplClass == null)
        return null;
    if (!Service.class.isAssignableFrom(serviceTypeOrImplClass))
        return null;
    final Set<String> groups = groups0 == null ? new HashSet<>() : groups0;
    ResourceFactory.checkResourceName(name);
    final int mod = serviceTypeOrImplClass.getModifiers();
    boolean realed = !(java.lang.reflect.Modifier.isAbstract(mod) || serviceTypeOrImplClass.isInterface());
    if (!java.lang.reflect.Modifier.isPublic(mod))
        return null;
    final String supDynName = serviceTypeOrImplClass.getName().replace('.', '/');
    final String clientName = SncpClient.class.getName().replace('.', '/');
    final String resDesc = Type.getDescriptor(Resource.class);
    final String clientDesc = Type.getDescriptor(SncpClient.class);
    final String sncpDynDesc = Type.getDescriptor(SncpDyn.class);
    final String anyValueDesc = Type.getDescriptor(AnyValue.class);
    final ClassLoader loader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
    // final String newDynName = supDynName.substring(0, supDynName.lastIndexOf('/') + 1) + REMOTEPREFIX + serviceTypeOrImplClass.getSimpleName();
    final String newDynName = "org/redkaledyn/service/remote/_DynRemoteService__" + serviceTypeOrImplClass.getName().replace('.', '_').replace('$', '_');
    try {
        Class clz = RedkaleClassLoader.findDynClass(newDynName.replace('/', '.'));
        Class newClazz = clz == null ? loader.loadClass(newDynName.replace('/', '.')) : clz;
        T service = (T) newClazz.getDeclaredConstructor().newInstance();
        SncpClient client = new SncpClient(name, serviceTypeOrImplClass, service, messageAgent, transportFactory, true, realed ? createLocalServiceClass(loader, name, serviceTypeOrImplClass) : serviceTypeOrImplClass, clientAddress);
        client.setRemoteGroups(groups);
        if (transportFactory != null)
            client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups));
        {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_client");
            c.setAccessible(true);
            c.set(service, client);
        }
        if (messageAgent != null) {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_messageagent");
            c.setAccessible(true);
            c.set(service, messageAgent);
            if (service instanceof WebSocketNode) {
                c = WebSocketNode.class.getDeclaredField("messageAgent");
                c.setAccessible(true);
                c.set(service, messageAgent);
            }
        }
        {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_conf");
            c.setAccessible(true);
            c.set(service, conf);
        }
        if (transportFactory != null)
            transportFactory.addSncpService(service);
        return service;
    } catch (Throwable ex) {
    }
    // ------------------------------------------------------------------------------
    ClassWriter cw = new ClassWriter(COMPUTE_FRAMES);
    FieldVisitor fv;
    MethodDebugVisitor mv;
    AnnotationVisitor av0;
    cw.visit(V11, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, newDynName, null, serviceTypeOrImplClass.isInterface() ? "java/lang/Object" : supDynName, serviceTypeOrImplClass.isInterface() ? new String[] { supDynName } : null);
    {
        av0 = cw.visitAnnotation(resDesc, true);
        av0.visit("name", name);
        av0.visitEnd();
    }
    {
        av0 = cw.visitAnnotation(Type.getDescriptor(ResourceType.class), true);
        ResourceType rty = serviceTypeOrImplClass.getAnnotation(ResourceType.class);
        av0.visit("value", Type.getType(Type.getDescriptor(rty == null ? serviceTypeOrImplClass : rty.value())));
        av0.visitEnd();
    }
    {
        av0 = cw.visitAnnotation(sncpDynDesc, true);
        av0.visit("remote", Boolean.TRUE);
        av0.visitEnd();
    }
    {
        // 给新类加上 原有的Annotation
        for (Annotation ann : serviceTypeOrImplClass.getAnnotations()) {
            if (ann instanceof Resource || ann instanceof SncpDyn || ann instanceof ResourceType)
                continue;
            MethodDebugVisitor.visitAnnotation(cw.visitAnnotation(Type.getDescriptor(ann.annotationType()), true), ann);
        }
    }
    {
        fv = cw.visitField(ACC_PRIVATE, FIELDPREFIX + "_conf", anyValueDesc, null, null);
        fv.visitEnd();
    }
    {
        fv = cw.visitField(ACC_PRIVATE, FIELDPREFIX + "_client", clientDesc, null, null);
        fv.visitEnd();
    }
    {
        fv = cw.visitField(ACC_PRIVATE, FIELDPREFIX + "_messageagent", Type.getDescriptor(MessageAgent.class), null, null);
        fv.visitEnd();
    }
    {
        // 构造函数
        mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null));
        // mv.setDebug(true);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKESPECIAL, serviceTypeOrImplClass.isInterface() ? "java/lang/Object" : supDynName, "<init>", "()V", false);
        mv.visitInsn(RETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    {
        // init
        mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, "init", "(" + anyValueDesc + ")V", null, null));
        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 2);
        mv.visitEnd();
    }
    {
        // stop
        mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, "stop", "(" + anyValueDesc + ")V", null, null));
        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 2);
        mv.visitEnd();
    }
    {
        // destroy
        mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, "destroy", "(" + anyValueDesc + ")V", null, null));
        mv.visitInsn(RETURN);
        mv.visitMaxs(0, 2);
        mv.visitEnd();
    }
    {
        // toString()
        mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, "toString", "()Ljava/lang/String;", null, null));
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, newDynName, FIELDPREFIX + "_client", clientDesc);
        Label l1 = new Label();
        mv.visitJumpInsn(IFNONNULL, l1);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "getName", "()Ljava/lang/String;", false);
        Label l2 = new Label();
        mv.visitJumpInsn(GOTO, l2);
        mv.visitLabel(l1);
        mv.visitVarInsn(ALOAD, 0);
        mv.visitFieldInsn(GETFIELD, newDynName, FIELDPREFIX + "_client", clientDesc);
        mv.visitMethodInsn(INVOKEVIRTUAL, clientName, "toSimpleString", "()Ljava/lang/String;", false);
        mv.visitLabel(l2);
        mv.visitInsn(ARETURN);
        mv.visitMaxs(1, 1);
        mv.visitEnd();
    }
    int i = -1;
    for (final SncpAction entry : SncpClient.getSncpActions(realed ? createLocalServiceClass(loader, name, serviceTypeOrImplClass) : serviceTypeOrImplClass)) {
        final int index = ++i;
        final java.lang.reflect.Method method = entry.method;
        {
            mv = new MethodDebugVisitor(cw.visitMethod(ACC_PUBLIC, method.getName(), Type.getMethodDescriptor(method), null, null));
            // mv.setDebug(true);
            {
                // 给参数加上 Annotation
                final Annotation[][] anns = method.getParameterAnnotations();
                for (int k = 0; k < anns.length; k++) {
                    for (Annotation ann : anns[k]) {
                        MethodDebugVisitor.visitAnnotation(mv.visitParameterAnnotation(k, Type.getDescriptor(ann.annotationType()), true), ann);
                    }
                }
            }
            mv.visitVarInsn(ALOAD, 0);
            mv.visitFieldInsn(GETFIELD, newDynName, FIELDPREFIX + "_client", clientDesc);
            MethodDebugVisitor.pushInt(mv, index);
            {
                // 传参数
                int paramlen = entry.paramTypes.length;
                MethodDebugVisitor.pushInt(mv, paramlen);
                mv.visitTypeInsn(ANEWARRAY, "java/lang/Object");
                java.lang.reflect.Type[] paramtypes = entry.paramTypes;
                int insn = 0;
                for (int j = 0; j < paramtypes.length; j++) {
                    final java.lang.reflect.Type pt = paramtypes[j];
                    mv.visitInsn(DUP);
                    insn++;
                    MethodDebugVisitor.pushInt(mv, j);
                    if (pt instanceof Class && ((Class) pt).isPrimitive()) {
                        if (pt == long.class) {
                            mv.visitVarInsn(LLOAD, insn++);
                        } else if (pt == float.class) {
                            mv.visitVarInsn(FLOAD, insn++);
                        } else if (pt == double.class) {
                            mv.visitVarInsn(DLOAD, insn++);
                        } else {
                            mv.visitVarInsn(ILOAD, insn);
                        }
                        Class bigclaz = java.lang.reflect.Array.get(java.lang.reflect.Array.newInstance((Class) pt, 1), 0).getClass();
                        mv.visitMethodInsn(INVOKESTATIC, bigclaz.getName().replace('.', '/'), "valueOf", "(" + Type.getDescriptor((Class) pt) + ")" + Type.getDescriptor(bigclaz), false);
                    } else {
                        mv.visitVarInsn(ALOAD, insn);
                    }
                    mv.visitInsn(AASTORE);
                }
            }
            mv.visitMethodInsn(INVOKEVIRTUAL, clientName, "remote", "(I[Ljava/lang/Object;)Ljava/lang/Object;", false);
            // mv.visitMethodInsn(INVOKEVIRTUAL, convertName, "convertFrom", convertFromDesc, false);
            if (method.getGenericReturnType() == void.class) {
                mv.visitInsn(POP);
                mv.visitInsn(RETURN);
            } else {
                Class returnclz = method.getReturnType();
                Class bigPrimitiveClass = returnclz.isPrimitive() ? java.lang.reflect.Array.get(java.lang.reflect.Array.newInstance(returnclz, 1), 0).getClass() : returnclz;
                mv.visitTypeInsn(CHECKCAST, (returnclz.isPrimitive() ? bigPrimitiveClass : returnclz).getName().replace('.', '/'));
                if (returnclz.isPrimitive()) {
                    String bigPrimitiveName = bigPrimitiveClass.getName().replace('.', '/');
                    try {
                        java.lang.reflect.Method pm = bigPrimitiveClass.getMethod(returnclz.getSimpleName() + "Value");
                        mv.visitMethodInsn(INVOKEVIRTUAL, bigPrimitiveName, pm.getName(), Type.getMethodDescriptor(pm), false);
                    } catch (Exception ex) {
                        // 不可能会发生
                        throw new RuntimeException(ex);
                    }
                    if (returnclz == long.class) {
                        mv.visitInsn(LRETURN);
                    } else if (returnclz == float.class) {
                        mv.visitInsn(FRETURN);
                    } else if (returnclz == double.class) {
                        mv.visitInsn(DRETURN);
                    } else {
                        mv.visitInsn(IRETURN);
                    }
                } else {
                    mv.visitInsn(ARETURN);
                }
            }
            mv.visitMaxs(20, 20);
            mv.visitEnd();
        }
    }
    cw.visitEnd();
    byte[] bytes = cw.toByteArray();
    Class<?> newClazz = new ClassLoader(loader) {

        public final Class<?> loadClass(String name, byte[] b) {
            return defineClass(name, b, 0, b.length);
        }
    }.loadClass(newDynName.replace('/', '.'), bytes);
    RedkaleClassLoader.putDynClass(newDynName.replace('/', '.'), bytes, newClazz);
    RedkaleClassLoader.putReflectionPublicConstructors(newClazz, newDynName.replace('/', '.'));
    RedkaleClassLoader.putReflectionDeclaredConstructors(newClazz, newDynName.replace('/', '.'));
    try {
        T service = (T) newClazz.getDeclaredConstructor().newInstance();
        SncpClient client = new SncpClient(name, serviceTypeOrImplClass, service, messageAgent, transportFactory, true, realed ? createLocalServiceClass(loader, name, serviceTypeOrImplClass) : serviceTypeOrImplClass, clientAddress);
        client.setRemoteGroups(groups);
        if (transportFactory != null)
            client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups));
        {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_client");
            c.setAccessible(true);
            c.set(service, client);
            RedkaleClassLoader.putReflectionField(newDynName.replace('/', '.'), c);
        }
        if (messageAgent != null) {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_messageagent");
            c.setAccessible(true);
            c.set(service, messageAgent);
            RedkaleClassLoader.putReflectionField(newDynName.replace('/', '.'), c);
            if (service instanceof WebSocketNode) {
                c = WebSocketNode.class.getDeclaredField("messageAgent");
                c.setAccessible(true);
                c.set(service, messageAgent);
                RedkaleClassLoader.putReflectionField(newDynName.replace('/', '.'), c);
            }
        }
        {
            Field c = newClazz.getDeclaredField(FIELDPREFIX + "_conf");
            c.setAccessible(true);
            c.set(service, conf);
            RedkaleClassLoader.putReflectionField(newDynName.replace('/', '.'), c);
        }
        if (transportFactory != null)
            transportFactory.addSncpService(service);
        return service;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : MethodDebugVisitor(org.redkale.asm.MethodDebugVisitor) java.lang.reflect(java.lang.reflect) SncpAction(org.redkale.net.sncp.SncpClient.SncpAction) Resource(javax.annotation.Resource) MessageAgent(org.redkale.mq.MessageAgent) Annotation(java.lang.annotation.Annotation) Type(org.redkale.asm.Type) WebSocketNode(org.redkale.net.http.WebSocketNode)

Example 57 with Resource

use of javax.annotation.Resource in project fess by codelibs.

the class BadWordService method importCsv.

public void importCsv(final Reader reader) {
    @SuppressWarnings("resource") final CsvReader csvReader = new CsvReader(reader, new CsvConfig());
    try {
        List<String> list;
        // ignore header
        csvReader.readValues();
        while ((list = csvReader.readValues()) != null) {
            String targetWord = getValue(list, 0);
            if (StringUtil.isBlank(targetWord)) {
                // skip
                continue;
            }
            try {
                boolean isDelete = false;
                if (targetWord.startsWith(DELETE_PREFIX)) {
                    isDelete = true;
                    targetWord = targetWord.substring(2);
                }
                final String target = targetWord;
                // TODO
                BadWord badWord = badWordBhv.selectEntity(cb -> cb.query().setSuggestWord_Equal(target)).orElse(null);
                final long now = ComponentUtil.getSystemHelper().getCurrentTimeAsLong();
                if (isDelete) {
                    badWordBhv.delete(badWord);
                } else if (badWord == null) {
                    badWord = new BadWord();
                    badWord.setSuggestWord(targetWord);
                    badWord.setCreatedBy(Constants.SYSTEM_USER);
                    badWord.setCreatedTime(now);
                    badWordBhv.insert(badWord);
                } else {
                    badWord.setUpdatedBy(Constants.SYSTEM_USER);
                    badWord.setUpdatedTime(now);
                    badWordBhv.update(badWord);
                }
            } catch (final Exception e) {
                logger.warn("Failed to read a sugget elevate word: {}", list, e);
            }
        }
        // TODO replace _all
        searchEngineClient.refresh("_all");
    } catch (final IOException e) {
        logger.warn("Failed to read a sugget elevate word.", e);
    }
}
Also used : CsvReader(com.orangesignal.csv.CsvReader) BeanUtil(org.codelibs.core.beans.util.BeanUtil) EntityRowHandler(org.dbflute.bhv.readable.EntityRowHandler) Constants(org.codelibs.fess.Constants) OptionalEntity(org.dbflute.optional.OptionalEntity) Resource(javax.annotation.Resource) StringUtil(org.codelibs.core.lang.StringUtil) CsvWriter(com.orangesignal.csv.CsvWriter) IOException(java.io.IOException) SearchEngineClient(org.codelibs.fess.es.client.SearchEngineClient) BadWordBhv(org.codelibs.fess.es.config.exbhv.BadWordBhv) Reader(java.io.Reader) ArrayList(java.util.ArrayList) CsvConfig(com.orangesignal.csv.CsvConfig) List(java.util.List) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) Logger(org.apache.logging.log4j.Logger) PagingResultBean(org.dbflute.cbean.result.PagingResultBean) BadWord(org.codelibs.fess.es.config.exentity.BadWord) ComponentUtil(org.codelibs.fess.util.ComponentUtil) Writer(java.io.Writer) BadWordPager(org.codelibs.fess.app.pager.BadWordPager) LogManager(org.apache.logging.log4j.LogManager) CsvReader(com.orangesignal.csv.CsvReader) BadWordCB(org.codelibs.fess.es.config.cbean.BadWordCB) BadWord(org.codelibs.fess.es.config.exentity.BadWord) CsvConfig(com.orangesignal.csv.CsvConfig) IOException(java.io.IOException) IOException(java.io.IOException)

Example 58 with Resource

use of javax.annotation.Resource in project fess by codelibs.

the class CrawlingInfoService method exportCsv.

public void exportCsv(final Writer writer) {
    final CsvConfig cfg = new CsvConfig(',', '"', '"');
    cfg.setEscapeDisabled(false);
    cfg.setQuoteDisabled(false);
    @SuppressWarnings("resource") final CsvWriter csvWriter = new CsvWriter(writer, cfg);
    try {
        final List<String> list = new ArrayList<>();
        list.add("SessionId");
        list.add("SessionCreatedTime");
        list.add("Key");
        list.add("Value");
        list.add("CreatedTime");
        csvWriter.writeValues(list);
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(CoreLibConstants.DATE_FORMAT_ISO_8601_EXTEND);
        crawlingInfoParamBhv.selectCursor(cb -> cb.query().matchAll(), new EntityRowHandler<CrawlingInfoParam>() {

            @Override
            public void handle(final CrawlingInfoParam entity) {
                final List<String> list = new ArrayList<>();
                entity.getCrawlingInfo().ifPresent(crawlingInfo -> {
                    addToList(list, crawlingInfo.getSessionId());
                    addToList(list, crawlingInfo.getCreatedTime());
                });
                // TODO
                if (!entity.getCrawlingInfo().isPresent()) {
                    addToList(list, "");
                    addToList(list, "");
                }
                addToList(list, entity.getKey());
                addToList(list, entity.getValue());
                addToList(list, entity.getCreatedTime());
                try {
                    csvWriter.writeValues(list);
                } catch (final IOException e) {
                    logger.warn("Failed to write a crawling session info: {}", entity, e);
                }
            }

            private void addToList(final List<String> list, final Object value) {
                if (value == null) {
                    list.add(StringUtil.EMPTY);
                } else if (value instanceof LocalDateTime) {
                    list.add(((LocalDateTime) value).format(formatter));
                } else {
                    list.add(value.toString());
                }
            }
        });
        csvWriter.flush();
    } catch (final IOException e) {
        logger.warn("Failed to write a crawling session info.", e);
    }
}
Also used : BeanUtil(org.codelibs.core.beans.util.BeanUtil) EntityRowHandler(org.dbflute.bhv.readable.EntityRowHandler) Constants(org.codelibs.fess.Constants) FessSystemException(org.codelibs.fess.exception.FessSystemException) CrawlingInfoBhv(org.codelibs.fess.es.config.exbhv.CrawlingInfoBhv) ListResultBean(org.dbflute.cbean.result.ListResultBean) LocalDateTime(java.time.LocalDateTime) SimpleDateFormat(java.text.SimpleDateFormat) ArrayList(java.util.ArrayList) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) CrawlingInfoParam(org.codelibs.fess.es.config.exentity.CrawlingInfoParam) PagingResultBean(org.dbflute.cbean.result.PagingResultBean) DateFormat(java.text.DateFormat) CrawlingInfoPager(org.codelibs.fess.app.pager.CrawlingInfoPager) OptionalEntity(org.dbflute.optional.OptionalEntity) CrawlingInfoParamBhv(org.codelibs.fess.es.config.exbhv.CrawlingInfoParamBhv) Resource(javax.annotation.Resource) StringUtil(org.codelibs.core.lang.StringUtil) CsvWriter(com.orangesignal.csv.CsvWriter) Set(java.util.Set) IOException(java.io.IOException) Reader(java.io.Reader) CoreLibConstants(org.codelibs.core.CoreLibConstants) Collectors(java.util.stream.Collectors) CrawlingInfoCB(org.codelibs.fess.es.config.cbean.CrawlingInfoCB) CsvConfig(com.orangesignal.csv.CsvConfig) List(java.util.List) Logger(org.apache.logging.log4j.Logger) CrawlingInfo(org.codelibs.fess.es.config.exentity.CrawlingInfo) ComponentUtil(org.codelibs.fess.util.ComponentUtil) DateTimeFormatter(java.time.format.DateTimeFormatter) Writer(java.io.Writer) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CsvReader(com.orangesignal.csv.CsvReader) LocalDateTime(java.time.LocalDateTime) CsvWriter(com.orangesignal.csv.CsvWriter) ArrayList(java.util.ArrayList) IOException(java.io.IOException) ArrayList(java.util.ArrayList) List(java.util.List) CsvConfig(com.orangesignal.csv.CsvConfig) DateTimeFormatter(java.time.format.DateTimeFormatter) CrawlingInfoParam(org.codelibs.fess.es.config.exentity.CrawlingInfoParam)

Example 59 with Resource

use of javax.annotation.Resource in project fess by codelibs.

the class ElevateWordService method importCsv.

public void importCsv(final Reader reader) {
    final PermissionHelper permissionHelper = ComponentUtil.getPermissionHelper();
    final CsvConfig cfg = new CsvConfig(',', '"', '"');
    cfg.setEscapeDisabled(false);
    cfg.setQuoteDisabled(false);
    @SuppressWarnings("resource") final CsvReader csvReader = new CsvReader(reader, cfg);
    try {
        List<String> list;
        // ignore header
        csvReader.readValues();
        while ((list = csvReader.readValues()) != null) {
            final String suggestWord = getValue(list, 0);
            if (StringUtil.isBlank(suggestWord)) {
                // skip
                continue;
            }
            try {
                final String[] permissions = split(getValue(list, 2), ",").get(stream -> stream.map(permissionHelper::encode).filter(StringUtil::isNotBlank).distinct().toArray(n -> new String[n]));
                final String[] labels = split(getValue(list, 3), ",").get(stream -> stream.filter(StringUtil::isNotBlank).distinct().toArray(n -> new String[n]));
                ElevateWord elevateWord = elevateWordBhv.selectEntity(cb -> {
                    cb.query().setSuggestWord_Equal(suggestWord);
                    if (permissions.length > 0) {
                        cb.query().setPermissions_InScope(stream(permissions).get(stream -> stream.collect(Collectors.toList())));
                    }
                }).orElse(null);
                final String reading = getValue(list, 1);
                final String boost = getValue(list, 4);
                final long now = ComponentUtil.getSystemHelper().getCurrentTimeAsLong();
                if (elevateWord == null) {
                    elevateWord = new ElevateWord();
                    elevateWord.setSuggestWord(suggestWord);
                    elevateWord.setReading(reading);
                    elevateWord.setPermissions(permissions);
                    elevateWord.setBoost(StringUtil.isBlank(boost) ? 1.0f : Float.parseFloat(boost));
                    elevateWord.setCreatedBy(Constants.SYSTEM_USER);
                    elevateWord.setCreatedTime(now);
                    elevateWordBhv.insert(elevateWord);
                    final String id = elevateWord.getId();
                    final List<ElevateWordToLabel> mappingList = stream(labels).get(stream -> stream.map(l -> labelTypeBhv.selectEntity(cb -> cb.query().setValue_Equal(l)).map(e -> {
                        final ElevateWordToLabel m = new ElevateWordToLabel();
                        m.setElevateWordId(id);
                        m.setLabelTypeId(e.getId());
                        return m;
                    }).orElse(null)).filter(e -> e != null).collect(Collectors.toList()));
                    if (!mappingList.isEmpty()) {
                        elevateWordToLabelBhv.batchInsert(mappingList);
                    }
                } else if (StringUtil.isBlank(reading) && StringUtil.isBlank(boost)) {
                    elevateWordBhv.delete(elevateWord);
                    final String id = elevateWord.getId();
                    elevateWordToLabelBhv.queryDelete(cb -> cb.query().setElevateWordId_Equal(id));
                } else {
                    elevateWord.setReading(reading);
                    elevateWord.setPermissions(permissions);
                    elevateWord.setBoost(StringUtil.isBlank(boost) ? 1.0f : Float.parseFloat(boost));
                    elevateWord.setUpdatedBy(Constants.SYSTEM_USER);
                    elevateWord.setUpdatedTime(now);
                    elevateWordBhv.update(elevateWord);
                    final String id = elevateWord.getId();
                    final List<ElevateWordToLabel> mappingList = stream(labels).get(stream -> stream.map(l -> labelTypeBhv.selectEntity(cb -> cb.query().setValue_Equal(l)).map(e -> {
                        final List<ElevateWordToLabel> mList = elevateWordToLabelBhv.selectList(cb -> {
                            cb.query().setElevateWordId_Equal(id);
                            cb.query().setLabelTypeId_Equal(e.getId());
                        });
                        if (!mList.isEmpty()) {
                            return null;
                        }
                        final ElevateWordToLabel m = new ElevateWordToLabel();
                        m.setElevateWordId(id);
                        m.setLabelTypeId(e.getId());
                        return m;
                    }).orElse(null)).filter(e -> e != null).collect(Collectors.toList()));
                    if (!mappingList.isEmpty()) {
                        elevateWordToLabelBhv.batchInsert(mappingList);
                    }
                }
            } catch (final Exception e) {
                logger.warn("Failed to read a sugget elevate word: {}", list, e);
            }
        }
        elevateWordBhv.refresh();
    } catch (final IOException e) {
        logger.warn("Failed to read a sugget elevate word.", e);
    }
}
Also used : BeanUtil(org.codelibs.core.beans.util.BeanUtil) EntityRowHandler(org.dbflute.bhv.readable.EntityRowHandler) Constants(org.codelibs.fess.Constants) ElevateWordPager(org.codelibs.fess.app.pager.ElevateWordPager) SearchEngineClient(org.codelibs.fess.es.client.SearchEngineClient) PermissionHelper(org.codelibs.fess.helper.PermissionHelper) LabelType(org.codelibs.fess.es.config.exentity.LabelType) ArrayList(java.util.ArrayList) FessConfig(org.codelibs.fess.mylasta.direction.FessConfig) StreamUtil.split(org.codelibs.core.stream.StreamUtil.split) PagingResultBean(org.dbflute.cbean.result.PagingResultBean) LabelTypeBhv(org.codelibs.fess.es.config.exbhv.LabelTypeBhv) ElevateWordBhv(org.codelibs.fess.es.config.exbhv.ElevateWordBhv) ElevateWordCB(org.codelibs.fess.es.config.cbean.ElevateWordCB) ElevateWordToLabel(org.codelibs.fess.es.config.exentity.ElevateWordToLabel) StreamUtil.stream(org.codelibs.core.stream.StreamUtil.stream) OptionalEntity(org.dbflute.optional.OptionalEntity) Resource(javax.annotation.Resource) StringUtil(org.codelibs.core.lang.StringUtil) CsvWriter(com.orangesignal.csv.CsvWriter) IOException(java.io.IOException) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) CsvConfig(com.orangesignal.csv.CsvConfig) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ComponentUtil(org.codelibs.fess.util.ComponentUtil) ElevateWordToLabelBhv(org.codelibs.fess.es.config.exbhv.ElevateWordToLabelBhv) Writer(java.io.Writer) ElevateWord(org.codelibs.fess.es.config.exentity.ElevateWord) LogManager(org.apache.logging.log4j.LogManager) CsvReader(com.orangesignal.csv.CsvReader) IOException(java.io.IOException) ElevateWordToLabel(org.codelibs.fess.es.config.exentity.ElevateWordToLabel) IOException(java.io.IOException) CsvReader(com.orangesignal.csv.CsvReader) ElevateWord(org.codelibs.fess.es.config.exentity.ElevateWord) PermissionHelper(org.codelibs.fess.helper.PermissionHelper) ArrayList(java.util.ArrayList) List(java.util.List) CsvConfig(com.orangesignal.csv.CsvConfig)

Aggregations

Resource (javax.annotation.Resource)59 Collectors (java.util.stream.Collectors)22 Set (java.util.Set)20 List (java.util.List)18 Subject (alien4cloud.security.Subject)17 Sets (com.google.common.collect.Sets)17 Arrays (java.util.Arrays)17 ArrayUtils (org.apache.commons.lang3.ArrayUtils)15 IGenericSearchDAO (alien4cloud.dao.IGenericSearchDAO)14 ApplicationEnvironmentService (alien4cloud.application.ApplicationEnvironmentService)12 ApplicationEnvironment (alien4cloud.model.application.ApplicationEnvironment)12 Audit (alien4cloud.audit.annotation.Audit)11 ResourcePermissionService (alien4cloud.authorization.ResourcePermissionService)11 RestResponse (alien4cloud.rest.model.RestResponse)11 RestResponseBuilder (alien4cloud.rest.model.RestResponseBuilder)11 ApplicationEnvironmentAuthorizationUpdateRequest (alien4cloud.rest.orchestrator.model.ApplicationEnvironmentAuthorizationUpdateRequest)11 ApiOperation (io.swagger.annotations.ApiOperation)11 IOException (java.io.IOException)11 MediaType (org.springframework.http.MediaType)11 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)11