// get drivername, user, pw & server, and return connection id public void serve(InputStream i, OutputStream o) throws IOException { // TODOServiceList.getSingleInstance(); initialize(); NameListMessage nameListMessage = null; try { // read input to know which target panel is required ObjectInputStream input = new ObjectInputStream(i); nameListMessage = (NameListMessage) input.readObject(); // parse the required panel parseSqlFile(nameListMessage); } catch (ClassNotFoundException ex) { if (Debug.isDebug()) ex.printStackTrace(); nameListMessage.errorMessage = ex.toString(); } // send object to the caller ObjectOutputStream output = new ObjectOutputStream(o); output.writeObject(nameListMessage); // end socket connection o.close(); i.close(); }
private static void moveVoicemail(String strContact, String strID, String strTempVMTS) { System.out.println(strContact + " " + strID + " " + strTempVMTS); try { File fSrc = new File(strSrcVMDir + "/" + strID + ".amr"); File fDest = new File(strDestVMDir + strContact + "/" + strTempVMTS + ".amr"); InputStream isSrc = new FileInputStream(fSrc); OutputStream osDest = new FileOutputStream(fDest); byte[] buf = new byte[1024]; int len; while ((len = isSrc.read(buf)) > 0) { osDest.write(buf, 0, len); } isSrc.close(); osDest.close(); System.out.println("File copied."); } catch (Exception e) { System.err.println(e.getLocalizedMessage()); System.err.println(); System.err.println(e.getStackTrace()); System.exit(0); } }
public static void addToResultsFile( String executingDatabaseName, long runTime, long rowsLoaded, long rowsLoadedPerSecond, File resultsFile) { boolean resultsFileCreated = false; try { if (!resultsFile.exists()) { resultsFileCreated = resultsFile.createNewFile(); } OutputStream resultsFileStream = new FileOutputStream(resultsFile, true); if (resultsFileCreated) { // Write header lines. String header = "timeOfTest, runTime, databaseBeingTested, rowsLoaded, rowsLoadedPerSecond, hotStart, config, replicas" + "\n"; resultsFileStream.write(header.getBytes()); } String results = startDate.getTime() + ", " + runTime + ", " + executingDatabaseName + ", " + rowsLoaded + ", " + rowsLoadedPerSecond + ", " + hotStart + ", " + configInfo + ", " + numberOfReplicas + "\n"; resultsFileStream.write(results.getBytes()); resultsFileStream.flush(); resultsFileStream.close(); } catch (IOException e) { e.printStackTrace(); } }
public static int pipe_stream(InputStream is, OutputStream os, boolean wantsKeepOpen) throws IOException { // U: copia de un stream al otro int cnt = 0; int n; byte[] buffer = new byte[BUFF_SZ]; while ((n = is.read(buffer)) > -1) { cnt += n; os.write(buffer, 0, n); } if (!wantsKeepOpen) { is.close(); os.close(); } return cnt; }
/** ���ļ���ͬһ��Ŀ¼�¸���һ�� fileName ԭ4�ļ��� path �ļ���·�� cFileName ���ƺ���ļ��� */ public static void copy(String fileName, String cFileName, String path) { // ԭ�ļ� File file = new File(path + fileName); if (file.isFile()) { InputStream is = null; OutputStream out = null; try { // ԭ�ļ���һ�������� is = new FileInputStream(file); // �����ļ���·�� File toFile = new File(path + cFileName); if (toFile.exists()) { toFile.delete(); } // ���������ļ� toFile.createNewFile(); // �����ļ�������� out = new FileOutputStream(toFile); // ���� byte[] b = new byte[256]; for (int length = 0; (length = is.read(b, 0, 256)) > 0; ) { out.write(b, 0, length); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ex1) { } try { if (out != null) { out.close(); } } catch (IOException ex2) { } } // file.delete(); } // return abstractPath; }
/** * �����Ƶ���ǰ���µ��ļ���,���������·�� * * @param fileName String */ public static String move(String fileName, String loadPath) { String path = getPath(loadPath); // �������µ��ļ�·���ַ� String abstractPath = getAbstractPath(path); File file = new File(path + fileName); if (file.isFile()) { InputStream is = null; OutputStream out = null; try { is = new FileInputStream(file); path = path + abstractPath + fileName; File toFile = new File(path); if (toFile.exists()) { toFile.delete(); } toFile.createNewFile(); out = new FileOutputStream(toFile); byte[] b = new byte[256]; for (int length = 0; (length = is.read(b, 0, 256)) > 0; ) { out.write(b, 0, length); } } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException ex1) { } try { if (out != null) { out.close(); } } catch (IOException ex2) { } } file.delete(); } return abstractPath; }
/** * Doesn't write the file atomically. Logs, but doesn't throw upon failure. * * @param file can't be null. * @param userId only for logging. * @param content * @param errorLevel if true log an error level message; otherwise warning level. */ private void touchFile(File file, byte[] content, int userId, boolean errorLevel) { OutputStream out = null; try { file.getParentFile().mkdirs(); out = new FileOutputStream(file); out.write(content); out.close(); out = null; } catch (IOException ioe) { LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Unable to touch cache file"); lmg.param(LoggingConsts.USER_ID, userId); lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath()); lmg.param(LoggingConsts.CONTENT, content); if (errorLevel) { m_logCategory.error(lmg.toString(), ioe); } else { m_logCategory.warn(lmg.toString(), ioe); } } finally { // normally closed above; just for leak prevention. IOUtils.safeClose(out, false, m_logCategory); } }
public static void main(String[] args) { try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); ; Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@192.168.117.110:1521:WFZF", "qzkj", "qzkj"); conn.setAutoCommit(false); ; BLOB blob = null; PreparedStatement pstmt = conn.prepareStatement("insert into sys_file(uuid,content,name) values(?,empty_blob(),?)"); String uuid = Tool.getStringUUid(); pstmt.setString(1, uuid); pstmt.setString(2, "test.flv"); pstmt.executeUpdate(); pstmt.close(); pstmt = conn.prepareStatement("select content from sys_file where uuid= ? for update"); pstmt.setString(1, uuid); ResultSet rset = pstmt.executeQuery(); ; if (rset.next()) blob = (BLOB) rset.getBlob(1); ; String fileName = "test.flv"; File f = new File( "C://Documents and Settings//Administrator//桌面//FlvPlayer201002//FlvPlayer201002//" + fileName); FileInputStream fin = new FileInputStream(f); ; System.out.println("file size = " + fin.available()); pstmt = conn.prepareStatement("update sys_file set content=? where uuid=?"); ; OutputStream out = blob.getBinaryOutputStream(); ; int count = -1, total = 0; byte[] data = new byte[(int) fin.available()]; fin.read(data); ; out.write(data); ; /* byte[] data = new byte[blob.getBufferSize();]; 另一种实现方法,节省内存 while ((count = fin.read(data);); != -1); { total += count; out.write(data, 0, count);; } */ fin.close(); ; out.close(); ; pstmt.setBlob(1, blob); ; pstmt.setString(2, uuid); pstmt.executeUpdate(); ; pstmt.close(); ; conn.commit(); ; conn.close(); ; } catch (SQLException e) { System.err.println(e.getMessage()); ; e.printStackTrace(); } catch (IOException e) { System.err.println(e.getMessage()); ; } }
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // create the workbook, its worksheet, and its title row Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet("User table"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("The User table"); // create the header row row = sheet.createRow(2); row.createCell(0).setCellValue("UserID"); row.createCell(1).setCellValue("LastName"); row.createCell(2).setCellValue("FirstName"); row.createCell(3).setCellValue("Email"); try { // read database rows ConnectionPool pool = ConnectionPool.getInstance(); Connection connection = pool.getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM User ORDER BY UserID"; ResultSet results = statement.executeQuery(query); // create spreadsheet rows int i = 3; while (results.next()) { row = sheet.createRow(i); row.createCell(0).setCellValue(results.getInt("UserID")); row.createCell(1).setCellValue(results.getString("LastName")); row.createCell(2).setCellValue(results.getString("FirstName")); row.createCell(3).setCellValue(results.getString("Email")); i++; } results.close(); statement.close(); connection.close(); } catch (SQLException e) { this.log(e.toString()); } // set response object headers response.setHeader("content-disposition", "attachment; filename=users.xls"); response.setHeader("cache-control", "no-cache"); // get the output stream String encodingString = request.getHeader("accept-encoding"); OutputStream out; if (encodingString != null && encodingString.contains("gzip")) { out = new GZIPOutputStream(response.getOutputStream()); response.setHeader("content-encoding", "gzip"); // System.out.println("User table encoded with gzip"); } else { out = response.getOutputStream(); // System.out.println("User table not encoded with gzip"); } // send the workbook to the browser workbook.write(out); out.close(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Variable initializations. HttpSession session = request.getSession(); FileItem image_file = null; int record_id = 0; int image_id; // Check if a record ID has been entered. if (request.getParameter("recordID") == null || request.getParameter("recordID").equals("")) { // If no ID has been entered, send message to jsp. response_message = "<p><font color=FF0000>No Record ID Detected, Please Enter One.</font></p>"; session.setAttribute("msg", response_message); response.sendRedirect("UploadImage.jsp"); } try { // Parse the HTTP request to get the image stream. DiskFileUpload fu = new DiskFileUpload(); // Will get multiple image files if that happens and can be accessed through FileItems. List<FileItem> FileItems = fu.parseRequest(request); // Connect to the database and create a statement. conn = getConnected(drivername, dbstring, username, password); stmt = conn.createStatement(); // Process the uploaded items, assuming only 1 image file uploaded. Iterator<FileItem> i = FileItems.iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); // Test if item is a form field and matches recordID. if (item.isFormField()) { if (item.getFieldName().equals("recordID")) { // Covert record id from string to integer. record_id = Integer.parseInt(item.getString()); String sql = "select count(*) from radiology_record where record_id = " + record_id; int count = 0; try { rset = stmt.executeQuery(sql); while (rset != null && rset.next()) { count = (rset.getInt(1)); } } catch (SQLException e) { response_message = e.getMessage(); } // Check if recordID is in the database. if (count == 0) { // Invalid recordID, send message to jsp. response_message = "<p><font color=FF0000>Record ID Does Not Exist In Database.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } else { image_file = item; if (image_file.getName().equals("")) { // No file, send message to jsp. response_message = "<p><font color=FF0000>No File Selected For Record ID.</font></p>"; session.setAttribute("msg", response_message); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); } } } // Get the image stream. InputStream instream = image_file.getInputStream(); BufferedImage full_image = ImageIO.read(instream); BufferedImage thumbnail = shrink(full_image, 10); BufferedImage regular_image = shrink(full_image, 5); // First, to generate a unique img_id using an SQL sequence. rset1 = stmt.executeQuery("SELECT image_id_sequence.nextval from dual"); rset1.next(); image_id = rset1.getInt(1); // Insert an empty blob into the table first. Note that you have to // use the Oracle specific function empty_blob() to create an empty blob. stmt.execute( "INSERT INTO pacs_images VALUES(" + record_id + "," + image_id + ", empty_blob(), empty_blob(), empty_blob())"); // to retrieve the lob_locator // Note that you must use "FOR UPDATE" in the select statement String cmd = "SELECT * FROM pacs_images WHERE image_id = " + image_id + " FOR UPDATE"; rset = stmt.executeQuery(cmd); rset.next(); BLOB myblobFull = ((OracleResultSet) rset).getBLOB(5); BLOB myblobThumb = ((OracleResultSet) rset).getBLOB(3); BLOB myblobRegular = ((OracleResultSet) rset).getBLOB(4); // Write the full size image to the blob object. OutputStream fullOutstream = myblobFull.getBinaryOutputStream(); ImageIO.write(full_image, "jpg", fullOutstream); // Write the thumbnail size image to the blob object. OutputStream thumbOutstream = myblobThumb.getBinaryOutputStream(); ImageIO.write(thumbnail, "jpg", thumbOutstream); // Write the regular size image to the blob object. OutputStream regularOutstream = myblobRegular.getBinaryOutputStream(); ImageIO.write(regular_image, "jpg", regularOutstream); // Commit the changes to database. stmt.executeUpdate("commit"); response_message = "<p><font color=00CC00>Upload Successful.</font></p>"; session.setAttribute("msg", response_message); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); response.sendRedirect("UploadImage.jsp"); instream.close(); fullOutstream.close(); thumbOutstream.close(); regularOutstream.close(); // Close connection. conn.close(); } catch (Exception ex) { response_message = ex.getMessage(); } }
// initiate either a server or a user session public void run() { if (isDaemon) { daemon(); return; } ; boolean loggedIn = false; int i, h1; String di, str1, user = "******", user_id = "0"; InetAddress localNode; byte dataBuffer[] = new byte[1024]; String command = null; StringBuffer statusMessage = new StringBuffer(40); File targetFile = null; try { // start mysql Class.forName("com.mysql.jdbc.Driver").newInstance(); this.db_conn = DriverManager.getConnection(db_url); this.db_stmt = this.db_conn.createStatement(); this.db_stmt.executeUpdate("INSERT INTO test_table (name) VALUES ('hello world')"); incoming.setSoTimeout(inactivityTimer); // enforce I/O timeout remoteNode = incoming.getInetAddress(); localNode = InetAddress.getLocalHost(); BufferedReader in = new BufferedReader(new InputStreamReader(incoming.getInputStream(), TELNET)); PrintWriter out = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream(), TELNET), true); str1 = "220 Flickr FTP Server Ready"; out.println(str1); if (log) System.out.println(remoteNode.getHostName() + " " + str1); boolean done = false; char dataType = 0; while (!done) { statusMessage.setLength(0); // obtain and tokenize command String str = in.readLine(); if (str == null) break; // EOS reached i = str.indexOf(' '); if (i == -1) i = str.length(); command = str.substring(0, i).toUpperCase().intern(); if (log) System.out.print( user + "@" + remoteNode.getHostName() + " " + (String) ((command != "PASS") ? str : "PASS ***")); str = str.substring(i).trim(); try { if (command == "USER") { user = str; statusMessage.append("331 Password"); } else if (command == "PASS") { String pass = str; String pass_md5 = md5(pass); this.db_rs = this.db_stmt.executeQuery( "SELECT * FROM users WHERE email='" + user + "' AND password='******'"); if (this.db_rs.first()) { loggedIn = true; user_id = this.db_rs.getString("id"); System.out.println("Account id is " + user_id); } statusMessage.append(loggedIn ? "230 logged in User" : "530 Login Incorrect"); } else if (!loggedIn) { statusMessage.append("530 Not logged in"); } else if (command == "RETR") { statusMessage.append("999 Not likely"); } else if (command == "STOR") { out.println(BINARY_XFER); // trim a leading slash off the filename if there is one if (str.substring(0, 1).equals("/")) str = str.substring(1); String filename = user_id + "_" + str; // TODO: sanitise filename targetFile = new File(upload_root + "/" + filename); RandomAccessFile dataFile = null; InputStream inStream = null; OutputStream outStream = null; BufferedReader br = null; PrintWriter pw = null; try { int amount; dataSocket = setupDataLink(); // ensure timeout on reads. dataSocket.setSoTimeout(inactivityTimer); dataFile = new RandomAccessFile(targetFile, "rw"); inStream = dataSocket.getInputStream(); while ((amount = inStream.read(dataBuffer)) != -1) dataFile.write(dataBuffer, 0, amount); statusMessage.append(XFER_COMPLETE); shell_exec(ingest_path + " " + user_id + " " + filename); } finally { try { if (inStream != null) inStream.close(); } catch (Exception e1) { } ; try { if (outStream != null) outStream.close(); } catch (Exception e1) { } ; try { if (dataFile != null) dataFile.close(); } catch (Exception e1) { } ; try { if (dataSocket != null) dataSocket.close(); } catch (Exception e1) { } ; dataSocket = null; } } else if (command == "REST") { statusMessage.append("502 Sorry, no resuming"); } else if (command == "TYPE") { if (Character.toUpperCase(str.charAt(0)) == 'I') { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504 Only binary baybee"); } } else if (command == "DELE" || command == "RMD" || command == "XRMD" || command == "MKD" || command == "XMKD" || command == "RNFR" || command == "RNTO" || command == "CDUP" || command == "XCDUP" || command == "CWD" || command == "SIZE" || command == "MDTM") { statusMessage.append("502 None of that malarky!"); } else if (command == "QUIT") { statusMessage.append(COMMAND_OK).append("GOOD BYE"); done = true; } else if (command == "PWD" | command == "XPWD") { statusMessage.append("257 \"/\" is current directory"); } else if (command == "PORT") { int lng, lng1, lng2, ip2; String a1 = "", a2 = ""; lng = str.length() - 1; lng2 = str.lastIndexOf(","); lng1 = str.lastIndexOf(",", lng2 - 1); for (i = lng1 + 1; i < lng2; i++) { a1 = a1 + str.charAt(i); } for (i = lng2 + 1; i <= lng; i++) { a2 = a2 + str.charAt(i); } remotePort = Integer.parseInt(a1); ip2 = Integer.parseInt(a2); remotePort = (remotePort << 8) + ip2; statusMessage.append(COMMAND_OK).append(remotePort); } else if (command == "LIST" | command == "NLST") { try { out.println("150 ASCII data"); dataSocket = setupDataLink(); PrintWriter out2 = new PrintWriter(dataSocket.getOutputStream(), true); if ((command == "NLST")) { out2.println("."); out2.println(".."); } else { out2.println("total 8.0k"); out2.println("dr--r--r-- 1 owner group 213 Aug 26 16:31 ."); out2.println("dr--r--r-- 1 owner group 213 Aug 26 16:31 .."); } // socket MUST be closed before signalling EOD dataSocket.close(); dataSocket = null; statusMessage.setLength(0); statusMessage.append(XFER_COMPLETE); } finally { try { if (dataSocket != null) dataSocket.close(); } catch (Exception e) { } ; dataSocket = null; } } else if (command == "NOOP") { statusMessage.append(COMMAND_OK); } else if (command == "SYST") { statusMessage.append("215 UNIX"); // allows NS to do long dir } else if (command == "MODE") { if (Character.toUpperCase(str.charAt(0)) == 'S') { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504"); } } else if (command == "STRU") { if (str.equals("F")) { statusMessage.append(COMMAND_OK); } else { statusMessage.append("504"); } } else if (command == "PASV") { try { int num = 0, j = 0; if (passiveSocket != null) try { passiveSocket.close(); } catch (Exception e) { } ; passiveSocket = new ServerSocket(0); // any port // ensure timeout on reads. passiveSocket.setSoTimeout(inactivityTimer); statusMessage.append("227 Entering Passive Mode ("); String s = localNode.getHostAddress().replace('.', ','); // get host # statusMessage.append(s).append(','); num = passiveSocket.getLocalPort(); // get port # j = (num >> 8) & 0xff; statusMessage.append(j); statusMessage.append(','); j = num & 0xff; statusMessage.append(j); statusMessage.append(')'); } catch (Exception e) { try { if (passiveSocket != null) passiveSocket.close(); } catch (Exception e1) { } ; passiveSocket = null; throw e; } } else { statusMessage.append("502 unimplemented ").append(command); } } // shutdown causes an interruption to be thrown catch (InterruptedException e) { throw (e); } catch (Exception e) // catch all for any errors (including files) { statusMessage.append(FAULT).append(e.getMessage()); if (debug) { System.out.println("\nFAULT - lastfile " + targetFile); e.printStackTrace(); } ; } // send result status to remote out.println(statusMessage); if (log) System.out.println("\t" + statusMessage); } } catch (Exception e) // usually network errors (including timeout) { if (log) System.out.println("forced instance exit " + e); if (debug) e.printStackTrace(); } finally // exiting server instance { // tear down mysql if (this.db_rs != null) { try { this.db_rs.close(); } catch (SQLException SQLE) {; } } if (this.db_stmt != null) { try { this.db_stmt.close(); } catch (SQLException SQLE) {; } } if (this.db_pstmt != null) { try { this.db_pstmt.close(); } catch (SQLException SQLE) {; } } if (this.db_conn != null) { try { this.db_conn.close(); } catch (SQLException SQLE) {; } } forceClose(); } }
public static void set_stream(OutputStream os, String data, String encoding) throws IOException { os.write(data.getBytes(encoding)); os.close(); }