/** * Walk through tall Files and remove the ones for the current device. * * @param dirsToRefresh list of the directory to refresh, null if all of them * @return true if there was any file removed. */ private boolean cleanFiles(List<Directory> dirsToRefresh) { boolean bChanges = false; final List<org.jajuk.base.File> files = FileManager.getInstance().getFiles(); for (final org.jajuk.base.File file : files) { // check if it is a file located inside refreshed directory if (dirsToRefresh != null) { boolean checkIt = false; for (Directory directory : dirsToRefresh) { if (file.hasAncestor(directory)) { checkIt = true; } } // This item is not in given directories, just continue if (!checkIt) { continue; } } if (!ExitService.isExiting() && file.getDirectory().getDevice().equals(this) && file.isReady() && // Remove file if it doesn't exist any more or if it is a iTunes // file (useful for jajuk < 1.4) (!file.getFIO().exists() || file.getName().startsWith("._"))) { FileManager.getInstance().removeFile(file); Log.debug("Removed: " + file); bChanges = true; if (reporter != null) { reporter.notifyFileOrPlaylistDropped(); } } } return bChanges; }
@Override public boolean onKeyDown(int keycode, KeyEvent event) { String current = mFileMag.getCurrentDir(); if (keycode == KeyEvent.KEYCODE_BACK && mUseBackKey && !current.equals("/")) { mHandler.updateDirectory(mFileMag.getPreviousDir()); mPathLabel.setText(mFileMag.getCurrentDir()); return true; } else if (keycode == KeyEvent.KEYCODE_BACK && mUseBackKey && current.equals("/")) { Toast.makeText(FileImportActivity.this, R.string.root_directory_tip, Toast.LENGTH_SHORT) .show(); mUseBackKey = false; mPathLabel.setText(mFileMag.getCurrentDir()); return false; } else if (keycode == KeyEvent.KEYCODE_BACK && !mUseBackKey && current.equals("/")) { finish(); return false; } return false; }
@Test public void should_post_decorate_field_and_return_decorator_result() { // GIVEN IUploadFileService uploadFileServiceMock = mock(IUploadFileService.class); INotificationService notificationServiceMock = mock(INotificationService.class); String expectedResult = "post-decorator result"; when(uploadFileServiceMock.upload(anyString(), anyString())).thenReturn(expectedResult); FileManager fileManager = new FileManager(); field("uploadFileService") .ofType(IUploadFileService.class) // .in(fileManager) .postDecorateWith(uploadFileServiceMock) .returningDecoratorResult(); field("notificationService") .ofType(INotificationService.class) .in(fileManager) .set(notificationServiceMock); // WHEN String fileName = "testFileName"; fileManager.manage(fileName); // THEN verify(uploadFileServiceMock, times(1)).upload(eq("testFileName"), anyString()); verify(notificationServiceMock, times(1)).notify(eq(expectedResult)); }
public static void main(String[] args) { try { Scanner consoleInput = new Scanner(System.in); System.out.println("Enter file name: "); String fileName = consoleInput.next(); if (!fileName.endsWith(".t")) { System.out.println("Expecting a LOGO file"); return; } Root program = Parser.parse(Lexer.tokenise(FileManager.contentsOfFile(fileName))); System.out.println("Enter output file name"); String outFileName = consoleInput.next(); if (!outFileName.endsWith(".ps") && !outFileName.endsWith(".eps")) { outFileName += ".ps"; } String output = CodeGenerator.generateCodeText(program); if (ErrorLog.containsErrors()) { ErrorLog.displayErrors(); return; } else { FileManager.writeStringToFile(output, outFileName); } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (IOException IO) { System.out.println(IO.getMessage()); } }
/* * (non-Javadoc) * This will check if the user is at root dir. If so, if they press back * again, it will close the app. * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent) */ @Override public boolean onKeyDown(int keycode, KeyEvent event) { String current = flmg.getCurrentDir(); if (keycode == KeyEvent.KEYCODE_SEARCH) { showDialog(SEARCH_B); return true; } else if (keycode == KeyEvent.KEYCODE_BACK && use_back_key && !current.equals("/")) { if (handler.isMultiSelected()) { table.killMultiSelect(); Toast.makeText(Main.this, "Multi-select is now off", Toast.LENGTH_SHORT).show(); } handler.updateDirectory(flmg.getPreviousDir()); path_label.setText(flmg.getCurrentDir()); return true; } else if (keycode == KeyEvent.KEYCODE_BACK && use_back_key && current.equals("/")) { Toast.makeText(Main.this, "Press back again to quit.", Toast.LENGTH_SHORT).show(); use_back_key = false; path_label.setText(flmg.getCurrentDir()); return false; } else if (keycode == KeyEvent.KEYCODE_BACK && !use_back_key && current.equals("/")) { finish(); return false; } return false; }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); SharedPreferences.Editor editor = settings.edit(); boolean check; int color; /* resultCode must equal RESULT_CANCELED because the only way * out of that activity is pressing the back button on the phone * this publishes a canceled result code not an ok result code */ if (requestCode == SETTING_REQ && resultCode == RESULT_CANCELED) { // save the information we get from settings activity check = data.getBooleanExtra("HIDDEN", false); color = data.getIntExtra("COLOR", -1); editor.putBoolean(PREFS_HIDDEN, check); editor.putInt(PREFS_COLOR, color); editor.commit(); flmg.setShowHiddenFiles(check); handler.setTextColor(color); handler.updateDirectory(flmg.getNextDir(flmg.getCurrentDir(), true)); } }
public static void main(String[] args) { fm = new FileManager(); fm.addGroup(); fm.chooseAFile(0); }
// prompt the user to login static User login() { boolean hasUser = false; String username, pass; System.out.println("\nLogin Form (input \"back\" to cancel operation)"); while (!hasUser) { System.out.print("Username: "******"Password: "******"back") || pass.equalsIgnoreCase("back")) { System.out.println("Cancelling operation, reverting back to user menu.\n"); return null; } if (FileManager.userExist(username)) { if (FileManager.checkPass(username, pass)) { user = FileManager.loadUser(username); hasUser = true; } else { System.out.println("Incorrect Password!"); } } else { System.out.println("The username you have specified does not exist!"); } System.out.println(); // formating } return user; }
// Inherit interface docs. @Override public boolean tableExists(String tableName) throws IOException { String tblFileName = getTableFileName(tableName); FileManager fileManager = storageManager.getFileManager(); return fileManager.fileExists(tblFileName); }
protected void tearDown() throws IOException, DatabaseException { if (fileManager != null) { fileManager.clear(); fileManager.close(); } TestUtils.removeFiles("TearDown", envHome, FileManager.JE_SUFFIX); }
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home || item.getItemId() == 0) { return false; } mSettings.edit().putInt(PREFS_SORT, item.getItemId()).commit(); mFileMag.setSortType(item.getItemId()); mHandler.updateDirectory(mFileMag.getNextDir(mFileMag.getCurrentDir(), true)); return true; }
public void saveFile() throws IOException { if (currentOpenedFile != null) fileManager.saveFile(pCanvas, currentOpenedFile); else { fc = new JFileChooser(); fc.setFileFilter(new FileNameExtensionFilter("绘图数据文件(.drw)", "drw")); fc.showSaveDialog(this); currentOpenedFile = fileManager.saveFile(pCanvas, fc.getSelectedFile()); } pCanvas.setModified(false); }
public FileHeader fileValues(String filePathName) { FileHeader fileHeader = new FileHeader(); FileManager fileManager = new FileManager(); fileHeader.setFileExtension(fileManager.getFileExtension(filePathName)); fileHeader.setFileName(fileManager.getFileName(filePathName)); fileHeader.setFileSize(fileManager.getFileSize(filePathName)); fileHeader.setNumberofChunks(fileManager.getNumberOfParts(filePathName)); return fileHeader; }
@Override public void run() { DuelManager dm = plugin.getDuelManager(); FileManager fm = plugin.getFileManager(); MessageManager mm = plugin.getMessageManager(); int duelTime = fm.getDuelTime(); String senderName = sender.getName(); String targetName = target.getName(); UUID senderUUID = sender.getUniqueId(); UUID targetUUID = target.getUniqueId(); int duelSize = duelArena.getPlayers().size(); if (plugin.isDebugEnabled()) { SendConsoleMessage.debug("Duel size: " + duelSize); } if (duelSize == 0) { dm.endDuel(duelArena); this.cancel(); } if (this.countDown > 0 && duelSize == 2) { String duelStartActionBar = mm.getDuelStartingActionBarMessage(); duelStartActionBar = duelStartActionBar.replaceAll("%seconds%", String.valueOf(this.countDown)); Util.sendActionBarMessage(sender, target, duelStartActionBar); this.countDown--; } else { if (duelSize == 2) { Util.setTime(sender, target, this.countDown); Util.sendMsg(sender, target, ChatColor.YELLOW + "Duel!"); duelArena.setDuelState(DuelState.STARTED); dm.surroundLocation(duelArena.getSpawnpoint1(), Material.AIR); dm.surroundLocation(duelArena.getSpawnpoint2(), Material.AIR); dm.updateDuelStatusSign(duelArena); } // dm.removeFrozenPlayer(senderUUID); // dm.removeFrozenPlayer(targetUUID); if (plugin.isDebugEnabled()) { SendConsoleMessage.debug("Stopping duel start thread."); } this.cancel(); if (duelTime != 0 && duelSize == 2) { if (plugin.isDebugEnabled()) { SendConsoleMessage.debug("Duel time limit is set, starting countdown task."); } new DuelTimeThread(plugin, sender, target, duelArena, duelTime) .runTaskTimer(plugin, 20L, 20L); } } }
@Test public void zipFileWithoutInnerClasses() throws IOException { FileManager fm = new FileManager(); fm.acceptInnerClasses(false); JavaClassBuilder builder = new JavaClassBuilder(fm); Collection classes = builder.buildClasses(zipFile); assertEquals(4, classes.size()); assertClassesExist(classes); }
public static void genMap(BufferedReader reader, Map<String, String> map) { String temp, tempArray[]; temp = FileManager.nextUncommentedLine(reader); if (temp != null) { do { tempArray = temp.split("\t"); if (tempArray.length == 2) { map.put(tempArray[0], tempArray[1]); } temp = FileManager.nextUncommentedLine(reader); } while (temp != null); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // Create path components to save the file final Part filePart = request.getPart("RemoteFile"); final String fileName = getFileName(filePart); FileManager manager = new FileManager(); manager.saveToDb(getServletContext(), response, filePart.getInputStream(), fileName); // manager.saveToDisk(getServletContext(), response, filePart.getInputStream(), // fileName); }
private void update(final IOperation<? extends IOperationModel, ? extends OperationData> end) { if (fileManager.getContext() == null) return; if (job == null) { job = new UpdateJob(fileManager.getContext()); } else { job.cancel(); } job.setPath(selectedFile); job.setEndOperation(end); job.schedule(); }
/** * This construct is called to create a new MovieQueue or to create one from a a saved file. * * @param numberOfMovies the MAX number of movies that the queue will hold * @param numberOfPriortities the MAX number of different priorities that might be assigned * @throws ClassNotFoundException * @throws IOException */ MovieQueue(int numberOfMovies, int numberOfPriortities) throws IOException, ClassNotFoundException { FileManager fm = new FileManager(); MyQueue<Movie> q = fm.getSavedHomeQueue(); PriorityQueue<Movie> p = fm.getSavedWaitingQueue(); if (p == null || q == null) { waitingQueue = new PriorityQueue<Movie>(numberOfMovies, numberOfPriortities); atHomeQueue = new MyQueue<Movie>(numberOfMovies); } else { waitingQueue = p; atHomeQueue = q; } }
private void doGet(OutputStream os, String url) throws IOException { if ("/".equals(url)) url = "/index.html"; List<String> headers = new ArrayList<String>(); headers.add("HTTP/1.1 200 OK\r\n"); byte[] content = fm.get(url); if (content == null) { returnStatusCode(404, os); return; } ProcessorsList pl = new ProcessorsList(); pl.add(new Compressor(6)); // pl.add(new Chunker(30)); // comment content = pl.process(content, headers); if (content == null) { returnStatusCode(500, os); return; } // uncomment next line headers.add("Content-Length: " + content.length + "\r\n"); headers.add("Connection: close\r\n\r\n"); os.write(getBinaryHeaders(headers)); os.write(content); }
public static boolean setUserLogFile(String fileName) { if (fileName == null) { fileName = System.getProperty("sikuli.LogfileUser"); } if (fileName != null) { if ("".equals(fileName)) { if (Settings.isMacApp) { fileName = "UserLog.txt"; } else { fileName = FileManager.slashify(System.getProperty("user.dir"), true) + "UserLog.txt"; } } try { if (printoutuser != null) { printoutuser.close(); } printoutuser = new PrintStream(fileName); log(3, "Debug: setLogFile: " + fileName); return true; } catch (FileNotFoundException ex) { System.out.printf("[Error] User logfile %s not accessible - check given path", fileName); System.out.println(); return false; } } return false; }
/** * Something is wrong with this file. If there is no data in this file (the header is <= the file * header size) then move this last file aside and search the next "last" file. If the last file * does have data in it, return null and throw an exception back to the application, since we're * not sure what to do now. * * @param cause is a DatabaseException or ChecksumException. */ private Long attemptToMoveBadFile(Exception cause) throws IOException, ChecksumException, DatabaseException { String fileName = fileManager.getFullFileNames(window.currentFileNum())[0]; File problemFile = new File(fileName); if (problemFile.length() <= FileManager.firstLogEntryOffset()) { fileManager.clear(); // close all existing files /* Move this file aside. */ Long lastNum = fileManager.getFollowingFileNum(window.currentFileNum(), false); if (!fileManager.renameFile(window.currentFileNum(), FileManager.BAD_SUFFIX)) { throw EnvironmentFailureException.unexpectedState( "Could not rename file: 0x" + Long.toHexString(window.currentFileNum())); } return lastNum; } /* There's data in this file, throw up to the app. */ if (cause instanceof DatabaseException) { throw (DatabaseException) cause; } if (cause instanceof ChecksumException) { throw (ChecksumException) cause; } throw EnvironmentFailureException.unexpectedException(cause); }
@Override public boolean onInterceptTouchEvent(MotionEvent event) { /**/ if (!waitMoveDrag || (dragListener == null && dropListener == null)) { return super.onInterceptTouchEvent(event); } fileManager.clearClickTime(); int act = event.getAction(); waitMoveDrag = false; switch (act) { case MotionEvent.ACTION_DOWN: int x = (int) event.getX(); int y = (int) event.getY(); int itemNum = pointToPosition(x, y); if (itemNum == INVALID_POSITION) break; dragItemFrom = dragCurPos = itemNum; View item = (View) getChildAt(itemNum - getFirstVisiblePosition()); if (item == null) { break; } dragging = true; // itemHeight = item.getHeight(); // item.setBackgroundColor(Color.BLUE); item.setDrawingCacheEnabled(true); Bitmap bm = Bitmap.createBitmap(item.getDrawingCache()); startDrag(bm, (int) event.getRawX(), (int) event.getRawY()); startDragListener.startDrag(itemNum); return false; } /** */ return super.onInterceptTouchEvent(event); }
public void exit() { session.close(); if (dnsCache != null) { System.out.printf(" cache= %s%n", dnsCache.toString()); System.out.printf(" cache.size= %d%n", dnsCache.getSize()); System.out.printf(" cache.memorySize= %d%n", dnsCache.getMemoryStoreSize()); Statistics stats = dnsCache.getStatistics(); System.out.printf(" stats= %s%n", stats.toString()); } cacheManager.shutdown(); fileChooser.save(); managePanel.save(); accessLogPanel.save(); servletLogPanel.save(); urlDump.save(); Rectangle bounds = frame.getBounds(); prefs.putBeanObject(FRAME_SIZE, bounds); try { store.save(); } catch (IOException ioe) { ioe.printStackTrace(); } done = true; // on some systems, still get a window close event System.exit(0); }
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info) { super.onCreateContextMenu(menu, v, info); boolean multi_data = handler.hasMultiSelectData(); AdapterContextMenuInfo _info = (AdapterContextMenuInfo) info; selected_list_item = handler.getData(_info.position); if (flmg.isDirectory(selected_list_item)) { menu.setHeaderTitle("Folder operations"); menu.add(0, D_MENU_DELETE, 0, "Delete Folder"); menu.add(0, D_MENU_RENAME, 0, "Rename Folder"); menu.add(0, D_MENU_COPY, 0, "Copy Folder"); menu.add(0, D_MENU_ZIP, 0, "Zip Folder"); menu.add(0, D_MENU_PASTE, 0, "Paste into folder").setEnabled(holding_file || multi_data); menu.add(0, D_MENU_UNZIP, 0, "Extract here").setEnabled(holding_zip); } else { menu.setHeaderTitle("File Operations"); menu.add(0, F_MENU_DELETE, 0, "Delete File"); menu.add(0, F_MENU_RENAME, 0, "Rename File"); menu.add(0, F_MENU_COPY, 0, "Copy File"); menu.add(0, F_MENU_ATTACH, 0, "Email File"); } }
public void activate() { if (camera.open()) { camera.startPreview(); if (camera.unlock()) { try { this.setCamera(camera.getCamera()); this.setAudioSource(MediaRecorder.AudioSource.MIC); this.setVideoSource(MediaRecorder.VideoSource.CAMERA); this.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); this.setOutputFile(FileManager.getOutputMediaFile(MEDIA_TYPE_VIEDO).getAbsolutePath()); this.prepare(); this.start(); isRunning = true; } catch (final Exception e) { Runnable runnable = new Runnable() { @Override public void run() { Toast toast1 = (Toast.makeText( callingActivity, "Problem with Recorder!" + e.getMessage(), Toast.LENGTH_LONG)); toast1.show(); e.printStackTrace(); deactivate(); } }; callingActivity.runOnUiThread(runnable); isRunning = false; } } } }
/* * Reposition to the specified file, and fill starting at * startOffset. Position the window's buffer to point at the log entry * indicated by targetOffset */ public void slideAndFill( long windowfileNum, long windowStartOffset, long targetOffset, boolean forward) throws ChecksumException, FileNotFoundException, DatabaseException { FileHandle fileHandle = fileManager.getFileHandle(windowfileNum); try { startOffset = windowStartOffset; setFileNum(windowfileNum, fileHandle.getLogVersion()); boolean foundData = fillFromFile(fileHandle, targetOffset); /* * When reading backwards, we need to guarantee there is no log * gap, throws out an EnvironmentFailreException if it exists. */ if (!foundData && !forward) { throw EnvironmentFailureException.unexpectedState( "Detected a log file gap when reading backwards. " + "Target position = " + DbLsn.getNoFormatString(DbLsn.makeLsn(windowfileNum, targetOffset)) + " starting position = " + DbLsn.getNoFormatString(DbLsn.makeLsn(windowfileNum, windowStartOffset)) + " end position = " + DbLsn.getNoFormatString(DbLsn.makeLsn(windowfileNum, endOffset))); } } finally { fileHandle.release(); } }
protected static boolean addToClasspath(String jar) { Method method; URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); URL[] urls = sysLoader.getURLs(); log0(lvl, "before adding to classpath: " + jar); for (int i = 0; i < urls.length; i++) { log0(lvl, "%d: %s", i, urls[i]); } Class sysclass = URLClassLoader.class; try { jar = FileManager.slashify(new File(jar).getAbsolutePath(), false); if (Settings.isWindows()) { jar = "/" + jar; } URL u = (new URI("file", jar, null)).toURL(); method = sysclass.getDeclaredMethod("addURL", new Class[] {URL.class}); method.setAccessible(true); method.invoke(sysLoader, new Object[] {u}); } catch (Exception ex) { log0(-1, ex.getMessage()); return false; } urls = sysLoader.getURLs(); log0(lvl, "after adding to classpath"); for (int i = 0; i < urls.length; i++) { log0(lvl, "%d: %s", i, urls[i]); } return true; }
/* * Assume that the window is properly positioned. Try to fill the read * buffer with data from this file handle, starting at the location * indicated by the starting offset field. If this file contains more * data, return true. If this file doesn't contain more data, return * false. * * In all cases, leave the the read buffer pointing at the target * offset and in a state that's ready to support reads, even if there * is nothing in the buffer. Note that the target offset, which may not * be the same as starting offset. * @return true if more data was read, false if not. */ protected boolean fillFromFile(FileHandle fileHandle, long targetOffset) throws DatabaseException { boolean foundData = false; readBuffer.clear(); if (fileManager.readFromFile( fileHandle.getFile(), readBuffer, startOffset, fileHandle.getFileNum(), false /* dataKnownToBeInFile */)) { foundData = true; nReadOperations += 1; /* * Ensure that fileNum and logVersion are in sync. setFileNum * handles changes in the file number. But we must also update * the logVersion here to handle the first read after we * initialize fileNum and logVersion is unknown. */ logVersion = fileHandle.getLogVersion(); } /* * In all cases, setup read buffer for valid reading. If the buffer * has no data, it will be positioned at the beginning, and will be * able to correctly return the fact that there is no data present. */ endOffset = startOffset + threadSafeBufferPosition(readBuffer); threadSafeBufferFlip(readBuffer); threadSafeBufferPosition(readBuffer, (int) (targetOffset - startOffset)); return foundData; }
/** * Fill up the read buffer with more data, moving along to the following file (next largest * number) if needed. * * @return true if the fill moved us to a new file. */ protected boolean fillNext(boolean singleFile, int bytesNeeded) throws ChecksumException, FileNotFoundException, EOFException, DatabaseException { adjustReadBufferSize(bytesNeeded); FileHandle fileHandle = null; try { /* Get a file handle to read in more log. */ fileHandle = fileManager.getFileHandle(fileNum); /* * Check to see if we've come to the end of the file. If so, * get the next file. */ startOffset = endOffset; if (fillFromFile(fileHandle, startOffset)) { /* * Successfully filled the read buffer, but didn't move to * a new file. */ return false; } /* This file is done -- can we read in the next file? */ if (singleFile) { throw new EOFException("Single file only"); } Long nextFile = fileManager.getFollowingFileNum(fileNum, true /* forward */); if (nextFile == null) { throw new EOFException(); } fileHandle.release(); fileHandle = null; fileHandle = fileManager.getFileHandle(nextFile); setFileNum(nextFile, fileHandle.getLogVersion()); startOffset = 0; fillFromFile(fileHandle, 0); return true; } finally { if (fileHandle != null) { fileHandle.release(); } } }