Exemple #1
0
  public void run() {
    // ----------------------------------------- 建立
    log.infof("start TcpServer [%s] @ %d", Thread.currentThread().getName(), port);
    try {
      listener = new ServerSocket(port);
    } catch (IOException e1) {
      throw Lang.wrapThrow(e1);
    }
    // ----------------------------------------- 循环
    log.infof("TcpServer listen @ %d", port);
    while (!stop) {
      log.info("before accept ...");
      Socket socket = null;
      try {
        socket = listener.accept();
      } catch (IOException e) {
        log.fatalf("Fail to accept %s @ %d , System.exit!", Thread.currentThread().getName(), port);
        System.exit(0);
      }

      log.info("do listen ...");
      listen(socket);
      log.infof(
          "done for listen [%s:%d], stop=%b",
          socket.getInetAddress().getHostName(), socket.getPort(), stop);
    }
    // ----------------------------------------- 关闭
    try {
      listener.close();
      log.infof("TcpServer shutdown @ %d", port);
    } catch (IOException e) {
      throw Lang.wrapThrow(e);
    }
  }
Exemple #2
0
 /**
  * 获取一个字段的泛型参数数组,如果这个字段没有泛型,返回空数组
  *
  * @param f 字段
  * @return 泛型参数数组
  */
 public static Class<?>[] getGenericTypes(Field f) {
   String gts = f.toGenericString();
   Matcher m = PTN.matcher(gts);
   if (m.find()) {
     String s = m.group(2);
     String[] ss = Strings.splitIgnoreBlank(s);
     if (ss.length > 0) {
       Class<?>[] re = new Class<?>[ss.length];
       try {
         for (int i = 0; i < ss.length; i++) {
           String className = ss[i];
           if (className.length() > 0 && className.charAt(0) == '?') re[i] = Object.class;
           else {
             int pos = className.indexOf('<');
             if (pos < 0) re[i] = Lang.loadClass(className);
             else re[i] = Lang.loadClass(className.substring(0, pos));
           }
         }
         return re;
       } catch (ClassNotFoundException e) {
         throw Lang.wrapThrow(e);
       }
     }
   }
   return new Class<?>[0];
 }
Exemple #3
0
 /**
  * 根据一个文件路径建立一个输入流
  *
  * @param file 文件
  * @return 输入流
  */
 public static InputStream fileIn(File file) {
   try {
     return buff(Streams._input(file));
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #4
0
 protected void listen(Socket socket) {
   SocketHandler handler = getHandler();
   // 处理请求
   try {
     handler.handle(socket);
   }
   // 仅仅是关闭连接
   catch (SocketClosed e) {
   }
   // 停止服务
   catch (ServerStopped e) {
     stop = true;
   }
   // 处理异常
   catch (Throwable e) {
     handler.whenError(socket, e);
   }
   // 确保关闭
   finally {
     if (!socket.isClosed())
       try {
         socket.close();
       } catch (IOException e) {
         throw Lang.wrapThrow(e);
       }
   }
 }
Exemple #5
0
 public void addCastor(Class<?> klass) {
   try {
     fillMap(klass, new HashMap<Class<?>, Method>());
   } catch (Throwable e) {
     throw Lang.wrapThrow(Lang.unwrapThrow(e));
   }
 }
Exemple #6
0
 /**
  * 根据一个文件建立一个输出流
  *
  * @param file 文件
  * @return 输出流
  */
 public static OutputStream fileOut(File file) {
   try {
     return buff(new FileOutputStream(file));
   } catch (FileNotFoundException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #7
0
 @Override
 protected java.util.Date cast(String src, Class<?> toType, String... args) {
   try {
     return dateTimeFormat.parse(src);
   } catch (ParseException e) {
     throw Lang.wrapThrow(e);
   }
 }
 @Override
 public void close() throws IOException {
   try {
     for (MultipartItem item : items) item.close();
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   }
 }
 public MsgDigestInputStream(InputStream in, String name) {
   super(in);
   try {
     this.md = MessageDigest.getInstance(name);
   } catch (NoSuchAlgorithmException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #10
0
 /**
  * 将一个字节数组写入一个输出流。
  *
  * <p><b style=color:red>注意</b>,它会关闭输出流
  *
  * @param ops 输出流
  * @param bytes 字节数组
  */
 public static void writeAndClose(OutputStream ops, byte[] bytes) {
   try {
     write(ops, bytes);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(ops);
   }
 }
Exemple #11
0
 /**
  * 将对象转换成 Map
  *
  * @param <T>
  * @param obj POJO 对象
  * @param mapType Map 的类型
  * @return Map 对象
  */
 public static <T extends Map<String, Object>> T obj2map(Object obj, Class<T> mapType) {
   try {
     T map = mapType.newInstance();
     Lang.obj2map(obj, map, new HashMap<Object, Object>());
     return map;
   } catch (Exception e) {
     throw Lang.wrapThrow(e);
   }
 }
 public void init() {
   try {
     for (MultipartItem item : items) item.init();
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   }
   it = items.iterator();
   current = it.next();
 }
Exemple #13
0
 /**
  * 从一个文本流中读取全部内容并返回
  *
  * <p><b style=color:red>注意</b>,它会关闭输入流
  *
  * @param reader 文本输入流
  * @return 文本内容
  * @throws IOException
  */
 public static String readAndClose(Reader reader) {
   try {
     return read(reader).toString();
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(reader);
   }
 }
Exemple #14
0
 public static String encode(Object s) {
   if (null == s) return "";
   try {
     // Fix issue 283, 按照“茶几”的意见再次修改
     return URLEncoder.encode(s.toString(), Encoding.CHARSET_UTF8.name());
   } catch (UnsupportedEncodingException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #15
0
 /**
  * 将一段文本全部写入一个writer。
  *
  * <p><b style=color:red>注意</b>,它会关闭输出流
  *
  * @param writer 输出流
  * @param cs 文本
  */
 public static void writeAndClose(Writer writer, CharSequence cs) {
   try {
     write(writer, cs);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(writer);
   }
 }
Exemple #16
0
 /**
  * 将输入流写入一个输出流。块大小为 8192
  *
  * <p><b style=color:red>注意</b>,它会关闭输入/出流
  *
  * @param ops 输出流
  * @param ins 输入流
  * @return 写入的字节数
  */
 public static long writeAndClose(OutputStream ops, InputStream ins) {
   try {
     return write(ops, ins);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(ops);
     safeClose(ins);
   }
 }
Exemple #17
0
 /**
  * 将文本输入流写入一个文本输出流。块大小为 8192
  *
  * <p><b style=color:red>注意</b>,它会关闭输入/出流
  *
  * @param writer 输出流
  * @param reader 输入流
  */
 public static void writeAndClose(Writer writer, Reader reader) {
   try {
     write(writer, reader);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(writer);
     safeClose(reader);
   }
 }
Exemple #18
0
 /**
  * 将一段字符串写入一个文本输出流,并将该流关闭
  *
  * @param writer 文本输出流
  * @param str 字符串
  */
 public static void writeAll(Writer writer, String str) {
   try {
     writer.write(str);
     writer.flush();
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     Streams.safeClose(writer);
   }
 }
Exemple #19
0
 @Override
 protected Calendar cast(String src, Class<?> toType, String... args) {
   Calendar c = Calendar.getInstance();
   try {
     c.setTime(dateTimeFormat.parse(src));
   } catch (ParseException e) {
     throw Lang.wrapThrow(e);
   }
   return c;
 }
Exemple #20
0
 /**
  * 强制从字符串转换成一个 Class,将 ClassNotFoundException 包裹成 RuntimeException
  *
  * @param <T>
  * @param name 类名
  * @param type 这个类型的边界
  * @return 类对象
  */
 @SuppressWarnings("unchecked")
 public static <T> Class<T> forName(String name, Class<T> type) {
   Class<?> re;
   try {
     re = Class.forName(name);
     return (Class<T>) re;
   } catch (ClassNotFoundException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #21
0
 public static void appendWriteAndClose(File f, String text) {
   FileWriter fw = null;
   try {
     fw = new FileWriter(f, true);
     fw.write(text);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     safeClose(fw);
   }
 }
Exemple #22
0
 /**
  * 读取一个输入流中所有的字节,并关闭输入流
  *
  * @param ins 输入流,必须支持 available()
  * @return 一个字节数组
  * @throws IOException
  */
 public static byte[] readBytesAndClose(InputStream ins) {
   byte[] bytes = null;
   try {
     bytes = readBytes(ins);
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   } finally {
     Streams.safeClose(ins);
   }
   return bytes;
 }
  public static Map<String, NutMap> read(String path) {
    Map<String, NutMap> maps = new LinkedHashMap<>();
    Document doc = Xmls.xml(DubboConfigureReader.class.getClassLoader().getResourceAsStream(path));
    doc.normalizeDocument();
    Element top = doc.getDocumentElement();
    NodeList list = top.getChildNodes();
    int count = list.getLength();

    for (int i = 0; i < count; i++) {
      Node node = list.item(i);
      if (node instanceof Element) {
        Element ele = (Element) node;
        String eleName = ele.getNodeName();
        if (!eleName.startsWith("dubbo:")) continue; // 跳过非dubbo节点
        String typeName = eleName.substring("dubbo:".length());
        NutMap attrs = toAttrMap(ele.getAttributes());
        log.debug("found " + typeName);
        String genBeanName = ele.getAttribute("id");
        if (Strings.isBlank(genBeanName)) {
          if ("protocol".equals(typeName)) genBeanName = "dubbo";
          else {
            genBeanName = ele.getAttribute("interface");
            if (Strings.isBlank(genBeanName)) {
              try {
                genBeanName =
                    Class.forName(
                            "com.alibaba.dubbo.config." + Strings.upperFirst(typeName) + "Config")
                        .getName();
              } catch (ClassNotFoundException e) {
                throw Lang.wrapThrow(e);
              }
            }
          }
          if (maps.containsKey(genBeanName)) {
            int _count = 2;
            while (true) {
              String key = genBeanName + "_" + _count;
              if (maps.containsKey(key)) {
                _count++;
                continue;
              }
              genBeanName += "_" + _count;
              break;
            }
          }
        }
        attrs.put("_typeName", typeName);
        maps.put(genBeanName, attrs);
      }
    }
    return maps;
  }
Exemple #24
0
  public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) {
    int code = this.statusCode;
    if (obj != null && obj instanceof HttpStatusException) {
      code = ((HttpStatusException) obj).getStatus();
    }

    if (code >= 400)
      try {
        resp.sendError(code);
      } catch (IOException e) {
        throw Lang.wrapThrow(e);
      }
    else resp.setStatus(code);
  }
Exemple #25
0
 public static void loadProperties(String fileName) {
   InputStream is = null;
   try {
     pp = new Properties();
     File f = Files.findFile(fileName);
     if (f == null) throw new RuntimeException("nutz-test.properties Not FOUND!!!");
     is = Streams.fileIn(f);
     pp.load(is);
     pp.list(System.out);
   } catch (Exception e) {
     throw Lang.wrapThrow(e);
   } finally {
     Streams.safeClose(is);
   }
 }
Exemple #26
0
 /**
  * 根据字段名,得出一个字段注入方式。优先用 Setter
  *
  * @param fieldName 字段名
  * @return 注入方式。
  */
 public Injecting getInjecting(String fieldName) {
   Method[] sss = this.findSetters(fieldName);
   if (sss.length == 1) return new InjectBySetter(sss[0]);
   else
     try {
       Field field = this.getField(fieldName);
       try {
         return new InjectBySetter(this.getSetter(field));
       } catch (NoSuchMethodException e) {
         return new InjectByField(field);
       }
     } catch (NoSuchFieldException e) {
       throw Lang.wrapThrow(e);
     }
 }
Exemple #27
0
 /** 判断并移除UTF-8的BOM头 */
 public static InputStream utf8filte(InputStream in) {
   try {
     if (in.available() == -1) return in;
     PushbackInputStream pis = new PushbackInputStream(in, 3);
     byte[] header = new byte[3];
     int len = pis.read(header, 0, 3);
     if (len < 1) return in;
     if (header[0] != UTF_BOM[0] || header[1] != UTF_BOM[1] || header[2] != UTF_BOM[2]) {
       pis.unread(header, 0, len);
     }
     return pis;
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #28
0
 /**
  * 加载指定文件/文件夹的Properties文件,合并成一个Properties对象
  *
  * <p><b style=color:red>如果有重复的key,请务必注意加载的顺序!!<b/>
  *
  * @param paths 需要加载的Properties文件路径
  */
 public void setPaths(String... paths) {
   mp = new MultiLineProperties();
   List<NutResource> list = Scans.me().loadResource("^.+[.]properties$", paths);
   try {
     if (utf8) for (NutResource nr : list) mp.load(nr.getReader());
     else {
       Properties p = new Properties();
       for (NutResource nr : list) {
         p.load(nr.getInputStream());
       }
       mp.putAll(p);
     }
   } catch (IOException e) {
     throw Lang.wrapThrow(e);
   }
 }
Exemple #29
0
 /**
  * 根据字段名获得一个字段输入方式。优先用 Getter
  *
  * @param fieldName 字段名
  * @return 输出方式
  */
 public Ejecting getEjecting(String fieldName) {
   try {
     return new EjectByGetter(getGetter(fieldName));
   } catch (NoSuchMethodException e) {
     try {
       Field field = this.getField(fieldName);
       try {
         return new EjectByGetter(getGetter(field));
       } catch (NoSuchMethodException e1) {
         return new EjectByField(field);
       }
     } catch (NoSuchFieldException e1) {
       throw Lang.wrapThrow(e1);
     }
   }
 }
Exemple #30
0
 public static Ioc getIoc(String key) {
   Ioc nut = nuts.get(key);
   if (null == nut) {
     synchronized (Nutzs.class) {
       nut = nuts.get(key);
       try {
         if (null == nut) {
           nut = new NutIoc(new JsonLoader(key));
           nuts.put(key, nut);
         }
       } catch (Exception e) {
         throw Lang.wrapThrow(e);
       }
     }
   }
   return nut;
 }