List of usage examples for java.nio.channels FileChannel close
public final void close() throws IOException
From source file:org.blue.star.plugins.check_ftp.java
public boolean execute_check() { /* Declare variables */ FTPClient ftp = new FTPClient(); File filename = null;/*from ww w .j a v a 2 s. co m*/ FileChannel channel; InputStream is; OutputStream os; int reply; if (super.verbose > 0) verbose = true; /* Configure client to meet our requirements */ ftp.setDefaultPort(port); ftp.setDefaultTimeout(timeout); if (verbose) { System.out.println("Using FTP Server: " + hostname); System.out.println("Using FTP Port: " + port); System.out.println("Using Timeout of: " + timeout); } if (passive) { ftp.enterLocalPassiveMode(); if (verbose) System.out.println("Using Passive Mode"); } try { filename = new File(file); channel = new RandomAccessFile(filename, "rw").getChannel(); if (verbose) System.out.println("Attempting FTP Connection to " + hostname); ftp.connect(hostname); reply = ftp.getReplyCode(); /* Test to see if we actually managed to connect */ if (!FTPReply.isPositiveCompletion(reply)) { if (verbose) System.out.println("FTP Connection to " + hostname + " failed"); check_state = common_h.STATE_CRITICAL; check_message = ftp.getReplyString(); filename.delete(); ftp.disconnect(); return true; } /* Try and login if we're using username/password */ if (username != null && password != null) { if (verbose) System.out.println("Attempting to log in into FTP Server " + hostname); if (!ftp.login(username, password)) { if (verbose) System.out.println("Unable to log in to FTP Server " + hostname); check_state = common_h.STATE_CRITICAL; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } } if (verbose) System.out.println("Attempting to change to required directory"); /* Try and change to the given directory */ if (!ftp.changeWorkingDirectory(directory)) { if (verbose) System.out.println("Required directory cannot be found!"); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } if (verbose) System.out.println("Attempting to retrieve specified file!"); /* Try to get Stream on Remote File! */ is = ftp.retrieveFileStream(file); if (is == null) { if (verbose) System.out.println("Unable to locate required file."); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } /* OutputStream */ os = Channels.newOutputStream(channel); /* Create the buffer */ byte[] buf = new byte[4096]; if (verbose) System.out.println("Beginning File transfer..."); for (int len = -1; (len = is.read(buf)) != -1;) os.write(buf, 0, len); if (verbose) { System.out.println("...transfer complete."); System.out.println("Attempting to finalise Command"); } /* Finalise the transfer details */ if (!ftp.completePendingCommand()) { if (verbose) System.out.println("Unable to finalise command"); check_state = common_h.STATE_WARNING; check_message = ftp.getReplyString(); ftp.disconnect(); filename.delete(); return true; } /* Clean up */ if (verbose) System.out.println("Check Completed."); check_state = common_h.STATE_OK; check_message = ftp.getReplyString(); /* Close out things */ is.close(); os.close(); channel.close(); filename.delete(); } catch (IOException e) { check_state = common_h.STATE_CRITICAL; check_message = e.getMessage(); if (filename != null) filename.delete(); } finally { if (ftp.isConnected()) { try { ftp.logout(); ftp.disconnect(); } catch (Exception e) { } } } return true; }
From source file:es.pode.publicacion.negocio.servicios.SrvPublicacionServiceImpl.java
/** * Mueve el contenido de un directorio a otro directorio. * /*from ww w.ja v a 2s . c o m*/ * @param oldDir * Directorio origen. * @param newDir * Directorio destino. * @return devuelve el tamanio del directorio movido. * @throws Exception * */ protected Long handleMoveDir(File oldDir, File newDir) throws IOException { long longitudTransferida = 0; if (oldDir.isDirectory()) { newDir.mkdirs(); String list[] = oldDir.list(); for (int i = 0; i < list.length; i++) { String dest1 = newDir.getAbsolutePath() + "/" + list[i]; String src1 = oldDir.getAbsolutePath() + "/" + list[i]; longitudTransferida += handleMoveDir(new File(src1), new File(dest1)).longValue(); } } else { FileInputStream fin = new FileInputStream(oldDir); FileOutputStream fos = new FileOutputStream(newDir); FileChannel sourceChannel = fin.getChannel(); FileChannel targetChannel = fos.getChannel(); longitudTransferida = sourceChannel.size(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); } return new Long(longitudTransferida); }
From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java
/** * Starts copy of file/*from w w w . j a v a2s . co m*/ * Supports : {@link File}, {@link jcifs.smb.SmbFile}, {@link DocumentFile}, {@link CloudStorage} * @param lowOnMemory defines whether system is running low on memory, in which case we'll switch to * using streams instead of channel which maps the who buffer in memory. * TODO: Use buffers even on low memory but don't map the whole file to memory but * parts of it, and transfer each part instead. */ private void startCopy(boolean lowOnMemory) throws IOException { FileInputStream inputStream = null; FileOutputStream outputStream = null; FileChannel inChannel = null; FileChannel outChannel = null; BufferedInputStream bufferedInputStream = null; BufferedOutputStream bufferedOutputStream = null; try { // initializing the input channels based on file types if (mSourceFile.isOtgFile()) { // source is in otg ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentSourceFile = OTGUtil.getDocumentFile(mSourceFile.getPath(), mContext, false); bufferedInputStream = new BufferedInputStream( contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isSmb()) { // source is in smb bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isSftp()) { bufferedInputStream = new BufferedInputStream(mSourceFile.getInputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mSourceFile.isDropBoxFile()) { CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); bufferedInputStream = new BufferedInputStream( cloudStorageDropbox.download(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()))); } else if (mSourceFile.isBoxFile()) { CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); bufferedInputStream = new BufferedInputStream( cloudStorageBox.download(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()))); } else if (mSourceFile.isGoogleDriveFile()) { CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); bufferedInputStream = new BufferedInputStream( cloudStorageGdrive.download(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()))); } else if (mSourceFile.isOneDriveFile()) { CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE); bufferedInputStream = new BufferedInputStream(cloudStorageOnedrive .download(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()))); } else { // source file is neither smb nor otg; getting a channel from direct file instead of stream File file = new File(mSourceFile.getPath()); if (FileUtil.isReadable(file)) { if (mTargetFile.isOneDriveFile() || mTargetFile.isDropBoxFile() || mTargetFile.isGoogleDriveFile() || mTargetFile.isBoxFile() || lowOnMemory) { // our target is cloud, we need a stream not channel bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); } else { inChannel = new RandomAccessFile(file, "r").getChannel(); } } else { ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentSourceFile = FileUtil.getDocumentFile(file, mSourceFile.isDirectory(), mContext); bufferedInputStream = new BufferedInputStream( contentResolver.openInputStream(documentSourceFile.getUri()), DEFAULT_BUFFER_SIZE); } } // initializing the output channels based on file types if (mTargetFile.isOtgFile()) { // target in OTG, obtain streams from DocumentFile Uri's ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentTargetFile = OTGUtil.getDocumentFile(mTargetFile.getPath(), mContext, true); bufferedOutputStream = new BufferedOutputStream( contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isSftp()) { bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isSmb()) { bufferedOutputStream = new BufferedOutputStream(mTargetFile.getOutputStream(mContext), DEFAULT_BUFFER_SIZE); } else if (mTargetFile.isDropBoxFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX); if (mSourceFile.isDropBoxFile()) { // we're in the same provider, use api method cloudStorageDropbox.copy(CloudUtil.stripPath(OpenMode.DROPBOX, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath())); return; } else { cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); return; } } else if (mTargetFile.isBoxFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX); if (mSourceFile.isBoxFile()) { // we're in the same provider, use api method cloudStorageBox.copy(CloudUtil.stripPath(OpenMode.BOX, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath())); return; } else { cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else if (mTargetFile.isGoogleDriveFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE); if (mSourceFile.isGoogleDriveFile()) { // we're in the same provider, use api method cloudStorageGdrive.copy(CloudUtil.stripPath(OpenMode.GDRIVE, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath())); return; } else { cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else if (mTargetFile.isOneDriveFile()) { // API doesn't support output stream, we'll upload the file directly CloudStorage cloudStorageOnedrive = dataUtils.getAccount(OpenMode.ONEDRIVE); if (mSourceFile.isOneDriveFile()) { // we're in the same provider, use api method cloudStorageOnedrive.copy(CloudUtil.stripPath(OpenMode.ONEDRIVE, mSourceFile.getPath()), CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath())); return; } else { cloudStorageOnedrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, mTargetFile.getPath()), bufferedInputStream, mSourceFile.getSize(), true); bufferedInputStream.close(); return; } } else { // copying normal file, target not in OTG File file = new File(mTargetFile.getPath()); if (FileUtil.isWritable(file)) { if (lowOnMemory) { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); } else { outChannel = new RandomAccessFile(file, "rw").getChannel(); } } else { ContentResolver contentResolver = mContext.getContentResolver(); DocumentFile documentTargetFile = FileUtil.getDocumentFile(file, mTargetFile.isDirectory(), mContext); bufferedOutputStream = new BufferedOutputStream( contentResolver.openOutputStream(documentTargetFile.getUri()), DEFAULT_BUFFER_SIZE); } } if (bufferedInputStream != null) { if (bufferedOutputStream != null) copyFile(bufferedInputStream, bufferedOutputStream); else if (outChannel != null) { copyFile(bufferedInputStream, outChannel); } } else if (inChannel != null) { if (bufferedOutputStream != null) copyFile(inChannel, bufferedOutputStream); else if (outChannel != null) copyFile(inChannel, outChannel); } } catch (IOException e) { e.printStackTrace(); Log.d(getClass().getSimpleName(), "I/O Error!"); throw new IOException(); } catch (OutOfMemoryError e) { e.printStackTrace(); // we ran out of memory to map the whole channel, let's switch to streams AppConfig.toast(mContext, mContext.getString(R.string.copy_low_memory)); startCopy(true); } finally { try { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); if (bufferedInputStream != null) bufferedInputStream.close(); if (bufferedOutputStream != null) bufferedOutputStream.close(); } catch (IOException e) { e.printStackTrace(); // failure in closing stream } //If target file is copied onto the device and copy was successful, trigger media store //rescan if ((mTargetFile.isLocal() || mTargetFile.isOtgFile()) && mTargetFile.exists(mContext)) { DocumentFile documentFile = FileUtil.getDocumentFile(mTargetFile.getFile(), false, mContext); //If FileUtil.getDocumentFile() returns null, fall back to DocumentFile.fromFile() if (documentFile == null) documentFile = DocumentFile.fromFile(mTargetFile.getFile()); FileUtils.scanFile(documentFile.getUri(), mContext); } } }
From source file:net.yacy.yacy.java
/** * Starts up the whole application. Sets up all datastructures and starts * the main threads./*from w ww.jav a 2 s . com*/ * * @param homePath Root-path where all information is to be found. * @param startupFree free memory at startup time, to be used later for statistics */ private static void startup(final File dataHome, final File appHome, final long startupMemFree, final long startupMemTotal, final boolean gui) { String tmpdir = null; try { // start up System.out.println(copyright); System.out.println(hline); // ensure that there is a DATA directory, if not, create one and if that fails warn and die mkdirsIfNeseccary(dataHome); mkdirsIfNeseccary(appHome); File f = new File(dataHome, "DATA/"); mkdirsIfNeseccary(f); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + dataHome.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // set jvm tmpdir to a subdir for easy cleanup (as extensive use file.deleteonexit waists memory during long runs, as todelete files names are collected and never cleaned up during runtime) // keep this as earlier as possible, as any other class can use the "java.io.tmpdir" property, even the log manager, when the log file pattern uses "%t" as an alias for the tmp directory try { tmpdir = java.nio.file.Files.createTempDirectory("yacy-tmp-").toString(); // creates sub dir in jvm's temp (see System.property "java.io.tempdir") System.setProperty("java.io.tmpdir", tmpdir); } catch (IOException ex) { } // setting up logging f = new File(dataHome, "DATA/LOG/"); mkdirsIfNeseccary(f); f = new File(dataHome, "DATA/LOG/yacy.logging"); final File f0 = new File(appHome, "defaults/yacy.logging"); if (!f.exists() || f0.lastModified() > f.lastModified()) try { Files.copy(f0, f); } catch (final IOException e) { System.out.println("could not copy yacy.logging"); } try { ConcurrentLog.configureLogging(dataHome, new File(dataHome, "DATA/LOG/yacy.logging")); } catch (final IOException e) { System.out.println("could not find logging properties in homePath=" + dataHome); ConcurrentLog.logException(e); } ConcurrentLog.config("STARTUP", "YaCy version: " + yacyBuildProperties.getVersion() + "/" + yacyBuildProperties.getSVNRevision()); ConcurrentLog.config("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); ConcurrentLog.config("STARTUP", "Operation system: " + System.getProperty("os.name", "unknown")); ConcurrentLog.config("STARTUP", "Application root-path: " + appHome); ConcurrentLog.config("STARTUP", "Data root-path: " + dataHome); ConcurrentLog.config("STARTUP", "Time zone: UTC" + GenericFormatter.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); ConcurrentLog.config("STARTUP", "Maximum file system path length: " + OS.maxPathLength); f = new File(dataHome, "DATA/yacy.running"); final String conf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); if (!f.createNewFile()) ConcurrentLog.severe("STARTUP", "WARNING: the file " + f + " can not be created!"); try { new FileOutputStream(f).write(Integer.toString(OS.getPID()).getBytes()); } catch (final Exception e) { } // write PID f.deleteOnExit(); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.tryLock(); // lock yacy.running } catch (final Exception e) { } try { sb = new Switchboard(dataHome, appHome, "defaults/yacy.init".replace("/", File.separator), conf); } catch (final RuntimeException e) { ConcurrentLog.severe("STARTUP", "YaCy cannot start: " + e.getMessage(), e); System.exit(-1); } //sbSync.V(); // signal that the sb reference was set // switch the memory strategy MemoryControl.setStandardStrategy(sb.getConfigBool("memory.standardStrategy", true)); // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // start gui if wanted if (gui) YaCyApp.start("localhost", sb.getLocalPort()); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); double oldVer; try { String tmpversion = sb.getConfig(Seed.VERSION, ""); if (tmpversion.isEmpty()) { // before 1.83009737 only the svnRevision nr was in config (like 9737) tmpversion = yacyBuildProperties.getVersion(); int oldRev = Integer.parseInt(sb.getConfig("svnRevision", "0")); if (oldRev > 1) { oldVer = Double.parseDouble(tmpversion) + oldRev / 100000000.0; } else { oldVer = Double.parseDouble(yacyBuildProperties.getLongVersion()); // failsafe (assume current version = no migration) } } else { oldVer = Double.parseDouble(tmpversion); } } catch (final NumberFormatException e) { oldVer = 0.0d; } final double newRev = Double.parseDouble(yacyBuildProperties.getLongVersion()); sb.setConfig(Seed.VERSION, yacyBuildProperties.getLongVersion()); sb.setConfig("applicationRoot", appHome.toString()); sb.setConfig("dataRoot", dataHome.toString()); // create some directories final File htRootPath = new File(appHome, sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); mkdirIfNeseccary(htRootPath); htDocsPath = sb.getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT); mkdirIfNeseccary(htDocsPath); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // copy the donate iframe (better to copy this once here instead of doing this in an actual iframe in the search result) importDonationIFrame(sb, htDocsPath); // create default notifier picture File notifierFile = new File(htDocsPath, "notifier.gif"); if (!notifierFile.exists()) try { Files.copy(new File(htRootPath, "env/grafics/empty.gif"), notifierFile); } catch (final IOException e) { } final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try { FileUtils.copy(("This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme); } catch (final IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } shareDefaultPath = new File(htDocsPath, "share"); mkdirIfNeseccary(shareDefaultPath); shareDumpDefaultPath = new File(shareDefaultPath, "dump"); mkdirIfNeseccary(shareDumpDefaultPath); migration.migrate(sb, oldVer, newRev); // delete old release files final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyRelease.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays); // set user-agent HTTPClient.setDefaultUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent); // start main threads final int port = sb.getLocalPort(); try { // start http server YaCyHttpServer httpServer; httpServer = new Jetty9HttpServerImpl(port); httpServer.startupServer(); sb.setHttpServer(httpServer); // TODO: this has no effect on Jetty (but needed to reflect configured value and limit is still used) ConnectionInfo.setServerMaxcount(sb.getConfigInt("connectionsMax", ConnectionInfo.getMaxcount())); ConcurrentLog.info("STARTUP", httpServer.getVersion()); // open the browser window final boolean browserPopUpTrigger = sb .getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) try { final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); //boolean properPW = (sb.getConfig(SwitchboardConstants.ADMIN_ACCOUNT, "").isEmpty()) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; /* YaCy main startup process must not hang because browser opening is long or fails. * Let's open try opening the browser in a separate thread */ new Thread("Browser opening") { @Override public void run() { Browser.openBrowser(("http://localhost:" + port) + "/" + browserPopUpPage); } }.start(); // Browser.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage); } catch (final Throwable e) { // cannot open browser. This may be normal in headless environments //Log.logException(e); } // enable browser popup, http server is ready now sb.tray.setReady(); //regenerate Locales from Translationlist, if needed final File locale_source = sb.getAppPath("locale.source", "locales"); final String lang = sb.getConfig("locale.language", ""); // on lang=browser all active translation should be checked (because any could be requested by client) List<String> langlist; if (lang.endsWith("browser")) langlist = Translator.activeTranslations(); // get all translated languages else { langlist = new ArrayList<String>(); langlist.add(lang); } for (String tmplang : langlist) { if (!tmplang.equals("") && !tmplang.equals("default") && !tmplang.equals("browser")) { //locale is used String currentRev = null; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream( new File(sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang + "/version")))); currentRev = br.readLine(); // may return null } catch (final IOException e) { //Error } finally { try { br.close(); } catch (IOException ioe) { ConcurrentLog.warn("STARTUP", "Could not close " + tmplang + " version file"); } } if (currentRev == null || !currentRev.equals(sb.getConfig(Seed.VERSION, ""))) { try { //is this another version?! final File sourceDir = new File(sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); final File destDir = new File( sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang); if (new TranslatorXliff().translateFilesRecursive(sourceDir, destDir, new File(locale_source, tmplang + ".lng"), "html,template,inc", "locale")) { //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter( new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig(Seed.VERSION, "Error getting Version")); bw.close(); } } catch (final IOException e) { } } } } // initialize number formatter with this locale if (!lang.equals("browser")) // "default" is handled by .setLocale() Formatter.setLocale(lang); // registering shutdown hook ConcurrentLog.config("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(sb, shutdownSemaphore)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitBGC", MemoryControl.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitAGC", MemoryControl.total()); //} catch (final ConcurrentModificationException e) {} // wait for server shutdown try { sb.waitForShutdown(); } catch (final Exception e) { ConcurrentLog.severe("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(), e); } // shut down Array.terminate(); ConcurrentLog.config("SHUTDOWN", "caught termination signal"); httpServer.stop(); ConcurrentLog.config("SHUTDOWN", "server has terminated"); sb.close(); } catch (final Exception e) { ConcurrentLog.severe("STARTUP", "Unexpected Error: " + e.getClass().getName(), e); //System.exit(1); } if (lock != null) lock.release(); if (channel != null) channel.close(); } catch (final Exception ee) { ConcurrentLog.severe("STARTUP", "FATAL ERROR: " + ee.getMessage(), ee); } finally { } if (tmpdir != null) FileUtils.deletedelete(new File(tmpdir)); // clean up temp dir (set at startup as subdir of system.propery "java.io.tmpdir") ConcurrentLog.config("SHUTDOWN", "goodbye. (this is the last line)"); ConcurrentLog.shutdown(); shutdownSemaphore.release(1000); try { System.exit(0); } catch (final Exception e) { } // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }
From source file:com.zoffcc.applications.zanavi.Navit.java
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return;/*ww w.j a v a 2s.c o m*/ } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public Object[] subsetObjectVector(File tabfile, int column, int varcount, int casecount, int columntype, boolean compatmode) throws IOException { Object[] retVector = null;/*from w w w. j a va 2 s . c o m*/ boolean isString = false; boolean isDouble = false; boolean isLong = false; boolean isFloat = false; //Locale loc = new Locale("en", "US"); if (columntype == COLUMN_TYPE_STRING) { isString = true; retVector = new String[casecount]; } else if (columntype == COLUMN_TYPE_DOUBLE) { isDouble = true; retVector = new Double[casecount]; } else if (columntype == COLUMN_TYPE_LONG) { isLong = true; retVector = new Long[casecount]; } else if (columntype == COLUMN_TYPE_FLOAT) { isFloat = true; retVector = new Float[casecount]; } else { throw new IOException("Unsupported column type: " + columntype); } File rotatedImageFile = getRotatedImage(tabfile, varcount, casecount); long[] columnEndOffsets = extractColumnOffsets(rotatedImageFile, varcount, casecount); long columnOffset = 0; long columnLength = 0; if (column > 0) { columnOffset = columnEndOffsets[column - 1]; columnLength = columnEndOffsets[column] - columnEndOffsets[column - 1]; } else { columnOffset = varcount * 8; columnLength = columnEndOffsets[0] - varcount * 8; } FileChannel fc = (FileChannel.open(Paths.get(rotatedImageFile.getAbsolutePath()), StandardOpenOption.READ)); fc.position(columnOffset); int MAX_COLUMN_BUFFER = 8192; ByteBuffer in = ByteBuffer.allocate(MAX_COLUMN_BUFFER); if (columnLength < MAX_COLUMN_BUFFER) { in.limit((int) (columnLength)); } long bytesRead = 0; long bytesReadTotal = 0; int caseindex = 0; int byteoffset = 0; byte[] leftover = null; while (bytesReadTotal < columnLength) { bytesRead = fc.read(in); byte[] columnBytes = in.array(); int bytecount = 0; while (bytecount < bytesRead) { if (columnBytes[bytecount] == '\n') { /* String token = new String(columnBytes, byteoffset, bytecount-byteoffset, "UTF8"); if (leftover != null) { String leftoverString = new String (leftover, "UTF8"); token = leftoverString + token; leftover = null; } */ /* * Note that the way I was doing it at first - above - * was not quite the correct way - because I was creating UTF8 * strings from the leftover bytes, and the bytes in the * current buffer *separately*; which means, if a multi-byte * UTF8 character got split in the middle between one buffer * and the next, both chunks of it would become junk * characters, on each side! * The correct way of doing it, of course, is to create a * merged byte buffer, and then turn it into a UTF8 string. * -- L.A. 4.0 */ String token = null; if (leftover == null) { token = new String(columnBytes, byteoffset, bytecount - byteoffset, "UTF8"); } else { byte[] merged = new byte[leftover.length + bytecount - byteoffset]; System.arraycopy(leftover, 0, merged, 0, leftover.length); System.arraycopy(columnBytes, byteoffset, merged, leftover.length, bytecount - byteoffset); token = new String(merged, "UTF8"); leftover = null; merged = null; } if (isString) { if ("".equals(token)) { // An empty string is a string missing value! // An empty string in quotes is an empty string! retVector[caseindex] = null; } else { // Strip the outer quotes: token = token.replaceFirst("^\\\"", ""); token = token.replaceFirst("\\\"$", ""); // We need to restore the special characters that // are stored in tab files escaped - quotes, new lines // and tabs. Before we do that however, we need to // take care of any escaped backslashes stored in // the tab file. I.e., "foo\t" should be transformed // to "foo<TAB>"; but "foo\\t" should be transformed // to "foo\t". This way new lines and tabs that were // already escaped in the original data are not // going to be transformed to unescaped tab and // new line characters! String[] splitTokens = token.split(Matcher.quoteReplacement("\\\\"), -2); // (note that it's important to use the 2-argument version // of String.split(), and set the limit argument to a // negative value; otherwise any trailing backslashes // are lost.) for (int i = 0; i < splitTokens.length; i++) { splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\""); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r"); } // TODO: // Make (some of?) the above optional; for ex., we // do need to restore the newlines when calculating UNFs; // But if we are subsetting these vectors in order to // create a new tab-delimited file, they will // actually break things! -- L.A. Jul. 28 2014 token = StringUtils.join(splitTokens, '\\'); // "compatibility mode" - a hack, to be able to produce // unfs identical to those produced by the "early" // unf5 jar; will be removed in production 4.0. // -- L.A. (TODO: ...) if (compatmode && !"".equals(token)) { if (token.length() > 128) { if ("".equals(token.trim())) { // don't ask... token = token.substring(0, 129); } else { token = token.substring(0, 128); //token = String.format(loc, "%.128s", token); token = token.trim(); //dbgLog.info("formatted and trimmed: "+token); } } else { if ("".equals(token.trim())) { // again, don't ask; // - this replicates some bugginness // that happens inside unf5; token = "null"; } else { token = token.trim(); } } } retVector[caseindex] = token; } } else if (isDouble) { try { // TODO: verify that NaN and +-Inf are // handled correctly here! -- L.A. // Verified: new Double("nan") works correctly, // resulting in Double.NaN; // Double("[+-]Inf") doesn't work however; // (the constructor appears to be expecting it // to be spelled as "Infinity", "-Infinity", etc. if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Double.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Double.NEGATIVE_INFINITY; } else if (token == null || token.equals("")) { // missing value: retVector[caseindex] = null; } else { retVector[caseindex] = new Double(token); } } catch (NumberFormatException ex) { dbgLog.warning("NumberFormatException thrown for " + token + " as Double"); retVector[caseindex] = null; // missing value // TODO: ? } } else if (isLong) { try { retVector[caseindex] = new Long(token); } catch (NumberFormatException ex) { retVector[caseindex] = null; // assume missing value } } else if (isFloat) { try { if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Float.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Float.NEGATIVE_INFINITY; } else if (token == null || token.equals("")) { // missing value: retVector[caseindex] = null; } else { retVector[caseindex] = new Float(token); } } catch (NumberFormatException ex) { dbgLog.warning("NumberFormatException thrown for " + token + " as Float"); retVector[caseindex] = null; // assume missing value (TODO: ?) } } caseindex++; if (bytecount == bytesRead - 1) { byteoffset = 0; } else { byteoffset = bytecount + 1; } } else { if (bytecount == bytesRead - 1) { // We've reached the end of the buffer; // This means we'll save whatever unused bytes left in // it - i.e., the bytes between the last new line // encountered and the end - in the leftover buffer. // *EXCEPT*, there may be a case of a very long String // that is actually longer than MAX_COLUMN_BUFFER, in // which case it is possible that we've read through // an entire buffer of bytes without finding any // new lines... in this case we may need to add this // entire byte buffer to an already existing leftover // buffer! if (leftover == null) { leftover = new byte[(int) bytesRead - byteoffset]; System.arraycopy(columnBytes, byteoffset, leftover, 0, (int) bytesRead - byteoffset); } else { if (byteoffset != 0) { throw new IOException( "Reached the end of the byte buffer, with some leftover left from the last read; yet the offset is not zero!"); } byte[] merged = new byte[leftover.length + (int) bytesRead]; System.arraycopy(leftover, 0, merged, 0, leftover.length); System.arraycopy(columnBytes, byteoffset, merged, leftover.length, (int) bytesRead); //leftover = null; leftover = merged; merged = null; } byteoffset = 0; } } bytecount++; } bytesReadTotal += bytesRead; in.clear(); if (columnLength - bytesReadTotal < MAX_COLUMN_BUFFER) { in.limit((int) (columnLength - bytesReadTotal)); } } fc.close(); if (caseindex != casecount) { throw new IOException("Faile to read " + casecount + " tokens for column " + column); //System.out.println("read "+caseindex+" tokens instead of expected "+casecount+"."); } return retVector; }
From source file:com.zoffcc.applications.zanavi.Navit.java
private void import_map_points_from_sdcard() { String orig_file = NAVIT_DATA_SHARE_DIR + Navit_DEST_FILENAME; String dest_file_dir = CFG_FILENAME_PATH + "../export/"; try {/*from w w w . jav a 2s . co m*/ File source = new File(dest_file_dir + Navit_DEST_FILENAME); File destination = new File(orig_file); if (source.exists()) { FileInputStream fi = new FileInputStream(source); FileOutputStream fo = new FileOutputStream(destination); FileChannel src = fi.getChannel(); FileChannel dst = fo.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); fi.close(); fo.close(); } } catch (Exception e) { e.printStackTrace(); } read_map_points(); }
From source file:com.zoffcc.applications.zanavi.Navit.java
private void export_map_points_to_sdcard() { String orig_file = NAVIT_DATA_SHARE_DIR + Navit_DEST_FILENAME; String dest_file_dir = CFG_FILENAME_PATH + "../export/"; try {/*from w w w . j av a 2 s .c o m*/ File dir = new File(dest_file_dir); dir.mkdirs(); } catch (Exception e) { e.printStackTrace(); } try { File source = new File(orig_file); File destination = new File(dest_file_dir + Navit_DEST_FILENAME); if (source.exists()) { FileInputStream fi = new FileInputStream(source); FileOutputStream fo = new FileOutputStream(destination); FileChannel src = fi.getChannel(); FileChannel dst = fo.getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); fi.close(); fo.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
private byte[] readIntoBytes(InputStream zin, String fName, long length) throws IOException { byte[] buffer = new byte[4096]; File f = File.createTempFile("asgnup", "tmp"); FileOutputStream fout = new FileOutputStream(f); try {/*from w w w . j a va2 s. co m*/ int len; while ((len = zin.read(buffer)) > 0) { fout.write(buffer, 0, len); } zin.close(); } finally { try { fout.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileOutputStream " + ioException.getMessage()); } } FileInputStream fis = new FileInputStream(f); FileChannel fc = fis.getChannel(); byte[] data = null; try { data = new byte[(int) (fc.size())]; // fc.size returns the size of the file which backs the channel ByteBuffer bb = ByteBuffer.wrap(data); fc.read(bb); } finally { try { fc.close(); // The file channel needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileChannel " + ioException.getMessage()); } try { fis.close(); // The file inputstream needs to be closed before the deletion. } catch (IOException ioException) { M_log.warn(this + "readIntoBytes: problem closing FileInputStream " + ioException.getMessage()); } } //remove the file f.delete(); return data; }