Search in sources :

Example 1 with DefaultAnyValue

use of org.redkale.util.AnyValue.DefaultAnyValue in project redkale by redkale.

the class MultiContext method parts.

/**
 * 获取上传文件信息列表
 *
 * @return Iterable
 * @throws IOException IOException
 */
public Iterable<MultiPart> parts() throws IOException {
    if (!isMultipart())
        return emptyIterable;
    final String boundarystr = "--" + this.boundary;
    final Pattern fielnameReg = this.fielnamePattern;
    final String endboundary = boundarystr + "--";
    final byte[] boundarray = ("\n" + boundarystr).getBytes();
    final byte[] buffer = new byte[boundarray.length];
    final InputStream input = this.in;
    final DefaultAnyValue params = this.parameters;
    final AtomicBoolean finaled = new AtomicBoolean(false);
    return () -> new Iterator<MultiPart>() {

        private String boundaryline;

        private MultiPart lastentry;

        @Override
        public boolean hasNext() {
            try {
                if (lastentry != null) {
                    lastentry.skip();
                    if (finaled.get())
                        return false;
                }
                if (boundaryline == null)
                    boundaryline = readBoundary();
                // if (debug) System.out.print("boundaryline=" + boundaryline + "  ");
                if (endboundary.equals(boundaryline) || !boundarystr.equals(boundaryline)) {
                    // 结尾或异常
                    lastentry = null;
                    return false;
                }
                final String disposition = readLine();
                // if (debug) System.out.println("disposition=" + disposition);
                if (disposition.contains("; filename=\"")) {
                    // 是上传文件
                    String contentType = "";
                    // 读掉HTTP Header和空白行 通常情况下Content-Type后面就是内容,但是有些特殊情况下后面会跟其他如Content-Length: xxx等HTTP header,所以需要循环读取
                    String rl;
                    while (!(rl = readLine()).isEmpty()) {
                        if (rl.startsWith("Content-Type:"))
                            contentType = rl.substring(rl.indexOf(':') + 1).trim();
                    }
                    // if (debug) System.out.println("file.contentType=" + contentType);
                    String name = parseValue(disposition, "name");
                    String filename = parseValue(disposition, "filename");
                    if (filename == null || filename.isEmpty()) {
                        // 没有上传
                        // 读掉空白行
                        readLine();
                        this.boundaryline = null;
                        this.lastentry = null;
                        return this.hasNext();
                    } else {
                        int p1 = filename.lastIndexOf('/');
                        if (p1 < 0)
                            p1 = filename.lastIndexOf('\\');
                        if (p1 >= 0)
                            filename = filename.substring(p1 + 1);
                    }
                    final AtomicLong counter = new AtomicLong(0);
                    InputStream source = new InputStream() {

                        private int bufposition = buffer.length;

                        private boolean end;

                        @Override
                        public int read() throws IOException {
                            if (end)
                                return -1;
                            final byte[] buf = buffer;
                            int ch = (this.bufposition < buf.length) ? (buf[this.bufposition++] & 0xff) : input.read();
                            if ((ch == '\r' && readBuffer()))
                                return -1;
                            counter.incrementAndGet();
                            return ch;
                        }

                        private boolean readBuffer() throws IOException {
                            final byte[] buf = buffer;
                            final int pos = this.bufposition;
                            int s = 0;
                            for (int i = pos; i < buf.length; i++) {
                                buf[s++] = buf[i];
                            }
                            int readed = 0;
                            while ((readed += input.read(buf, s + readed, pos - readed)) != pos) ;
                            this.bufposition = 0;
                            if (Arrays.equals(boundarray, buf)) {
                                this.end = true;
                                int c1 = input.read();
                                int c2 = input.read();
                                finaled.set(c1 == '-' && c2 == '-');
                                return true;
                            }
                            return false;
                        }

                        @Override
                        public long skip(long count) throws IOException {
                            if (end)
                                return -1;
                            if (count <= 0)
                                return 0;
                            long s = 0;
                            while (read() != -1) {
                                s++;
                                if (--count <= 0)
                                    break;
                            }
                            return s;
                        }
                    };
                    this.lastentry = new MultiPart(filename, name, contentType, counter, source);
                    if (fielnameReg != null && !fielnameReg.matcher(filename).matches()) {
                        return this.hasNext();
                    }
                    return true;
                } else {
                    // 不是文件
                    // 读掉空白
                    readLine();
                    params.addValue(parseValue(disposition, "name"), readLine());
                    this.boundaryline = null;
                    this.lastentry = null;
                    return this.hasNext();
                }
            } catch (IOException ex) {
                logger.log(Level.FINER, "list multiparts abort", ex);
                return false;
            }
        }

        @Override
        public MultiPart next() {
            return lastentry;
        }
    };
}
Also used : DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue)

Example 2 with DefaultAnyValue

use of org.redkale.util.AnyValue.DefaultAnyValue in project redkale by redkale.

the class Application method load.

private static AnyValue load(final InputStream in0) {
    final DefaultAnyValue any = new DefaultAnyValue();
    try (final InputStream in = in0) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(in);
        Element root = doc.getDocumentElement();
        load(any, root);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return any;
}
Also used : DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue)

Example 3 with DefaultAnyValue

use of org.redkale.util.AnyValue.DefaultAnyValue in project redkale by redkale.

the class NodeServer method createClassFilter.

protected ClassFilter createClassFilter(final String localGroup, Class<? extends Annotation> ref, Class inter, Class[] excludeSuperClasses, Class<? extends Annotation> ref2, String properties, String property) {
    ClassFilter cf = new ClassFilter(this.serverClassLoader, ref, inter, excludeSuperClasses, null);
    if (properties == null && properties == null) {
        cf.setRefused(true);
        return cf;
    }
    if (this.serverConf == null) {
        cf.setRefused(true);
        return cf;
    }
    AnyValue[] proplist = this.serverConf.getAnyValues(properties);
    if (proplist == null || proplist.length < 1) {
        cf.setRefused(true);
        return cf;
    }
    cf = null;
    for (AnyValue list : proplist) {
        DefaultAnyValue prop = null;
        String sc = list.getValue("groups");
        if (sc != null) {
            sc = sc.trim();
            if (sc.endsWith(";"))
                sc = sc.substring(0, sc.length() - 1);
        }
        if (sc == null)
            sc = localGroup;
        if (sc != null) {
            prop = new AnyValue.DefaultAnyValue();
            prop.addValue("groups", sc);
        }
        ClassFilter filter = new ClassFilter(this.serverClassLoader, ref, inter, excludeSuperClasses, prop);
        for (AnyValue av : list.getAnyValues(property)) {
            // <service>、<filter>、<servlet> 节点
            final AnyValue[] items = av.getAnyValues("property");
            if (av instanceof DefaultAnyValue && items.length > 0) {
                // 存在 <property>节点
                DefaultAnyValue dav = DefaultAnyValue.create();
                final AnyValue.Entry<String>[] strings = av.getStringEntrys();
                if (strings != null) {
                    // 将<service>、<filter>、<servlet>节点的属性值传给dav
                    for (AnyValue.Entry<String> en : strings) {
                        dav.addValue(en.name, en.getValue());
                    }
                }
                final AnyValue.Entry<AnyValue>[] anys = av.getAnyEntrys();
                if (anys != null) {
                    for (AnyValue.Entry<AnyValue> en : anys) {
                        // 将<service>、<filter>、<servlet>节点的非property属性节点传给dav
                        if (!"property".equals(en.name))
                            dav.addValue(en.name, en.getValue());
                    }
                }
                DefaultAnyValue ps = DefaultAnyValue.create();
                for (AnyValue item : items) {
                    ps.addValue(item.getValue("name"), item.getValue("value"));
                }
                dav.addValue("properties", ps);
                av = dav;
            }
            if (!av.getBoolValue("ignore", false)) {
                filter.filter(av, av.getValue("value"), false);
            }
        }
        if (list.getBoolValue("autoload", true)) {
            String includes = list.getValue("includes", "");
            String excludes = list.getValue("excludes", "");
            filter.setIncludePatterns(includes.split(";"));
            filter.setExcludePatterns(excludes.split(";"));
        } else if (ref2 == null || ref2 == Annotation.class) {
            // service如果是autoload=false则不需要加载
            filter.setRefused(true);
        } else if (ref2 != Annotation.class) {
            filter.setAnnotationClass(ref2);
        }
        cf = (cf == null) ? filter : cf.or(filter);
    }
    return cf;
}
Also used : FilterEntry(org.redkale.boot.ClassFilter.FilterEntry) DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue) DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue) DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue)

Example 4 with DefaultAnyValue

use of org.redkale.util.AnyValue.DefaultAnyValue in project redkale by redkale.

the class TransportWatchService method removeNode.

@RestMapping(name = "removenode", auth = false, comment = "动态删除指定Group的Node节点")
public RetResult removeNode(@RestParam(name = "group", comment = "Group节点名") final String group, @RestParam(name = "addr", comment = "节点IP") final String addr, @RestParam(name = "port", comment = "节点端口") final int port) throws IOException {
    if (group == null)
        return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
    final InetSocketAddress address = new InetSocketAddress(addr, port);
    if (!group.equals(transportFactory.findGroupName(address)))
        return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") not belong to group(" + group + ")");
    synchronized (this) {
        if (transportFactory.findGroupInfo(group) == null) {
            return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
        }
        transportFactory.removeGroupInfo(group, address);
        for (Service service : transportFactory.getServices()) {
            if (!Sncp.isSncpDyn(service))
                continue;
            SncpClient client = Sncp.getSncpClient(service);
            if (Sncp.isRemote(service)) {
                if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
                    client.getRemoteGroupTransport().removeRemoteAddresses(address);
                }
            } else {
                if (group.equals(client.getSameGroup())) {
                    client.getSameGroupTransport().removeRemoteAddresses(address);
                }
                if (client.getDiffGroups() != null && client.getDiffGroups().contains(group)) {
                    for (Transport transport : client.getDiffGroupTransports()) {
                        transport.removeRemoteAddresses(address);
                    }
                }
            }
        }
        for (AnyValue groupconf : application.getAppConfig().getAnyValue("resources").getAnyValues("group")) {
            if (group.equals(groupconf.getValue("name"))) {
                ((DefaultAnyValue) groupconf).removeValue("node", DefaultAnyValue.create("addr", addr).addValue("port", port));
                break;
            }
        }
        application.restoreConfig();
    }
    return RetResult.success();
}
Also used : DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue) DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue)

Example 5 with DefaultAnyValue

use of org.redkale.util.AnyValue.DefaultAnyValue in project redkale by redkale.

the class ClassFilter method filter.

/**
 * 过滤指定的class
 *
 * @param property  application.xml中对应class节点下的property属性项
 * @param clazzname class名称
 * @param autoscan  为true表示自动扫描的, false表示显著调用filter, AutoLoad的注解将被忽略
 * @param url       URL
 */
public final void filter(AnyValue property, String clazzname, boolean autoscan, URL url) {
    boolean r = accept0(property, clazzname);
    ClassFilter cf = r ? this : null;
    if (r && ands != null) {
        for (ClassFilter filter : ands) {
            if (!filter.accept(property, clazzname))
                return;
        }
    }
    if (!r && ors != null) {
        for (ClassFilter filter : ors) {
            if (filter.accept(filter.conf, clazzname)) {
                cf = filter;
                property = cf.conf;
                break;
            }
        }
    }
    if (cf == null || clazzname.startsWith("sun.") || clazzname.contains("module-info"))
        return;
    try {
        Class clazz = classLoader.loadClass(clazzname);
        if (!cf.accept(property, clazz, autoscan))
            return;
        if (cf.conf != null) {
            if (property == null) {
                property = cf.conf;
            } else if (property instanceof DefaultAnyValue) {
                ((DefaultAnyValue) property).addAllStringSet(cf.conf);
            } else {
                DefaultAnyValue dav = new DefaultAnyValue();
                dav.addAllStringSet(property);
                dav.addAllStringSet(cf.conf);
                property = dav;
            }
        }
        AutoLoad auto = (AutoLoad) clazz.getAnnotation(AutoLoad.class);
        if ((expectPredicate != null && expectPredicate.test(clazzname)) || (autoscan && auto != null && !auto.value())) {
            // 自动扫描且被标记为@AutoLoad(false)的
            expectEntrys.add(new FilterEntry(clazz, autoscan, true, property));
        } else {
            entrys.add(new FilterEntry(clazz, autoscan, false, property));
        }
    } catch (Throwable cfe) {
        if (finest && !clazzname.startsWith("sun.") && !clazzname.startsWith("javax.") && !clazzname.startsWith("com.sun.") && !clazzname.startsWith("jdk.") && !clazzname.startsWith("META-INF") && !clazzname.startsWith("com.mysql.") && !clazzname.startsWith("com.microsoft.") && !clazzname.startsWith("freemarker.") && !clazzname.startsWith("org.redkale") && (clazzname.contains("Service") || clazzname.contains("Servlet"))) {
            // && (!(cfe instanceof NoClassDefFoundError) || (cfe instanceof UnsupportedClassVersionError) || ((NoClassDefFoundError) cfe).getMessage().startsWith("java.lang.NoClassDefFoundError: java"))) {
            logger.log(Level.FINEST, ClassFilter.class.getSimpleName() + " filter error for class: " + clazzname + (url == null ? "" : (" in " + url)), cfe);
        }
    }
}
Also used : DefaultAnyValue(org.redkale.util.AnyValue.DefaultAnyValue)

Aggregations

DefaultAnyValue (org.redkale.util.AnyValue.DefaultAnyValue)18 FilterEntry (org.redkale.boot.ClassFilter.FilterEntry)6 java.io (java.io)1 IOException (java.io.IOException)1 java.lang.reflect (java.lang.reflect)1 java.net (java.net)1 InetSocketAddress (java.net.InetSocketAddress)1 HttpClient (java.net.http.HttpClient)1 ByteBuffer (java.nio.ByteBuffer)1 java.nio.channels (java.nio.channels)1 AsynchronousSocketChannel (java.nio.channels.AsynchronousSocketChannel)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Path (java.nio.file.Path)1 java.util (java.util)1 java.util.concurrent (java.util.concurrent)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 java.util.concurrent.atomic (java.util.concurrent.atomic)1 java.util.logging (java.util.logging)1 javax.annotation (javax.annotation)1 SSLContext (javax.net.ssl.SSLContext)1