miscmodule.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 1,774 行 · 第 1/3 页

JAVA
1,774
字号
      os.close();      StringValue sb = env.createUnicodeBuilder();      int ch;      while ((ch = is.read()) >= 0) {        sb.append((char) ch);      }      is.close();      if ((ch = es.read()) >= 0) {        env.print((char)ch);                while ((ch = es.read()) >= 0) {          env.print((char)ch);        }                return NullValue.NULL;      }            es.close();      int status = process.waitFor();      return sb;    } catch (Exception e) {      log.log(Level.FINE, e.getMessage(), e);      env.warning(e.getMessage(), e);      return NullValue.NULL;    }  }  /**   * Execute a system command.   */  public static void passthru(Env env, String command,			       @Optional @Reference Value result)  {    try {      String []args = new String[3];      if (Path.isWindows()) {        args[0] = "cmd";        args[1] = "/c";      }      else {        args[0] = "sh";        args[1] = "-c";      }      args[2] = command;      ProcessBuilder processBuilder = new ProcessBuilder(args);      processBuilder.redirectErrorStream(true);      final Process process = processBuilder.start();      try {        InputStream is = process.getInputStream();        OutputStream os = process.getOutputStream();        os.close();        env.getOut().writeStream(is);        is.close();        int status = process.waitFor();      }      finally {        process.destroy();      }    } catch (Exception e) {      env.warning(e.getMessage(), e);    }  }  /*   * Basic implementation of proc_open.   * XXX: options   */  @ReturnNullAsFalse   public static ProcOpenResource proc_open(Env env,                                            String command,                                            ArrayValue descriptorArray,                                           @Reference Value pipes,                                           @Optional Path pwd,                                           @Optional ArrayValue envArray,                                           @Optional ArrayValue options)  {    String []args = new String[3];    try {      if (Path.isWindows()) {        args[0] = "cmd";        args[1] = "/c";      }      else {        args[0] = "sh";        args[1] = "-c";      }      args[2] = command;      String []envStrings = null;      File pwdFile = null;            if (envArray != null) {        int size = envArray.getSize();                envStrings = new String[size];                int i = 0;        for (Map.Entry<Value,Value> entry : envArray.entrySet()) {          envStrings[i++] = entry.getKey() + "=" + entry.getValue();        }      }            if (pwd != null) {        pwdFile = new File(pwd.getFullPath());      }      Process process = Runtime.getRuntime().exec(args, envStrings, pwdFile);            ProcOpenOutput in = null;      ProcOpenInput out = null;      ProcOpenInput es = null;      ArrayValue array = pipes.toAutoArray().toArrayValue(env);      pipes.set(array);      array.clear();            for (Map.Entry<Value,Value> entry : descriptorArray.entrySet()) {        Value key = entry.getKey();        Value val = entry.getValue();        String type = val.get(LongValue.ZERO).toString();        StringValue name = val.get(LongValue.ONE).toStringValue();        String mode = val.get(LongValue.create(2)).toString();                // input to the command        if (key.equals(LongValue.ZERO)) {          if (type.equals("pipe")) {            in = new ProcOpenOutput(env, process.getOutputStream());            array.put(LongValue.ZERO, env.wrapJava(in));          }          else if (type.equals("file")) {            OutputStream processOut = process.getOutputStream();                        BinaryStream stream = FileModule.fopen(env, name, mode, false, null);                        if (stream instanceof FileInput) {              FileInput file = (FileInput) stream;                            int ch;              while ((ch = file.read()) >= 0) {                processOut.write(ch);              }            }                        stream.close();            processOut.close();          }        }        // place to put output from the command        else if (key.equals(LongValue.ONE)) {          if (type.equals("pipe")) {            out = new ProcOpenInput(env, process.getInputStream());            array.put(LongValue.ONE, env.wrapJava(out));          }          else if (type.equals("file")) {            BinaryStream stream = FileModule.fopen(env, name, mode, false, null);            if (stream instanceof FileOutput) {              FileOutput file = (FileOutput) stream;                            out = new ProcOpenInput(env, process.getInputStream(), file);            }            else if (stream != null)              stream.close();          }        }        // place to put error output from the command        else if (key.equals(new LongValue(2))) {          if (type.equals("pipe")) {            es = new ProcOpenInput(env, process.getErrorStream());                        array.put(new LongValue(2), env.wrapJava(es));          }          else if (type.equals("file")) {            BinaryStream stream = FileModule.fopen(env, name, mode, false, null);                        if (stream instanceof FileOutput) {              FileOutput file = (FileOutput) stream;                            es = new ProcOpenInput(env, process.getErrorStream(), file);            }            else if (stream != null)              stream.close();          }        }      }            return new ProcOpenResource(env, process, in, out, es);    } catch (Exception e) {      log.log(Level.FINE, e.getMessage(), e);      env.warning(e);      return null;    }  }    /*   * Closes the process opened by proc_open.   */  public static int proc_close(Env env,                               @NotNull ProcOpenResource stream)  {    if (stream == null) {      log.log(Level.FINE, "input to proc_close must not be null");      env.warning("input to proc_close must not be null");            return -1;    }       return stream.pclose();  }    /*   * Forcibly terminates the process opened by proc_open.   */  public static boolean proc_terminate(Env env,                                       @NotNull ProcOpenResource stream)  {    if (stream == null) {      log.log(Level.FINE, "input to proc_close must not be null");      env.warning("input to proc_close must not be null");            return false;    }       return stream.terminate();  }    /**   * Returns the disconnect ignore setting   */  public static int ignore_user_abort(@Optional boolean set)  {    return 0;  }  /**   * Returns a unique id.   */  public String uniqid(@Optional String prefix, @Optional boolean moreEntropy)  {    StringBuilder sb = new StringBuilder();    if (prefix != null)      sb.append(prefix);    addUnique(sb);    if (moreEntropy)      addUnique(sb);    return sb.toString();  }  private void addUnique(StringBuilder sb)  {    long value = RandomUtil.getRandomLong();    if (value < 0)      value = -value;    int limit = 13;    for (; limit > 0; limit--) {      long digit = value % 26;      value = value / 26;      sb.append((char) ('a' + digit));    }  }  /**   * Sleep for a number of microseconds.   */  public static Value usleep(long microseconds)  {    try {      Thread.sleep(microseconds / 1000);    } catch (Throwable e) {    }    return NullValue.NULL;  }  /**   * Sleep for a number of seconds.   */  public static long sleep(long seconds)  {    try {      Thread.sleep(seconds * 1000);    } catch (Throwable e) {    }    return seconds;  }  /**   * Execute a system command.   */  public static String system(Env env, String command,			      @Optional @Reference Value result)  {    return exec(env, command, null, result);  }  private static ArrayList<PackSegment> parsePackFormat(Env env, String format)  {    ArrayList<PackSegment> segments = new ArrayList<PackSegment>();    int length = format.length();    for (int i = 0; i < length; i++) {      char ch = format.charAt(i);            int count = 0;      char ch1 = ' ';      for (i++;	   i < length && '0' <= (ch1 = format.charAt(i)) && ch1 <= '9';	   i++) {	count = 10 * count + ch1 - '0';      }      if (ch1 == '*' && count == 0) {	i++;	count = Integer.MAX_VALUE;      }      else if (count == 0)	count = 1;      if (i < length)	i--;      switch (ch) {      case 'a':	segments.add(new SpacePackSegment(env, count, (byte) 0));	break;      case 'A':	segments.add(new SpacePackSegment(env, count, (byte) 0x20));	break;      case 'h':	segments.add(new RevHexPackSegment(count));	break;      case 'H':	segments.add(new HexPackSegment(env, count));	break;      case 'c':      case 'C':	segments.add(new BigEndianPackSegment(count, 1));	break;      case 's':      case 'n':      case 'S':	segments.add(new BigEndianPackSegment(count, 2));	break;      case 'v':	segments.add(new LittleEndianPackSegment(count, 2));	break;      case 'l':      case 'L':      case 'N':	segments.add(new BigEndianPackSegment(count, 4));	break;      case 'V':	segments.add(new LittleEndianPackSegment(count, 4));	break;      case 'i':      case 'I':	segments.add(new BigEndianPackSegment(count, 8));	break;      case 'd':	segments.add(new DoublePackSegment(count));	break;      case 'f':	segments.add(new FloatPackSegment(count));	break;      case 'x':	segments.add(new NullPackSegment(count));	break;      case '@':	segments.add(new PositionPackSegment(count));	break;      }    }    return segments;  }  private static ArrayList<PackSegment> parseUnpackFormat(Env env,							  String format)  {    ArrayList<PackSegment> segments = new ArrayList<PackSegment>();    int length = format.length();    for (int i = 0; i < length; i++) {      char ch = format.charAt(i);            int count = 0;      char ch1 = ' ';      for (i++;	   i < length && '0' <= (ch1 = format.charAt(i)) && ch1 <= '9';	   i++) {	count = 10 * count + ch1 - '0';      }            if (count == 0)	count = 1;      if (i < length)	i--;      StringBuilder sb = new StringBuilder();            for (i++; i < length && (ch1 = format.charAt(i)) != '/'; i++) {	sb.append(ch1);      }      String name = sb.toString();      switch (ch) {      case 'a':	segments.add(new SpacePackSegment(env, name, count, (byte) 0));	break;      case 'A':	segments.add(new SpacePackSegment(env, name, count, (byte) 0x20));	break;      case 'h':	segments.add(new RevHexPackSegment(name, count));	break;      case 'H':	segments.add(new HexPackSegment(env, name, count));	break;      case 'c':	segments.add(new BigEndianPackSegment(name, count, 1, true));	break;      case 'C':	segments.add(new BigEndianPackSegment(name, count, 1, false));	break;      case 's':	segments.add(new BigEndianPackSegment(name, count, 2, true));	break;      case 'n':      case 'S':	segments.add(new BigEndianPackSegment(name, count, 2, false));	break;      case 'v':	segments.add(new LittleEndianPackSegment(name, count, 2));	break;      case 'l':	segments.add(new BigEndianPackSegment(name, count, 4, true));	break;      case 'L':      case 'N':	segments.add(new BigEndianPackSegment(name, count, 4, true));	break;      case 'V':	segments.add(new LittleEndianPackSegment(name, count, 4));	break;      case 'i':      case 'I':	segments.add(new BigEndianPackSegment(name, count, 8, false));	break;      case 'd':	segments.add(new DoublePackSegment(name, count));	break;      case 'f':	segments.add(new FloatPackSegment(name, count));	break;      case 'x':	segments.add(new NullPackSegment(name, count));	break;      case '@':	segments.add(new PositionPackSegment(name, count));	break;      }    }    return segments;  }  abstract static class PackSegment {    abstract public int pack(Env env, StringValue bb,			      int i, Value []args)      throws IOException;        abstract public void unpack(Env env, ArrayValue array, InputStream is)      throws IOException;  }  static class SpacePackSegment extends PackSegment {    private final StringValue _name;    private final int _length;    private final byte _pad;    SpacePackSegment(Env env, int length, byte pad)    {      this(env, "", length, pad);    }    SpacePackSegment(Env env, String name, int length, byte pad)    {      _name = env.createString(name);      _length = length;      _pad = pad;    }        @Override    public int pack(Env env, StringValue bb, int i, Value []args)      throws IOException    {      Value arg;      if (i < args.length) {	arg = args[i];	i++;      }      else {	env.warning("a: not enough arguments");	return i;      }      InputStream is = arg.toInputStream();      int length = _length;      for (int j = 0; j < length; j++) {	int ch = is.read();	if (ch >= 0)	  bb.appendByte(ch);	else if (length == Integer.MAX_VALUE)	  return i;	else	  bb.appendByte(_pad);      }      return i;    }        @Override    public void unpack(Env env, ArrayValue result, InputStream is)      throws IOException    {      StringValue bb = env.createBinaryBuilder();            for (int i = 0; i < _length; i++) {	int ch = is.read();	if (ch == _pad) {	}	else if (ch >= 0)	  bb.appendByte(ch);	else	  break;      }      result.put(_name, bb);    }  }  static class HexPackSegment extends PackSegment {    private final StringValue _name;    private final int _length;    HexPackSegment(Env env, int length)    {      this(env, "", length);    }    HexPackSegment(Env env, String name, int length)    {      _name = env.createString(name);      _length = length;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?