protected void createDirs(File target) throws FMFileManagerException { if (clone) { return; } deleteDirs(); File parent = target.getParentFile(); if (!parent.exists()) { List new_dirs = new ArrayList(); File current = parent; while (current != null && !current.exists()) { new_dirs.add(current); current = current.getParentFile(); } created_dirs_leaf = target; created_dirs = new ArrayList(); if (FileUtil.mkdirs(parent)) { created_dirs = new_dirs; /* for (int i=created_dirs.size()-1;i>=0;i--){ System.out.println( "created " + created_dirs.get(i)); } */ } else { // had some reports of this exception being thrown when starting a torrent // double check in case there's some parallel creation being triggered somehow try { Thread.sleep(RandomUtils.nextInt(1000)); } catch (Throwable e) { } FileUtil.mkdirs(parent); if (parent.isDirectory()) { created_dirs = new_dirs; } else { throw (new FMFileManagerException("Failed to create parent directory '" + parent + "'")); } } } }
/** Returns the value in the proper format: "value". */ protected String getValue(String strUser, String strValue) { ArrayList aListValues = WUtil.strToAList(strValue); String strNewValue = ""; if (strValue == null || strValue.trim().length() <= 0) return ""; String strPath = FileUtil.openPath("SYSPROF" + File.separator + strUser) + File.pathSeparator + FileUtil.openPath("USRPROF" + File.separator + strUser); HashMap hmUser = WFileUtil.getHashMap(strPath); for (int i = 0; i < aListValues.size(); i++) { strNewValue = (String) aListValues.get(i); if (strNewValue == null) strNewValue = ""; // if the value is of the form: $home, then parse the value if (hmUser != null && strNewValue.indexOf('$') >= 0) { strValue = WFileUtil.parseValue(strNewValue, hmUser); if (strValue != null && strValue.trim().length() > 0) strNewValue = strValue; } } return strNewValue; }
public static synchronized void printPS(Origin o, String printerAlias, int copyCount) throws Exception { String command = Properties.get(Names.PS_PRINT_APP); Printer printer = find(printerAlias); File printTemp = new File( Properties.get(Names.TEMP_DIR) + Names.PATH_SEPARATOR + "print-queue", "print-" + getNextCount()); if (printTemp.exists()) FileUtil.delete(printTemp); printTemp.mkdirs(); InputStream in = Downloader.download(o); File print = new File(printTemp, o.getName()); if (print.exists()) print.delete(); FileUtil.save(in, print, true); File work = new File( Properties.get(Names.WORKING_DIR) + Names.PATH_SEPARATOR + "print", "work-" + getNextCount()); if (!work.exists()) work.mkdirs(); int i; for (i = 0; i < copyCount; i++) { ExecShell shell = new ExecShell(); shell.setExecutable(command); shell.setWorkingDirectory(work); shell.addCommandLineArgument("/D:" + printer.getPath(), false); shell.addCommandLineArgument(print.getAbsolutePath(), true); { } // Logwriter.printOnConsole("sleeping for 2.."); Thread.sleep(2000); { } // Logwriter.printOnConsole("waking up"); shell.execute(); } }
/** * method to return the Localized version of the file whose name is passed as an argument. The * localization is done based on localization subdirectories under the docBase. * * <p>The method performs a resource lookup in a manner similar to the one used for JavaHelp * resources. * * <p>Search for localized versions of the file are looked for: * * <p><docBase> + "/" + language1 + "_" + country1 + "_" + variant1 + file <docBase> + "/" + * language1 + "_" + country1 + file <docBase> + "/" + language1 + file <docBase> + "/" + * language2 + "_" + country2 + "_" + variant1 + file <docBase> + "/" + language2 + "_" + country2 * + file <docBase> + "/" + language2 + file <docBase> + file * * <p>Where language1, country1, variant1 are associated with the Locale passed as an argument and * language2, country2, variant are associated with the fallback Locale passed as argument. * * @param path the pathname for the resource whose localized version we are seeking * @param loc the Locale we are interested in. * @param fbLoc the fallback Locale to use if unsuccessful * @param locType the type of localization required "file", "docbase" * @return a String with the path of the "best localized match" for the file whose path has been * passed as argument. */ public String getRealPath(String path, Locale reqLocale, Locale fbLocale, String locType) { String base = getAbsolutePath(); if (path == null) path = ""; String realPath = null; if ("file".equals(locType)) realPath = FileUtil.getLocalizedFile(base, path, reqLocale, fbLocale); else if ("docbase".equals(locType)) realPath = FileUtil.getDocBaseLocalizedFile(base, path, reqLocale, fbLocale); if (debug > 5) { log( "Get real path " + path + " " + realPath + " " + base + reqLocale.toString() + " " + fbLocale.toString()); } return realPath; }
private void writeFile(SpectralClustering cluster) { FileUtil.clean(output); int[] lab = cluster.getClusterLabel(); for (int x = 0; x < lab.length; x++) { final Doc doc = list.get(x); String one = doc.url + "\n" + doc.title + "\n" + doc.text + "\n" + hr; FileUtil.write(new File(output, lab[x] + ".txt"), one, true); } }
// the method which actually copies the caches locally and unjars/unzips them // and does chmod for the files private static Path localizeCache( Configuration conf, URI cache, long confFileStamp, CacheStatus cacheStatus, boolean isArchive) throws IOException { FileSystem fs = getFileSystem(cache, conf); FileSystem localFs = FileSystem.getLocal(conf); Path parchive = null; if (isArchive) { parchive = new Path( cacheStatus.localizedLoadPath, new Path(cacheStatus.localizedLoadPath.getName())); } else { parchive = cacheStatus.localizedLoadPath; } if (!localFs.mkdirs(parchive.getParent())) { throw new IOException( "Mkdirs failed to create directory " + cacheStatus.localizedLoadPath.toString()); } String cacheId = cache.getPath(); fs.copyToLocalFile(new Path(cacheId), parchive); if (isArchive) { String tmpArchive = parchive.toString().toLowerCase(); File srcFile = new File(parchive.toString()); File destDir = new File(parchive.getParent().toString()); if (tmpArchive.endsWith(".jar")) { RunJar.unJar(srcFile, destDir); } else if (tmpArchive.endsWith(".zip")) { FileUtil.unZip(srcFile, destDir); } else if (isTarFile(tmpArchive)) { FileUtil.unTar(srcFile, destDir); } // else will not do anyhting // and copy the file into the dir as it is } long cacheSize = FileUtil.getDU(new File(parchive.getParent().toString())); cacheStatus.size = cacheSize; addCacheInfoUpdate(cacheStatus); // do chmod here try { // Setting recursive permission to grant everyone read and execute Path localDir = new Path(cacheStatus.localizedBaseDir, cacheStatus.uniqueParentDir); LOG.info("Doing chmod on localdir :" + localDir); FileUtil.chmod(localDir.toString(), "ugo+rx", true); } catch (InterruptedException e) { LOG.warn("Exception in chmod" + e.toString()); } // update cacheStatus to reflect the newly cached file cacheStatus.mtime = getTimestamp(conf, cache); return cacheStatus.localizedLoadPath; }
public String loadText() { File file = getPropertyFile(); InputStream fin = null; try { fin = new FileInputStream(file); byte[] buff = FileUtil.readAll(fin); return new String(buff); } catch (Exception e) { } finally { FileUtil.close(fin); } return null; }
/** Write file with position and size of the login box */ public static void writePersistence() { Messages.postDebug("LoginBox", "LoginBox.writePersistence"); // If the panel has not been created, don't try to write a file if (position == null) return; String filepath = FileUtil.savePath("USER/PERSISTENCE/LoginPanel"); FileWriter fw; PrintWriter os; try { File file = new File(filepath); fw = new FileWriter(file); os = new PrintWriter(fw); os.println("Login Panel"); os.println(height); os.println(width); double xd = position.getX(); int xi = (int) xd; os.println(xi); double yd = position.getY(); int yi = (int) yd; os.println(yi); os.close(); } catch (Exception er) { Messages.postError("Problem creating " + filepath); Messages.writeStackTrace(er); } }
protected String gettitle(String strFreq) { StringBuffer sbufTitle = new StringBuffer().append("VnmrJ "); String strPath = FileUtil.openPath(FileUtil.SYS_VNMR + "/vnmrrev"); BufferedReader reader = WFileUtil.openReadFile(strPath); String strLine; String strtype = ""; if (reader == null) return sbufTitle.toString(); try { while ((strLine = reader.readLine()) != null) { strtype = strLine; } strtype = strtype.trim(); if (strtype.equals("merc")) strtype = "Mercury"; else if (strtype.equals("mercvx")) strtype = "Mercury-Vx"; else if (strtype.equals("mercplus")) strtype = "MERCURY plus"; else if (strtype.equals("inova")) strtype = "INOVA"; String strHostName = m_strHostname; if (strHostName == null) strHostName = ""; sbufTitle.append(" ").append(strHostName); sbufTitle.append(" ").append(strtype); sbufTitle.append(" - ").append(strFreq); reader.close(); } catch (Exception e) { // e.printStackTrace(); Messages.logError(e.toString()); } return sbufTitle.toString(); }
protected void setData(String strChecksum) { String strValue = (String) m_cmbPath.getSelectedItem(); if (strValue == null || strValue.equals("")) return; m_cmbChecksum.removeAllItems(); String strPath = strValue.substring(strValue.lastIndexOf("/") + 1); strPath = UtilB.unixPathToWindows(FileUtil.SYS_VNMR + "/p11/checksums/" + strPath); strPath = FileUtil.openPath(strPath); if (strPath != null) { File file = new File(strPath); String[] files = file.list(); int nSize = files.length; for (int i = 0; i < nSize; i++) { String strfile = files[i]; m_cmbChecksum.addItem(strfile); } int nIndex = strChecksum.lastIndexOf("/"); if (nIndex < 0) nIndex = strChecksum.lastIndexOf(File.separator); if (nIndex + 1 < strChecksum.length()) strChecksum = strChecksum.substring(nIndex + 1); m_cmbChecksum.setSelectedItem(strChecksum); } }
@Override @NotNull public byte[] contentsToByteArray(int contentId) throws IOException { final DataInputStream stream = readContentById(contentId); assert stream != null : contentId; return FileUtil.loadBytes(stream); }
public synchronized boolean reload(boolean force) { long now = System.currentTimeMillis(); if (force == false && now < last_check + 3000) return false; last_check = now; File file = getPropertyFile(); if (file.lastModified() == last_load_time) { return false; } last_load_time = file.lastModified(); Properties temp = new Properties(); if (file.canRead()) { FileInputStream in = null; try { in = new FileInputStream(file); temp.load(in); } catch (Exception e) { e.printStackTrace(); } finally { FileUtil.close(in); } } property = ConfigValueUtil.replaceSysProp(temp); apply(); ConfObserver.run(); return true; }
private static Collection<? extends File> findFiles( Collection<String> extensions, File directory) { Set<File> result = new HashSet<File>(); File[] children = directory.listFiles(); if (children == null) { return result; // No permission? } for (File child : children) { if (child.isDirectory()) { result.addAll(UtilFindFiles.findFiles(extensions, child)); } else { String extension = FileUtil.getFileExtension(child); if (extension != null) { if (extensions.contains(extension)) { result.add(child); } } } } return result; }
public Labyrinth(String fileName) throws Exception { List<GeometricObject> objs = new ArrayList<GeometricObject>(); String[] lines = FileUtil.readTextLines(fileName); int nRect = 0; int nSpace = 0; int maxWidth = 0; for (int y = 0; y < lines.length; y++) { char[] line = lines[y].toCharArray(); if (maxWidth < line.length) { maxWidth = line.length; } for (int x = 0; x < line.length; x++) { switch (line[x]) { case rectangleChar: objs.add( new GeometricObject( new Vertex(rectangleLength * x, rectangleLength * y), rectangleLength, rectangleLength)); nRect++; break; case spaceChar: nSpace++; break; default: throw new Exception("Unsupported char:" + line[x] + " in file:" + fileName); } } } this.objects = objs.toArray(new GeometricObject[0]); this.width = maxWidth * (int) rectangleLength; this.height = lines.length * (int) rectangleLength; }
private String copyFromLocal(FileSystem fs, Path basePath, String[] files) throws IOException { StringBuilder csv = new StringBuilder(files.length * (basePath.toString().length() + 16)); for (String localFile : files) { Path src = new Path(localFile); String filename = src.getName(); Path dst = new Path(basePath, filename); URI localFileURI = null; try { localFileURI = new URI(localFile); } catch (URISyntaxException e) { throw new IOException(e); } if (localFileURI.getScheme() == null || localFileURI.getScheme().startsWith("file")) { LOG.info("Copy {} from local filesystem to {}", localFile, dst); fs.copyFromLocalFile(false, true, src, dst); } else { LOG.info("Copy {} from DFS to {}", localFile, dst); FileUtil.copy(fs, src, fs, dst, false, true, conf); } if (csv.length() > 0) { csv.append(LIB_JARS_SEP); } csv.append(dst.toString()); } return csv.toString(); }
public void buildPanel() { String path = FileUtil.getLayoutPath(layoutDir, fname); if (path == null) { Messages.postError("Could not open xml file:" + fname); return; } removeAll(); try { LayoutBuilder.build(pane, vnmrIf, path); } catch (Exception e) { String strError = "Error building file: " + path; Messages.postError(strError); Messages.writeStackTrace(e); return; } if (bScrollBar) { spane = new JScrollPane( pane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); add(spane); } else { spane = null; add(pane); } paramsLayout.preferredLayoutSize(pane); }
/** * Implements getResource() See getRealPath(), it have to be local to the current Context - and * can't go to a sub-context. That means we don't need any overhead. */ public URL getResource(String rpath) throws MalformedURLException { if (rpath == null) return null; if (URLUtil.hasEscape(rpath)) return null; URL url = null; String absPath = getAbsolutePath(); if ("".equals(rpath)) return new URL("file", null, 0, absPath); if (!rpath.startsWith("/")) rpath = "/" + rpath; String realPath = FileUtil.safePath(absPath, rpath); if (realPath == null) { log("Unsafe path " + absPath + " " + rpath); return null; } try { url = new URL("file", null, 0, realPath); if (debug > 9) log("getResourceURL=" + url + " request=" + rpath); return url; } catch (IOException ex) { ex.printStackTrace(); return null; } }
protected void setTrays() { String strPath = FileUtil.openPath(TRAYINFO); if (strPath == null) return; setTrayPresent(strPath); setTrayActive(m_strDir); repaint(); }
private FsRoot( @NotNull NewVirtualFileSystem fs, int id, VfsData.Segment segment, VfsData.DirectoryData data, @NotNull String basePath) { super(id, segment, data, fs); myName = FileUtil.toSystemIndependentName(basePath); }
private void _dimension() { FileUtil.clean(root); int x = 0; for (File file : root1.listFiles()) { Doc doc = buildDoc(x, file); // System.out.println(doc.vector.getTFIDFValues()); Iterator<Map.Entry<String, Double>> it = doc.vector.getTFIDFValues().entrySet().iterator(); for (; it.hasNext(); ) { if (it.next().getValue() < 0.05) { it.remove(); } } String str = StringUtils.join(doc.vector.getTFIDFValues().keySet().iterator(), " "); str = doc.url + "\n" + doc.title + "\n" + str + "\n" + doc.text; FileUtil.write(new File(root, file.getName()), str, false); x++; } }
@NotNull private static String normalizeRootUrl( @NotNull String basePath, @NotNull NewVirtualFileSystem fs) { // need to protect against relative path of the form "/x/../y" return UriUtil.trimTrailingSlashes( fs.getProtocol() + URLUtil.SCHEME_SEPARATOR + VfsImplUtil.normalize(fs, FileUtil.toCanonicalPath(basePath))); }
@Override @NotNull public byte[] contentsToByteArray(@NotNull final VirtualFile file, boolean cacheContent) throws IOException { InputStream contentStream = null; boolean reloadFromDelegate; boolean outdated; int fileId; synchronized (myInputLock) { fileId = getFileId(file); outdated = checkFlag(fileId, MUST_RELOAD_CONTENT) || FSRecords.getLength(fileId) == -1L; reloadFromDelegate = outdated || (contentStream = readContent(file)) == null; } if (reloadFromDelegate) { final NewVirtualFileSystem delegate = getDelegate(file); final byte[] content; if (outdated) { // in this case, file can have out-of-date length. so, update it first (it's needed for // correct contentsToByteArray() work) // see IDEA-90813 for possible bugs FSRecords.setLength(fileId, delegate.getLength(file)); content = delegate.contentsToByteArray(file); } else { // a bit of optimization content = delegate.contentsToByteArray(file); FSRecords.setLength(fileId, content.length); } ApplicationEx application = (ApplicationEx) ApplicationManager.getApplication(); // we should cache every local files content // because the local history feature is currently depends on this cache, // perforce offline mode as well if ((!delegate.isReadOnly() || // do not cache archive content unless asked cacheContent && !application.isInternal() && !application.isUnitTestMode()) && content.length <= PersistentFSConstants.FILE_LENGTH_TO_CACHE_THRESHOLD) { synchronized (myInputLock) { writeContent(file, new ByteSequence(content), delegate.isReadOnly()); setFlag(file, MUST_RELOAD_CONTENT, false); } } return content; } else { try { final int length = (int) file.getLength(); assert length >= 0 : file; return FileUtil.loadBytes(contentStream, length); } catch (IOException e) { throw FSRecords.handleError(e); } } }
public static void copyFileLazy(String source, String destination) throws IOException { String oldContent = null; try { oldContent = FileUtil.read(source); } catch (FileNotFoundException fnfe) { return; } String newContent = null; try { newContent = FileUtil.read(destination); } catch (FileNotFoundException fnfe) { } if (oldContent == null || !oldContent.equals(newContent)) { FileUtil.copyFile(source, destination); } }
private void forFirstRun() { if (Gl.getIsFirstRun()) { if (!Gl.getAdON()) StatsService.checkAdSwitchAsync(); StatsUtil.setNextSendTime(false); if (PlayerUtil.isDataExpired()) { FileUtil.delFile(PlayerUtil.TTS_DATA_BG_PATH); Toast.makeText(Gl.Ct(), 0x7f0b0221, 1).show(); } } }
/** Return the absolute path for the docBase, if we are file-system based, null otherwise. */ public String getAbsolutePath() { if (absPath != null) return absPath; if (FileUtil.isAbsolute(docBase)) absPath = docBase; else absPath = contextM.getHome() + File.separator + docBase; try { absPath = new File(absPath).getCanonicalPath(); } catch (IOException npe) { } return absPath; }
private void save() { File file = getCacheFile(); file.getParentFile().mkdirs(); System.out.println("Writing cache: " + file); FileUtil.writeResilientFile(file, contents); dirty = false; }
public static String getSbin() { String strSbin = "/usr/varian/sbin/"; if (Util.iswindows()) { strSbin = "/vnmr/bin/"; } else { UNFile file = new UNFile(strSbin); if (!file.exists()) strSbin = FileUtil.sysdir() + "/bin/"; } return strSbin; }
protected void buildPanel(String strPath) { strPath = FileUtil.openPath(strPath); ArrayList aListPath = new ArrayList(); BufferedReader reader = WFileUtil.openReadFile(strPath); if (reader == null) return; String strLine; try { while ((strLine = reader.readLine()) != null) { StringTokenizer strTok = new StringTokenizer(strLine, ":"); if (strTok.countTokens() < 4) continue; boolean bChecksum = false; boolean bShow = false; String strDir = strTok.nextToken(); String strChecksum = strTok.nextToken(); if (strChecksum.equalsIgnoreCase("checksum")) bChecksum = true; if (bChecksum && (strDir.equals("file") || strDir.equals("dir"))) { String strValue = strTok.nextToken(); String strShow = strTok.nextToken(); if (strShow.equalsIgnoreCase("yes")) bShow = true; if (bShow) aListPath.add(strValue); } } m_cmbPath = new JComboBox(aListPath.toArray()); JPanel pnlDisplay = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints( 0, 0, 1, 1, 0.2, 0.2, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0); pnlDisplay.add(m_cmbPath, gbc); gbc.gridx = 1; pnlDisplay.add(m_cmbChecksum, gbc); add(pnlDisplay, BorderLayout.NORTH); add(m_txaChecksum, BorderLayout.CENTER); } catch (Exception e) { e.printStackTrace(); } }
public void load(String filename) { Map data = FileUtil.readResilientConfigFile(filename, false); // horrendous recursive loading going on here due to logger + config depedencies. If already // loaded // then use the existing data as it might have already been written to... if (propertiesMap == null) { ConcurrentHashMapWrapper<String, Object> c_map = new ConcurrentHashMapWrapper<String, Object>(data.size() + 256, 0.75f, 8); c_map.putAll(data); propertiesMap = c_map; } /* * Can't do this yet. Sometimes, there's a default set to x, but the code * calls get..Parameter(..., y). y != x. When the user sets the the parameter * to x, we remove it from the list. Later, the get..Parameter(.., y) returns * y because there is no entry. * * The solution is to not allow get..Parameter(.., y) when there's a default * value. Another reason to not allow it is that having two defaults confuses * coders. * // Remove entries that are default. Saves memory, reduces // file size when saved again ConfigurationDefaults def = ConfigurationDefaults.getInstance(); Iterator it = new TreeSet(propertiesMap.keySet()).iterator(); while (it.hasNext()) { String key = (String)it.next(); Object defValue = def.getDefaultValueAsObject(key); if (defValue == null) continue; if (defValue instanceof Long) { int iDefValue = ((Long)defValue).intValue(); int iValue = getIntParameter(key, iDefValue); if (iValue == iDefValue) propertiesMap.remove(key); } if (defValue instanceof String) { String sDefValue = defValue.toString(); String sValue = getStringParameter(key, sDefValue); if (sValue.compareTo(sDefValue) == 0) propertiesMap.remove(key); } } */ }
public LongTermStatsImpl(AzureusCore _core, GlobalManagerStats _gm_stats) { core = _core; gm_stats = _gm_stats; stats_dir = FileUtil.getUserFile("stats"); COConfigurationManager.addParameterListener( "long.term.stats.enable", new ParameterListener() { public void parameterChanged(String name) { boolean enabled = COConfigurationManager.getBooleanParameter(name); synchronized (LongTermStatsImpl.this) { if (enabled) { if (!active) { sessionStart(); } } else { if (active) { sessionEnd(); } } } } }); _core.addLifecycleListener( new AzureusCoreLifecycleAdapter() { public void componentCreated(AzureusCore core, AzureusCoreComponent component) { if (component instanceof GlobalManager) { synchronized (LongTermStatsImpl.this) { sessionStart(); } } } public void stopped(AzureusCore core) { synchronized (LongTermStatsImpl.this) { closing = true; if (active) { sessionEnd(); } } } }); }