// --------------------------------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(); }
@Override public void validatePlatform() throws InstallException { try { boolean valid = true; if (targetConfDir.exists() && !targetConfDir.getType().getName().equals(FileType.FOLDER.getName()) && targetLibDir.exists() && !targetLibDir.getType().getName().equals(FileType.FOLDER.getName())) { valid = false; getPrinter().printErrStatus("LiferayHome", "Cannot find Liferay 5 webapp root."); } if (!valid) throw new InstallException( "Target does not seem a " + getTargetPlatform().getDescription() + " install."); } catch (IOException e) { getPrinter().printErrStatus("Liferay 5 root", e.getMessage()); throw new InstallException(e.getMessage(), e); } getPrinter().printOkStatus("Liferay 5 root"); }
/** * Creates new HTTP requests handler. * * @param hnd Handler. * @param authChecker Authentication checking closure. * @param log Logger. */ GridJettyRestHandler( GridRestProtocolHandler hnd, GridClosure<String, Boolean> authChecker, GridLogger log) { assert hnd != null; assert log != null; this.hnd = hnd; this.log = log; this.authChecker = authChecker; // Init default page and favicon. try { initDefaultPage(); if (log.isDebugEnabled()) log.debug("Initialized default page."); } catch (IOException e) { U.warn(log, "Failed to initialize default page: " + e.getMessage()); } try { initFavicon(); if (log.isDebugEnabled()) log.debug( favicon != null ? "Initialized favicon, size: " + favicon.length : "Favicon is null."); } catch (IOException e) { U.warn(log, "Failed to initialize favicon: " + e.getMessage()); } }
private void server() { new CountDown(60).start(); while (true) { try { Socket socket = serverSock.accept(); System.out.println("New Client:" + socket); if (readyState[6] == 1) { System.out.println("正在游戏中,无法加入"); continue; } for (i = 0; i <= 5; i++) { if (players[i].equals("虚位以待")) break; } if (i > 5) { System.out.println("房间已满,无法加入"); continue; } i++; ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream()); clients.addElement(remoteOut); ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream()); new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start(); } catch (IOException e) { System.out.println(e.getMessage() + ": Failed to connect to client."); try { serverSock.close(); } catch (IOException x) { System.out.println(e.getMessage() + ": Failed to close server socket."); } } } }
public static String readExecutionPlanConfigFile( String fileName, AxisConfiguration axisConfiguration) throws ExecutionPlanConfigurationException { BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try { String filePath = getFilePathFromFilename(fileName, axisConfiguration); bufferedReader = new BufferedReader(new FileReader(filePath)); String line = null; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } } catch (FileNotFoundException e) { throw new ExecutionPlanConfigurationException( "Execution plan file not found, " + fileName + "," + e.getMessage(), e); } catch (IOException e) { throw new ExecutionPlanConfigurationException( "Cannot read the execution plan file, " + fileName + "," + e.getMessage(), e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { log.error("Error occurred when reading the file, " + fileName + "," + e.getMessage(), e); } } return stringBuilder.toString().trim(); }
private String getPublicKey(String pubKeyUrl) { URL url; InputStream in = null; try { url = new URL(pubKeyUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); log.debug("url request in success"); in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine; String separator = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); while ((readLine = br.readLine()) != null) { sb.append(readLine).append(separator); } String result = sb.toString(); result = result.replace("-----BEGIN PUBLIC KEY-----", ""); result = result.replace("-----END PUBLIC KEY-----", ""); return result; } catch (IOException e) { log.error(e.getMessage()); } finally { try { if (in != null) { in.close(); } } catch (IOException e) { log.error(e.getMessage()); } } return null; }
/** * Get the cause of an I/O exception if caused by a possible disk error * * @param ioe an I/O exception * @return cause if the I/O exception is caused by a possible disk error; null otherwise. */ static IOException getCauseIfDiskError(IOException ioe) { if (ioe.getMessage() != null && ioe.getMessage().startsWith(DISK_ERROR)) { return (IOException) ioe.getCause(); } else { return null; } }
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 readEventBuilderConfigurationFile(String filePath) throws EventBuilderConfigurationException { BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try { bufferedReader = new BufferedReader(new FileReader(filePath)); String line; while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } } catch (FileNotFoundException e) { throw new EventBuilderConfigurationException( "Event builder file not found : " + e.getMessage(), e); } catch (IOException e) { throw new EventBuilderConfigurationException( "Cannot read the event builder file : " + e.getMessage(), e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { log.error("Error occurred when reading the file : " + e.getMessage(), e); } } return stringBuilder.toString().trim(); }
// function to do the join use case public static void share() throws Exception { HttpPost method = new HttpPost(url + "/share"); String ipAddress = null; Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); while (en.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) en.nextElement(); if (ni.getName().equals("eth0")) { Enumeration<InetAddress> en2 = ni.getInetAddresses(); while (en2.hasMoreElements()) { InetAddress ip = (InetAddress) en2.nextElement(); if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } break; } } method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } // get present time date = new Date(); long start = date.getTime(); // Execute the vishwa share process Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp); String ch = "alive"; System.out.println("Type kill to unjoin from the grid"); while (!ch.equals("kill")) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); ch = in.readLine(); } p.destroy(); date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/shareAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public static void extractEntryToFile(ZipEntry entry, ZipFile zipSrc, String tempUserDir) throws ResourceNotFoundFault { String entryName; FileOutputStream fileoutputstream = null; InputStream zipinputstream = null; try { zipinputstream = zipSrc.getInputStream(entry); int lastIndex = entry.getName().lastIndexOf('/'); entryName = entry.getName().substring(lastIndex + 1).toLowerCase(); String fileName = entryName.toLowerCase(); String fileExtension = extractFileExtension(fileName); fileName = extractFileName(fileName); entryName = removeSpecialCharactersFromString(fileName) + "." + fileExtension; logger.info("INFO: Found file " + entryName); fileoutputstream = new FileOutputStream(tempUserDir + entryName); byte[] buf = new byte[1024]; int n; while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } } catch (IOException ioe) { logger.error("ERROR on extractEntryToFile(): " + ioe.getMessage()); throw new ResourceNotFoundFault(ioe.getMessage()); } finally { try { fileoutputstream.close(); zipinputstream.close(); } catch (IOException e) { } } }
// function to do the compute use case public static void compute() throws Exception { HttpPost method = new HttpPost(url + "/compute"); method.setEntity(new StringEntity(username, "UTF-8")); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); connIp = client.execute(method, responseHandler); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } System.out.println("Give the file name which has to be put in the grid for computation"); // input of the file name to be computed BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String name = in.readLine(); // get the absolute path of the current working directory File directory = new File("."); String pwd = directory.getAbsolutePath(); // get present time date = new Date(); long start = date.getTime(); String cmd = "java -classpath " + pwd + "/vishwa/JVishwa.jar:. " + name + " " + connIp; System.out.println(cmd); // Execute the vishwa compute process Process p = Runtime.getRuntime().exec(cmd); // wait till the compute process is completed // check for the status code (0 for successful termination) int status = p.waitFor(); if (status == 0) { System.out.println("Compute operation successful. Check the directory for results"); } date = new Date(); long end = date.getTime(); long durationInt = end - start; String duration = String.valueOf(durationInt); method = new HttpPost(url + "/computeAck"); method.setEntity(new StringEntity(username + ";" + duration, "UTF-8")); try { client.execute(method); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } }
public DeviceResponse sendCommand(DeviceCommand command) { if (socket == null || socket.isClosed()) { try { socket = new Socket(device.getInetAddress(), device.getPort()); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } } try { BufferedReader deviceInput = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter deviceOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String commandString = command.getCommandString(); deviceOutput.write(commandString + "\n"); deviceOutput.flush(); StringBuffer fullResponse = new StringBuffer(); String partialResponse; while (!(partialResponse = deviceInput.readLine().trim()).equals("")) { fullResponse.append(partialResponse); fullResponse.append("\n"); } int contentLength = 0; if (fullResponse.indexOf("Content-Length:") != -1) { String cls = "Content-Length:"; int si = fullResponse.indexOf(cls); int ei = fullResponse.indexOf("\n", si + cls.length()); contentLength = Integer.parseInt(fullResponse.substring(si + cls.length(), ei).trim()); } StringBuffer content = null; if (contentLength > 0) { content = new StringBuffer(contentLength); char buffer[] = new char[1024]; int read, totalRead = 0; do { read = deviceInput.read(buffer); totalRead += read; content.append(buffer, 0, read); } while (read != -1 && totalRead < contentLength); } return new DeviceResponse( fullResponse.toString(), content == null ? null : content.toString()); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
protected void configureWebXml() throws InstallException { // -------------------------------------------------------------------- // Configure web.xml // -------------------------------------------------------------------- FileObject webXml = null; try { webXml = targetDir.resolveFile("WEB-INF/web.xml"); // Get a DOM document of the web.xml : Node webXmlNode = loadAsDom(webXml); boolean modified = false; // Perform specific configurations if (configureFilters(webXmlNode)) modified = true; if (modified) { // Backup Container configuration. If we cannot perform a backup, do nothing if (!backupFile(webXml, targetDir)) { getPrinter() .printActionWarnStatus( "Configure", targetDir.getName().getFriendlyURI() + "/WEB-INF/web.xml", "Must be done manually (Follow setup guide)"); return; } // Write modifications to file writeContentFromDom(webXmlNode, webXml); getPrinter() .printActionOkStatus( "Save", webXml.getName().getBaseName(), webXml.getName().getFriendlyURI()); } } catch (IOException e) { log.error(e.getMessage(), e); getPrinter().printErrStatus("Cannot configure container : ", e.getMessage()); } catch (SAXException e) { log.error(e.getMessage(), e); getPrinter().printErrStatus("Cannot configure container : ", e.getMessage()); } catch (Exception e) { log.error(e.getMessage(), e); getPrinter().printErrStatus("Cannot configure container : ", e.getMessage()); getPrinter() .printActionWarnStatus( "Configure", targetDir.getName().getFriendlyURI() + "/WEB-INF/web.xml", "Must be done manually (Follow setup guide)"); } }
@Override public Object apply(List<Object> args, Context context) throws ParseException { File outFile = null; String editor = getEditor(); try { outFile = File.createTempFile("stellar_shell", "out"); if (args.size() > 0) { String arg = (String) args.get(0); try (PrintWriter pw = new PrintWriter(outFile)) { IOUtils.write(arg, pw); } } } catch (IOException e) { String message = "Unable to create temp file: " + e.getMessage(); LOG.error(message, e); throw new IllegalStateException(message, e); } Optional<Object> console = context.getCapability(CONSOLE, false); try { PausableInput.INSTANCE.pause(); // shut down the IO for the console ProcessBuilder processBuilder = new ProcessBuilder(editor, outFile.getAbsolutePath()); processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); try { Process p = processBuilder.start(); // wait for termination. p.waitFor(); try (BufferedReader br = new BufferedReader(new FileReader(outFile))) { String ret = IOUtils.toString(br).trim(); return ret; } } catch (Exception e) { String message = "Unable to read output: " + e.getMessage(); LOG.error(message, e); return null; } } finally { try { PausableInput.INSTANCE.unpause(); if (console.isPresent()) { ((Console) console.get()).pushToInputStream("\b\n"); } } catch (IOException e) { LOG.error("Unable to unpause: " + e.getMessage(), e); } if (outFile.exists()) { outFile.delete(); } } }
public void run() { URL url; Base64Encoder base64 = new Base64Encoder(); try { url = new URL(urlString); } catch (MalformedURLException e) { System.err.println("Invalid URL"); return; } try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass)); httpIn = new BufferedInputStream(conn.getInputStream(), 8192); } catch (IOException e) { System.err.println("Unable to connect: " + e.getMessage()); return; } int prev = 0; int cur = 0; try { while (keepAlive && (cur = httpIn.read()) >= 0) { if (prev == 0xFF && cur == 0xD8) { jpgOut = new ByteArrayOutputStream(8192); jpgOut.write((byte) prev); } if (jpgOut != null) { jpgOut.write((byte) cur); } if (prev == 0xFF && cur == 0xD9) { synchronized (curFrame) { curFrame = jpgOut.toByteArray(); } frameAvailable = true; jpgOut.close(); } prev = cur; } } catch (IOException e) { System.err.println("I/O Error: " + e.getMessage()); } try { jpgOut.close(); httpIn.close(); } catch (IOException e) { System.err.println("Error closing streams: " + e.getMessage()); } conn.disconnect(); }
public static boolean saveFile( HttpServlet servlet, String contentPath, String path, HttpServletRequest req, HttpServletResponse res) { // @todo Need to use logServerAccess() below here. boolean debugRequest = Debug.isSet("SaveFile"); if (debugRequest) log.debug(" saveFile(): path= " + path); String filename = contentPath + path; // absolute path File want = new File(filename); // backup current version if it exists int version = getBackupVersion(want.getParent(), want.getName()); String fileSave = filename + "~" + version; File file = new File(filename); if (file.exists()) { try { IO.copyFile(filename, fileSave); } catch (IOException e) { log.error( "saveFile(): Unable to save copy of file " + filename + " to " + fileSave + "\n" + e.getMessage()); return false; } } // save new file try { OutputStream out = new BufferedOutputStream(new FileOutputStream(filename)); IO.copy(req.getInputStream(), out); out.close(); if (debugRequest) log.debug("saveFile(): ok= " + filename); res.setStatus(HttpServletResponse.SC_CREATED); log.info(UsageLog.closingMessageForRequestContext(HttpServletResponse.SC_CREATED, -1)); return true; } catch (IOException e) { log.error( "saveFile(): Unable to PUT file " + filename + " to " + fileSave + "\n" + e.getMessage()); return false; } }
/** Doc duong dan script */ public void readScript() { FileInputStream fstream; try { fstream = new FileInputStream(this.get_fileurl()); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { // Neu bat dau bang select thi moi them vao. this.set_getquery( this.get_getquery() + strLine + '\n'); // Cong them 1 khoang trang de cau script dung // System.out.println (strLine); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); e.printStackTrace(); } // Get the object of DataInputStream catch (IOException e) { // TODO Auto-generated catch block logger.error(e.getMessage()); e.printStackTrace(); } }
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; }
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(); }
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$ } } }
/** * 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>(); }
// 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) { } } }
/** * 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!"); } }
/** * 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; }
// Method: runTest // Runs the script specified in the test case object public void runTest() { try { Process p = Runtime.getRuntime().exec(this.execCommandLine); InputStreamReader esr = new InputStreamReader(p.getErrorStream()); BufferedReader ereader = new BufferedReader(esr); InputStreamReader isr = new InputStreamReader(p.getInputStream()); BufferedReader ireader = new BufferedReader(isr); String line = null; String line1 = null; while ((line = ireader.readLine()) != null) { // System.out.println("Output: " + line); System.out.println(line); } while ((line1 = ereader.readLine()) != null) { System.err.println("Error: " + line1); } int exitValue = p.waitFor(); tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue); if (exitValue == 0) { setTestCaseResult(Result.Pass); } else { setTestCaseResult(Result.Fail); } } catch (IOException ioe) { System.out.println("Error: " + ioe.getMessage()); } catch (InterruptedException e) { System.out.println("Error: " + e.getMessage()); } }
public int luaCB_read(Lua l, LuaPlugin plugin) { l.pushNil(); l.pushNil(); try { long offset = (long) l.checkNumber(2); int length = (int) l.checkNumber(3); if (length <= 0) { l.pushNil(); l.pushString("Length is not positive"); return 2; } byte[] tmp = new byte[length]; object.seek(offset); length = object.read(tmp); if (length < 0) { l.pushNil(); l.pushNil(); return 2; } StringBuffer buf = new StringBuffer(length); for (byte x : tmp) buf.appendCodePoint((int) x & 0xFF); l.push(buf.toString()); } catch (IOException e) { l.pushNil(); l.pushString("IOException: " + e.getMessage()); return 2; } return 1; }
/** Añadir Bytes. MODO NO FIABLE. */ void addBytes(byte[] aBytes, int iBytes) throws IOException { if (this.file == null) return; if (lBytesLeidos < lFileSize) { // Ajustar tamaño... lBytesLeidos += iBytes; this.jDialogRecepcion.setBytesRecibidos(lBytesLeidos); try { this.fileOutputStream.write(aBytes, 0, iBytes); } catch (IOException e) { mensajeErrorEscribiendo(e.getMessage()); throw e; } } else { if (this.jDialogRecepcion != null) this.jDialogRecepcion.setVisible(false); this.resumenRecepcion(); // Cerrar Flujos if (this.fileOutputStream != null) this.fileOutputStream.close(); // Eliminar de ProtocolcFTP this.protocolcFTP.removeFileRecepcion(this.id_socket); } }
private boolean connectSPPMon() { if (state == ConnectionEvent.CONNECTION_PENDING) { ExpCoordinator.print( new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0); while (state == ConnectionEvent.CONNECTION_PENDING) { try { Thread.sleep(500); } catch (java.lang.InterruptedException e) { } } return (isConnected()); } state = ConnectionEvent.CONNECTION_PENDING; if (nonProxy != null) { try { nonProxy.connect(); } catch (UnknownHostException e) { boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage()); return rtn; } catch (SocketTimeoutException e) { boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage()); return rtn; } catch (IOException e) { boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage()); return rtn; } } return (isConnected()); }
public static void main(String[] args) { // TODO Auto-generated method stub Scanner ler = new Scanner(System.in); System.out.printf("informe o nome do arquivo de texto: \n"); String nome = ler.nextLine(); System.out.printf("\nconteudo do arquivo texto"); try { FileReader arq = new FileReader(nome); BufferedReader lerArq = new BufferedReader(arq); String linha = lerArq.readLine(); while (linha != null) { System.out.printf("%s\n", linha); linha = lerArq.readLine(); String val1 = linha.substring(0, linha.indexOf(',')); int a = Integer.parseInt(val1); String val2 = linha.substring(linha.indexOf(',') + 1, linha.lastIndexOf(',')); int b = Integer.parseInt(val2); String val3 = linha.substring(linha.lastIndexOf(',') + 1, linha.length()); int c = Integer.parseInt(val3); setValida(new ValidaTriangulo(a, b, c)); } arq.close(); } catch (IOException e) { System.out.printf("erra na abertura do arquivo: %s.n", e.getMessage()); } System.out.println(); }