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()); } } }
/** * 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; } }
public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * This is for debug only: print out training matrices in a CSV type format so that the matrices * can be examined in a spreadsheet program for debugging purposes. */ private void WriteCSVfile( List<String> rowNames, List<String> colNames, float[][] buf, String fileName) { p("tagList.size()=" + tagList.size()); try { FileWriter fw = new FileWriter(fileName + ".txt"); PrintWriter bw = new PrintWriter(new BufferedWriter(fw)); // write the first title row: StringBuffer sb = new StringBuffer(500); for (int i = 0, size = colNames.size(); i < size; i++) { sb.append("," + colNames.get(i)); } bw.println(sb.toString()); // loop on remaining rows: for (int i = 0, size = buf.length; i < size; i++) { sb.delete(0, sb.length()); sb.append(rowNames.get(i)); for (int j = 0, size2 = buf[i].length; j < size2; j++) { sb.append("," + buf[i][j]); } bw.println(sb.toString()); } bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
// --------------------------------actionConnect------------------------------ private void actionConnect() { if (oParty == null) { JOptionPane.showMessageDialog(frame, "Make a party before trying to connect."); return; } String[] oResults = (String[]) DialogManager.show(DialogManager.CONNECT, frame); if (oResults[DialogManager.RETURN_IP].equals("cancel")) return; lblStatus3.setText("Connecting..."); try { oConn.connect( oResults[DialogManager.RETURN_IP], Integer.parseInt(oResults[DialogManager.RETURN_PORT])); } catch (UnknownHostException e) { JOptionPane.showMessageDialog( frame, "The IP of the host cannot be determined.", "Unknown Host Exception", JOptionPane.ERROR_MESSAGE); frame.repaint(); return; } catch (IOException e) { JOptionPane.showMessageDialog( frame, e.getMessage(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE); frame.repaint(); return; } echo("Connected to opponent!"); tConn = new Thread(oConn, "conn"); tConn.start(); tMain = new Thread(this, "main"); tMain.start(); }
public int doEndTag() throws JspException { if ((jspFile.indexOf("..") >= 0) || (jspFile.toUpperCase().indexOf("/WEB-INF/") != 0) || (jspFile.toUpperCase().indexOf("/META-INF/") != 0)) throw new JspTagException("Invalid JSP file " + jspFile); InputStream in = pageContext.getServletContext().getResourceAsStream(jspFile); if (in == null) throw new JspTagException("Unable to find JSP file: " + jspFile); InputStreamReader reader = new InputStreamReader(in); JspWriter out = pageContext.getOut(); try { out.println("<body>"); out.println("<pre>"); for (int ch = in.read(); ch != -1; ch = in.read()) if (ch == '<') out.print("<"); else out.print((char) ch); out.println("</pre>"); out.println("</body>"); } catch (IOException ex) { throw new JspTagException("IOException: " + ex.toString()); } return super.doEndTag(); }
public void processFile(String inputFileName) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName)))); String[] headers = reader.readLine().split(SEPARATOR); for (String s : headers) { attrByValue.put(s, new HashSet<String>()); } String line = null; while ((line = reader.readLine()) != null) { String[] columnValues = line.split(SEPARATOR); if (columnValues.length != headers.length) { System.err.println("There is a huge problem with data file"); } for (int i = 0; i < columnValues.length; i++) { attrByValue.get(headers[i]).add(columnValues[i]); } } reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) { BufferedImage destinationImage = generateDestinationImage(); Graphics2D graphics2D = destinationImage.createGraphics(); AffineTransform transformation = AffineTransform.getScaleInstance( ((double) getQualifiedWidth() / bufferedImage.getWidth()), ((double) getQualifiedHeight() / bufferedImage.getHeight())); graphics2D.drawRenderedImage(bufferedImage, transformation); graphics2D.addRenderingHints(retrieveRenderingHints()); try { if (target instanceof File) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "File")); ImageIO.write(destinationImage, imageType.toString(), (File) target); } else if (target instanceof ImageOutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream")); ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target); } else if (target instanceof OutputStream) { LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream")); ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target); } else { target = null; } } catch (IOException e) { e.printStackTrace(); } return target; }
private void handleKeepAlive() { Connection c = null; try { netCode = ois.readInt(); c = checkConnectionNetCode(); if (c != null && c.getState() == Connection.STATE_CONNECTED) { oos.writeInt(ACK_KEEP_ALIVE); oos.flush(); System.out.println("->ACK_KEEP_ALIVE"); // $NON-NLS-1$ } else { System.out.println("->NOT_CONNECTED"); // $NON-NLS-1$ oos.writeInt(NOT_CONNECTED); oos.flush(); } } catch (IOException e) { System.out.println("handleKeepAlive: " + e.getMessage()); // $NON-NLS-1$ if (c != null) { c.setState(Connection.STATE_DISCONNECTED); System.out.println( "Connection closed with " + c.getRemoteAddress() + //$NON-NLS-1$ ":" + c.getRemotePort()); // $NON-NLS-1$ } } }
/** * compare the byte-array representation of two TaskObjects. * * @param f TaskObject * @param s TaskObject * @return true if the two arguments have the same byte-array */ private boolean sameBytes(TaskObject f, TaskObject s) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(f); byte[] fs = bos.toByteArray(); out.writeObject(s); byte[] ss = bos.toByteArray(); if (fs.length != ss.length) return false; for (int i = 0; i < fs.length; i++) { if (fs[i] != ss[i]) return false; } return true; } catch (IOException e) { e.printStackTrace(); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } try { bos.close(); } catch (IOException e) { // ignore } } } }
/** * Pack the structure to the network message * * @return the network message in byte[] * @throws MeasurementError stream writer failed */ public byte[] getByteArray() throws MeasurementError { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(byteOut); try { dataOut.writeInt(type); dataOut.writeInt(burstCount); dataOut.writeInt(packetNum); dataOut.writeInt(intervalNum); dataOut.writeLong(timestamp); dataOut.writeInt(packetSize); dataOut.writeInt(seq); dataOut.writeInt(udpInterval); } catch (IOException e) { throw new MeasurementError("Create rawpacket failed! " + e.getMessage()); } byte[] rawPacket = byteOut.toByteArray(); try { byteOut.close(); } catch (IOException e) { throw new MeasurementError("Error closing outputstream!"); } return rawPacket; }
/** * This is for book production only: print out training matrices in a Latex type format so that * the matrices can be inserted into my manuscript: * * <p>\begin{table}[htdp] \caption{Runtimes by Method} \centering * * <p>\begin{tabular}{|l|l|l|} \hline \textbf{Class.method name}&\textbf{Percent of total * runtime}&\textbf{Percent in this method}\\ \hline Chess.main&97.7&0.0\\ * GameSearch.playGame&96.5&0.0\\ * * <p>Chess.calcPieceMoves&1.7&0.8\\ \hline \end{tabular} * * <p>\label{tab:runtimes_by_method} \end{table} */ private void WriteLatexFile( List<String> rowNames, List<String> colNames, float[][] buf, String fileName) { p("tagList.size()=" + tagList.size()); int SKIP = 6; try { FileWriter fw = new FileWriter(fileName + ".latex"); PrintWriter bw = new PrintWriter(new BufferedWriter(fw)); int size = colNames.size() - SKIP; bw.print("\\begin{table*}[htdp]\n\\caption{ADD CAPTION}\\centering\\begin{tabular}{|"); for (int i = 0; i < size + 1; i++) bw.print("l|"); bw.println("}\n\\hline"); bw.print(" &"); for (int i = 0; i < size; i++) { bw.print("\\emph{" + colNames.get(i) + "}"); if (i < (size - 1)) bw.print("&"); } bw.println("\\\\\n\\hline"); // bw.printf(format, args) // loop on remaining rows: for (int i = 0, size3 = buf.length - SKIP; i < size3; i++) { bw.print(rowNames.get(i) + "&"); for (int j = 0, size2 = buf[i].length - SKIP; j < size2; j++) { bw.printf("%.2f", buf[i][j]); if (j < (size2 - 1)) bw.print("&"); } bw.println("\\\\"); } bw.println("\\hline\n\\end{tabular}\n\\label{tab:CHANGE_THIS_LABEL}\n\\end{table*}"); bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
/** * 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(); } }
/** * Checks for string in output stream. String must be contained within one line. * * @param ostream send read data to this output stream (usually System.out) * @param checkFor the string to check for * @param regexp if true, the string is considered a regular expression * @param copyToFile if non-null, the output is copied to this file */ public OutputStreamChecker( OutputStream ostream, String checkFor, boolean regexp, File copyToFile) { this.ostream = ostream; this.checkFor = checkFor; this.regexp = regexp; lastLine = null; buf = null; bufOffset = 0; lastLine = new StringBuffer(); if (!regexp) buf = new char[checkFor.length()]; found = false; foundLine = null; out = null; this.copyToFile = copyToFile; if (copyToFile != null) { try { out = new PrintWriter(new BufferedWriter(new FileWriter(this.copyToFile))); } catch (IOException e) { System.out.println(e.getMessage()); out = null; } } listeners = new ArrayList<OutputStreamCheckerListener>(); }
/** * Read parse trees from a Reader. * * @param filename * @param in The <code>Reader</code> * @param simplifiedTagset If `true`, convert part-of-speech labels to a simplified version of the * EAGLES tagset, where the tags do not include extensive morphological analysis * @param aggressiveNormalization Perform aggressive "normalization" on the trees read from the * provided corpus documents: split multi-word tokens into their constituent words (and infer * parts of speech of the constituent words). * @param retainNER Retain NER information in preterminals (for later use in * `MultiWordPreprocessor) and add NER-specific parents to single-word NE tokens * @param detailedAnnotations Retain detailed tree node annotations. These annotations on parse * tree constituents may be useful for e.g. training a parser. */ public SpanishXMLTreeReader( String filename, Reader in, boolean simplifiedTagset, boolean aggressiveNormalization, boolean retainNER, boolean detailedAnnotations) { TreebankLanguagePack tlp = new SpanishTreebankLanguagePack(); this.simplifiedTagset = simplifiedTagset; this.detailedAnnotations = detailedAnnotations; stream = new ReaderInputStream(in, tlp.getEncoding()); treeFactory = new LabeledScoredTreeFactory(); treeNormalizer = new SpanishTreeNormalizer(simplifiedTagset, aggressiveNormalization, retainNER); DocumentBuilder parser = XMLUtils.getXmlParser(); try { final Document xml = parser.parse(stream); final Element root = xml.getDocumentElement(); sentences = root.getElementsByTagName(NODE_SENT); sentIdx = 0; } catch (SAXException e) { System.err.println("Parse exception while reading " + filename); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public ByteBuffer run(Retriever retriever) { if (!retriever.getState().equals(Retriever.RETRIEVER_STATE_SUCCESSFUL)) return null; HTTPRetriever htr = (HTTPRetriever) retriever; if (htr.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { // Mark tile as missing to avoid excessive attempts MercatorTiledImageLayer.this.levels.markResourceAbsent(tile); return null; } if (htr.getResponseCode() != HttpURLConnection.HTTP_OK) return null; URLRetriever r = (URLRetriever) retriever; ByteBuffer buffer = r.getBuffer(); String suffix = WWIO.makeSuffixForMimeType(htr.getContentType()); if (suffix == null) { return null; // TODO: log error } String path = tile.getPath().substring(0, tile.getPath().lastIndexOf(".")); path += suffix; final File outFile = WorldWind.getDataFileStore().newFile(path); if (outFile == null) return null; try { WWIO.saveBuffer(buffer, outFile); return buffer; } catch (IOException e) { e.printStackTrace(); // TODO: log error return null; } }
public void run() { System.out.println("ExeUDPServer开始监听..." + UDP_PORT); DatagramSocket ds = null; try { ds = new DatagramSocket(UDP_PORT); } catch (BindException e) { System.out.println("UDP端口使用中...请重关闭程序启服务器"); } catch (SocketException e) { e.printStackTrace(); } while (ds != null) { DatagramPacket dp = new DatagramPacket(buf, buf.length); try { ds.receive(dp); // 得到把该数据包发来的端口和Ip int rport = dp.getPort(); InetAddress addr = dp.getAddress(); String recvStr = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server receive:" + recvStr + " from " + addr + " " + rport); // 给客户端回应 String sendStr = "echo of " + recvStr; byte[] sendBuf; sendBuf = sendStr.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, rport); ds.send(sendPacket); } catch (IOException e) { e.printStackTrace(); } } }
public void generateDiagram(String outputDirectory, File dotFile) { try { Runtime run = Runtime.getRuntime(); Process pr = run.exec( "dot " + dotFile.getAbsolutePath() + " -Tpng -o" + outputDirectory + FILE_SEPARATOR + "graph.png"); pr.waitFor(); // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); // should the output be really printed? // String line; // while ( ( line = buf.readLine() ) != null ) // { // System.out.println(line) ; // } // FIXME how to handle exceptions in listener? } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InterruptedException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
@Override public InputStream inputStream() { try { if (myEncryptionInfo != null) { return null; } InputStream stream = baseInputStream(); if (ENCODING_NONE.equals(myEncoding)) { return stream; } else if (ENCODING_HEX.equals(myEncoding)) { return new HexInputStream(stream); } else if (ENCODING_BASE64.equals(myEncoding)) { stream = new Base64InputStream(stream); final int len = (int) stream.skip(stream.available()); stream.close(); return new SliceInputStream(new Base64InputStream(baseInputStream()), 0, len); } else { System.err.println("unsupported encoding: " + myEncoding); return null; } } catch (IOException e) { e.printStackTrace(); return null; } }
// Starts redirection of streams. public void run() { BufferedReader r = new BufferedReader(new InputStreamReader(in), 1); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out)); byte[] buf = new byte[256]; try { String line; /* This is to check that the distant vm has started, * if such a vm has been provided at construction : * - As soon as we can read something from r BufferedReader, * that means the distant vm is already started. * Thus we signal associated JavaVM object that it is now started. */ if (((line = r.readLine()) != null) && (javaVM != null)) { javaVM.setStarted(); } // Redirects r on w. while (line != null) { w.write(preamble); w.write(line); w.newLine(); w.flush(); line = r.readLine(); } } catch (IOException e) { System.err.println("*** IOException in StreamPipe.run:"); e.printStackTrace(); } }
private void setJasperResourceNames(ToolBoxDTO toolBoxDTO, String barDir) throws BAMToolboxDeploymentException { String jasperDirectory = barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR + File.separator + BAMToolBoxDeployerConstants.JASPER_DIR; if (new File(jasperDirectory).exists()) { toolBoxDTO.setJasperParentDirectory( barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR + File.separator + BAMToolBoxDeployerConstants.JASPER_DIR); Properties properties = new Properties(); try { properties.load( new FileInputStream( barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR + File.separator + BAMToolBoxDeployerConstants.JASPER_META_FILE)); setJasperTabAndJrxmlNames(toolBoxDTO, properties); toolBoxDTO.setDataSource(properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE)); toolBoxDTO.setDataSourceConfiguration( barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR + File.separator + properties.getProperty(BAMToolBoxDeployerConstants.DATASOURCE_CONFIGURATION)); } catch (FileNotFoundException e) { log.error( "No " + BAMToolBoxDeployerConstants.JASPER_META_FILE + " found in dir:" + barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR, e); throw new BAMToolboxDeploymentException( "No " + BAMToolBoxDeployerConstants.JASPER_META_FILE + " found in dir:" + barDir + File.separator + BAMToolBoxDeployerConstants.DASHBOARD_DIR, e); } catch (IOException e) { log.error(e.getMessage(), e); throw new BAMToolboxDeploymentException(e.getMessage(), e); } } else { toolBoxDTO.setJasperParentDirectory(null); toolBoxDTO.setJasperTabs(new ArrayList<JasperTabDTO>()); } }
public static String CreateZip(String[] filesToZip, String zipFileName) { byte[] buffer = new byte[18024]; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); out.setLevel(Deflater.BEST_COMPRESSION); for (int i = 0; i < filesToZip.length; i++) { FileInputStream in = new FileInputStream(filesToZip[i]); String fileName = null; for (int X = filesToZip[i].length() - 1; X >= 0; X--) { if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') { fileName = filesToZip[i].substring(X + 1); break; } else if (X == 0) fileName = filesToZip[i]; } out.putNextEntry(new ZipEntry(fileName)); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); } out.close(); } catch (IllegalArgumentException e) { return "Failed to create zip: " + e.toString(); } catch (FileNotFoundException e) { return "Failed to create zip: " + e.toString(); } catch (IOException e) { return "Failed to create zip: " + e.toString(); } return "Success"; }
public static int driver( String inputMaf, String outputMaf, boolean useCache, boolean sort, boolean addMissing) { Date start = new Date(); int oncoResult = 0; Oncotator tool = new Oncotator(useCache); tool.setSortColumns(sort); tool.setAddMissingCols(addMissing); try { oncoResult = tool.oncotateMaf(new File(inputMaf), new File(outputMaf)); } catch (IOException e) { System.out.println("IO error occurred: " + e.getMessage()); e.printStackTrace(); } catch (OncotatorServiceException e) { System.out.println("Service error occurred: " + e.getMessage()); e.printStackTrace(); } finally { Date end = new Date(); double timeElapsed = (end.getTime() - start.getTime()) / 1000.0; System.out.println("Total number of records processed: " + tool.getNumRecordsProcessed()); if (tool.getBuildNumErrors() > 0) { System.out.println( "Number of records skipped due to incompatible build no: " + tool.getBuildNumErrors()); } System.out.println("Total time: " + timeElapsed + " seconds."); } return oncoResult; }
public static String visitWeb(String urlStr) { URL url = null; HttpURLConnection httpConn = null; InputStream in = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)"); in = httpConn.getInputStream(); return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } return null; }
Parser(String uri) { try { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser = parserFactory.newSAXParser(); ConfigHandler handler = new ConfigHandler(); parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true); parser.parse(new File(uri), handler); } catch (IOException e) { System.out.println("Error reading URI: " + e.getMessage()); } catch (SAXException e) { System.out.println("Error in parsing: " + e.getMessage()); } catch (ParserConfigurationException e) { System.out.println("Error in XML parser configuration: " + e.getMessage()); } // System.out.println("Number of Persons : " + Person.numberOfPersons()); // nameLengthStatistics(); // System.out.println("Number of Publications with authors/editors: " + // Publication.getNumberOfPublications()); // System.out.println("Maximum number of authors/editors in a publication: " + // Publication.getMaxNumberOfAuthors()); // publicationCountStatistics(); // Person.enterPublications(); // Person.printCoauthorTable(); // Person.printNamePartTable(); // Person.findSimilarNames(); }
// Reads the lines that you tell it to via startLine and endLine public void readFile(int startLine, int endLine) { int currentLineNo = 0; BufferedReader in = null; try { in = new BufferedReader( new FileReader( "C:\\Users\\kyle\\Documents\\Tribalwars\\" + villageFileName + ".txt")); // read to startLine while (currentLineNo < startLine) { if (in.readLine() == null) { // early end throw new IOException("File too small"); } currentLineNo++; } // read until endLine while (currentLineNo <= endLine) { String line = in.readLine(); if (line == null) { return; } System.out.println(line); currentLineNo++; } } catch (IOException ex) { System.out.println("Problem reading file.\n" + ex.getMessage()); } finally { try { if (in != null) in.close(); } catch (IOException ignore) { } } }
public void run() { // run this first, ie shutdown the container before closing jarFiles to avoid errors with // classes missing if (callMethod != null) { try { callMethod.invoke(callObject); } catch (Exception e) { System.out.println("Error in shutdown: " + e.toString()); } } // give things a couple seconds to destroy; this way of running is mostly for dev/test where // this should be sufficient try { synchronized (this) { this.wait(2000); } } catch (Exception e) { System.out.println("Shutdown wait interrupted"); } System.out.println( "========== Shutting down Moqui Executable (closing jars, etc) =========="); // close all jarFiles so they will "deleteOnExit" for (JarFile jarFile : jarFileList) { try { jarFile.close(); } catch (IOException e) { System.out.println("Error closing jar [" + jarFile + "]: " + e.toString()); } } }
public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // containing IP ecc. // figure out response String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } socket.close(); }
/** * Gets the token. * * @param scope the scope * @return the token */ private String getToken(String scope) { Process curlProc; String outputString; DataInputStream curlIn = null; String access_token = null; String command = "curl -X POST -H Content-Type:application/x-www-form-urlencoded " + adminUrl + "/oauth2/token --insecure --data" + " client_id=" + client_id + "&" + "client_secret=" + client_secret + "&grant_type=client_credentials&scope=" + scope; try { curlProc = Runtime.getRuntime().exec(command); curlIn = new DataInputStream(curlProc.getInputStream()); while ((outputString = curlIn.readLine()) != null) { JSONObject obj = new JSONObject(outputString); access_token = obj.getString("access_token"); } } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return access_token; }
/** * Unpack received message and fill the structure * * @param cliId corresponding client identifier * @param rawdata network message * @throws MeasurementError stream reader failed */ public MeasurementPacket(ClientIdentifier cliId, byte[] rawdata) throws MeasurementError { this.clientId = cliId; ByteArrayInputStream byteIn = new ByteArrayInputStream(rawdata); DataInputStream dataIn = new DataInputStream(byteIn); try { type = dataIn.readInt(); burstCount = dataIn.readInt(); packetNum = dataIn.readInt(); intervalNum = dataIn.readInt(); timestamp = dataIn.readLong(); packetSize = dataIn.readInt(); seq = dataIn.readInt(); udpInterval = dataIn.readInt(); } catch (IOException e) { throw new MeasurementError("Fetch payload failed! " + e.getMessage()); } try { byteIn.close(); } catch (IOException e) { throw new MeasurementError("Error closing inputstream!"); } }