List of usage examples for java.lang StringBuffer append
@Override public synchronized StringBuffer append(double d)
From source file:grnet.filter.XMLFiltering.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { Core core = new Core(); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName()); System.out.println("Number of files to filter:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); FilteringReport report = null; if (enviroment.getArguments().getProps().getProperty(Constants.createReport) .equalsIgnoreCase("true")) { report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderFilteredIn().getName()); }//from w ww. j a v a 2s .c o m ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(enviroment.dataProviderFilteredIn.getName()); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries()); if (xmlIsFilteredIn) { logString.append(" " + "FilteredIn"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData); report.raiseFilteredInFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } else { logString.append(" " + "FilteredOut"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData); report.raiseFilteredOutFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } } if (report != null) { report.appendXPathExpression(enviroment.getArguments().getQueries()); report.appendGeneralInfo(); } System.out.println("Filtering is done."); } } }
From source file:grnet.validation.XMLValidation.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { String schemaUrl = enviroment.getArguments().getSchemaURL(); Core core = new Core(schemaUrl); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Validating repository:" + sourceFile.getName()); System.out.println("Number of files to validate:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); System.out.println("Validating against schema:" + schemaUrl + "..."); ValidationReport report = null; if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) { report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderValid().getName()); }/*from w ww . j av a 2s. co m*/ ConnectionFactory factory = new ConnectionFactory(); factory.setHost(enviroment.getArguments().getQueueHost()); factory.setUsername(enviroment.getArguments().getQueueUserName()); factory.setPassword(enviroment.getArguments().getQueuePassword()); while (iterator.hasNext()) { StringBuffer logString = new StringBuffer(); logString.append(sourceFile.getName()); logString.append(" " + schemaUrl); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsValid = core.validateXMLSchema(xmlFile); if (xmlIsValid) { logString.append(" " + "Valid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { report.raiseValidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { logString.append(" " + "Invalid"); slf4jLogger.info(logString.toString()); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes()); channel.close(); connection.close(); try { if (report != null) { if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true")) report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData, core.getReason()); report.raiseInvalidFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } if (report != null) { report.writeErrorBank(core.getErrorBank()); report.appendGeneralInfo(); } System.out.println("Validation is done."); } } }
From source file:ReplayTest.java
public static void main(String[] args) throws IOException { int cnt = 0;//from www . j a va2s . c om String operateTime = ""; String operateType = ""; String uuid = ""; String programId = ""; List<String> lines = Files.readLines(new File("e:\\test\\sample4.txt"), Charsets.UTF_8); System.out.println(lines.size()); for (String value1 : lines) { String[] values = value1.split(SPLIT_T); //logArr16?operateDate=2014-04-25 17:59:59 621, operateType=STARTUP, deviceCode=010333501065233, versionId=, mac=10:48:b1:06:4d:23, platformId=00000032AmlogicMDZ-05-201302261821793, ipAddress=60.10.133.10 if (values.length != 16) { continue; } String logContent = values[15]; if (logContent == null || logContent.trim().length() <= 0) { System.out.println("logContent"); return; } String[] contentArr = logContent.split(COMMA_SIGN);//content if (contentArr == null || contentArr.length != 3) { System.out.println("logContentArr:" + contentArr.length); return; } StringBuffer stringBuffer = new StringBuffer(); //1.CNTVID?? stringBuffer.append(StringsUtils.getEncodeingStr(values[3])).append(SPLIT); //2.IP? if (null == values[7] || EMPTY.equals(values[7])) { stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT); } else { stringBuffer.append(StringsUtils.getEncodeingStr(values[7].trim())).append(SPLIT); } //3.OperateTtype ? 1: 2:? operateType = StringUtils.substringAfter(contentArr[0].trim(), EQUAL_SIGN); if (null == operateType || EMPTY.equals(operateType)) { stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT); } else if ("on".equals(operateType)) { stringBuffer.append(StringsUtils.getEncodeingStr("1")).append(SPLIT); } else if ("out".equals(operateType)) { stringBuffer.append(StringsUtils.getEncodeingStr("2")).append(SPLIT); } // 4.operateTime ? operateTime = DateUtil.convertDateToString("yyyyMMdd HHmmss", DateUtil.convertStringToDate("yyyy-MM-dd HH:mm:ss SSS", values[10].trim())); if (operateTime == null || EMPTY.equals(operateTime)) { stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT); } else { stringBuffer.append(StringsUtils.getEncodeingStr(operateTime)).append(SPLIT); } //5.url_addr ? stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT); //6.channel? uuid = StringUtils.substringAfter(contentArr[1].trim(), EQUAL_SIGN); if (uuid == null || EMPTY.equals(uuid)) { stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)).append(SPLIT); } else { stringBuffer.append(StringsUtils.getEncodeingStr(uuid)).append(SPLIT); } //7.programId id programId = StringUtils.substringAfter(contentArr[2].trim(), EQUAL_SIGN); if (!programId.matches("\\d+")) { //id???? return; } else { stringBuffer.append(StringsUtils.getEncodeingStr(programId)).append(SPLIT); } //8.EPGCode EPG?,?EPGCode? stringBuffer.append(StringsUtils.getEncodeingStr("06")).append(SPLIT); //9.DataSource??12 stringBuffer.append(DATA_SOURCE).append(SPLIT); //10.Fsource??????? stringBuffer.append(F_SOURCE).append(SPLIT); //11.resolution ?,? stringBuffer.append(StringsUtils.getEncodeingStr(EMPTY)); System.out.println(stringBuffer.toString()); cnt++; } System.out.println(":" + cnt); }
From source file:net.sf.ehcache.distribution.RemoteDebugger.java
/** * A Remote Debugger which prints out the cache size of the monitored cache. * Additional logging messages can be observed by setting the logging level to debug * or trace for net.sf.ehcache.distribution * * @param args path_to_ehcache.xml and a cache name * @throws InterruptedException thrown when it is interrupted. It will keep going until then. *///from www. ja v a 2 s . c om public static void main(String[] args) throws InterruptedException { if (args.length < 1 || args.length > 2) { LOG.info( "Command line to list caches to monitor: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml\n" + "Command line to monitor a specific cache: java -jar ehcache-remote-debugger.jar path_to_ehcache.xml" + " cacheName"); System.exit(2); } if (!LOG.isTraceEnabled()) { LOG.info("Increase the net.sf.ehcache.distribution logging level to debug or trace to see distributed" + " cache operations as they occur."); } CacheManager manager = new CacheManager(args[0]); String[] cacheNames = manager.getCacheNames(); StringBuffer availableCaches = new StringBuffer(); if (args.length == 1) { for (int i = 0; i < cacheNames.length; i++) { String name = cacheNames[i]; availableCaches.append(name).append(' '); } LOG.info("Available caches are: " + availableCaches); System.exit(1); } else { String cacheName = args[1]; Ehcache cache = manager.getCache(cacheName); if (cache == null) { LOG.error("No cache named " + cacheName + " exists. Available caches are: " + availableCaches); } else { LOG.info("Monitoring cache: " + cacheName); while (true) { Thread.sleep(TWO_SECONDS); LOG.info("Cache size: " + cache.getSize()); } } } }
From source file:MD5.java
public static void main(String[] args) { //String password = args[0]; String password = "test"; MessageDigest digest = null;//from ww w .j av a2s . co m try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { digest.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); StringBuffer printable = new StringBuffer(); for (int i = 0; i < rawData.length; i++) { printable.append(carr[((rawData[i] & 0xF0) >> 4)]); printable.append(carr[(rawData[i] & 0x0F)]); } String phpbbPassword = printable.toString(); System.out.println("PHPBB : " + phpbbPassword); System.out.println("MVNFORUM : " + getMD5_Base64(password)); System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword)); }
From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java
/** * The main method./*from w w w . j a v a2s.c o m*/ * * @param args the command line arguments */ public static void main(String[] args) { GnuParser parser = new GnuParser(); Options opts = FluxbusterCLI.initializeOptions(); CommandLine cli; try { cli = parser.parse(opts, args); if (cli.hasOption('?')) { throw new ParseException(null); } if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) { if (log.isInfoEnabled()) { StringBuffer arginfo = new StringBuffer("\n"); arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n"); arginfo.append("calc-features: " + cli.hasOption('f') + "\n"); arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n"); arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n"); arginfo.append("start-date: " + cli.getOptionValue('d') + "\n"); arginfo.append("end-date: " + cli.getOptionValue('e') + "\n"); log.info(arginfo.toString()); } try { boolean clus = true, feat = true, simil = true, clas = true; if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) { if (!cli.hasOption('g')) { clus = false; } if (!cli.hasOption('f')) { feat = false; } if (!cli.hasOption('s')) { simil = false; } if (!cli.hasOption('c')) { clas = false; } } DBInterfaceFactory.init(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd"); Date logdate = df.parse(cli.getOptionValue('d')); long startTime = logdate.getTime() / 1000; long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000; if (clus) { ClusterGenerator cg = new ClusterGenerator(); List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true); cg.storeClusters(clusters, logdate); } if (feat) { FeatureCalculator calc = new FeatureCalculator(); calc.updateFeatures(logdate); } if (simil) { ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator(); calc2.updateClusterSimilarities(logdate); } if (clas) { Classifier calc3 = new Classifier(); calc3.updateClusterClasses(logdate, 30); } } catch (Exception e) { if (log.isFatalEnabled()) { log.fatal("", e); } } finally { DBInterfaceFactory.shutdown(); } } else { throw new ParseException(null); } } catch (ParseException e1) { PrintWriter writer = new PrintWriter(System.out); HelpFormatter usageFormatter = new HelpFormatter(); usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified " + "then the program will execute as if all of them " + "have been specified. Otherwise, the program will " + "only execute the options specified.", opts, 0, 2, ""); writer.close(); } }
From source file:com.welocalize.dispatcherMW.client.Main.java
public static void main(String[] args) throws InterruptedException, IOException { if (args.length >= 3) { String type = args[0];/* w w w. j a v a 2 s .c o m*/ if (TYPE_TRANSLATE.equalsIgnoreCase(type)) { setbasicURl(args[1]); doJob(args[2], args[3]); return; } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) { setbasicURl(args[1]); checkJobStaus(args[2]); return; } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) { setbasicURl(args[1]); downloadJob(args[2], args[3]); return; } } else if (args.length == 1) { Properties properties = new Properties(); properties.load(new FileInputStream(args[0])); String type = properties.getProperty("type"); setbasicURl(properties.getProperty("URL")); String securityCode = properties.getProperty(JSONPN_SECURITY_CODE); String filePath = properties.getProperty("filePath"); String jobID = properties.getProperty(JSONPN_JOBID); if (TYPE_TRANSLATE.equalsIgnoreCase(type)) { doJob(securityCode, filePath); return; } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) { String status = checkJobStaus(jobID); System.out.println("The Status of Job:" + jobID + " is " + status + ". "); return; } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) { downloadJob(jobID, securityCode); System.out.println("Download Job:" + jobID); return; } } // Print Help Message StringBuffer msg = new StringBuffer(); msg.append("The Input is incorrect.").append("\n"); msg.append("If you want to translate the XLF file, use this command:").append("\n"); msg.append(" translate $URL $securityCode $filePath").append("\n"); msg.append("If you only want to check job status, use this command:").append("\n"); msg.append(" checkStatus $URL $jobID").append("\n"); msg.append("If you only want to download the job file, use this command:").append("\n"); msg.append(" download $URL $jobID $securityCode").append("\n"); System.out.println(msg.toString()); }
From source file:com.digitalgeneralists.assurance.Application.java
public static void main(String[] args) { Logger logger = Logger.getLogger(Application.class); logger.info("App is starting."); Properties applicationProperties = new Properties(); String applicationInfoFileName = "/version.txt"; InputStream inputStream = Application.class.getResourceAsStream(applicationInfoFileName); applicationInfoFileName = null;/*from www. j a v a 2s . co m*/ try { if (inputStream != null) { applicationProperties.load(inputStream); Application.applicationShortName = applicationProperties.getProperty("name"); Application.applicationName = applicationProperties.getProperty("applicationName"); Application.applicationVersion = applicationProperties.getProperty("version"); Application.applicationBuildNumber = applicationProperties.getProperty("buildNumber"); applicationProperties = null; } } catch (IOException e) { logger.warn("Could not load application version information.", e); } finally { try { inputStream.close(); } catch (IOException e) { logger.error("Couldn't close the application version input stream."); } inputStream = null; } javax.swing.SwingUtilities.invokeLater(new Runnable() { private Logger logger = Logger.getLogger(Application.class); public void run() { logger.info("Starting the Swing run thread."); try { Application.installDb(); } catch (IOException e) { logger.fatal("Unable to install the application database.", e); System.exit(1); } catch (SQLException e) { logger.fatal("Unable to install the application database.", e); System.exit(1); } IApplicationUI window = null; ClassPathXmlApplicationContext springContext = null; try { springContext = new ClassPathXmlApplicationContext("/META-INF/spring/app-context.xml"); StringBuffer message = new StringBuffer(256); logger.info(message.append("Spring Context: ").append(springContext)); message.setLength(0); window = (IApplicationUI) springContext.getBean("ApplicationUI"); } finally { if (springContext != null) { springContext.close(); } springContext = null; } if (window != null) { logger.info("Launching the window."); window.display(); } else { logger.fatal("The main application window object is null."); } logger = null; } }); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.BuildRetrofitLexicons.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.GIZA_ROOT_DIR_PARAM, null, true, CommonParams.GIZA_ROOT_DIR_DESC); options.addOption(CommonParams.GIZA_ITER_QTY_PARAM, null, true, CommonParams.GIZA_ITER_QTY_DESC); options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC); options.addOption(OUT_FILE_PARAM, null, true, OUT_FILE_DESC); options.addOption(MIN_PROB_PARAM, null, true, MIN_PROB_DESC); options.addOption(FORMAT_PARAM, null, true, FORMAT_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {//from w w w . ja va 2 s.com CommandLine cmd = parser.parse(options, args); String gizaRootDir = cmd.getOptionValue(CommonParams.GIZA_ROOT_DIR_PARAM); int gizaIterQty = -1; if (cmd.hasOption(CommonParams.GIZA_ITER_QTY_PARAM)) { gizaIterQty = Integer.parseInt(cmd.getOptionValue(CommonParams.GIZA_ITER_QTY_PARAM)); } else { Usage("Specify: " + CommonParams.GIZA_ITER_QTY_PARAM, options); } String outFileName = cmd.getOptionValue(OUT_FILE_PARAM); if (null == outFileName) { Usage("Specify: " + OUT_FILE_PARAM, options); } String indexDir = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM); if (null == indexDir) { Usage("Specify: " + CommonParams.MEMINDEX_DESC, options); } FormatType outType = FormatType.kOrig; String outTypeStr = cmd.getOptionValue(FORMAT_PARAM); if (null != outTypeStr) { if (outTypeStr.equals(ORIG_TYPE)) { outType = FormatType.kOrig; } else if (outTypeStr.equals(WEIGHTED_TYPE)) { outType = FormatType.kWeighted; } else if (outTypeStr.equals(UNWEIGHTED_TYPE)) { outType = FormatType.kUnweighted; } else { Usage("Unknown format type: " + outTypeStr, options); } } float minProb = 0; if (cmd.hasOption(MIN_PROB_PARAM)) { minProb = Float.parseFloat(cmd.getOptionValue(MIN_PROB_PARAM)); } else { Usage("Specify: " + MIN_PROB_PARAM, options); } System.out.println(String.format( "Saving lexicon to '%s' (output format '%s'), keep only entries with translation probability >= %f", outFileName, outType.toString(), minProb)); // We use unlemmatized text here, because lemmatized dictionary is going to be mostly subset of the unlemmatized one. InMemForwardIndex textIndex = new InMemForwardIndex(FeatureExtractor.indexFileName(indexDir, FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID])); InMemForwardIndexFilterAndRecoder filterAndRecoder = new InMemForwardIndexFilterAndRecoder(textIndex); String prefix = gizaRootDir + "/" + FeatureExtractor.mFieldNames[FeatureExtractor.TEXT_UNLEMM_FIELD_ID] + "/"; GizaVocabularyReader answVoc = new GizaVocabularyReader(prefix + "source.vcb", filterAndRecoder); GizaVocabularyReader questVoc = new GizaVocabularyReader(prefix + "target.vcb", filterAndRecoder); GizaTranTableReaderAndRecoder gizaTable = new GizaTranTableReaderAndRecoder(false, // we don't need to flip the table for the purpose prefix + "/output.t1." + gizaIterQty, filterAndRecoder, answVoc, questVoc, (float) FeatureExtractor.DEFAULT_PROB_SELF_TRAN, minProb); BufferedWriter outFile = new BufferedWriter(new FileWriter(outFileName)); for (int srcWordId = 0; srcWordId <= textIndex.getMaxWordId(); ++srcWordId) { GizaOneWordTranRecs tranRecs = gizaTable.getTranProbs(srcWordId); if (null != tranRecs) { String wordSrc = textIndex.getWord(srcWordId); StringBuffer sb = new StringBuffer(); sb.append(wordSrc); for (int k = 0; k < tranRecs.mDstIds.length; ++k) { float prob = tranRecs.mProbs[k]; if (prob >= minProb) { int dstWordId = tranRecs.mDstIds[k]; if (dstWordId == srcWordId && outType != FormatType.kWeighted) continue; // Don't duplicate the word, unless it's probability weighted sb.append(' '); String dstWord = textIndex.getWord(dstWordId); if (null == dstWord) { throw new Exception( "Bug or inconsistent data: Couldn't retriev a word for wordId = " + dstWordId); } if (dstWord.indexOf(':') >= 0) throw new Exception( "Illegal dictionary word '" + dstWord + "' b/c it contains ':'"); sb.append(dstWord); if (outType != FormatType.kOrig) { sb.append(':'); sb.append(outType == FormatType.kWeighted ? prob : 1); } } } outFile.write(sb.toString()); outFile.newLine(); } } outFile.close(); } catch (ParseException e) { e.printStackTrace(); Usage("Cannot parse arguments", options); } catch (Exception e) { e.printStackTrace(); System.err.println("Terminating due to an exception: " + e); System.exit(1); } System.out.println("Terminated successfully!"); }
From source file:PrintServiceWebInterface.java
public static void main(String[] args) throws IOException { // Get the character encoders and decoders we'll need Charset charset = Charset.forName("ISO-8859-1"); CharsetEncoder encoder = charset.newEncoder(); // The HTTP headers we send back to the client are fixed String headers = "HTTP/1.1 200 OK\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n" + "\r\n"; // We'll use two buffers in our response. One holds the fixed // headers, and the other holds the variable body of the response. ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = encoder.encode(CharBuffer.wrap(headers)); ByteBuffer body = ByteBuffer.allocateDirect(16 * 1024); buffers[1] = body;/* w w w . j a v a 2 s .c om*/ // Find all available PrintService objects to describe PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null); // All of the channels we use in this code will be in non-blocking // mode. So we create a Selector object that will block while // monitoring all of the channels and will only stop blocking when // one or more of the channels is ready for I/O of some sort. Selector selector = Selector.open(); // Create a new ServerSocketChannel, and bind it to port 8000. // Note that we have to do this using the underlying ServerSocket. ServerSocketChannel server = ServerSocketChannel.open(); server.socket().bind(new java.net.InetSocketAddress(8000)); // Put the ServerSocketChannel into non-blocking mode server.configureBlocking(false); // Now register the channel with the Selector. The SelectionKey // represents the registration of this channel with this Selector. SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT); for (;;) { // The main server loop. The server runs forever. // This call blocks until there is activity on one of the // registered channels. This is the key method in non-blocking I/O. selector.select(); // Get a java.util.Set containing the SelectionKey objects for // all channels that are ready for I/O. Set keys = selector.selectedKeys(); // Use a java.util.Iterator to loop through the selected keys for (Iterator i = keys.iterator(); i.hasNext();) { // Get the next SelectionKey in the set, and then remove it // from the set. It must be removed explicitly, or it will // be returned again by the next call to select(). SelectionKey key = (SelectionKey) i.next(); i.remove(); // Check whether this key is the SelectionKey we got when // we registered the ServerSocketChannel. if (key == serverkey) { // Activity on the ServerSocketChannel means a client // is trying to connect to the server. if (key.isAcceptable()) { // Accept the client connection, and obtain a // SocketChannel to communicate with the client. SocketChannel client = server.accept(); // Make sure we actually got a connection if (client == null) continue; // Put the client channel in non-blocking mode. client.configureBlocking(false); // Now register the client channel with the Selector, // specifying that we'd like to know when there is // data ready to read on the channel. SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ); } } else { // If the key we got from the Set of keys is not the // ServerSocketChannel key, then it must be a key // representing one of the client connections. // Get the channel from the key. SocketChannel client = (SocketChannel) key.channel(); // If we got here, it should mean that there is data to // be read from the channel, but we double-check here. if (!key.isReadable()) continue; // Now read bytes from the client. We assume that // we get all the client's bytes in one read operation client.read(body); // The data we read should be some kind of HTTP GET // request. We don't bother checking it however since // there is only one page of data we know how to return. body.clear(); // Build an HTML document as our reponse. // The body of the document contains PrintService details StringBuffer response = new StringBuffer(); response.append( "<html><head><title>Printer Status</title></head>" + "<body><h1>Printer Status</h1>"); for (int s = 0; s < services.length; s++) { PrintService service = services[s]; response.append("<h2>").append(service.getName()).append("</h2><table>"); Attribute[] attrs = service.getAttributes().toArray(); for (int a = 0; a < attrs.length; a++) { Attribute attr = attrs[a]; response.append("<tr><td>").append(attr.getName()).append("</td><td>").append(attr) .append("</tr>"); } response.append("</table>"); } response.append("</body></html>\r\n"); // Encode the response into the body ByteBuffer encoder.reset(); encoder.encode(CharBuffer.wrap(response), body, true); encoder.flush(body); body.flip(); // Prepare the body buffer to be drained // While there are bytes left to write while (body.hasRemaining()) { // Write both header and body buffers client.write(buffers); } buffers[0].flip(); // Prepare header buffer for next write body.clear(); // Prepare body buffer for next read // Once we've sent our response, we have no more interest // in the client channel or its SelectionKey client.close(); // Close the channel. key.cancel(); // Tell Selector to stop monitoring it. } } } }