List of usage examples for java.io RandomAccessFile RandomAccessFile
public RandomAccessFile(File file, String mode) throws FileNotFoundException
From source file:com.ettrema.zsync.UploadReader.java
/** * Copies the contents of the source file to the destination file and sets the destination * file's length./*from ww w . j av a2 s.c o m*/ * * @param inFile The source file * @param outFile The destination file * @param length The desired length of the destination file * @throws IOException */ private static void copyFile(File inFile, File outFile, long length) throws IOException { InputStream fIn = null; OutputStream fOut = null; RandomAccessFile randAccess = null; try { fIn = new FileInputStream(inFile); fOut = new FileOutputStream(outFile); PartialEntity.sendBytes(fIn, fOut, inFile.length()); } finally { StreamUtils.close(fIn); StreamUtils.close(fOut); } try { randAccess = new RandomAccessFile(outFile, "rw"); randAccess.setLength(length); } finally { Util.close(randAccess); } }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIOnJDKUpgrade(String javaHome) { logger.debug("Updating INI file if JDK path is updated"); RandomAccessFile file = null; boolean isUpdated = false; try {//from w w w. ja v a 2 s . co m file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; while (file.getFilePointer() != file.length()) { if (StringUtils.equals(file.readLine(), "-vm")) { String currentLine = file.readLine(); if (StringUtils.equals(currentLine, javaHome)) { logger.debug("JAVA_HOME and -vm in configuration file are same"); } else { logger.debug( "JAVA_HOME and -vm in configuration file are different. Updating configuration file with JAVA_HOME"); file.seek(0); file.readFully(text); file.seek(0); updateData(text, javaHome, currentLine, file); isUpdated = true; } break; } } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while closing " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:com.emc.vipr.sync.source.FilesystemSource.java
protected void delete(File file) { // Try to lock the file first. If this fails, the file is // probably open for write somewhere. // Note that on a mac, you can apparently delete files that // someone else has open for writing, and can lock files // too.//from ww w. ja v a 2 s . c o m // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files. if (file.isDirectory()) { File metaDir = getMetaFile(file).getParentFile(); if (metaDir.exists()) metaDir.delete(); // Just try and delete dir if (!file.delete()) { LogMF.warn(l4j, "Failed to delete directory {0}", file); } } else { boolean tryDelete = true; if (deleteOlderThan > 0) { if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) { LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan); tryDelete = false; } } if (deleteCheckScript != null) { String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() }; try { l4j.debug("delete check: " + Arrays.asList(args)); Process p = Runtime.getRuntime().exec(args); while (true) { try { int exitCode = p.exitValue(); if (exitCode == 0) { LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode); } else { LogMF.info(l4j, "delete check failed, exit code {0}. Not deleting file.", exitCode); tryDelete = false; } break; } catch (IllegalThreadStateException e) { // Ignore. } } } catch (IOException e) { LogMF.info(l4j, "error executing delete check script: {0}. Not deleting file.", e.toString()); tryDelete = false; } } RandomAccessFile raf = null; if (tryDelete) { try { raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); FileLock flock = fc.lock(); // If we got here, we should be good. flock.release(); if (!file.delete()) { throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file)); } } catch (IOException e) { throw new RuntimeException(MessageFormat .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage())); } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignore. } } } } } }
From source file:io.milton.zsync.UploadReader.java
/** * Copies the contents of the source file to the destination file and sets * the destination file's length.//from w w w . j a va2 s . c o m * * @param inFile The source file * @param outFile The destination file * @param length The desired length of the destination file * @throws IOException */ private static void copyFile(File inFile, File outFile, long length) throws IOException { InputStream fIn = null; OutputStream fOut = null; RandomAccessFile randAccess = null; try { fIn = new FileInputStream(inFile); fOut = new FileOutputStream(outFile); RangeUtils.sendBytes(fIn, fOut, inFile.length()); } finally { StreamUtils.close(fIn); StreamUtils.close(fOut); } try { randAccess = new RandomAccessFile(outFile, "rw"); randAccess.setLength(length); } finally { Util.close(randAccess); } }
From source file:au.org.ala.layers.grid.GridClassBuilder.java
public static HashMap<Integer, GridClass> buildFromGrid(String filePath) throws IOException { File wktDir = new File(filePath); wktDir.mkdirs();//from w w w .ja v a 2 s . c om int[] wktMap = null; //track values for the SLD ArrayList<Integer> maxValues = new ArrayList<Integer>(); ArrayList<String> labels = new ArrayList<String>(); HashMap<Integer, GridClass> classes = new HashMap<Integer, GridClass>(); Properties p = new Properties(); p.load(new FileReader(filePath + ".txt")); boolean mergeProperties = false; Map<String, Set<Integer>> groupedKeys = new HashMap<String, Set<Integer>>(); Map<Integer, Integer> translateKeys = new HashMap<Integer, Integer>(); Map<String, Integer> translateValues = new HashMap<String, Integer>(); ArrayList<Integer> keys = new ArrayList<Integer>(); for (String key : p.stringPropertyNames()) { try { int k = Integer.parseInt(key); keys.add(k); //grouping of property file keys by value String value = p.getProperty(key); Set<Integer> klist = groupedKeys.get(value); if (klist == null) klist = new HashSet<Integer>(); else mergeProperties = true; klist.add(k); groupedKeys.put(value, klist); if (!translateValues.containsKey(value)) translateValues.put(value, translateValues.size() + 1); translateKeys.put(k, translateValues.get(value)); } catch (NumberFormatException e) { logger.info("Excluding shape key '" + key + "'"); } catch (Exception e) { logger.error(e.getMessage(), e); } } java.util.Collections.sort(keys); Grid g = new Grid(filePath); boolean generateWkt = false; //((long) g.nrows) * ((long) g.ncols) < (long) Integer.MAX_VALUE; if (mergeProperties) { g.replaceValues(translateKeys); if (!new File(filePath + ".txt.old").exists()) FileUtils.moveFile(new File(filePath + ".txt"), new File(filePath + ".txt.old")); StringBuilder sb = new StringBuilder(); for (String value : translateValues.keySet()) { sb.append(translateValues.get(value)).append("=").append(value).append('\n'); } FileUtils.writeStringToFile(new File(filePath + ".txt"), sb.toString()); return buildFromGrid(filePath); } if (generateWkt) { for (String name : groupedKeys.keySet()) { try { Set<Integer> klist = groupedKeys.get(name); String key = klist.iterator().next().toString(); int k = Integer.parseInt(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); if (klist.size() == 1) klist = null; logger.info("getting wkt for " + filePath + " > " + key); Map wktIndexed = Envelope.getGridSingleLayerEnvelopeAsWktIndexed( filePath + "," + key + "," + key, klist, wktMap); //write class wkt File zipFile = new File(filePath + File.separator + key + ".wkt.zip"); ZipOutputStream zos = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); zos.putNextEntry(new ZipEntry(key + ".wkt")); zos.write(((String) wktIndexed.get("wkt")).getBytes()); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } BufferedOutputStream bos = null; try { bos = new BufferedOutputStream( new FileOutputStream(filePath + File.separator + key + ".wkt")); bos.write(((String) wktIndexed.get("wkt")).getBytes()); bos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (bos != null) { try { bos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("wkt written to file"); gc.setArea_km(SpatialUtil.calculateArea((String) wktIndexed.get("wkt")) / 1000.0 / 1000.0); //store map wktMap = (int[]) wktIndexed.get("map"); //write wkt index FileWriter fw = null; try { fw = new FileWriter(filePath + File.separator + key + ".wkt.index"); fw.append((String) wktIndexed.get("index")); fw.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fw != null) { try { fw.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //write wkt index a binary, include extents (minx, miny, maxx, maxy) and area (sq km) int minPolygonNumber = 0; int maxPolygonNumber = 0; RandomAccessFile raf = null; try { raf = new RandomAccessFile(filePath + File.separator + key + ".wkt.index.dat", "rw"); String[] index = ((String) wktIndexed.get("index")).split("\n"); for (int i = 0; i < index.length; i++) { if (index[i].length() > 1) { String[] cells = index[i].split(","); int polygonNumber = Integer.parseInt(cells[0]); raf.writeInt(polygonNumber); //polygon number int polygonStart = Integer.parseInt(cells[1]); raf.writeInt(polygonStart); //character offset if (i == 0) { minPolygonNumber = polygonNumber; } else if (i == index.length - 1) { maxPolygonNumber = polygonNumber; } } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (raf != null) { try { raf.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //for SLD maxValues.add(gc.getMaxShapeIdx()); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(minPolygonNumber); gc.setMaxShapeIdx(maxPolygonNumber); logger.info("getting multipolygon for " + filePath + " > " + key); MultiPolygon mp = Envelope.getGridEnvelopeAsMultiPolygon(filePath + "," + key + "," + key); gc.setBbox(mp.getEnvelope().toText().replace(" (", "(").replace(", ", ",")); classes.put(k, gc); try { //write class kml zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".kml.zip")); zos.putNextEntry(new ZipEntry(key + ".kml")); Encoder encoder = new Encoder(new KMLConfiguration()); encoder.setIndenting(true); encoder.encode(mp, KML.Geometry, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("kml written to file"); final SimpleFeatureType TYPE = DataUtilities.createType("class", "the_geom:MultiPolygon,id:Integer,name:String"); FeatureJSON fjson = new FeatureJSON(); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); SimpleFeature sf = featureBuilder.buildFeature(null); //write class geojson zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".geojson.zip")); zos.putNextEntry(new ZipEntry(key + ".geojson")); featureBuilder.add(mp); featureBuilder.add(k); featureBuilder.add(name); fjson.writeFeature(sf, zos); zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("geojson written to file"); //write class shape file File newFile = new File(filePath + File.separator + key + ".shp"); ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); params.put("url", newFile.toURI().toURL()); params.put("create spatial index", Boolean.FALSE); ShapefileDataStore newDataStore = null; try { newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params); newDataStore.createSchema(TYPE); newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); Transaction transaction = new DefaultTransaction("create"); String typeName = newDataStore.getTypeNames()[0]; SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName); SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); List<SimpleFeature> features = new ArrayList<SimpleFeature>(); DefaultFeatureCollection collection = new DefaultFeatureCollection(); collection.addAll(features); featureStore.setTransaction(transaction); features.add(sf); featureStore.addFeatures(collection); transaction.commit(); transaction.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (newDataStore != null) { try { newDataStore.dispose(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } zos = null; try { zos = new ZipOutputStream( new FileOutputStream(filePath + File.separator + key + ".shp.zip")); //add .dbf .shp .shx .prj String[] exts = { ".dbf", ".shp", ".shx", ".prj" }; for (String ext : exts) { zos.putNextEntry(new ZipEntry(key + ext)); FileInputStream fis = null; try { fis = new FileInputStream(filePath + File.separator + key + ext); byte[] buffer = new byte[1024]; int size; while ((size = fis.read(buffer)) > 0) { zos.write(buffer, 0, size); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } //remove unzipped files new File(filePath + File.separator + key + ext).delete(); } zos.flush(); } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (zos != null) { try { zos.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } } logger.info("shape file written to zip"); } catch (Exception e) { logger.error(e.getMessage(), e); } } catch (Exception e) { logger.error(e.getMessage(), e); } } //write polygon mapping g.writeGrid(filePath + File.separator + "polygons", wktMap, g.xmin, g.ymin, g.xmax, g.ymax, g.xres, g.yres, g.nrows, g.ncols); //copy the header file to get it exactly the same, but change the data type copyHeaderAsInt(filePath + ".grd", filePath + File.separator + "polygons.grd"); } else { //build classes without generating polygons Map<Float, float[]> info = new HashMap<Float, float[]>(); for (int j = 0; j < keys.size(); j++) { info.put(keys.get(j).floatValue(), new float[] { 0, Float.NaN, Float.NaN, Float.NaN, Float.NaN }); } g.getClassInfo(info); for (int j = 0; j < keys.size(); j++) { int k = keys.get(j); String key = String.valueOf(k); String name = p.getProperty(key); GridClass gc = new GridClass(); gc.setName(name); gc.setId(k); //for SLD maxValues.add(Integer.valueOf(key)); labels.add(name.replace("\"", "'")); gc.setMinShapeIdx(Integer.valueOf(key)); gc.setMaxShapeIdx(Integer.valueOf(key)); float[] stats = info.get(keys.get(j).floatValue()); //only include if area > 0 if (stats[0] > 0) { gc.setBbox("POLYGON((" + stats[1] + " " + stats[2] + "," + stats[1] + " " + stats[4] + "," + stats[3] + " " + stats[4] + "," + stats[3] + " " + stats[2] + "," + stats[1] + " " + stats[2] + "))"); gc.setArea_km((double) stats[0]); classes.put(k, gc); } } } //write sld exportSLD(filePath + File.separator + "polygons.sld", new File(filePath + ".txt").getName(), maxValues, labels); writeProjectionFile(filePath + File.separator + "polygons.prj"); //write .classes.json ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File(filePath + ".classes.json"), classes); return classes; }
From source file:net.yacy.yacy.java
/** * Starts up the whole application. Sets up all datastructures and starts * the main threads.//w w w .java2 s . c om * * @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:MSUmpire.SpectrumParser.mzXMLParser.java
private void ParseElutionIndex() throws Exception { if (ScanIndex == null | ScanIndex.isEmpty()) { return;//from w ww. ja va 2 s .c om } try (RandomAccessFile fileHandler = new RandomAccessFile(filename, "r")) { Iterator<Entry<Integer, Long>> iter = ScanIndex.entrySet().iterator(); Long currentIdx = iter.next().getValue(); while (iter.hasNext()) { long startposition = currentIdx; long nexposition = iter.next().getValue(); currentIdx = nexposition; fileHandler.seek(startposition); byte[] bufr = new byte[(int) (nexposition - startposition)]; fileHandler.readFully(bufr, 0, (int) (nexposition - startposition)); String temp = new String(bufr); float rt = 0f; int scanno = 0; int mslevel = 0; //float precursorF=0f; if (!temp.contains("<scan")) { fileHandler.close(); return; } if (temp.contains("<scan num=") && (temp.contains("retentionTime=\"PT"))) { String substr = temp.substring(temp.indexOf("<scan num=") + 11); scanno = Integer.parseInt(substr.substring(0, substr.indexOf("\""))); rt = Float.parseFloat(temp.substring(temp.indexOf("retentionTime=\"PT") + 17).split("S\"")[0]); rt = rt / 60f; mslevel = Integer .parseInt(temp.substring(temp.indexOf("msLevel=") + 9, temp.indexOf("msLevel=") + 10)); if (temp.contains("scanType=\"calibration\"")) { mslevel = -1; } if (mslevel == 1) { NoMS1Scans++; if (temp.contains("scanType=\"SIM\"") && datatype == SpectralDataType.DataType.WiSIM) { int startidx = temp.indexOf("lowMz=\"") + 7; int stopidx = startidx + 1; for (int i = startidx + 1; i < temp.length(); i++) { if (temp.charAt(i) == '\"') { stopidx = i; break; } } float lowmz = Float.parseFloat(temp.substring(startidx, stopidx)); startidx = temp.indexOf("highMz=\"") + 8; stopidx = startidx + 1; for (int i = startidx + 1; i < temp.length(); i++) { if (temp.charAt(i) == '\"') { stopidx = i; break; } } float highmz = Float.parseFloat(temp.substring(startidx, stopidx)); for (XYData MS1win : dIA_Setting.MS1Windows.keySet()) { if (MS1win.getX() <= lowmz && MS1win.getY() >= highmz) { dIA_Setting.MS1Windows.get(MS1win).add(scanno); } } } } //If it is DIA data, parse isolation window ranges if (datatype != SpectralDataType.DataType.DDA) { if (mslevel == 2) { if (datatype == SpectralDataType.DataType.MSX) { substr = temp; while (substr.contains("</precursorMz>")) { int stopidx = substr.indexOf("</precursorMz>"); int startidx = 0; for (int i = stopidx; i > 0; i--) { if (substr.charAt(i) == '>') { startidx = i + 1; break; } } float precursormz = Float.parseFloat(substr.substring(startidx, stopidx)); startidx = substr.indexOf("windowWideness=\"") + 16; stopidx = startidx + 1; for (int i = startidx + 1; i < substr.length(); i++) { if (substr.charAt(i) == '\"') { stopidx = i; break; } } float windowwideness = Float.parseFloat(substr.substring(startidx, stopidx)); //Assuming the precursor m/z is at the center of isolation window, it's for Thermo MSX data float Loffset = windowwideness / 2f; float Roffset = windowwideness / 2f; if (!dIA_Setting.DIAWindows.containsKey( new XYData(precursormz - Loffset, precursormz + Roffset))) { ArrayList<Integer> scanList = new ArrayList<>(); dIA_Setting.DIAWindows.put( new XYData(precursormz - Loffset, precursormz + Roffset), scanList); } dIA_Setting.DIAWindows .get(new XYData(precursormz - Loffset, precursormz + Roffset)) .add(scanno); substr = substr.substring(substr.indexOf("</precursorMz>") + 14); } } else if (datatype == SpectralDataType.DataType.DIA_F_Window || datatype == SpectralDataType.DataType.pSMART || datatype == SpectralDataType.DataType.WiSIM) { int stopidx = temp.indexOf("</precursorMz>"); if (stopidx == -1) { Logger.getRootLogger() .error("Parsing </precursorMz> failed. scan number :" + scanno); System.exit(3); } int startidx = 0; for (int i = stopidx; i > 0; i--) { if (temp.charAt(i) == '>') { startidx = i + 1; break; } } float precursormz = Float.parseFloat(temp.substring(startidx, stopidx)); //By default, assuming it's 5600 data, //and assume the precursor m/z is at 0.25 * window size Da to the lower bound of isolation window float Loffset = (dIA_Setting.F_DIA_WindowSize + 1) * 0.2f; float Roffset = (dIA_Setting.F_DIA_WindowSize + 1) * 0.8f; //If the scan contains "windowWideness", then it is a Thermo data, overwrite the isolation window ranges if (temp.contains("windowWideness=\"")) { startidx = temp.indexOf("windowWideness=\"") + 16; stopidx = startidx + 1; for (int i = startidx + 1; i < temp.length(); i++) { if (temp.charAt(i) == '\"') { stopidx = i; break; } } float windowwideness = Float.parseFloat(temp.substring(startidx, stopidx)); //Again assume the precursor m/z is at the center of isolation window, because it is a Thermo data Loffset = windowwideness / 2f; Roffset = windowwideness / 2f; } if (!dIA_Setting.DIAWindows .containsKey(new XYData(precursormz - Loffset, precursormz + Roffset))) { ArrayList<Integer> scanList = new ArrayList<>(); dIA_Setting.DIAWindows.put( new XYData(precursormz - Loffset, precursormz + Roffset), scanList); } dIA_Setting.DIAWindows.get(new XYData(precursormz - Loffset, precursormz + Roffset)) .add(scanno); } else if (datatype == SpectralDataType.DataType.DIA_V_Window) { //if the DIA data is variable window size setting, then use the pre-defined setting int stopidx = temp.indexOf("</precursorMz>"); int startidx = 0; for (int i = stopidx; i > 0; i--) { if (temp.charAt(i) == '>') { startidx = i + 1; break; } } float precursormz = Float.parseFloat(temp.substring(startidx, stopidx)); for (XYData window : dIA_Setting.DIAWindows.keySet()) { if (window.getX() <= precursormz && window.getY() >= precursormz) { dIA_Setting.DIAWindows.get(window).add(scanno); break; } } } else if (datatype == SpectralDataType.DataType.MSe) { float mzlowF = 0f; float mzhighF = 10000f; if (!dIA_Setting.DIAWindows.containsKey(new XYData(mzlowF, mzhighF))) { ArrayList<Integer> scanList = new ArrayList<>(); dIA_Setting.DIAWindows.put(new XYData(mzlowF, mzhighF), scanList); } dIA_Setting.DIAWindows.get(new XYData(mzlowF, mzhighF)).add(scanno); } } } } else { Logger.getRootLogger().error("index of mzXML error"); System.exit(1); } ElutionTimeToScanNoMap.put(rt, scanno); ScanToElutionTime.put(scanno, rt); MsLevelList.put(scanno, mslevel); } ScanToElutionTime.compact(); fileHandler.close(); } }
From source file:org.messic.server.api.APISong.java
@Transactional public AudioSongStream getAudioSong(User user, long sid) throws IOException { MDOUser mdouser = daoUser.getUserByLogin(user.getLogin()); MDOSong song = daoSong.get(mdouser.getLogin(), sid); if (song != null) { MDOMessicSettings settings = daoSettings.getSettings(); if (mdouser.getAllowStatistics()) { MDOSongStatistics statistics = song.getStatistics(); if (statistics == null) { statistics = new MDOSongStatistics(); daoSongStatistics.save(statistics); statistics = daoSongStatistics.getStatistics(user.getLogin(), song.getSid()); song.setStatistics(statistics); }//from w w w . j a v a 2 s.c om statistics.addTimePlayed(); daoSong.save(song); } String filePath = song.calculateAbsolutePath(settings); File fsong = new File(filePath); if (fsong.exists()) { AudioSongStream ass = new AudioSongStream(); ass.raf = new RandomAccessFile(fsong, "r"); ass.is = new FileInputStream(fsong); // ass.is = new FileInputStream( fsong ); ass.contentLength = fsong.length(); ass.lastModified = fsong.lastModified(); ass.songFileName = fsong.getName(); return ass; } } return null; }
From source file:hotbeans.support.FileSystemHotBeanModuleRepository.java
/** * Obtains a file lock on the repository lock file. *///from w ww .jav a2 s .c o m protected RepositoryFileLock obtainRepositoryFileLock(final boolean shared, final int timeout) throws IOException { Log logger = this.getLog(); if (logger.isDebugEnabled()) logger.debug("Obtaining repository file lock (shared: " + shared + ")."); RepositoryFileLock repositoryFileLock = null; FileLock lock = null; final long beginWait = System.currentTimeMillis(); while (repositoryFileLock == null) { try { RandomAccessFile lockFile = new RandomAccessFile( new File(moduleRepositoryDirectory, LOCK_FILE_NAME), "rws"); FileChannel channel = lockFile.getChannel(); // Attempt to obtain a lock on the file lock = channel.tryLock(0L, Long.MAX_VALUE, shared); if (!shared && (lockFile.length() == 0)) { lockFile.write(new String("LOCK").getBytes()); lockFile.getFD().sync(); } repositoryFileLock = new RepositoryFileLock(lockFile, lock); } catch (IOException ioe) { if (logger.isDebugEnabled()) logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ioe); if (timeout < 0) throw ioe; } catch (OverlappingFileLockException ofle) { if (logger.isDebugEnabled()) logger.debug("Error obtaining repository file lock (shared: " + shared + ").", ofle); if (timeout < 0) throw ofle; } if (repositoryFileLock == null) // This statement shouldn't be reaced if timeout is < 0 { if ((System.currentTimeMillis() - beginWait) > timeout) // Wait a maximum of timeout milliseconds on lock { throw new IOException("Timeout while waiting for file lock on repository lock file!"); } else { // Otherwise - wait a while before trying to obtain a lock again try { Thread.sleep(Math.min(250, timeout - (System.currentTimeMillis() - beginWait))); } catch (InterruptedException ie) { } } } } if (logger.isDebugEnabled()) logger.debug("Repository file lock (shared: " + shared + ") obtained."); return repositoryFileLock; }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>//from w w w . j av a2s . c om * * @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; }