@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; }
/** * Load a system library from a stream. Copies the library to a temp file and loads from there. * * @param libname name of the library (just used in constructing the library name) * @param is InputStream pointing to the library */ private void loadLibraryFromStream(String libname, InputStream is) { try { File tempfile = createTempFile(libname); OutputStream os = new FileOutputStream(tempfile); logger.debug("tempfile.getPath() = " + tempfile.getPath()); long savedTime = System.currentTimeMillis(); // Leo says 8k block size is STANDARD ;) byte buf[] = new byte[8192]; int len; while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); InputStream lock = new FileInputStream(tempfile); os.close(); double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3; logger.debug("Copying took " + seconds + " seconds."); logger.debug("Loading library from " + tempfile.getPath() + "."); System.load(tempfile.getPath()); lock.close(); } catch (IOException io) { logger.error("Could not create the temp file: " + io.toString() + ".\n"); } catch (UnsatisfiedLinkError ule) { logger.error("Couldn't load copied link file: " + ule.toString() + ".\n"); throw ule; } }
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()); } } }
public ConsoleManager(GlowServer server) { this.server = server; // install Ansi code handler, which makes colors work on Windows AnsiConsole.systemInstall(); for (Handler h : logger.getHandlers()) { logger.removeHandler(h); } // used until/unless gui is created consoleHandler = new FancyConsoleHandler(); // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE)); logger.addHandler(consoleHandler); // todo: why is this here? Runtime.getRuntime().addShutdownHook(new ServerShutdownThread()); // reader must be initialized before standard streams are changed try { reader = new ConsoleReader(); } catch (IOException ex) { logger.log(Level.SEVERE, "Exception initializing console reader", ex); } reader.addCompleter(new CommandCompleter()); // set system output streams System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true)); System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true)); }
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)); }
/** * 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); } } }
/** * main method * * <p>This uses the system properties: * * <ul> * <li><code>rjava.path</code> : path of the rJava package * <li><code>rjava.lib</code> : lib sub directory of the rJava package * <li><code>main.class</code> : main class to "boot", assumes Main if not specified * <li><code>rjava.class.path</code> : set of paths to populate the initiate the class path * </ul> * * <p>and boots the "main" method of the specified <code>main.class</code>, passing the args down * to the booted class * * <p>This makes sure R and rJava are known by the class loader */ public static void main(String[] args) { String rJavaPath = System.getProperty("rjava.path"); if (rJavaPath == null) { System.err.println("ERROR: rjava.path is not set"); System.exit(2); } String rJavaLib = System.getProperty("rjava.lib"); if (rJavaLib == null) { // it is not really used so far, just for rJava.so, so we can guess rJavaLib = rJavaPath + File.separator + "libs"; } RJavaClassLoader cl = new RJavaClassLoader(u2w(rJavaPath), u2w(rJavaLib)); String mainClass = System.getProperty("main.class"); if (mainClass == null || mainClass.length() < 1) { System.err.println("WARNING: main.class not specified, assuming 'Main'"); mainClass = "Main"; } String classPath = System.getProperty("rjava.class.path"); if (classPath != null) { StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator); while (st.hasMoreTokens()) { String dirname = u2w(st.nextToken()); cl.addClassPath(dirname); } } try { cl.bootClass(mainClass, "main", args); } catch (Exception ex) { System.err.println("ERROR: while running main method: " + ex); ex.printStackTrace(); } }
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)
/** * invoke as: <CODE> * java -cp <classpath> 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."); } }
public static void copyFile(String filenameIn, String filenameOut, boolean buffer) throws IOException { long lenIn = new File(filenameIn).length(); if (debug) System.out.println("read " + filenameIn + " len = " + lenIn); InputStream in = new FileInputStream(filenameIn); if (buffer) new BufferedInputStream(in, 10000); OutputStream out = new FileOutputStream(filenameOut); if (buffer) out = new BufferedOutputStream(out, 1000); long start = System.currentTimeMillis(); IO.copyB(in, out, 10000); out.flush(); double took = .001 * (System.currentTimeMillis() - start); out.close(); in.close(); long lenOut = new File(filenameOut).length(); if (debug) System.out.println(" write file= " + filenameOut + " len = " + lenOut); double rate = lenIn / took / (1000 * 1000); String name = buffer ? "buffer" : "no buffer"; System.out.println(" copy (" + name + ") took = " + took + " sec; rate = " + rate + "Mb/sec"); }
/** * 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; }
/** * Periodically ping (that is send a CONNECT_MEDIATOR packet) the BackEnd to detect when the * device is reachable again. When the BackEnd receives a CONNECT_MEDIATOR packet it resets the * input connection --> If blocked waiting for incoming commands, the InputManager thread should * get an IOException. */ public void run() { int attemptCnt = 0; long startTime = System.currentTimeMillis(); try { while (!ping(attemptCnt)) { attemptCnt++; if ((System.currentTimeMillis() - startTime) > maxDisconnectionTime) { throw new ICPException("Max disconnection timeout expired"); } else { waitABit(retryTime); } } // Ping succeeded myLogger.log(Logger.INFO, "Reconnection ping OK."); synchronized (this) { pingOK = true; setReachable(); myKeepAliveManager.update(); // Activate postponed commands flushing waitingForFlush = myStub.flush(); } } catch (ICPException icpe) { // Impossible to reconnect to the BackEnd myLogger.log( Logger.SEVERE, "Impossible to reconnect to the BackEnd (" + System.currentTimeMillis() + ")", icpe); if (myConnectionListener != null) { myConnectionListener.handleConnectionEvent(ConnectionListener.RECONNECTION_FAILURE, null); } } }
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); }
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); } }
/** 基类实现消息监听接口,加上打印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; }
public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage: evaluateCustomMath formula [model containing values]"); System.exit(1); } String formula = args[0]; String filename = args.length == 2 ? args[1] : null; ASTNode math = libsbml.parseFormula(formula); if (math == null) { System.out.println("Invalid formula, aborting."); System.exit(1); } SBMLDocument doc = null; if (filename != null) { doc = libsbml.readSBML(filename); if (doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0) { System.out.println("The models contains errors, please correct them before continuing."); doc.printErrors(); System.exit(1); } // the following maps a list of ids to their corresponding model values // this makes it possible to evaluate expressions involving SIds. SBMLTransforms.mapComponentValues(doc.getModel()); } else { // create dummy document doc = new SBMLDocument(3, 1); } double result = SBMLTransforms.evaluateASTNode(math, doc.getModel()); System.out.println(String.format("%s = %s", formula, result)); }
/** * Terminates with one of the following codes 1 A newer (or same version) jar file is already * installed 0 No newer jar file was found -1 An internal error occurred */ public static void main(String args[]) { if (args.length < 1) { System.err.println("Usage: extcheck [-verbose] <jar file>"); System.exit(-1); } int argIndex = 0; boolean verboseFlag = false; if (args[argIndex].equals("-verbose")) { verboseFlag = true; argIndex++; } String jarName = args[argIndex]; argIndex++; File jarFile = new File(jarName); if (!jarFile.exists()) { ExtCheck.error("Jarfile " + jarName + " does not exist"); } if (argIndex < args.length) { ExtCheck.error("Extra command line argument :" + args[argIndex]); } ExtCheck jt = ExtCheck.create(jarFile, verboseFlag); boolean result = jt.checkInstalledAgainstTarget(); if (result) { System.exit(0); } else { System.exit(1); } }
public static void readFile(String filenameIn, int bufferSize) throws IOException { long lenIn = new File(filenameIn).length(); if (debug) System.out.println("read " + filenameIn + " len = " + lenIn); InputStream in = new FileInputStream(filenameIn); long total = 0; long start = System.currentTimeMillis(); byte[] buffer = new byte[bufferSize]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; total += buffer[0]; } double took = .001 * (System.currentTimeMillis() - start); in.close(); double rate = lenIn / took / (1000 * 1000); System.out.println( " copy (" + bufferSize + ") took = " + took + " sec; rate = " + rate + "Mb/sec total=" + total); }
@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; }
@Before public void dbInit() throws Exception { String configFileName = System.getProperty("user.home"); if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { configFileName += "/.pokerth/config.xml"; } else { configFileName += "/AppData/Roaming/pokerth/config.xml"; } File file = new File(configFileName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0); Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0); String dbAddress = dbAddressNode.getAttribute("value"); Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0); String dbUser = dbUserNode.getAttribute("value"); Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0); String dbPassword = dbPasswordNode.getAttribute("value"); Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0); String dbName = dbNameNode.getAttribute("value"); final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName; Class.forName("com.mysql.jdbc.Driver").newInstance(); dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); }
/** * 验证项目是否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; } }
public void run(String[] args) { File inDir = new File("input/SampleZoomLevel"); File outFile = new File("output/SampleZoomLevel/map.png"); File[] fileList = inDir.listFiles(); int i; // Stitching a map with 4 rows and 4 columns; the program is generalized, // so you can use higher multiples of 4, such as 8 by 8 and 16 by 16. int rows = 4; int cols = 4; int total = rows * cols; BufferedImage images[] = new BufferedImage[total]; try { for (i = 0; i < total; i++) { File inFile = fileList[i]; int c1; int c2; // The code below deals with the naming convention we use // for each map tile. // See the ReadMe for more on the naming convention. String s = inFile.getName().substring(0, 2); c1 = Integer.parseInt(s); s = inFile.getName().substring(3, 5); c2 = Integer.parseInt(s); BufferedImage image = null; image = ImageIO.read(inFile); images[c1 * cols + c2] = image; } } catch (IOException e) { System.err.println(e); System.exit(1); } // Our map tiles are square, with dimensions of 256 by 256 pixels. With 4 rows and //4 // columns, we create a 1024 by 1024 image. BufferedImage outputImage = new BufferedImage(256 * cols, 256 * rows, BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g = outputImage.createGraphics(); // Loop through the rows and columns for (i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { g.drawImage(images[i * cols + j], j * 256, i * 256, 256, 256, null); } } try { ImageIO.write(outputImage, "png", outFile); } catch (IOException e) { System.err.println(e); System.exit(1); } }
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"); }
/** * Main method. * * @param args command-line arguments */ public static void main(final String[] args) { try { // initialize timer final long time = System.nanoTime(); // create session final BaseXClient session = new BaseXClient("localhost", 1984, "admin", "admin"); // version 1: perform command and print returned string System.out.println(session.execute("info")); // version 2 (faster): perform command and pass on result to output stream final OutputStream out = System.out; session.execute("xquery 1 to 10", out); // close session session.close(); // print time needed final double ms = (System.nanoTime() - time) / 1000000d; System.out.println("\n\n" + ms + " ms"); } catch (final IOException ex) { // print exception ex.printStackTrace(); } }
/** * 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); } }
private void indexFiles(String dir, String index, int featureIndex, boolean createNewIndex) throws IOException { ArrayList<String> images = FileUtils.getAllImages(new File(dir), true); IndexWriter iw = LuceneUtils.createIndexWriter( index, createNewIndex, LuceneUtils.AnalyzerType.WhitespaceAnalyzer); // select one feature for the large index: int count = 0; long ms = System.currentTimeMillis(); DocumentBuilder builder = new ChainedDocumentBuilder(); ((ChainedDocumentBuilder) builder).addBuilder(builders[featureIndex]); // ((ChainedDocumentBuilder) builder).addBuilder(builders[0]); for (Iterator<String> iterator = images.iterator(); iterator.hasNext(); ) { count++; if (count > 100 && count % 5000 == 0) { System.out.println( count + " files indexed. " + (System.currentTimeMillis() - ms) / (count) + " ms per file"); } String file = iterator.next(); try { iw.addDocument(builder.createDocument(new FileInputStream(file), file)); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } iw.close(); }
public void initGame() { String cfgname = null; if (isApplet()) { cfgname = getParameter("configfile"); } else { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(System.getProperty("user.dir"))); chooser.setDialogTitle("Choose a config file"); int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { cfgname = chooser.getSelectedFile().getAbsolutePath(); } else { System.exit(0); } // XXX read this as resource! // cfgname = "mygeneratedgame.appconfig"; } gamecfg = new AppConfig("Game parameters", this, cfgname); gamecfg.loadFromFile(); gamecfg.defineFields("gp_", "", "", ""); gamecfg.saveToObject(); initMotionPars(); // unpause and copy settingswhen config window is closed gamecfg.setListener( new ActionListener() { public void actionPerformed(ActionEvent e) { start(); requestGameFocus(); initMotionPars(); } }); defineMedia("simplegeneratedgame.tbl"); setFrameRate(35, 1); }
/** * Constructor. The first time an RJavaClassLoader is created, it is cached as the primary loader. * * @param path path of the rJava package * @param libpath lib sub directory of the rJava package */ public RJavaClassLoader(String path, String libpath) { super(new URL[] {}); // respect rJava.debug level String rjd = System.getProperty("rJava.debug"); if (rjd != null && rjd.length() > 0 && !rjd.equals("0")) verbose = true; if (verbose) System.out.println("RJavaClassLoader(\"" + path + "\",\"" + libpath + "\")"); if (primaryLoader == null) { primaryLoader = this; if (verbose) System.out.println(" - primary loader"); } else { if (verbose) System.out.println(" - NOT primrary (this=" + this + ", primary=" + primaryLoader + ")"); } libMap = new HashMap /*<String,UnixFile>*/(); classPath = new Vector /*<UnixFile>*/(); classPath.add(new UnixDirectory(path + "/java")); rJavaPath = path; rJavaLibPath = libpath; /* load the rJava library */ UnixFile so = new UnixFile(rJavaLibPath + "/rJava.so"); if (!so.exists()) so = new UnixFile(rJavaLibPath + "/rJava.dll"); if (so.exists()) libMap.put("rJava", so); /* load the jri library */ UnixFile jri = new UnixFile(path + "/jri/libjri.so"); String rarch = System.getProperty("r.arch"); if (rarch != null && rarch.length() > 0) { UnixFile af = new UnixFile(path + "/jri" + rarch + "/libjri.so"); if (af.exists()) jri = af; else { af = new UnixFile(path + "/jri" + rarch + "/jri.dll"); if (af.exists()) jri = af; } } if (!jri.exists()) jri = new UnixFile(path + "/jri/libjri.jnilib"); if (!jri.exists()) jri = new UnixFile(path + "/jri/jri.dll"); if (jri.exists()) { libMap.put("jri", jri); if (verbose) System.out.println(" - registered JRI: " + jri); } /* if we are the primary loader, make us the context loader so projects that rely on the context loader pick us */ if (primaryLoader == this) Thread.currentThread().setContextClassLoader(this); if (verbose) { System.out.println("RJavaClassLoader initialized.\n\nRegistered libraries:"); for (Iterator entries = libMap.keySet().iterator(); entries.hasNext(); ) { Object key = entries.next(); System.out.println(" " + key + ": '" + libMap.get(key) + "'"); } System.out.println("\nRegistered class paths:"); for (Enumeration e = classPath.elements(); e.hasMoreElements(); ) System.out.println(" '" + e.nextElement() + "'"); System.out.println("\n-- end of class loader report --"); } }
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); } } }
/** 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); }