List of usage examples for java.io RandomAccessFile close
public void close() throws IOException
From source file:it.drwolf.ridire.session.async.JobDBDataUpdater.java
private String getJobStatus(String encodedJobName) throws HttpException, IOException, DocumentException { // back compatibility Heritrix 2 if (encodedJobName.startsWith("completed-")) { return CrawlStatus.FINISHED.toString(); }// w w w . j av a 2 s . c o m File jobDir = new File(this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName); String[] files = jobDir.list(); if (files == null || files.length < 2) { return CrawlStatus.CREATED.toString(); } String ret = CrawlStatus.CREATED.toString(); RandomAccessFile progressStatistics = null; Calendar now = new GregorianCalendar(); Date comparingDate = DateUtils.addDays(now.getTime(), -3); try { progressStatistics = new RandomAccessFile( this.jobsDir + CrawlerManager.FILE_SEPARATOR + encodedJobName + CrawlerManager.FILE_SEPARATOR + "logs" + CrawlerManager.FILE_SEPARATOR + "progress-statistics.log", "r"); if (progressStatistics != null) { progressStatistics.seek(Math.max(0, progressStatistics.length() - 3000)); String line = progressStatistics.readLine(); StringBuffer buffer = new StringBuffer(); while (line != null) { buffer.append(line + "\n"); line = progressStatistics.readLine(); } String progressStatisticsContent = buffer.toString(); Matcher m = this.progressStatisticsDatePattern.matcher(progressStatisticsContent); int start = 0; String lastDateString = ""; while (m.find(start)) { start = m.end(); lastDateString = m.group(); } Date lastDate = this.progressStatisticsDateFormat.parse(lastDateString); if (!progressStatisticsContent.contains("CRAWL ENDED - Finished") && lastDate.after(comparingDate)) { ret = CrawlStatus.RUNNING.toString(); } else { ret = CrawlStatus.FINISHED.toString(); } } } catch (FileNotFoundException e) { // TODO: handle exception } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (progressStatistics != null) { progressStatistics.close(); } } // File crawlReport = new File(this.jobsDir + FILE_SEPARATOR // + encodedJobName + FILE_SEPARATOR + "reports" + FILE_SEPARATOR // + "crawl-report.txt"); // if (crawlReport != null && crawlReport.canRead()) { // String crawlReportContent = FileUtils.readFileToString(crawlReport); // if (crawlReportContent.contains("crawl status: Finished")) { // ret = CrawlStatus.FINISHED.toString(); // } // } return ret; }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>//from w w w.j av a 2 s . co m * * @param publicKey * @return */ private synchronized boolean addKey(String publicKey) { m_log.debug("add key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped appending publicKey"); return true; } //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); m_log.debug("faileName" + fileName); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean add = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? channel.position(channel.size()); //? String writeData = "\n" + publicKey; // m_log.debug("add key : " + writeData); //????? ByteBuffer buffer = ByteBuffer.allocate(512); //??? buffer.clear(); buffer.put(writeData.getBytes()); buffer.flip(); channel.write(buffer); } add = true; } catch (Exception e) { m_log.error(e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } if (lock != null) { // lock.release(); } } catch (Exception e) { } } return add; }
From source file:edu.harvard.i2b2.patientMapping.ui.PatientIDConversionJFrame.java
private void jConvertButtonActionPerformed(java.awt.event.ActionEvent evt) { int inputIndex = jInputComboBox.getSelectedIndex() + 1; int outputIndex = jOutputComboBox.getSelectedIndex() + 1; if ((inputIndex == 2 && outputIndex != 2) || (inputIndex == 4 && outputIndex != 5)) { Display.getDefault().syncExec(new Runnable() { public void run() { MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK); messageBox.setText("Not valid selections"); messageBox.setMessage("Input and output pair selected is not valid."); messageBox.open();/* w w w.j a v a 2s .c o m*/ } }); return; } //jConvertButton.setCursor(new Cursor(Cursor.WAIT_CURSOR)); String inputFile = this.jInputFilePathTextField.getText(); if (inputFile == null || inputFile.equalsIgnoreCase("")) { JOptionPane.showMessageDialog(this, "Please select a input file."); return; } final String outputFile = this.jOutputFilePathTextField.getText(); if (outputFile == null || outputFile.equalsIgnoreCase("")) { JOptionPane.showMessageDialog(this, "Please select an output file."); return; } final File oDelete = new File(outputFile); Display.getDefault().syncExec(new Runnable() { public void run() { if (oDelete != null && oDelete.exists()) { MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.YES | SWT.NO); messageBox.setText("Warning"); messageBox.setMessage(outputFile + " already exists,\nDo you want to replace it?"); int buttonID = messageBox.open(); switch (buttonID) { case SWT.YES: oDelete.delete(); break; case SWT.NO: return; case SWT.CANCEL: // does nothing ... } } } }); log.info("Selected output file: " + outputFile); //if (fileName != null && fileName.trim().length() > 0) { log.info("Selected input file: " + inputFile); PatientIDConversionFactory converter = new PatientIDConversionFactory(); if ((inputIndex == 1 && (outputIndex == 2 || outputIndex == 3)) || (inputIndex == 3 && (outputIndex == 5 || outputIndex == 6))) { converter.sitename(jSiteTextField.getText()); } FileReader fr; BufferedReader inbr = null; RandomAccessFile f = null; //append(f, resultFile.toString()); jConvertButton.setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { f = new RandomAccessFile(outputFile, "rw"); fr = new FileReader(new File(inputFile)); inbr = new BufferedReader(fr); //String line = inbr.readLine(); /*if(!line.startsWith("@@i2b2 patient mapping file@@")) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); JOptionPane.showMessageDialog(jLabel1, "The file is not in a valid format.", "Error importing", JOptionPane.ERROR_MESSAGE); } }); //JOptionPane.showMessageDialog(null, "The file is not a valid.", "Error importing", JOptionPane.ERROR_MESSAGE); return; }*/ String line = inbr.readLine(); //log.info("column name: "+line); int rowCount = 0; while (line != null) { log.info(line); String outputline = ""; /*String[] cols = line.split(","); String id; if(cols.length < 2) { id = ""; } else { id = converter.convert(cols[1], 1, 1); }*/ outputline = converter.convertLine(line, inputIndex, outputIndex); append(f, outputline);//cols[0]+","+id+"\n"); rowCount++; line = inbr.readLine(); } log.info("From " + inputIndex + " to " + outputIndex + " total lines: " + rowCount); inbr.close(); f.close(); } catch (Exception e) { e.printStackTrace(); if (inbr != null) { try { inbr.close(); } catch (Exception e1) { } } if (f != null) { try { f.close(); } catch (Exception e1) { } } } jConvertButton.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); }
From source file:edu.harvard.i2b2.patientMapping.ui.PatientMappingJPanel.java
private void jSaveButtonActionPerformed(java.awt.event.ActionEvent evt) { //final Display display = Display.getDefault(); Display.getDefault().syncExec(new Runnable() { public void run() { Shell shell = new Shell(Display.getDefault()); FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterNames(new String[] { "Text Files", "All Files (*.*)" }); dialog.setFilterExtensions(new String[] { "*.txt", "*.*" }); // Windows // wild // cards dialog.setFilterPath("c:\\"); // Windows path dialog.setFileName(saveFileName + ".txt"); String filename = dialog.open(); //System.out.println("Save to: " + filename); if (filename == null) { return; }//w w w.j a v a2 s. c o m File oDelete = new File(filename); if (oDelete != null && oDelete.exists()) { MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO); messageBox.setText("Warning"); messageBox.setMessage(filename + " already exists,\nDo you want to replace it?"); int buttonID = messageBox.open(); switch (buttonID) { case SWT.YES: oDelete.delete(); break; case SWT.NO: return; case SWT.CANCEL: // does nothing ... } } StringBuilder resultFile = new StringBuilder(); // resultFile.append("@@i2b2 patient mapping file@@ Total columns: "+jTable1.getColumnCount()+"\n"); for (int i = 0; i < jTable1.getColumnCount(); i++) { resultFile.append(jTable1.getColumnName(i) + ","); } for (int i = 0; i < jTable1.getRowCount(); i++) { resultFile.append("\n"); for (int j = 0; j < jTable1.getColumnCount(); j++) { if (jTable1.getValueAt(i, j) != null) { resultFile.append("" + jTable1.getValueAt(i, j) + ","); } else { resultFile.append(""/*+jTable1.getValueAt(i, j)*/ + ","); } } } try { RandomAccessFile f = new RandomAccessFile(filename, "rw"); append(f, resultFile.toString()); f.close(); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.commoncrawl.service.listcrawler.CrawlList.java
/** * serialize metadata to disk /* w w w. j av a 2 s.c o m*/ * @throws IOException */ void writeMetadataToDisk() throws IOException { synchronized (_metadata) { RandomAccessFile file = new RandomAccessFile(_listMetadataFile, "rw"); try { file.seek(0); _metadata.serialize(file, new BinaryProtocol()); } finally { file.close(); } } }
From source file:com.joey.software.MoorFLSI.RepeatImageTextReader.java
public void loadTextDataFluxSingle(File file) { try {/*from w w w .j a va 2s.co m*/ RandomAccessFile in = new RandomAccessFile(file, "r"); // Skip header in.readLine(); in.readLine(); in.readLine(); // Skip Subject Information in.readLine(); in.readLine(); in.readLine(); in.readLine(); in.readLine(); in.readLine(); String startTimeInput = in.readLine(); String commentsInput = in.readLine(); String data = in.readLine(); while (!data.startsWith("2) System Configuration")) { commentsInput += data; data = in.readLine(); } // System configuration // in.readLine(); in.readLine(); String timeCounstantInput = in.readLine(); String cameraGainInput = in.readLine(); String exposureTimeInput = in.readLine(); in.readLine(); in.readLine(); in.readLine(); String resolutionInput = in.readLine(); // in.readLine(); // System.out.println(in.readLine()); // in.readLine(); // Parse important Size high = (new Scanner(resolutionInput.split(":")[1])).nextInt(); wide = (new Scanner(resolutionInput.split(",")[1])).nextInt(); int tot = 1; while (!data.startsWith("3) Flux Image Data")) { System.out.println(data); data = in.readLine(); } in.readLine(); // Parse Image Data /* * Close Random access file and switch to scanner first store pos * then move to correct point. */ long pos = in.getFilePointer(); in.close(); FileInputStream fIn = new FileInputStream(file); fIn.skip(pos); BufferedInputStream bIn = new BufferedInputStream(fIn); Scanner sIn = new Scanner(bIn); short[][] holder = new short[wide][high]; JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); StatusBarPanel stat = new StatusBarPanel(); stat.setMaximum(high); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(stat, BorderLayout.CENTER); f.setSize(200, 60); f.setVisible(true); // Skip over the heading values sIn.reset(); for (int y = 0; y < high; y++) { System.out.println(sIn.nextInt()); try { for (int x = 0; x < wide; x++) { holder[x][y] = sIn.nextShort(); } } catch (Throwable e) { } } addData(new Date(), holder); FrameFactroy.getFrame(new DynamicRangeImage(holder)); // Start Image Data } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java
private static TarReader openFirstFileWithValidIndex(List<File> files, boolean memoryMapping) { for (File file : files) { String name = file.getName(); try {// w ww. j a va 2 s . c o m RandomAccessFile access = new RandomAccessFile(file, "r"); try { ByteBuffer index = loadAndValidateIndex(access, name); if (index == null) { log.info("No index found in tar file {}, skipping...", name); } else { // found a file with a valid index, drop the others for (File other : files) { if (other != file) { log.info("Removing unused tar file {}", other.getName()); other.delete(); } } if (memoryMapping) { try { FileAccess mapped = new FileAccess.Mapped(access); // re-read the index, now with memory mapping int indexSize = index.remaining(); index = mapped.read(mapped.length() - indexSize - 16 - 1024, indexSize); return new TarReader(file, mapped, index); } catch (IOException e) { log.warn( "Failed to mmap tar file {}. Falling back to normal file " + "IO, which will negatively impact repository performance. " + "This problem may have been caused by restrictions on the " + "amount of virtual memory available to the JVM. Please make " + "sure that a 64-bit JVM is being used and that the process " + "has access to unlimited virtual memory (ulimit option -v).", name, e); } } FileAccess random = new FileAccess.Random(access); // prevent the finally block from closing the file // as the returned TarReader will take care of that access = null; return new TarReader(file, random, index); } } finally { if (access != null) { access.close(); } } } catch (IOException e) { log.warn("Could not read tar file {}, skipping...", name, e); } } return null; }
From source file:com.mediatek.systemupdate.HttpManager.java
int writeFile(HttpResponse response, long currSize) { Xlog.i(TAG, "writeFile"); if (mDownloadInfo.getDLSessionStatus() != DownloadInfo.STATE_QUERYNEWVERSION) { //mNotification.clearNotification(NotifyManager.NOTIFY_DOWNLOADING); mNotification.showDownloadingNotificaton(mDownloadInfo.getVerNum(), (int) (((double) Util.getFileSize(Util.getPackageFileName(mContext)) / (double) mDownloadInfo.getUpdateImageSize()) * 100), true);//from ww w . ja va 2 s . co m } Util.cancelAlarm(mContext, Util.Action.ACTION_AUTO_DL_TIME_OUT); mDownloadInfo.setOtaAutoDlStatus(false); mDownloadInfo.setIfPauseWithinTime(false); try { // response.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, // 10000); InputStream in = response.getEntity().getContent(); File ifolder = new File(Util.getPackagePathName(mContext)); if (!ifolder.exists()) { ifolder.mkdirs(); } RandomAccessFile out = null; String pkgFile = Util.getPackageFileName(mContext); if (pkgFile == null) { Xlog.e(TAG, "pkgFile is null"); mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; return mErrorCode; } try { out = new RandomAccessFile(pkgFile, "rws"); out.seek(currSize); } catch (IOException e) { e.printStackTrace(); onShutdownConn(); mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; return mErrorCode; } byte[] buff = new byte[4096]; int rc = 0; int i = 0; int j = 0; boolean rightnow = false; boolean finish = false; File fPkg = new File(pkgFile); if (fPkg == null) { out.close(); mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; return mErrorCode; } while ((rc = in.read(buff, 0, 4096)) > 0) { // to-do: handle Intent.ACTION_MEDIA_EJECT /* * synchronized (this) { if (mEjectFlag) { try { out.close(); } * catch (IOException e) { e.printStackTrace(); } * onShutdownConn(); return mErrorCode = * HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; } } */ try { if (fPkg.exists()) { out.write(buff, 0, rc); } else { Xlog.e(TAG, "file not exist during downloading "); setPauseState(); out.close(); onShutdownConn(); mErrorCode = HTTP_FILE_NOT_EXIST; sendErrorMessage(); return mErrorCode; } } catch (IOException e) { e.printStackTrace(); out.close(); onShutdownConn(); mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; return mErrorCode; } i++; int status = mDownloadInfo.getDLSessionStatus(); if (status == DownloadInfo.STATE_PAUSEDOWNLOAD || status == DownloadInfo.STATE_QUERYNEWVERSION) { Xlog.i(TAG, "writeFile, DownloadInfo = " + status); mCookies = null; finish = false; out.close(); onShutdownConn(); return 0; } if (mHandler == null) { if (rightnow) { i = 200; rightnow = false; } if (i == 200) { onDownloadProcessUpdate(); i = 0; } } else { if (!rightnow) { i = 18; rightnow = true; } if (i == 20) { i = 0; onDownloadProcessUpdate(); } } j++; if (j == 20) { onTransferRatio(); j = 0; } finish = true; } Xlog.i(TAG, "writeFile, finish, rc = " + rc + "bytes" + ". finish = " + finish); if (finish) { onTransferRatio(); onDownloadProcessUpdate(); } long curSize = Util.getFileSize(Util.getPackageFileName(mContext)); Xlog.i(TAG, "curSize = " + curSize + " mNewVersionInfo.mSize = " + mDownloadInfo.getUpdateImageSize()); out.close(); if (curSize >= mDownloadInfo.getUpdateImageSize()) { onShutdownConn(); return 0; } } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } showNoNetworkToast(); if (mDownloadInfo.getDLSessionStatus() == DownloadInfo.STATE_DOWNLOADING) { setPauseState(); Xlog.e(TAG, "writeFile, exception to set pause state"); mDownloadInfo.setOtaAutoDlStatus(true); mDownloadInfo.setIfPauseWithinTime(true); Util.setAlarm(mContext, AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + AUTO_DL_TIME, Util.Action.ACTION_AUTO_DL_TIME_OUT); } onShutdownConn(); mErrorCode = HTTP_RESPONSE_NETWORK_ERROR; sendErrorMessage(); return mErrorCode; }
From source file:org.openmeetings.servlet.outputhandler.BackupExport.java
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, ServletContext servletCtx) throws ServletException, IOException { String sid = httpServletRequest.getParameter("sid"); if (sid == null) { sid = "default"; }/*from w w w.ja v a 2 s . c o m*/ log.debug("sid: " + sid); Long users_id = sessionManagement.checkSession(sid); Long user_level = userManagement.getUserLevelByID(users_id); log.debug("users_id: " + users_id); log.debug("user_level: " + user_level); if (authLevelManagement.checkAdminLevel(user_level)) { // if (true) { String includeFileOption = httpServletRequest.getParameter("includeFileOption"); boolean includeFiles = includeFileOption == null || "yes".equals(includeFileOption); String moduleName = httpServletRequest.getParameter("moduleName"); if (moduleName == null) { moduleName = "moduleName"; } log.debug("moduleName: " + moduleName); if (moduleName.equals("backup")) { /* * ##################### Create Base Folder structure */ String current_dir = servletCtx.getRealPath("/"); File working_dir = new File(new File(current_dir, OpenmeetingsVariables.UPLOAD_DIR), "backup"); if (!working_dir.exists()) { working_dir.mkdir(); } String dateString = "backup_" + CalendarPatterns.getTimeForStreamId(new Date()); File backup_dir = new File(working_dir, dateString); String requestedFile = dateString + ".zip"; File backupFile = new File(backup_dir, requestedFile); String full_path = backupFile.getAbsolutePath(); try { performExport(full_path, backup_dir, includeFiles, current_dir); RandomAccessFile rf = new RandomAccessFile(full_path, "r"); httpServletResponse.reset(); httpServletResponse.resetBuffer(); httpServletResponse.setContentType("APPLICATION/OCTET-STREAM"); httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + requestedFile + "\""); httpServletResponse.setHeader("Content-Length", "" + rf.length()); OutputStream out = httpServletResponse.getOutputStream(); byte[] buffer = new byte[1024]; int readed = -1; while ((readed = rf.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, readed); } rf.close(); out.flush(); out.close(); } catch (Exception er) { log.error("Error exporting: ", er); } if (backupFile.exists()) { // log.debug("DELETE :1: "+backupFile.getAbsolutePath()); backupFile.delete(); } deleteDirectory(backup_dir); } } else { log.debug("ERROR LangExport: not authorized FileDownload " + (new Date())); } }
From source file:com.hly.component.download.DownloadTransaction.java
public void run() { // TODO ?Daemon InputStream is = null;/*from w ww .j av a 2s .com*/ HttpURLConnection conn = null; RandomAccessFile randomFile = null; File tmpFile = null; try { // ?uri tmpFile = new File(mTempLocalUri); File parentFile = tmpFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } if (!tmpFile.exists()) { tmpFile.createNewFile(); } randomFile = new RandomAccessFile(mTempLocalUri, "rw"); long fileLength = randomFile.length(); completeSize = fileLength; if (isCancel) { return; } String connUrl = mUri; // ?uri???? // getRedirectUrl(connUrl); if (!T.ckIsEmpty(mRedirectUri)) { connUrl = mRedirectUri; } conn = getHttpConnetion(connUrl); conn.setRequestProperty("range", "bytes=" + fileLength + "-"); conn.connect(); int contentLength = conn.getContentLength(); totalSize = completeSize + contentLength; if (contentLength == -1 || contentLength > 0) { // randomFile.seek(fileLength); byte[] buffer = new byte[8192]; is = conn.getInputStream(); int length = -1; while ((length = is.read(buffer)) != -1) { if (isCancel) { return; } randomFile.write(buffer, 0, length); completeSize += length; notifyProgress(length); } } mTransactionState.setState(TransactionState.SUCCESS); } catch (Throwable t) { Log.w(TAG, Log.getStackTraceString(t)); } finally { isRunning = false; isCancel = false; try { if (randomFile != null) { randomFile.close(); } } catch (IOException e) { e.printStackTrace(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (conn != null) { conn.disconnect(); } if (mTransactionState.getState() != TransactionState.SUCCESS) { mTransactionState.setState(TransactionState.FAILED); Log.e(TAG, "Delivery failed."); } else { if (tmpFile == null) { mTransactionState.setState(TransactionState.FAILED); } else { File localFile = new File(this.mLocalUri); boolean flag = tmpFile.renameTo(localFile); if (flag) { Log.d(TAG, "rename pic succ" + this.mLocalUri); } else { mTransactionState.setState(TransactionState.FAILED); Log.d(TAG, "rename pic failed" + this.mLocalUri); } } } notifyObservers(); } }