/** * Creates the directory where the MRU file list will be written. The "lf5" directory is created * in the Documents and Settings directory on Windows 2000 machines and where ever the user.home * variable points on all other platforms. */ public static void createConfigurationDirectory() { String home = System.getProperty("user.home"); String sep = System.getProperty("file.separator"); File f = new File(home + sep + "lf5"); if (!f.exists()) { try { f.mkdir(); } catch (SecurityException e) { e.printStackTrace(); } } }
public int getImageResourceByFileExt(String ext) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException { Field field = null; if (ext == null || ext.equals("")) return this.dir; try { field = this.drawableClass.getDeclaredField(ext); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block return this.unknowFile; } return field.getInt(this.drawableClass); }
/** * Function that creates a "ARCHIVE" folder that is going to contain all the archives that will be * created by this program. * * @return folder that is going to contain all the archives that will be created by this program */ private File createArchive() { archiveDirectory = null; try { String homePath = System.getProperty("user.home"); archiveDirectory = new File(homePath + File.separatorChar + "Archive"); if (!archiveDirectory.exists()) archiveDirectory.mkdir(); } catch (SecurityException ex) { ex.printStackTrace(); } catch (NullPointerException ex) { ex.printStackTrace(); } catch (IllegalArgumentException ex) { ex.printStackTrace(); } return archiveDirectory; }
/** * Loads the SWIG-generated libSBML Java module when this class is loaded, or reports a sensible * diagnostic message about why it failed. */ static { String varname; String shlibname; if (System.getProperty("os.name").startsWith("Mac OS")) { varname = "DYLD_LIBRARY_PATH"; // We're on a Mac. shlibname = "'libsbmlj.jnilib'"; } else { varname = "LD_LIBRARY_PATH"; // We're not on a Mac. shlibname = "'libsbmlj.so' and/or 'libsbml.so'"; } try { System.loadLibrary("sbmlj"); // For extra safety, check that the jar file is in the classpath. Class.forName("org.sbml.libsbml.libsbml"); } catch (UnsatisfiedLinkError e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println( "Please check the value of your " + varname + " environment variable and/or" + " your 'java.library.path' system property" + " (depending on which one you are using) to" + " make sure it list the directories needed to" + " find the " + shlibname + " library file and the" + " libraries it depends upon (e.g., the XML parser)."); System.exit(1); } catch (ClassNotFoundException e) { System.err.println( "Error: unable to load the file 'libsbmlj.jar'." + " It is likely that your -classpath command line " + " setting or your CLASSPATH environment variable " + " do not include the file 'libsbmlj.jar'."); System.exit(1); } catch (SecurityException e) { System.err.println("Error encountered while attempting to load libSBML:"); e.printStackTrace(); System.err.println( "Could not load the libSBML library files due to a" + " security exception.\n"); System.exit(1); } }
public static Integer getProcessID(Process p) { try { Field f = p.getClass().getDeclaredField("pid"); f.setAccessible(true); Integer s = (Integer) f.get(p); return s; } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
public static void startLog() { FileHandler fh; try { // This block configure the logger with handler and formatter fh = new FileHandler("server_log.log"); logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); // the following statement is used to log any messages logger.info("server_log"); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public boolean saveMidiFile(File file) { try { int[] fileTypes = MidiSystem.getMidiFileTypes(sequence); if (fileTypes.length == 0) { System.out.println("Can't save sequence"); return false; } else { if (MidiSystem.write(sequence, fileTypes[0], file) == -1) { throw new IOException("Problems writing to file"); } return true; } } catch (SecurityException ex) { ex.printStackTrace(); return false; } catch (Exception ex) { ex.printStackTrace(); return false; } }
public static void main(String[] argv) { if (argv.length != 3) { usage(); } String tempFile = argv[0]; String testFile = argv[1]; int fileSize = Integer.valueOf(argv[2]).intValue(); int exitcode = 0; int numRead; int numThisBuf; int numWritten; if ((fileSize <= 0) || (fileSize % 4096 != 0)) { System.out.println("Error: size is not a multiple of 4096!!!!!!"); System.out.println(); usage(); } try { int bufSize = 4096; byte[] inBytes = new byte[bufSize]; byte[] outBytes = new byte[bufSize]; Random ioRandom = new Random(2006); ioRandom.nextBytes(outBytes); ByteBuffer inBuf = ByteBuffer.allocate(bufSize); ByteBuffer outBuf = ByteBuffer.wrap(outBytes); // // Loop forever // while (true) { // // Write the temporary file // FileOutputStream fos = new FileOutputStream(tempFile); FileChannel foc = fos.getChannel(); numWritten = 0; while (numWritten < fileSize) { outBuf.clear(); // sets limit to capacity & position to zero while (outBuf.hasRemaining()) { numWritten += foc.write(outBuf); } } // // Move to permanent location // FileChannel srcChannel = new FileInputStream(tempFile).getChannel(); FileChannel dstChannel = new FileOutputStream(testFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); boolean success = (new File(tempFile)).delete(); if (!success) { System.out.println("Warning: unable to delete temporary file"); } // // Read and compare // FileInputStream fis = new FileInputStream(testFile); FileChannel fic = fis.getChannel(); for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) { inBuf.rewind(); // Set the buffer position to 0 numThisBuf = fic.read(inBuf); while (numThisBuf < bufSize) { numThisBuf += fic.read(inBuf); } numRead += bufSize; inBuf.rewind(); // Set the buffer position to 0 inBuf.get(inBytes); boolean same = Arrays.equals(inBytes, outBytes); if (same = false) { System.out.println("Data read does not equal data written at " + numRead + " bytes"); } } } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(System.err); exitcode = 1; // break; } catch (SecurityException se) { se.printStackTrace(System.err); exitcode = 1; // break; } catch (Throwable t) { t.printStackTrace(System.err); exitcode = 1; } System.exit(exitcode); }
public boolean connect(Onion options, OobdBus receiveListener) { msgReceiver = receiveListener; System.out.println("Starting Bluetooth Detection and Device Pairing"); if (mBluetoothAdapter == null) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.w(this.getClass().getSimpleName(), "Bluetooth not supported."); return false; } if (!mBluetoothAdapter.isEnabled()) { Log.w(this.getClass().getSimpleName(), "Bluetooth switched off."); return false; } } obdDevice = mBluetoothAdapter.getRemoteDevice(BTAddress); if (obdDevice != null) { // Get a BluetoothSocket to connect // with the given BluetoothDevice try { Log.v(this.getClass().getSimpleName(), "Device " + obdDevice.getName()); java.lang.reflect.Method m = obdDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); // "createInsecureRfcommSocket", new Class[] { int.class }); serialPort = null; serialPort = (BluetoothSocket) m.invoke(obdDevice, 1); if (serialPort != null) { try { mBluetoothAdapter.cancelDiscovery(); serialPort.connect(); Log.d("OOBD:Bluetooth", "Bluetooth connected"); inputStream = serialPort.getInputStream(); outputStream = serialPort.getOutputStream(); OOBDApp.getInstance().displayToast("Bluetooth connected"); myThread = new Thread() { @Override public void run() { byte[] buffer = new byte[1024]; // buffer store // for the // stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an // exception occurs Log.d("OOBD:Bluetooth", "receiver task runs"); while (true) { if (inputStream != null) { try { // Read from the InputStream bytes = inputStream.read(buffer); if (bytes > 0) { Log.v(this.getClass().getSimpleName(), "Debug: received something"); String recString = new String(buffer); recString = recString.substring(0, bytes); msgReceiver.receiveString(recString); } } catch (IOException e) { break; } } else { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }; myThread.start(); return true; } catch (IOException ex) { Log.e(this.getClass().getSimpleName(), "Error: Could not connect to socket.", ex); OOBDApp.getInstance().displayToast("Bluetooth NOT connected!"); } } else { Log.e("OOBD:Bluetooth", "Bluetooth NOT connected!"); OOBDApp.getInstance().displayToast("Bluetooth NOT connected!"); if (serialPort != null) { try { serialPort.close(); } catch (IOException closeEx) { } } return false; } // do not yet connect. Connect before calling the // socket. } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; }
/** * Function that implements archive algorithm. Function archives all the files that were found by * search and were selected by user to be archived. Function places an archive either in user's * DropBox account or saves it on users hard drive, according to users choice. At the end function * updates the list of files that displayed in Handler window.Function returns JList<String> of * remaining files. * * @param l - list of file with selected files to be compressed to archive. * @return updated list of files. */ @SuppressWarnings({"rawtypes", "serial", "unchecked"}) public JList<String> archiveFiles(JList<String> l) { list = l; if (list.getMaxSelectionIndex() == -1) JOptionPane.showMessageDialog( null, "Please select files to be archived! ", "DrCleaner", JOptionPane.INFORMATION_MESSAGE); else { int j = JOptionPane.showConfirmDialog( null, "Are you sure you want to archive selected fles? ", "DrCleaner", JOptionPane.YES_NO_OPTION); if (j == JOptionPane.YES_OPTION) { String[] choises = {"Desktop Archive", "Dropbox archive", "Cancel"}; int responce = JOptionPane.showOptionDialog( handlerFrame, "Please choose where to place your archive", "Archive", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, new ImageIcon( HandlerView.class.getResource("/resources/document-archive-icon.png")), choises, "Desktop Archive"); switch (responce) { case 0: case 1: { String archiveName = now(); File newArchive = new File(archiveDirectory.getAbsolutePath() + File.separatorChar + archiveName); newArchive.mkdir(); final File zipFile = new File(newArchive.getAbsolutePath() + ".zip"); long space = 0; int numOfFilesThatCouldntArchive = 0; int numOfselected = 0; final Vector<String> temp = new Vector<String>(); Vector<File> archiveListOfFileNames = new Vector<File>(); // Will contain files that are placed in archive for (int i = 0; i < list.getModel().getSize(); i++) { if (list.isSelectedIndex(i)) { numOfselected++; /* * Because in the archive files stored only by their names(not the full path). we need to check if there are * files that have same names and rename them by adding "(index)" at the end of the name and just before the extension **/ File from = new File((String) list.getModel().getElementAt(i)); int extensionStartsAt = from.getName().lastIndexOf('.'); String newName = from.getName().substring(0, extensionStartsAt); String extension = from.getName().substring(extensionStartsAt, from.getName().length()); int counterOfFilesWithSameName = 2; String newName2 = new String(newName); File to = new File(newArchive.getAbsolutePath() + File.separatorChar + from.getName()); for (int k = 0; k < archiveListOfFileNames.size(); k++) { if (archiveListOfFileNames.get(k).getName().equals(to.getName())) { newName2 = newName + "(" + counterOfFilesWithSameName + ")"; to = new File( newArchive.getAbsolutePath() + File.separatorChar + newName2 + extension); counterOfFilesWithSameName++; k = -1; } } try { copyFile(from, to); archiveListOfFileNames.add(to); space += from.length(); // check that copy of file was made and that it is not corrupted. if (to.exists() && from.length() == to.length()) from.delete(); } catch (IOException ex) { ex.printStackTrace(); } } else temp.add((String) list.getModel().getElementAt(i)); } try { // making archive file from all selected files zipDirectory(newArchive, zipFile); // checking that zip file is not corrupted if (isValid(zipFile)) { for (File f : newArchive.listFiles()) f.delete(); newArchive.delete(); } if (responce == 1) { /* * in case that user choose to place the archive in DropBox account - open transfer dialog. * */ SwingUtilities.invokeLater( new Runnable() { @Override public void run() { TransferDialog t = new TransferDialog(zipFile); t.setVisible(true); } }); } } catch (IOException ex) { JOptionPane.showMessageDialog( null, "Problem occured while making archive ", "DrCleaner", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } catch (SecurityException ex) { JOptionPane.showMessageDialog( null, "Problem occured while deleting old files that were supposed to move to archive ", "DrCleaner", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } list.setModel( new javax.swing.AbstractListModel() { public int getSize() { return temp.size(); } public Object getElementAt(int i) { return temp.get(i); } }); list.repaint(); if (responce == 0) { // Feedback that concludes archive operation long savedSpace = space - zipFile.length(); String str = "From " + numOfselected + " selected files, " + (numOfselected - numOfFilesThatCouldntArchive) + " were archived\n Total saved space is: " + (savedSpace / 1024) + "KB\n" + "Your archive file is at: " + newArchive.getAbsolutePath(); JOptionPane.showMessageDialog( null, str, "DrCleaner", JOptionPane.INFORMATION_MESSAGE); } if (temp.isEmpty()) { JOptionPane.showMessageDialog( handlerFrame, "You have no more files to handle", "DrCleaner", JOptionPane.INFORMATION_MESSAGE); handlerFrame.dispose(); } break; } case 2: case -1: { JOptionPane.showMessageDialog( handlerFrame, "Operation was canceled", "DrCleaner", JOptionPane.INFORMATION_MESSAGE); } } } } return list; }
/** * Function that implements deleting algorithm. Function deletes all the files that were found by * search and were selected by user to be deleted. At the end function updates the list of files * that displayed in Handler window. * * @param l - list of file with selected files to be deleted * @return updated list of files */ @SuppressWarnings({"rawtypes", "serial", "unchecked"}) public JList<String> deleteFiles(JList<String> l) { list = l; if (list.getMaxSelectionIndex() == -1) JOptionPane.showMessageDialog( null, "Please select files to be deleted! ", "DrCleaner", JOptionPane.INFORMATION_MESSAGE); else { int j = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete selected fles? ", "DrCleaner", JOptionPane.YES_NO_OPTION); if (j == JOptionPane.YES_OPTION) { long space = 0; int numOfFilesThatCouldntDelete = 0; int numOfselected = 0; final Vector<String> temp = new Vector<String>(); for (int i = 0; i < list.getModel().getSize(); i++) { if (list.isSelectedIndex(i)) { numOfselected++; File f = new File((String) list.getModel().getElementAt(i)); space += f.length(); try { if (!f.delete()) { space -= f.length(); numOfFilesThatCouldntDelete++; } } catch (SecurityException e) { // TODO: handle exception e.printStackTrace(); } } else temp.add((String) list.getModel().getElementAt(i)); } list.setModel( new javax.swing.AbstractListModel() { public int getSize() { return temp.size(); } public Object getElementAt(int i) { return temp.get(i); } }); list.repaint(); String str = "From " + numOfselected + " selected files, " + (numOfselected - numOfFilesThatCouldntDelete) + " were deleted\n Total saved space is: " + (space / 1024) + "KB"; JOptionPane.showMessageDialog(null, str, "DrCleaner", JOptionPane.INFORMATION_MESSAGE); if (temp.isEmpty()) { JOptionPane.showMessageDialog( handlerFrame, "You have no more files to handle", "DrCleaner", JOptionPane.INFORMATION_MESSAGE); handlerFrame.dispose(); } } } return list; }
/** * Installs all necessary files and starts the Tor OP in offline mode (e.g. * networkEnabled(false)). This would only be used if you wanted to start the Tor OP so that the * install and related is all done but aren't ready to actually connect it to the network. * * @return True if all files installed and Tor OP successfully started * @throws java.io.IOException - IO Exceptions * @throws java.lang.InterruptedException - If we are, well, interrupted */ public synchronized boolean installAndStartTorOp() throws IOException, InterruptedException { // The Tor OP will die if it looses the connection to its socket so if there is no controlSocket // defined // then Tor is dead. This assumes, of course, that takeOwnership works and we can't end up with // Zombies. if (controlConnection != null) { LOG.info("Tor is already running"); return true; } // The code below is why this method is synchronized, we don't want two instances of it running // at once // as the result would be a mess of screwed up files and connections. LOG.info("Tor is not running"); installAndConfigureFiles(); LOG.info("Starting Tor"); File cookieFile = onionProxyContext.getCookieFile(); if (cookieFile.getParentFile().exists() == false && cookieFile.getParentFile().mkdirs() == false) { throw new RuntimeException("Could not create cookieFile parent directory"); } // The original code from Briar watches individual files, not a directory and Android's file // observer // won't work on files that don't exist. Rather than take 5 seconds to rewrite Briar's code I // instead // just make sure the file exists if (cookieFile.exists() == false && cookieFile.createNewFile() == false) { throw new RuntimeException("Could not create cookieFile"); } File workingDirectory = onionProxyContext.getWorkingDirectory(); // Watch for the auth cookie file being created/updated WriteObserver cookieObserver = onionProxyContext.generateWriteObserver(cookieFile); // Start a new Tor process String torPath = onionProxyContext.getTorExecutableFile().getAbsolutePath(); String configPath = onionProxyContext.getTorrcFile().getAbsolutePath(); String pid = onionProxyContext.getProcessId(); String[] cmd = {torPath, "-f", configPath, OWNER, pid}; String[] env = onionProxyContext.getEnvironmentArgsForExec(); ProcessBuilder processBuilder = new ProcessBuilder(cmd); onionProxyContext.setEnvironmentArgsAndWorkingDirectoryForStart(processBuilder); Process torProcess = null; try { // torProcess = Runtime.getRuntime().exec(cmd, env, workingDirectory); torProcess = processBuilder.start(); CountDownLatch controlPortCountDownLatch = new CountDownLatch(1); eatStream(torProcess.getInputStream(), false, controlPortCountDownLatch); eatStream(torProcess.getErrorStream(), true, null); // On platforms other than Windows we run as a daemon and so we need to wait for the process // to detach // or exit. In the case of Windows the equivalent is running as a service and unfortunately // that requires // managing the service, such as turning it off or uninstalling it when it's time to move on. // Any number // of errors can prevent us from doing the cleanup and so we would leave the process running // around. Rather // than do that on Windows we just let the process run on the exec and hence don't look for an // exit code. // This does create a condition where the process has exited due to a problem but we should // hopefully // detect that when we try to use the control connection. if (OsData.getOsType() != OsData.OsType.Windows) { int exit = torProcess.waitFor(); torProcess = null; if (exit != 0) { LOG.warn("Tor exited with value " + exit); return false; } } // Wait for the auth cookie file to be created/updated if (!cookieObserver.poll(COOKIE_TIMEOUT, MILLISECONDS)) { LOG.warn("Auth cookie not created"); FileUtilities.listFilesToLog(workingDirectory); return false; } // Now we should be able to connect to the new process controlPortCountDownLatch.await(); controlSocket = new Socket("127.0.0.1", control_port); // Open a control connection and authenticate using the cookie file TorControlConnection controlConnection = new TorControlConnection(controlSocket); controlConnection.authenticate(FileUtilities.read(cookieFile)); // Tell Tor to exit when the control connection is closed controlConnection.takeOwnership(); controlConnection.resetConf(Collections.singletonList(OWNER)); // Register to receive events from the Tor process controlConnection.setEventHandler(new OnionProxyManagerEventHandler()); controlConnection.setEvents(Arrays.asList(EVENTS)); // We only set the class property once the connection is in a known good state this.controlConnection = controlConnection; return true; } catch (SecurityException e) { LOG.warn(e.toString(), e); return false; } catch (InterruptedException e) { LOG.warn("Interrupted while starting Tor", e); Thread.currentThread().interrupt(); return false; } finally { if (controlConnection == null && torProcess != null) { // It's possible that something 'bad' could happen after we executed exec but before we // takeOwnership() // in which case the Tor OP will hang out as a zombie until this process is killed. This is // problematic // when we want to do things like torProcess.destroy(); } } }