List of usage examples for java.io File getParent
public String getParent()
null
if this pathname does not name a parent directory. From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.report.MalletBatchTrainTestReport.java
@Override public void execute() throws Exception { StorageService store = getContext().getStorageService(); FlexTable<String> table = FlexTable.forClass(String.class); Map<String, List<Double>> key2resultValues = new HashMap<String, List<Double>>(); for (TaskContextMetadata subcontext : getSubtasks()) { if (subcontext.getType().startsWith(MalletTestTask.class.getName())) { Map<String, String> discriminatorsMap = store .retrieveBinary(subcontext.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter()) .getMap();//from w w w.ja va2 s .c o m Map<String, String> resultMap = store .retrieveBinary(subcontext.getId(), Constants.RESULTS_FILENAME, new PropertiesAdapter()) .getMap(); String key = getKey(discriminatorsMap); List<Double> results; if (key2resultValues.get(key) == null) { results = new ArrayList<Double>(); } else { results = key2resultValues.get(key); } key2resultValues.put(key, results); Map<String, String> values = new HashMap<String, String>(); Map<String, String> cleanedDiscriminatorsMap = new HashMap<String, String>(); for (String disc : discriminatorsMap.keySet()) { if (!ReportUtils.containsExcludePattern(disc, discriminatorsToExclude)) { cleanedDiscriminatorsMap.put(disc, discriminatorsMap.get(disc)); } } values.putAll(cleanedDiscriminatorsMap); values.putAll(resultMap); table.addRow(subcontext.getLabel(), values); } } // Excel cannot cope with more than 255 columns if (table.getColumnIds().length <= 255) { getContext().storeBinary(EVAL_FILE_NAME + "_compact" + SUFFIX_EXCEL, table.getExcelWriter()); } getContext().storeBinary(EVAL_FILE_NAME + "_compact" + SUFFIX_CSV, table.getCsvWriter()); table.setCompact(false); // Excel cannot cope with more than 255 columns if (table.getColumnIds().length <= 255) { getContext().storeBinary(EVAL_FILE_NAME + SUFFIX_EXCEL, table.getExcelWriter()); } getContext().storeBinary(EVAL_FILE_NAME + SUFFIX_CSV, table.getCsvWriter()); // output the location of the batch evaluation folder // otherwise it might be hard for novice users to locate this File dummyFolder = store.getStorageFolder(getContext().getId(), "dummy"); // TODO can we also do this without creating and deleting the dummy folder? getContext().getLoggingService().message(getContextLabel(), "Storing detailed results in:\n" + dummyFolder.getParent() + "\n"); dummyFolder.delete(); }
From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java
/** * Speichert den Kontoauszug im Dateisystem bzw. Messaging. * @param k der Kontoauszug. Er muss eine ID besitzen - also bereits gespeichert worden sein. * @param data die rohen Binaer-Daten./* ww w .j a va2 s .c o m*/ * @throws RemoteException * @throws ApplicationException */ public static void receive(Kontoauszug k, byte[] data) throws RemoteException, ApplicationException { if (k == null) throw new ApplicationException(i18n.tr("Kein Kontoauszug angegeben")); if (data == null || data.length == 0) throw new ApplicationException(i18n.tr("Kein Daten angegeben")); final Konto konto = k.getKonto(); if (konto == null) throw new ApplicationException(i18n.tr("Kein Konto angegeben")); // Per Messaging speichern? if (MessagingAvailableConsumer.haveMessaging() && Boolean.parseBoolean(MetaKey.KONTOAUSZUG_STORE_MESSAGING.get(konto))) { QueryMessage qm = new QueryMessage(CHANNEL, data); Application.getMessagingFactory().getMessagingQueue("jameica.messaging.put").sendSyncMessage(qm); k.setUUID(qm.getData().toString()); k.store(); Logger.info("stored account statement data in messaging archive [id: " + k.getID() + ", uuid: " + k.getUUID() + "]"); return; } // Im Dateisystem speichern String path = createPath(konto, k); try { File file = new File(path).getCanonicalFile(); Logger.info("storing account statement data in file [id: " + k.getID() + ", file: " + file + "]"); File dir = file.getParentFile(); if (!dir.exists()) { Logger.info("auto-creating parent dir: " + dir); if (!dir.mkdirs()) throw new ApplicationException( i18n.tr("Erstellen des Ordners fehlgeschlagen. Ordner-Berechtigungen korrekt?")); } if (!dir.canWrite()) throw new ApplicationException(i18n.tr("Kein Schreibzugriff in {0}", dir.toString())); OutputStream os = null; try { File target = file; int i = 0; while (i < 10000) { // Checken, ob die Datei schon existiert. Wenn ja, haengen wir einen Zaehler hinten drin. // Um sicherzugehen, dass wir die Datei nicht ueberschreiben. if (!target.exists()) break; // OK, die Datei gibts schon. Wir haengen den Counter hinten an i++; target = indexedFile(file, i); } os = new BufferedOutputStream(new FileOutputStream(target)); os.write(data); k.setPfad(target.getParent()); k.setDateiname(target.getName()); k.store(); } finally { IOUtil.close(os); } } catch (IOException e) { Logger.error("unable to store account statement data in file: " + path, e); throw new ApplicationException( i18n.tr("Speichern des Kontoauszuges fehlgeschlagen: {0}", e.getMessage())); } }
From source file:de.tudarmstadt.ukp.dkpro.tc.ml.liblinear.LiblinearBatchTrainTestReport.java
@Override public void execute() throws Exception { // FIXME this implementation is pretty close to what the other ML implementations do // once we have an evaluation module, there should be no need for a ML framework specific version StorageService store = getContext().getStorageService(); FlexTable<String> table = FlexTable.forClass(String.class); Map<String, List<Double>> key2resultValues = new HashMap<String, List<Double>>(); for (TaskContextMetadata subcontext : getSubtasks()) { if (subcontext.getType().startsWith(LiblinearTestTask.class.getName())) { Map<String, String> discriminatorsMap = store .retrieveBinary(subcontext.getId(), Task.DISCRIMINATORS_KEY, new PropertiesAdapter()) .getMap();//from w ww .j ava 2 s. c o m Map<String, String> resultMap = store .retrieveBinary(subcontext.getId(), Constants.RESULTS_FILENAME, new PropertiesAdapter()) .getMap(); String key = getKey(discriminatorsMap); List<Double> results; if (key2resultValues.get(key) == null) { results = new ArrayList<Double>(); } else { results = key2resultValues.get(key); } key2resultValues.put(key, results); Map<String, String> values = new HashMap<String, String>(); Map<String, String> cleanedDiscriminatorsMap = new HashMap<String, String>(); for (String disc : discriminatorsMap.keySet()) { if (!ReportUtils.containsExcludePattern(disc, discriminatorsToExclude)) { cleanedDiscriminatorsMap.put(disc, discriminatorsMap.get(disc)); } } values.putAll(cleanedDiscriminatorsMap); values.putAll(resultMap); table.addRow(subcontext.getLabel(), values); } } getContext().getLoggingService().message(getContextLabel(), ReportUtils.getPerformanceOverview(table)); // Excel cannot cope with more than 255 columns if (table.getColumnIds().length <= 255) { getContext().storeBinary(EVAL_FILE_NAME + "_compact" + SUFFIX_EXCEL, table.getExcelWriter()); } getContext().storeBinary(EVAL_FILE_NAME + "_compact" + SUFFIX_CSV, table.getCsvWriter()); table.setCompact(false); // Excel cannot cope with more than 255 columns if (table.getColumnIds().length <= 255) { getContext().storeBinary(EVAL_FILE_NAME + SUFFIX_EXCEL, table.getExcelWriter()); } getContext().storeBinary(EVAL_FILE_NAME + SUFFIX_CSV, table.getCsvWriter()); // output the location of the batch evaluation folder // otherwise it might be hard for novice users to locate this File dummyFolder = store.getStorageFolder(getContext().getId(), "dummy"); // TODO can we also do this without creating and deleting the dummy folder? getContext().getLoggingService().message(getContextLabel(), "Storing detailed results in:\n" + dummyFolder.getParent() + "\n"); dummyFolder.delete(); }
From source file:org.trpr.platform.runtime.impl.bootstrap.spring.Bootstrap.java
/** * Method to configure logging properties based on bootstrap location *//*from w w w .j av a 2 s. c o m*/ public void configureLogging() { File[] loggingConfigFiles = FileLocator.findFiles(RuntimeConstants.LOGGING_FILE, new File(this.bootstrapConfigFile).getParent()); if (loggingConfigFiles.length == 0) { System.out.println("Logging configuration file : " + RuntimeConstants.LOGGING_FILE + " not found!. Unable to initialize logging framework"); return; } if (loggingConfigFiles.length > 1) { // multiple logging configurations found. // Prefer the logging config co-located with bootstrap config. Use first occurrence otherwise. for (File loggingFile : loggingConfigFiles) { if (loggingFile.getParent().equals(new File(getBootstrapConfigPath()).getParent())) { System.out.println("Multiple ( Total: " + loggingConfigFiles.length + " ) logging config files found. Using the occurence co-located with bootstrap config file."); configureLoggingFromFile(loggingFile); return; } } } System.out.println("Using logging config file : " + loggingConfigFiles[0].getAbsolutePath()); configureLoggingFromFile(loggingConfigFiles[0]); }
From source file:com.lovejoy777sarootool.rootool.fragments.BrowserFragment.java
public boolean onBackPressed(int keycode) { if (keycode == KeyEvent.KEYCODE_BACK && mUseBackKey && !mCurrentPath.equals("/")) { File file = new File(mCurrentPath); navigateTo(file.getParent()); // get position of the previous folder in ListView mListView.setSelection(mListAdapter.getPosition(file.getPath())); return true; } else if (keycode == KeyEvent.KEYCODE_BACK && mUseBackKey && mCurrentPath.equals("/")) { Toast.makeText(mActivity, getString(R.string.pressbackagaintoquit), Toast.LENGTH_SHORT).show(); mUseBackKey = false;/*from w ww.j a v a2 s. co m*/ return false; } else if (keycode == KeyEvent.KEYCODE_BACK && !mUseBackKey && mCurrentPath.equals("/")) { mActivity.finish(); return false; } return true; }
From source file:me.jdknight.ums.ccml.tmp.RealFileWithVirtualFolderThumbnails.java
/** * Return the input stream to use for this file's thumbnail. * // www . j a v a 2 s. co m * @return The input stream. * * @throws IOException Thrown when the creation of an input stream has failed. */ @Override public InputStream getThumbnailInputStream() throws IOException { // Virtual folder support. if ((getParent() instanceof VirtualFolder) == false) { return super.getThumbnailInputStream(); } File file = getFile(); File foundThumbnail = null; // Attempt to find the thumbnail for this resource: // -Check for local thumbnail. // -Check for thumbnail in alternate directory. boolean shouldCheckForAlternatives = true; String resourcePath = file.getParent() + File.separator; do { String resourceBaseName = FilenameUtils.getBaseName(file.getName()); foundThumbnail = new File(resourcePath + resourceBaseName + ".png"); //$NON-NLS-1$ if (foundThumbnail.isFile() == false) foundThumbnail = new File(resourcePath + resourceBaseName + ".jpg"); //$NON-NLS-1$ if (foundThumbnail.isFile() == false) foundThumbnail = new File(resourcePath + file.getName() + ".cover.png"); //$NON-NLS-1$ if (foundThumbnail.isFile() == false) foundThumbnail = new File(resourcePath + file.getName() + ".cover.jpg"); //$NON-NLS-1$ if (shouldCheckForAlternatives == true && foundThumbnail.isFile() == false) { String alternativeThumbnailFolder = PMS.getConfiguration().getAlternateThumbFolder(); if (new File(alternativeThumbnailFolder).isDirectory() == false) { resourcePath = alternativeThumbnailFolder + File.separator; shouldCheckForAlternatives = false; } } if (shouldCheckForAlternatives == false) { break; } shouldCheckForAlternatives = false; } while (true); // No thumbnail found? Try to grab the local folder's thumbnail. if (foundThumbnail == null || foundThumbnail.isFile() == false) { foundThumbnail = new File(file.getParent() + File.separator + "folder.png"); //$NON-NLS-1$ if (foundThumbnail.isFile() == false) { foundThumbnail = new File(file.getParent() + File.separator + "folder.jpg"); //$NON-NLS-1$ } } // Still no thumbnail found? Just resort to default in original method. if (foundThumbnail == null || foundThumbnail.isFile() == false) { return super.getThumbnailInputStream(); } else { return new FileInputStream(foundThumbnail); } }
From source file:com.nominum.build.LinkAssetsMojo.java
public void execute() throws MojoExecutionException { File outputDir = absolutePath(outputDirectory); File assetDir = absolutePath(assetDirectory); if (!outputDir.exists()) { boolean created = outputDir.mkdirs(); if (!created) throw new MojoExecutionException("Failed to create output directory"); }/*www .j a v a 2s . com*/ String linkName = assetDir.getAbsolutePath().substring(assetDir.getParent().length() + 1); File linkTarget = new File(outputDir, linkName); // recreate link if it exists if (linkTarget.exists()) { boolean deleted = linkTarget.delete(); if (!deleted) { throw new MojoExecutionException( "Failed to delete " + linkName + " prior to linking asset directory"); } } String[] command; getLog().info("OS name:" + System.getProperty("os.name")); if (System.getProperty("os.name").indexOf("indows") > 0) { command = new String[] { "cmd", "/c", "mklink", "/D", linkTarget.getAbsolutePath(), assetDir.getAbsolutePath() }; } else { command = new String[] { "ln", "-s", assetDir.getAbsolutePath(), linkTarget.getAbsolutePath() }; } try { getLog().info("Linking " + assetDirectory + " to " + linkTarget); Process proc = Runtime.getRuntime().exec(command, null, new File(".")); int exitVal = proc.waitFor(); if (exitVal != 0) { throw new MojoExecutionException( "linking assets directory failed. Command: \"" + StringUtils.join(command, " ") + "\""); } getLog().info("Linking " + assetDirectory + " to " + linkTarget + " done"); } catch (InterruptedException e) { throw new MojoExecutionException("link command failed", e); } catch (IOException e) { throw new MojoExecutionException("Unable to execute link command, run as administrator.", e); } }
From source file:com.tealeaf.ResourceDownloaderTask.java
@Override protected Boolean doInBackground(Activity... params) { lastFilename = null;// ww w . j ava 2s. c o m //get options and resource manager TeaLeafOptions opts = new TeaLeafOptions(); opts.setAppID(appInfo.appid); final ResourceManager resourceManager = new ResourceManager(params[0], opts); //get the storage directory final String storageDir = resourceManager.getStorageDirectory(); File storage = new File(storageDir); //assure storage directory folders are there if (!storage.exists()) { storage.mkdirs(); } HTTP http = new HTTP(); // get the file containing the hashes of the last download if it exists File hashFile = new File(storageDir + "/resource_list.json"); JSONObject prevHashes = new JSONObject(); if (hashFile.exists()) { String hashFileString = fileToString(hashFile); try { prevHashes = new JSONObject(hashFileString); } catch (JSONException e) { logger.log(e); } } //form the simulate url String simulateUrl = "http://" + host + ":" + port + "/simulate/debug/" + appInfo.id + "/native-android/"; //first get native.js String url = simulateUrl + "native.js"; http = new HTTP(); String nativejsPath = storageDir + "/" + "native.js"; http.getFile(URI.create(url), nativejsPath); //get loading.png url = simulateUrl + "splash/portrait960"; String loadingPngPath = storageDir + "/" + "loading.png"; File splash = http.getFile(URI.create(url), loadingPngPath); //try again if we couldn't find the higher res splash if (splash == null || !splash.exists()) { url = simulateUrl + "splash/portrait480"; http.getFile(URI.create(url), loadingPngPath); } HashMap<String, String> requestHeaders = new HashMap<String, String>(); //get new resource list String body = null; int retry = 3; while (retry-- > 0) { url = simulateUrl + "resource_list.json"; body = http.get(URI.create(url)); if (body != null && !body.equals("")) { break; } } JSONObject serverHashes = null; try { // loop through all resources and download any // that we don't have cached locally serverHashes = new JSONObject(body); int numFiles = serverHashes.length(); @SuppressWarnings("unchecked") // using legacy API, remove warning Iterator<String> files = serverHashes.keys(); publishProgress(1.f, 1.f, (float) numFiles); http = new HTTP(); int currentFile = 0; while (files.hasNext()) { String filePath = files.next(); lastFilename = filePath; if (filePath.contains("native.js")) { continue; } String fullPath = storageDir + "/" + filePath; // need to get the directory this file is in and create it File fullPathFile = new File(fullPath); new File(fullPathFile.getParent() + "/").mkdirs(); // check if there is a previous hash String prevHash = null; try { prevHash = (String) prevHashes.get(filePath); } catch (JSONException e) { // expected to happen first load logger.log(e); } // check if the server hash is a match boolean cached = false; try { String hash = (String) serverHashes.get(filePath); if (hash != null && hash.equals(prevHash)) { cached = true; } } catch (JSONException e) { // oh well, just download it! } if (!cached || !(new File(fullPath).exists())) { // get the file and cache it to disk url = "http://" + host + ":" + port + "/simulate/debug/" + appInfo.id + "/native-android/" + filePath; url = url.replace(" ", "%20"); http.getFile(URI.create(url), fullPath, requestHeaders); } // update progress publishProgress(1.f, (float) ++currentFile, (float) numFiles); ; } } catch (Exception e) { logger.log("broken!"); logger.log("error is", e); errorDownloading = true; cancel(true); logger.log(e); } if (serverHashes != null) { stringToFile(hashFile, serverHashes.toString()); } return true; }
From source file:net.java.sen.StringTagger.java
/** * Read configuration file.//w w w . j a va 2 s . co m * * @param confFile * configuration file */ private void readConfig(String confFile) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); File cf = new File(confFile); String parent = cf.getParentFile().getParent(); if (parent == null) parent = "."; Document doc = builder.parse(new InputSource(confFile)); NodeList nl = doc.getFirstChild().getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { org.w3c.dom.Node n = nl.item(i); if (n.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { String nn = n.getNodeName(); String value = n.getFirstChild().getNodeValue(); if (nn.equals("charset")) { charset = value; } else if (nn.equals("unknown-pos")) { unknownPos = value; } else if (nn.equals("tokenizer")) { tokenizerClass = value; } if (nn.equals("dictionary")) { // read nested tag in <dictinary> NodeList dnl = n.getChildNodes(); for (int j = 0; j < dnl.getLength(); j++) { org.w3c.dom.Node dn = dnl.item(j); if (dn.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { String dnn = dn.getNodeName(); if (dn.getFirstChild() == null) { throw new IllegalArgumentException("element '" + dnn + "' is empty"); } String dvalue = dn.getFirstChild().getNodeValue(); if (dnn.equals("connection-cost")) { connectFile = SenUtils.getPath(dvalue, parent); } else if (dnn.equals("double-array-trie")) { doubleArrayFile = SenUtils.getPath(dvalue, parent); } else if (dnn.equals("token")) { tokenFile = SenUtils.getPath(dvalue, parent); } else if (dnn.equals("pos-info")) { posInfoFile = SenUtils.getPath(dvalue, parent); } else if (dnn.equals("compound")) { // do nothing } else { throw new IllegalArgumentException("element '" + dnn + "' is invalid"); } } } } } } } catch (ParserConfigurationException e) { throw new IllegalArgumentException(e.getMessage()); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e.getMessage()); } catch (SAXException e) { throw new IllegalArgumentException(e.getMessage()); } catch (IOException e) { throw new IllegalArgumentException(e.getMessage()); } }