static void genclass(DelegatorGenerator dg, Class intfcl, String fqcn, File srcroot) throws IOException { File genDir = new File(srcroot, dirForFqcn(fqcn)); if (!genDir.exists()) { System.err.println( JdbcProxyGenerator.class.getName() + " -- creating directory: " + genDir.getAbsolutePath()); genDir.mkdirs(); } String fileName = CodegenUtils.fqcnLastElement(fqcn) + ".java"; Writer w = null; try { w = new BufferedWriter(new FileWriter(new File(genDir, fileName))); dg.writeDelegator(intfcl, fqcn, w); w.flush(); System.err.println("Generated " + fileName); } finally { try { if (w != null) w.close(); } catch (Exception e) { e.printStackTrace(); } } }
public boolean logEvent( final IClient client, final String eventText, final InputStream logFileStream) { Integer id = executeWithConnection( new ConnectionExecuteFunction<Integer>() { public Integer execute(Connection c) throws SQLException { return logEvent(client, eventText, logFileStream, c); } }); if (id == null) { // DB error would have already been logged. return false; } boolean ok = false; if (logFileStream == null) { ok = true; } else { File userMailDir = client.getUserMailbox().getBaseDir(); File logFile = getEventLogFile(userMailDir, id.intValue()); try { FileUtils.copyStreamToFile(logFileStream, logFile); ok = true; } catch (IOException ioe) { m_logger .log("Can't write log file") .param(LoggingConsts.USER_ID, client.getUserId()) .param(LoggingConsts.FILENAME, logFile == null ? "" : logFile.getAbsolutePath()) .param(LoggingConsts.CONTENT, eventText) .error(ioe); } } return ok; }
public CacheFileNames getCacheFileNames(final UserAccount user) { SecureHashKeyResult toRet = executeWithConnection( new ConnectionExecuteFunction<SecureHashKeyResult>() { public SecureHashKeyResult execute(Connection c) throws SQLException { return getSecureHashKey(user, c); } }); if (toRet == null) { // A DB error should have been logged. return null; } // EMSDEV-7854. Signal file manipulation is done outside of a DB transaction. String stateFile = null; String newmailFile = null; ClientHashSupport hash = null; byte[] key = toRet.getKey(); if (key != null) { hash = new ClientHashSupport(); hash.setCustomerId(user.getCustomerID()); hash.setHashKey(key); hash.setUserId(user.getUserID()); hash.getStateCachePath(); hash.setLastActivationId(user.getLastActivationId()); // Lines below don't hit the spindle. File stateFileF = new File(getCacheBase(), hash.getStateCachePath()); stateFile = stateFileF.getAbsolutePath(); File newmailFileF = new File(getCacheBase(), hash.getNewMailCachePath()); newmailFile = newmailFileF.getAbsolutePath(); if (toRet.isJustCreated()) { // If Webmail doesn't find the signal file, it polls the database, // so ensure the files are there. updateSignalFiles(hash, user.getUserState(), user.isDeleted()); } } return new CacheFileNames(stateFile, newmailFile); }
// Fireup tomcat and register this servlet public static void main(String[] args) throws LifecycleException, SQLException { Tomcat tomcat = new Tomcat(); tomcat.setPort(8080); File base = new File(System.getProperty("java.io.tmpdir")); Context rootCtx = tomcat.addContext("/", base.getAbsolutePath()); Tomcat.addServlet(rootCtx, "log", new LogService()); rootCtx.addServletMapping("/*", "log"); tomcat.start(); tomcat.getServer().await(); }
/** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // TODO Auto-generated method stub HttpSession session = request.getSession(); request.setCharacterEncoding("UTF-8"); BufferedInputStream fileIn = new BufferedInputStream(request.getInputStream()); String fn = request.getParameter("fileName"); byte[] buf = new byte[1024]; File file = new File("/var/www/uploadres/" + session.getAttribute("username") + fn); BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(file)); while (true) { int bytesIn = fileIn.read(buf, 0, 1024); if (bytesIn == -1) break; else fileOut.write(buf, 0, bytesIn); } fileOut.flush(); fileOut.close(); System.out.println(file.getAbsolutePath()); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); try { Connection conn = DriverManager.getConnection(url, user, pwd); Statement stmt = conn.createStatement(); String sql = "UPDATE Users SET photo = '" + file.getName() + "' WHERE username='******'"; stmt.execute(sql); // PreparedStatement pstmt = conn.prepareStatement("UPDATE Users SET photo = ? WHERE // username='******'"); // InputStream inp = new BufferedInputStream(new FileInputStream(file)); // pstmt.setBinaryStream(1, inp, (int)file.length()); // pstmt.executeUpdate(); System.out.println("OK"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * Creates and returns an InputStream from the file path / http location given. * * @throws DataServiceFault * @see InputStream */ public static InputStream getInputStreamFromPath(String path) throws IOException, DataServiceFault { InputStream ins; if (path.startsWith("http://")) { /* This is a url file path */ URL url = new URL(path); ins = url.openStream(); } else if (isRegistryPath(path)) { try { RegistryService registryService = DataServicesDSComponent.getRegistryService(); if (registryService == null) { throw new DataServiceFault( "DBUtils.getInputStreamFromPath(): Registry service is not available"); } Registry registry; if (path.startsWith(DBConstants.CONF_REGISTRY_PATH_PREFIX)) { if (path.length() > DBConstants.CONF_REGISTRY_PATH_PREFIX.length()) { path = path.substring(DBConstants.CONF_REGISTRY_PATH_PREFIX.length()); registry = registryService.getConfigSystemRegistry(getCurrentTenantId()); } else { throw new DataServiceFault("Empty configuration registry path given"); } } else { if (path.length() > DBConstants.GOV_REGISTRY_PATH_PREFIX.length()) { path = path.substring(DBConstants.GOV_REGISTRY_PATH_PREFIX.length()); registry = registryService.getGovernanceSystemRegistry(getCurrentTenantId()); } else { throw new DataServiceFault("Empty governance registry path given"); } } if (registry.resourceExists(path)) { Resource serviceResource = registry.get(path); ins = serviceResource.getContentStream(); } else { throw new DataServiceFault( "The given XSLT resource path at '" + path + "' does not exist"); } } catch (RegistryException e) { String msg = "Error in retrieving the resource: " + path; log.error(msg, e); throw new DataServiceFault(e, msg); } } else { File csvFile = new File(path); if (path.startsWith("." + File.separator) || path.startsWith(".." + File.separator)) { /* this is a relative path */ path = csvFile.getAbsolutePath(); } /* local file */ ins = new FileInputStream(path); } return ins; }
/** * If 'file' exists, attempt to delete it. Logs, but doesn't throw upon failure. * * @param file * @param userId only for logging. */ private void deleteFileIfNeeded(File file, int userId) { if (file.exists()) { boolean ok = file.delete(); if (!ok) { // This is a problem because it may delay informing a client to leave // activation. LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Unable to delete file"); lmg.param(LoggingConsts.USER_ID, userId); lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath()); m_logCategory.error(lmg.toString()); } } }
public ClientSession getClientSession(String activationToken) { if (!StringUtils.hasValue(activationToken)) { m_logCategory.warn("activationToken is required"); return null; } File file = getSessionFile(activationToken); if (!file.exists()) { // Can't assume it's an authentication problem -- session file is removed // during active->recovery transition. // If this occurs, the client gets a 401 and will call into 'transition' or 'checkin'. LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Session file not found"); lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath()); m_logCategory.info(lmg.toString()); return null; } try { ClientSession clientSession = null; clientSession = new ClientSession(); clientSession.read(file); clientSession.setActivationToken(activationToken); return clientSession; } catch (IOException ioe) { // Possible if the state file was removed after the file.exists() above, // or some other problem. // info, not warning because a client could ask for this file right when // the session is being removed. The client will then do a 'checkin', // same as described above. LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Unable to read session file"); lmg.param(LoggingConsts.FILENAME, file.getAbsolutePath()); m_logCategory.info(lmg.toString(), ioe); } return null; }
public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); if (b == bu) { j14 = new JLabel("NEW IMAGE"); j14.setBounds(840, 200, 300, 300); q.add(j14); JFileChooser filechooser = new JFileChooser(); int result = filechooser.showOpenDialog(this); f = filechooser.getSelectedFile(); try { String dir1 = f.getAbsolutePath(); // setText(dir); str = dir1; // ResizeImage.resize(dir); f = new File(dir1); } catch (Exception e1) { } repaint(); // b=(JButton)e.getSource(); } if (b == ba) { try { read(); patient.add(tadd.getText(), tsym.getText(), f, str); JOptionPane.showMessageDialog(null, "Patient ID: " + patient.pid + " Record Added"); } catch (Exception e4) { System.out.println("" + e4); } } if (b == bm) { try { setVisible(false); } catch (Exception e4) { System.out.println("" + e4); } } }
/** * 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 void purgeLogEvents(final List<SearchConstraint> constraints, final int daysToKeep) { blockHereIfBadNfs(); StringBuffer sql = new StringBuffer( "select u.mail_directory || '/logs/' || e.event_id || '.log' " + "from dat_client_log_events e, dat_user_account u " + "where event_time < current_timestamp - (? || ' days')::interval " + "and e.has_log_file != 0 " + "and e.user_id = u.object_id"); appendWhereConstraints(sql, constraints, s_propToColumnMap); m_logCategory.info("Purge event logs query is\n" + sql); StringBuffer sql2 = new StringBuffer( "delete from dat_client_log_events " + "where event_time < current_timestamp - (? || ' days')::interval"); if (!constraints.isEmpty()) { sql2.append(" and event_id in (select e.event_id from dat_client_log_events e "); appendWhere(sql2, constraints, s_propToColumnMap); sql2.append(")"); } m_logCategory.info("Purge event logs query is\n" + sql2); try { Connection c = m_txManager.getConnection(); PreparedStatement stmt = null; ResultSet rs = null; boolean needsRollback = true; try { stmt = c.prepareStatement(sql.toString()); stmt.setInt(1, daysToKeep); rs = stmt.executeQuery(); while (rs.next()) { File logFile = new File(getNfsRoot(), rs.getString(1)); // nfs usage, but DB transaction takes no locks. if (logFile.exists()) { boolean ok = logFile.delete(); if (!ok) { m_logger .log("Unable to delete") .param(LoggingConsts.FILENAME, logFile.getAbsolutePath()) .warn(); } } // file exists. } // each row // Below, no nfs usage occurs. We can use the same connection. // the 'sql delete' may use DB locks. stmt = c.prepareStatement(sql2.toString()); stmt.setInt(1, daysToKeep); stmt.executeUpdate(); c.commit(); needsRollback = false; } finally { DbUtils.safeClose(rs); DbUtils.safeClose(stmt); if (needsRollback) { c.rollback(); } m_txManager.returnConnection(c); } } catch (Exception ex) { m_logger.log("Error in purgeLogEvents").warn(ex); } }
public ClientSession createClientSession(IClientInfo client, String clientType) { // Both OE and BB share the session file. Don't stomp an existing file. if (client == null || !client.isConfigured()) { throw new IllegalStateException("Client not configured."); } clientType = clientType == null ? "" : clientType; ClientSession session = null; String tmpName = null; String targetName = null; try { File targetFile = getSessionFile(client.getLastActivationToken()); targetName = targetFile.getAbsolutePath(); if (targetFile.exists()) { session = new ClientSession(); session.read(targetFile); if (session.getLastActivationId() != client.getLastActivationId() || session.getUserId() != client.getUserId()) { // Existing session file found but it's clearly not ours. // A hash collision is improbable. If this occurs, its more likely to be a // bug. We can't safely rewrite the session file because another client // might later call getClientSession() and read our email. // This is a support concern. LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Found existing session, but the content is unexpected."); lmg.param(LoggingConsts.FILENAME, targetFile.getAbsolutePath()); m_logCategory.error(lmg.toString()); throw new ClientServiceException(""); } session.setActivationToken(client.getLastActivationToken()); } // targetFile already found. if (session == null) { UserAccount user = m_userService.getUserAccount(client.getCustomerId(), client.getUserId()); session = client.createSession(user); // What if the BB and OE create a session at the same time? // This ensures a unique filename. // The client who does the last renameTo() below wins the race // and that becomes the common session file. tmpName = targetFile.getAbsolutePath() + "_tmp_" + clientType; File tmpFile = new File(tmpName); session.write(tmpFile); // If 'targetFile' already exists it'll get clobbered. // Makes the session targetFile generation atomic. boolean ok = FileUtils.clobberingRename(tmpFile, targetFile); if (!ok) { throw new IOException("Rename failed"); } } // need to create session. } catch (Exception ex) { if (ex instanceof ClientServiceException) { // We already logged it. throw (ClientServiceException) ex; } LogMessageGen lmg = new LogMessageGen(); lmg.setSubject("Unable to generate session file."); lmg.param(LoggingConsts.USER_ID, client.getUserId()); lmg.param(LoggingConsts.TEMP_NAME, tmpName); lmg.param(LoggingConsts.FILENAME, targetName); m_logCategory.error(lmg.toString(), ex); throw new ClientServiceException(""); } return session; }
public boolean parserCpYieldTxt(File txtFile) throws Exception { FileInputStream fIn = null; String fileNameUid = ""; try { Calendar calendar = Calendar.getInstance(); SimpleDateFormat df2 = new SimpleDateFormat("yyyyMM"); // Using Find Target "|=124" or ",=44" Count DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); logger.debug( "File " + txtFile.getAbsolutePath() + " " + txtFile.getName() + " " + new MimetypesFileTypeMap().getContentType(txtFile)); // 1.0 讀入檔案, 建立資料流 fIn = new FileInputStream(txtFile); // FileInputStream fIn2 = new FileInputStream(csvFile); InputStreamReader isr = null; BufferedReader br = null; isr = new InputStreamReader(fIn, "UTF-8"); br = new BufferedReader(isr); // byte[] byteArray = new byte[new Long(csvFile.length()).intValue()]; // 讀入File Data Byte..... // fIn2.read(byteArray); logger.debug(txtFile.getName() + "<--讀入資料檔...成功"); // Using get sign "\n" 抓行數... // 1.1 讀入行數資料, 略過行數 int l = -1; List<String> lineDataList = new ArrayList<String>(); for (int i = 0; i <= l; i++) { br.readLine(); } while (br.ready()) { String line = br.readLine(); line = null != line ? line : ""; // logger.debug(line); if (!line.trim().equals("")) { lineDataList.add(line); } } // 1.2 確認有資料開使處理 if (lineDataList != null) { CpYieldParserDao cpYieldParserDao = new CpYieldParserDao(); CpYieldLotTo cpYieldLotTo = new CpYieldLotTo(); String cpYieldUuid = UUID.randomUUID().toString().toUpperCase(); logger.debug("lineDataList.size() " + lineDataList.size()); fileNameUid = FilenameUtils.getBaseName(txtFile.getName()) + "_" + cpYieldUuid + "." + FilenameUtils.getExtension(txtFile.getName()); File bkFolder = new File(fileOutUrl + File.separator + df2.format(calendar.getTime()).toString()); bkFolder.mkdir(); File bkFile = new File(bkFolder.getPath().toString() + File.separator + fileNameUid); // 1.2.1 處理每行資料 String tmpWaferID = lineDataList.get(1); String arrayWafer[] = tmpWaferID.split("=")[1].trim().split("-"); // logger.debug("arrayWafer[] " + arrayWafer.length); // 1.3 Prepare Data String cpLot = arrayWafer[0].trim(); String waferId = arrayWafer[1].trim(); String machineId = arrayWafer[2].trim(); Integer cpTestTimes = cpYieldParserDao.getMaxCpTestTimes(cpLot, waferId); String xMaxCoor = lineDataList.get(2).split("=")[1].trim(); String yMaxCoor = lineDataList.get(3).split("=")[1].trim(); String flat = lineDataList.get(4).split("=")[1].trim(); logger.debug("xMaxCoor " + xMaxCoor); logger.debug("yMaxCoor " + yMaxCoor); logger.debug("flat " + flat); // 1.3 Find Bin Data int sb = 0, eb = 0; for (int i = 0; i < lineDataList.size(); i++) { if (lineDataList.get(i).indexOf("Wafer Bin Summary") >= 0) { sb = i + 1; break; } } for (int i = sb; i < lineDataList.size(); i++) { if (lineDataList.get(i).indexOf("bin") < 0) { eb = i - 1; break; } } logger.debug("sb " + sb); logger.debug(lineDataList.get(sb).trim()); logger.debug("eb " + eb); logger.debug(lineDataList.get(eb).trim()); // 1.3.1 Get Bin Data List<CpYieldLotBinTo> cpYieldLotBins = new ArrayList<CpYieldLotBinTo>(); String cpYieldBinUuid; String bin; Integer die; String percentage; String binString; for (int j = sb; j <= eb; j++) { cpYieldBinUuid = UUID.randomUUID().toString().toUpperCase(); CpYieldLotBinTo cpYieldLotBinTo = new CpYieldLotBinTo(); cpYieldLotBinTo.setCpYieldBinUuid(cpYieldBinUuid); cpYieldLotBinTo.setCpYieldUuid(cpYieldUuid); binString = lineDataList.get(j).trim(); binString = binString.replaceAll("bin", "").trim(); // Get Bin bin = binString.substring(0, binString.indexOf(" ")); logger.debug("bin " + bin); // Get Die bin = binString.substring(0, binString.indexOf(" ")); binString = binString.replaceAll(bin, "").trim(); die = Integer.parseInt(binString.substring(0, binString.indexOf(" "))); logger.debug("die " + die); // Get Percentage binString = binString.replaceAll(die.toString(), "").trim(); percentage = binString.substring(0, binString.length() - 1); logger.debug("percentage " + percentage); cpYieldLotBinTo.setBin(bin); cpYieldLotBinTo.setDie(die); cpYieldLotBinTo.setPercentage(percentage); cpYieldLotBins.add(cpYieldLotBinTo); } // 1.4 Die Data Integer passDie; Integer failDie; Integer totelDie; for (int i = eb + 1; i < lineDataList.size(); i++) { // pass die if (lineDataList.get(i).trim().indexOf("pass die") >= 0) { passDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim()); logger.debug("passDie " + passDie); cpYieldLotTo.setPassDie(passDie); continue; } // fail die if (lineDataList.get(i).trim().indexOf("fail die") >= 0) { failDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim()); logger.debug("failDie " + failDie); cpYieldLotTo.setFailDie(failDie); continue; } // totel die if (lineDataList.get(i).trim().indexOf("totel die") >= 0) { totelDie = Integer.parseInt(lineDataList.get(i).trim().split(":")[1].trim()); logger.debug("totelDie " + totelDie); cpYieldLotTo.setTotelDie(totelDie); continue; } } // 1.5 Set data in To cpYieldLotTo.setCpYieldUuid(cpYieldUuid); cpYieldLotTo.setCpTestTimes(cpTestTimes); cpYieldLotTo.setCpLot(cpLot); cpYieldLotTo.setWaferId(waferId); cpYieldLotTo.setMachineId(machineId); cpYieldLotTo.setxMaxCoor(xMaxCoor); cpYieldLotTo.setyMaxCoor(yMaxCoor); cpYieldLotTo.setFlat(flat); String fileMimeType = new MimetypesFileTypeMap().getContentType(txtFile); cpYieldLotTo.setFileName( df2.format(calendar.getTime()).toString() + File.separator + fileNameUid); cpYieldLotTo.setFileMimeType(fileMimeType); cpYieldLotTo.setFtpFlag("N"); fIn.close(); br.close(); Methods.copyFile(txtFile, bkFile); txtFile.delete(); // 1.6 DataBasse // 1.6.1 Insert CP Lot Table cpYieldParserDao.insertCpYieldLot(cpYieldLotTo); cpYieldParserDao.insertCpYieldLotBin(cpYieldLotBins); } fIn.close(); br.close(); logger.info(txtFile.getName() + " is Parser complete"); logger.info(fileNameUid + " is Parser complete"); // logger.debug(tapeList.size()); logger.info("---------------------------------"); } catch (Exception e) { if (fIn != null) { fIn.close(); } logger.info("ERROR MOVE FILE"); Methods.copyFile(txtFile, new File(fileErrorUrl + "\\" + txtFile.getName())); txtFile.delete(); StackTraceElement[] messages = e.getStackTrace(); Exception ex = new Exception(txtFile.getName()); ex.setStackTrace(messages); ex.printStackTrace(); throw ex; } finally { try { if (fIn != null) { fIn.close(); } } catch (IOException ie) { StackTraceElement[] messages = ie.getStackTrace(); int length = messages.length; String error = ""; for (int i = 0; i < length; i++) { error = error + "toString:" + messages[i].toString() + "\r\n"; } ie.printStackTrace(); logger.error(error); return false; } } return true; }
public static String temp_filePath(String namePattern, String ext) throws IOException, FileNotFoundException { File temp = File.createTempFile("temp-file-name", ".tmp"); return temp.getAbsolutePath(); }