コード例 #1
1
  /**
   * Creates a new Socket connected to the given IP address. The method uses connection settings
   * supplied in the constructor for connecting the socket.
   *
   * @param address the IP address to connect to
   * @return connected socket
   * @throws java.net.UnknownHostException if the hostname of the address or the proxy cannot be
   *     resolved
   * @throws java.io.IOException if an I/O error occured while connecting to the remote end or to
   *     the proxy
   */
  private Socket createSocket(InetSocketAddress address, int timeout) throws IOException {
    String socksProxyHost = System.getProperty("socksProxyHost");
    System.getProperties().remove("socksProxyHost");
    try {
      ConnectivitySettings cs = lastKnownSettings.get(address);
      if (cs != null) {
        try {
          return createSocket(cs, address, timeout);
        } catch (IOException e) {
          // not good anymore, try all proxies
          lastKnownSettings.remove(address);
        }
      }

      URI uri = addressToURI(address, "socket");
      try {
        return createSocket(uri, address, timeout);
      } catch (IOException e) {
        // we will also try https
      }

      uri = addressToURI(address, "https");
      return createSocket(uri, address, timeout);

    } finally {
      if (socksProxyHost != null) {
        System.setProperty("socksProxyHost", socksProxyHost);
      }
    }
  }
コード例 #2
1
ファイル: MapCheck.java プロジェクト: codehaus/jsr166-mirror
  static void serTest(Map s, int size) throws Exception {
    if (!(s instanceof Serializable)) return;
    System.out.print("Serialize              : ");

    for (int i = 0; i < size; i++) {
      s.put(new Integer(i), Boolean.TRUE);
    }

    long startTime = System.currentTimeMillis();

    FileOutputStream fs = new FileOutputStream("MapCheck.dat");
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs));
    out.writeObject(s);
    out.close();

    FileInputStream is = new FileInputStream("MapCheck.dat");
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is));
    Map m = (Map) in.readObject();

    long endTime = System.currentTimeMillis();
    long time = endTime - startTime;

    System.out.print(time + "ms");

    if (s instanceof IdentityHashMap) return;
    reallyAssert(s.equals(m));
  }
コード例 #3
1
 @NotNull
 public static char[] adaptiveLoadText(@NotNull Reader reader) throws IOException {
   char[] chars = new char[4096];
   List<char[]> buffers = null;
   int count = 0;
   int total = 0;
   while (true) {
     int n = reader.read(chars, count, chars.length - count);
     if (n <= 0) break;
     count += n;
     if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + reader);
     total += n;
     if (count == chars.length) {
       if (buffers == null) {
         buffers = new ArrayList<char[]>();
       }
       buffers.add(chars);
       int newLength = Math.min(1024 * 1024, chars.length * 2);
       chars = new char[newLength];
       count = 0;
     }
   }
   char[] result = new char[total];
   if (buffers != null) {
     for (char[] buffer : buffers) {
       System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
       total -= buffer.length;
     }
   }
   System.arraycopy(chars, 0, result, result.length - total, total);
   return result;
 }
コード例 #4
1
  private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
コード例 #5
0
 void updateMenus() {
   if (IJ.debugMode) {
     long start = System.currentTimeMillis();
     Menus.updateImageJMenus();
     IJ.log("Refresh Menus: " + (System.currentTimeMillis() - start) + " ms");
   } else Menus.updateImageJMenus();
 }
コード例 #6
0
 /**
  * creates a server socket listening on the port specified in the parameter of the constructor,
  * and waits for a single incoming client connection which it handles by invoking the <CODE>
  * addNewClientConnection(s)</CODE> method of the enclosing server, and then the thread exits.
  */
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(_port);
     System.out.println("Srv: Now Accepting Single Client Connection");
     // while (true) {
     try {
       Socket s = ss.accept();
       System.out.println("Srv: Client Added to the Network");
       addNewClientConnection(s);
       System.out.println("Srv: finished adding client connection");
     } catch (Exception e) {
       // e.printStackTrace();
       System.err.println("Client Connection failed, exiting...");
       System.exit(-1);
     }
     // }
   } catch (IOException e) {
     // e.printStackTrace();
     utils.Messenger.getInstance()
         .msg(
             "PDBTExecSingleCltWrkInitSrv.C2Thread.run(): "
                 + "Failed to create Server Socket, Server exiting.",
             0);
     System.exit(-1);
   }
 }
コード例 #7
0
  /**
   * Copies outer join data from a source MultiJoinRel to a new set of arrays. Also adjusts the
   * conditions to reflect the new position of an input if that input ends up being shifted to the
   * right.
   *
   * @param multiJoinRel the source MultiJoinRel
   * @param destConds the array where the join conditions will be copied
   * @param destJoinTypes the array where the join types will be copied
   * @param destPos starting position in the array where the copying starts
   * @param adjustmentAmount if > 0, the amount the RexInputRefs in the join conditions need to be
   *     adjusted by
   * @param srcFields the source fields that the original join conditions are referencing
   * @param destFields the destination fields that the new join conditions will be referencing
   */
  private void copyOuterJoinInfo(
      MultiJoinRel multiJoinRel,
      RexNode[] destConds,
      JoinRelType[] destJoinTypes,
      int destPos,
      int adjustmentAmount,
      RelDataTypeField[] srcFields,
      RelDataTypeField[] destFields) {
    RexNode[] srcConds = multiJoinRel.getOuterJoinConditions();
    JoinRelType[] srcJoinTypes = multiJoinRel.getJoinTypes();
    RexBuilder rexBuilder = multiJoinRel.getCluster().getRexBuilder();

    int len = srcConds.length;
    System.arraycopy(srcJoinTypes, 0, destJoinTypes, destPos, len);

    if (adjustmentAmount == 0) {
      System.arraycopy(srcConds, 0, destConds, 0, len);
    } else {
      int nFields = srcFields.length;
      int[] adjustments = new int[nFields];
      for (int idx = 0; idx < nFields; idx++) {
        adjustments[idx] = adjustmentAmount;
      }
      for (int i = 0; i < len; i++) {
        if (srcConds[i] != null) {
          destConds[i + destPos] =
              srcConds[i].accept(
                  new RelOptUtil.RexInputConverter(rexBuilder, srcFields, destFields, adjustments));
        }
      }
    }
  }
コード例 #8
0
ファイル: DTUHypothesis.java プロジェクト: QimingChen/cs224n
  @Override
  public String toString() {

    StringBuilder sb = new StringBuilder(super.toString()); // Hypothesis's
    // toString()
    sb.append(" segIx=").append(segmentIdx);
    sb.append(" id=").append(System.identityHashCode(this));
    sb.append(" tOpt=").append(System.identityHashCode(rule));
    sb.append(String.format(" c=[%.3f,%.3f,%.3f]", partialScore(), pendingPhrasesCost, h));

    if (pendingPhrases != null) {
      sb.append(" | expired:").append(hasExpired);
      sb.append(" | pending:");

      for (final PendingPhrase<TK, FV> discTargetPhrase : pendingPhrases) {
        DTURule<TK> opt = (DTURule<TK>) discTargetPhrase.concreteOpt.abstractRule;
        sb.append(" {");
        int si = discTargetPhrase.segmentIdx + 1;
        for (int i = si; i < opt.dtus.length; ++i) {
          if (i > si) sb.append(" ");
          sb.append(
              String.format(
                  "{%s} ([s=%d,e=%d,c=%.3f])",
                  opt.dtus[i].toString(" "),
                  discTargetPhrase.firstPosition,
                  discTargetPhrase.lastPosition,
                  discTargetPhrase.futureCosts[i]));
        }
        sb.append("} ");
      }
    }

    return sb.toString();
  }
コード例 #9
0
ファイル: DTUHypothesis.java プロジェクト: QimingChen/cs224n
  @Override
  public void debug() {
    System.err.println("###################");
    System.err.printf(
        "hypothesis [class=%s,id=%d,pos=%d,expired=%s,pending=%d]: %s\n",
        getClass(),
        System.identityHashCode(this),
        featurizable.targetPosition,
        hasExpired,
        pendingPhrases.size(),
        this);
    System.err.printf(
        "parent hypothesis [class=%s,id=%d,pos=%d,expired=%s]: %s\n",
        preceedingDerivation.getClass(),
        System.identityHashCode(preceedingDerivation),
        preceedingDerivation.featurizable.targetPosition,
        preceedingDerivation.hasExpired(),
        preceedingDerivation);
    System.err.println("pendingPhrasesCost: " + pendingPhrasesCost);

    DTUHypothesis<TK, FV> hyp = this;
    if (hyp.isDone() != hyp.featurizable.done) {
      System.err.println("Error in AbstractBeamInferer with: " + hyp);
      System.err.println("isDone(): " + hyp.isDone());
      System.err.println("pending phrases: " + hyp.pendingPhrases.size());
      System.err.println("f.done: " + hyp.featurizable.done);
      Derivation<TK, FV> curHyp = hyp;
      while (curHyp != null) {
        System.err.println("  " + curHyp.toString());
        curHyp = curHyp.preceedingDerivation;
      }
      throw new RuntimeException();
    }
  }
コード例 #10
0
  private List<String> buildPySparkShellCommand(Map<String, String> env) throws IOException {
    // For backwards compatibility, if a script is specified in
    // the pyspark command line, then run it using spark-submit.
    if (!appArgs.isEmpty() && appArgs.get(0).endsWith(".py")) {
      System.err.println(
          "Running python applications through 'pyspark' is not supported as of Spark 2.0.\n"
              + "Use ./bin/spark-submit <python file>");
      System.exit(-1);
    }

    checkArgument(appArgs.isEmpty(), "pyspark does not support any application options.");

    // When launching the pyspark shell, the spark-submit arguments should be stored in the
    // PYSPARK_SUBMIT_ARGS env variable.
    constructEnvVarArgs(env, "PYSPARK_SUBMIT_ARGS");

    // The executable is the PYSPARK_DRIVER_PYTHON env variable set by the pyspark script,
    // followed by PYSPARK_DRIVER_PYTHON_OPTS.
    List<String> pyargs = new ArrayList<>();
    pyargs.add(firstNonEmpty(System.getenv("PYSPARK_DRIVER_PYTHON"), "python"));
    String pyOpts = System.getenv("PYSPARK_DRIVER_PYTHON_OPTS");
    if (!isEmpty(pyOpts)) {
      pyargs.addAll(parseOptionString(pyOpts));
    }

    return pyargs;
  }
コード例 #11
0
 private boolean handshake() {
   boolean res;
   long started = System.currentTimeMillis();
   do {
     try {
       res = myPydevConsoleCommunication.handshake();
     } catch (XmlRpcException ignored) {
       res = false;
     }
     if (res) {
       break;
     } else {
       long now = System.currentTimeMillis();
       if (now - started > APPROPRIATE_TO_WAIT) {
         break;
       } else {
         try {
           Thread.sleep(100);
         } catch (InterruptedException ignored) {
         }
       }
     }
   } while (true);
   return res;
 }
コード例 #12
0
 public Program compileFile(String fileName) {
   String code = "";
   String dummy;
   try {
     long ms = System.currentTimeMillis();
     long atAll = ms;
     BufferedReader r;
     if (fileName.compareToIgnoreCase("stdin") == 0) {
       owner.writeLn("Please type in your Prolog program. EOF is indicated by \"#\".");
       r = new BufferedReader(new InputStreamReader(System.in));
     } else r = new BufferedReader(new FileReader(fileName));
     do {
       dummy = r.readLine();
       if (dummy != null) {
         if (dummy.compareTo("#") == 0) break;
         code += " " + dummy;
       }
     } while (dummy != null);
     owner.debug("File Operations: " + (System.currentTimeMillis() - ms) + " ms.", -1);
     Program p = compile(code);
     return p;
   } catch (Exception io) {
     owner.writeLn("File \"" + fileName + "\" could not be opened.");
     return null;
   }
 } // end of PrologCompiler.compileFile(String)
コード例 #13
0
ファイル: NutchBean.java プロジェクト: albanm/nutchbase
  /** For debugging. */
  public static void main(String[] args) throws Exception {
    final String usage = "NutchBean query";

    if (args.length == 0) {
      System.err.println(usage);
      System.exit(-1);
    }

    final Configuration conf = NutchConfiguration.create();
    final NutchBean bean = new NutchBean(conf);
    try {
      final Query query = Query.parse(args[0], conf);
      final Hits hits = bean.search(query, 10);
      System.out.println("Total hits: " + hits.getTotal());
      final int length = (int) Math.min(hits.getTotal(), 10);
      final Hit[] show = hits.getHits(0, length);
      final HitDetails[] details = bean.getDetails(show);
      final Summary[] summaries = bean.getSummary(details, query);

      for (int i = 0; i < hits.getLength(); i++) {
        System.out.println(" " + i + " " + details[i] + "\n" + summaries[i]);
      }
    } catch (Throwable t) {
      LOG.error("Exception occured while executing search: " + t, t);
      System.exit(1);
    }
    System.exit(0);
  }
コード例 #14
0
    /** {@inheritDoc} */
    @Override
    public Serializable execute() {
      synchronized (mux) {
        execCnt++;
      }

      if (log.isInfoEnabled()) log.info("Executing job: " + jobCtx.getJobId());

      long now = System.currentTimeMillis();

      while (!isCancelled && now < thresholdTime) {
        synchronized (mux) {
          try {
            mux.wait(thresholdTime - now);
          } catch (InterruptedException ignored) {
            // No-op.
          }
        }

        now = System.currentTimeMillis();
      }

      synchronized (mux) {
        return isCancelled ? 1 : 0;
      }
    }
コード例 #15
0
  public static void main(String[] args) {
    long head = 0;
    num_thread = Integer.parseInt(args[0]);
    long total = Long.parseLong(args[1]);
    section = total / ((long) num_thread);
    sectionHead = new long[num_thread];

    long start = System.currentTimeMillis();
    Thread[] threads = new Thread[num_thread];
    for (int i = 0; i < num_thread; i++) {
      threads[i] = new Thread(new CoinFlip(i));
      threads[i].start();
    }
    for (int j = 0; j < num_thread; j++) {
      try {
        threads[j].join();
        head = head + sectionHead[j];
      } catch (InterruptedException e) {
        System.out.println(
            "Thread interrupted.  Exception: " + e.toString() + " Message: " + e.getMessage());
        return;
      }
    }
    long end = System.currentTimeMillis();

    System.out.println(head + " heads in " + args[1] + " coin tosses");
    System.out.println("Elapsed time: " + ((end - start)) + "ms");
  }
コード例 #16
0
ファイル: HavenPanel.java プロジェクト: ProPuke/hafen-client
 public void run() {
   try {
     uglyjoglhack();
     if (state == null)
       throw (new RuntimeException("State applier is still null after redraw"));
     synchronized (drawfun) {
       drawfun.notifyAll();
     }
     while (true) {
       long then = System.currentTimeMillis();
       int waited = 0;
       synchronized (drawfun) {
         while ((curdraw = bufdraw) == null) drawfun.wait();
         bufdraw = null;
         drawfun.notifyAll();
         waited += System.currentTimeMillis() - then;
       }
       CPUProfile.Frame curf = null;
       if (Config.profile) curdraw.pf = curf = rprof.new Frame();
       uglyjoglhack();
       if (curf != null) {
         curf.tick("aux");
         curf.fin();
       }
       long now = System.currentTimeMillis();
       waited += now - curdraw.doneat;
       ridle = (ridle * 0.95) + (((double) waited / ((double) (now - then))) * 0.05);
       curdraw = null;
     }
   } catch (InterruptedException e) {
     return;
   }
 }
コード例 #17
0
  public void run(String[] args) {

    DatabaseFactory factory = new DatabaseFactory();
    if (System.getProperty("user.dir").isEmpty()) {
      System.out.println("user.dir is incorrect");
    }
    if (System.getProperty("fizteh.db.dir").isEmpty()) {
      System.out.println("fizteh.db.dir is incorrect");
    }

    Path pathDirection =
        Paths.get(System.getProperty("user.dir")).resolve(System.getProperty("fizteh.db.dir"));

    String dir = pathDirection.toString();

    DatabaseProvider dProvider = factory.create(dir);

    if (args.length == 0) {

      interactiveMode(dProvider);
    } else {

      pocketMode(args, dProvider);
    }
  }
コード例 #18
0
ファイル: BaseConsumer.java プロジェクト: jatsh/arch
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
コード例 #19
0
ファイル: PL02BranchGroup.java プロジェクト: bgarrels/jCAE
 /**
  * @param colors A color buffer
  * @param i The index in this buffer where to put the 12 components of this quad
  */
 public void updateColors(float[] colors, int i) {
   float[] baseColor = getColorForOrder(groupIdx, 6);
   System.arraycopy(baseColor, 0, colors, i, 3);
   System.arraycopy(baseColor, 0, colors, i + 3, 3);
   System.arraycopy(baseColor, 0, colors, i + 6, 3);
   System.arraycopy(baseColor, 0, colors, i + 9, 3);
 }
コード例 #20
0
ファイル: ActionServlet.java プロジェクト: fnppl/openSDX
  // Velocity init
  public static void initVelocity() {
    if (velocityCatch == null) {
      System.out.println("init VM");
      velocityCatch = new Object();

      Properties props = new Properties();
      props.setProperty("input.encoding", "UTF-8");
      props.setProperty("output.encoding", "UTF-8");

      if (getConfig().getChild("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", getConfig().getChildText("vmtemplatepath"));
      }
      if (System.getProperty("vmtemplatepath") != null) {
        props.setProperty("file.resource.loader.path", System.getProperty("vmtemplatepath"));
        // Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
        // System.getProperty("vmtemplatepath"));//oder new FIle()?
      }
      System.out.println("vmtemplatepath=" + props.getProperty("vmtemplatepath"));
      try {
        Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, VeloLog.getInstance());
        Velocity.init(props);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
コード例 #21
0
 public PropertyDescriptor[] getPropertyDescriptors() {
   PropertyDescriptor[] pds = super.properties;
   PropertyDescriptor[] ps = new PropertyDescriptor[pds.length + properties.length];
   System.arraycopy(pds, 0, ps, 0, pds.length);
   System.arraycopy(properties, 0, ps, pds.length, properties.length);
   return ps;
 }
コード例 #22
0
    protected void addTimeStamp(ClassNode node) {
      if (node.getDeclaredField(Verifier.__TIMESTAMP)
          == null) { // in case if verifier visited the call already
        FieldNode timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP,
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression(System.currentTimeMillis()));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);

        timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()),
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression((long) 0));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);
      }
    }
コード例 #23
0
ファイル: IdPreMap.java プロジェクト: fpapai/basex
 /**
  * Adds a record to the table and the ID index.
  *
  * @param i index in the table where the record should be inserted
  * @param pre pre value
  * @param fid first ID value
  * @param nid last ID value
  * @param inc increment value
  * @param oid original ID value
  */
 private void add(
     final int i, final int pre, final int fid, final int nid, final int inc, final int oid) {
   if (rows == pres.length) {
     final int s = Array.newSize(rows);
     pres = Arrays.copyOf(pres, s);
     fids = Arrays.copyOf(fids, s);
     nids = Arrays.copyOf(nids, s);
     incs = Arrays.copyOf(incs, s);
     oids = Arrays.copyOf(oids, s);
   }
   if (i < rows) {
     final int destPos = i + 1;
     final int length = rows - i;
     System.arraycopy(pres, i, pres, destPos, length);
     System.arraycopy(fids, i, fids, destPos, length);
     System.arraycopy(nids, i, nids, destPos, length);
     System.arraycopy(incs, i, incs, destPos, length);
     System.arraycopy(oids, i, oids, destPos, length);
   }
   pres[i] = pre;
   fids[i] = fid;
   nids[i] = nid;
   incs[i] = inc;
   oids[i] = oid;
   ++rows;
 }
コード例 #24
0
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
コード例 #25
0
 @NotNull
 public static byte[] adaptiveLoadBytes(@NotNull InputStream stream) throws IOException {
   byte[] bytes = new byte[4096];
   List<byte[]> buffers = null;
   int count = 0;
   int total = 0;
   while (true) {
     int n = stream.read(bytes, count, bytes.length - count);
     if (n <= 0) break;
     count += n;
     if (total > 1024 * 1024 * 10) throw new FileTooBigException("File too big " + stream);
     total += n;
     if (count == bytes.length) {
       if (buffers == null) {
         buffers = new ArrayList<byte[]>();
       }
       buffers.add(bytes);
       int newLength = Math.min(1024 * 1024, bytes.length * 2);
       bytes = new byte[newLength];
       count = 0;
     }
   }
   byte[] result = new byte[total];
   if (buffers != null) {
     for (byte[] buffer : buffers) {
       System.arraycopy(buffer, 0, result, result.length - total, buffer.length);
       total -= buffer.length;
     }
   }
   System.arraycopy(bytes, 0, result, result.length - total, total);
   return result;
 }
コード例 #26
0
  @Override
  public final void runBare() throws Throwable {
    // Patch a bug with maven that does not pass properly the system property
    // with an empty value
    if ("org.hsqldb.jdbcDriver".equals(System.getProperty("gatein.test.datasource.driver"))) {
      System.setProperty("gatein.test.datasource.password", "");
    }

    //
    log.info("Running unit test:" + getName());
    for (Map.Entry<?, ?> entry : System.getProperties().entrySet()) {
      if (entry.getKey() instanceof String) {
        String key = (String) entry.getKey();
        log.debug(key + "=" + entry.getValue());
      }
    }

    //
    beforeRunBare();

    //
    try {
      super.runBare();
      log.info("Unit test " + getName() + " completed");
    } catch (Throwable throwable) {
      log.error("Unit test " + getName() + " did not complete", throwable);

      //
      throw throwable;
    } finally {
      afterRunBare();
    }
  }
コード例 #27
0
 /**
  * invoke as: <CODE>
  * java -cp &lt;classpath&gt; parallel.distributed.PDBTExecSingleCltWrkInitSrv [workers_port(7890)] [client_port(7891)]
  * </CODE>
  *
  * @param args String[]
  */
 public static void main(String[] args) {
   int wport = 7890; // default port
   int cport = 7891;
   if (args.length > 0) {
     try {
       wport = Integer.parseInt(args[0]);
     } catch (Exception e) {
       e.printStackTrace();
       usage();
       System.exit(-1);
     }
     if (args.length > 1) {
       try {
         cport = Integer.parseInt(args[1]);
       } catch (Exception e) {
         e.printStackTrace();
         usage();
         System.exit(-1);
       }
     }
   }
   PDBTExecSingleCltWrkInitSrv server = new PDBTExecSingleCltWrkInitSrv(wport, cport);
   try {
     server.run();
   } catch (Exception e) {
     e.printStackTrace();
     System.err.println("Server exits due to exception.");
   }
 }
コード例 #28
0
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
 /**
  * 验证项目是否ok
  *
  * @param contextPath 项目路径
  */
 public static boolean isdomainok(String contextPath, String securityKey, String domiankey) {
   try {
     if (contextPath.indexOf("127.0.") > -1 || contextPath.indexOf("192.168.") > -1) {
       return true;
     }
     String dedomaininfo = PurseSecurityUtils.decryption(domiankey, securityKey);
     Gson gson = new Gson();
     JsonParser jsonParser = new JsonParser();
     JsonObject jsonObject = jsonParser.parse(dedomaininfo).getAsJsonObject();
     Map<String, String> map =
         gson.fromJson(jsonObject, new TypeToken<Map<String, String>>() {}.getType());
     String domain = map.get("domain");
     if (contextPath.indexOf(domain) < 0) {
       System.exit(2);
       return false;
     }
     String dt = map.get("dt");
     if (com.yizhilu.os.core.util.StringUtils.isNotEmpty(dt)) {
       Date t = DateUtils.toDate(dt, "yyyy-MM-dd");
       if (t.compareTo(new Date()) < 0) {
         System.exit(3);
         return false;
       }
     }
     return true;
   } catch (Exception e) {
     return false;
   }
 }
コード例 #29
0
  public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;

    try {
      serverSocket = new ServerSocket(10008);
      System.out.println("Enroll: 130050131071");
      System.out.println("Connection Socket Created");
      try {
        while (true) {
          System.out.println("Waiting for Connection");
          new EchoServer2(serverSocket.accept());
        }
      } catch (IOException e) {
        System.err.println("Accept failed.");
        System.exit(1);
      }
    } catch (IOException e) {
      System.err.println("Could not listen on port: 10008.");
      System.exit(1);
    } finally {
      try {
        serverSocket.close();
      } catch (IOException e) {
        System.err.println("Could not close port: 10008.");
        System.exit(1);
      }
    }
  }
コード例 #30
0
    protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }