public Preparation invoke(String ndkArchitecture) {
      // This usually points to ${basedir}/obj/local
      nativeLibDirectory = new File(nativeLibrariesOutputDirectory, ndkArchitecture);
      libsDirectoryExists = nativeLibDirectory.exists();

      // Determine how much of the output directory structure (most likely obj/...) does not exist
      // and based on what we find, determine how much of it we delete after the build
      directoryToRemove = nativeLibDirectory;
      if (!libsDirectoryExists) {
        getLog().info("Creating native output directory " + nativeLibDirectory);

        // This simply checks how much of the structure already exists - nothing (e.g. we make all
        // the dirs)
        // or just a partial part (the architecture part)?
        if (!nativeLibrariesOutputDirectory.exists()) {
          if (nativeLibrariesOutputDirectory.getParentFile().exists()) {
            nativeLibDirectory.mkdir();
          } else {
            nativeLibDirectory.mkdirs();
            directoryToRemove = nativeLibrariesOutputDirectory.getParentFile();
          }
        } else {
          if (nativeLibDirectory.getParentFile().exists()) {
            nativeLibDirectory.mkdir();
          } else {
            nativeLibDirectory.mkdirs();
            directoryToRemove = nativeLibDirectory.getParentFile();
          }
        }
      }
      return this;
    }
Beispiel #2
0
  /**
   * Creates a new sample file for the given style and stores it on disk. The sample dimensions
   * (width x height) are returned.
   *
   * @param style
   * @param pngOutputFormat
   * @return
   * @throws Exception
   */
  private Dimension createNewSample(StyleInfo style, GetLegendGraphicOutputFormat pngOutputFormat)
      throws Exception {
    GetLegendGraphicRequest legendGraphicRequest = new GetLegendGraphicRequest();
    File sampleLegendFolder = getSamplesFolder();

    legendGraphicRequest.setLayers(Arrays.asList((FeatureType) null));
    legendGraphicRequest.setStyles(Arrays.asList(style.getStyle()));
    legendGraphicRequest.setFormat(pngOutputFormat.getContentType());
    Object legendGraphic = pngOutputFormat.produceLegendGraphic(legendGraphicRequest);
    if (legendGraphic instanceof BufferedImageLegendGraphic) {
      BufferedImage image = ((BufferedImageLegendGraphic) legendGraphic).getLegend();

      PNGWriter writer = new PNGWriter();
      FileOutputStream outStream = null;
      try {
        File sampleFile =
            new File(
                sampleLegendFolder.getAbsolutePath() + File.separator + getSampleFileName(style));
        if (!sampleFile.getParentFile().exists()) {
          sampleFile.getParentFile().mkdirs();
        }
        outStream = new FileOutputStream(sampleFile);
        writer.writePNG(image, outStream, 0.0f, FilterType.FILTER_NONE);
        removeStyleSampleInvalidation(style);
        return new Dimension(image.getWidth(), image.getHeight());
      } finally {
        if (outStream != null) {
          outStream.close();
        }
      }
    }

    return null;
  }
Beispiel #3
0
  /**
   * @param file - the file to delete
   * @param deleteEmptyParents - removing empty parent folders flag
   * @param rootPath - if deleteEmptyParents is true, this parameters shows the parent folder where
   *     removing parents must stop
   * @return True, if the file has been successfully removed, otherwise returns false
   */
  public static boolean delete(File file, boolean deleteEmptyParents, String rootPath) {
    log.info("M-DELETE file: " + file);
    if (!file.exists()) {
      File rootFile = rootPath == null ? null : toFile(rootPath);
      boolean isParentReliable = isReliable(file.getParentFile(), rootFile);

      log.warn(
          format(
              isParentReliable
                  ? "File [%s] has already been deleted."
                  : "Cannot list file [%s]; is its parent-directory tree mounted and executable?",
              file));

      return isParentReliable;
    }
    if (!file.delete()) {
      log.warn("Failed to delete file: " + file);
      return false;
    }
    if (deleteEmptyParents) {
      File parentToKeep = null;
      if (rootPath != null) parentToKeep = toFile(rootPath);

      File parent = file.getParentFile();
      while (!parent.equals(parentToKeep) && parent.delete()) {
        log.info("M-DELETE directory: " + parent);
        parent = parent.getParentFile();
      }
    }
    return true;
  }
Beispiel #4
0
  /**
   * Finds the appropriate java executable for window-system execution (javaw on windows, but java
   * on mac).
   *
   * @return
   */
  public static File findJavaExecutable() {
    String vm = System.getProperty("eclipse.vm");
    if (Strings.isNullOrEmpty(vm)) {
      throw new RuntimeException(
          "Cannot determine JVM to use for updater: " + "System property missing.");
    }
    File javaExecutable = null;
    File vmFile = new File(vm);
    // look for a javaw or javaw.exe in a bin directory above
    // the current file, or JavaVM.framework/Home/bin/java in a Frameworks
    // directory (Mac)
    File candDir = vmFile.getParentFile();
    outerWhile:
    while (candDir != null) {
      for (String binary :
          new String[] { // windows (path varies):
            "javaw.exe",
            "bin/javaw.exe",
            // linux (eclipse.vm set to java executable):
            "java",
            // Mac OS:
            "JavaVM.framework/Home/bin/java"
          }) {
        File javaCand = new File(candDir, binary);
        if (javaCand.exists()) {
          javaExecutable = javaCand;
          break outerWhile;
        }
      }

      candDir = candDir.getParentFile();
    }
    return javaExecutable;
  }
Beispiel #5
0
  private BufferedWriter getExternLogFile(AutomatedInstallData installdata) {
    String logfile = installdata.getVariable(LOGFILE_PATH);
    BufferedWriter extLogWriter = null;
    if (logfile != null) {
      if (logfile.toLowerCase().startsWith("default")) {
        logfile = installdata.getInfo().getUninstallerPath() + "/install.log";
      }
      logfile = IoHelper.translatePath(logfile, variableSubstitutor);
      File outFile = new File(logfile);
      if (!outFile.getParentFile().exists()) {
        outFile.getParentFile().mkdirs();
      }
      FileOutputStream out = null;
      try {
        out = new FileOutputStream(outFile);
      } catch (FileNotFoundException e) {
        Debug.trace("Cannot create logfile!");
        Debug.error(e);
      }
      if (out != null) {
        extLogWriter = new BufferedWriter(new OutputStreamWriter(out));
      }
    }

    return extLogWriter;
  }
 @SuppressWarnings("deprecation")
 public URL getResource(String path) throws MalformedURLException {
   if (path == null) {
     return null;
   }
   path = adjustPath(path);
   File src = ResourceUtil.getResourceAsFile(".");
   File root = src.getParentFile();
   if (root.getName().equalsIgnoreCase("WEB-INF")) {
     root = root.getParentFile();
   }
   while (root != null) {
     File file = new File(root, path);
     if (file.exists()) {
       return file.toURL();
     }
     root = root.getParentFile();
   }
   if (ResourceUtil.isExist(path)) {
     return ResourceUtil.getResource(path);
   }
   if (path.startsWith("WEB-INF")) {
     path = path.substring("WEB-INF".length());
     return getResource(path);
   }
   return null;
 }
 private void scanPolygons(File file, Map<String, File> polygonFiles) {
   if (file.isDirectory()) {
     for (File c : file.listFiles()) {
       if (c.isDirectory()) {
         scanPolygons(c, polygonFiles);
       } else if (c.getName().endsWith(".poly")) {
         String name = c.getName().substring(0, c.getName().length() - 5);
         if (!polygonFiles.containsKey(name)) {
           polygonFiles.put(name, c);
         } else {
           File rm = polygonFiles.remove(name);
           System.out.println(
               "Polygon duplicate -> "
                   + rm.getParentFile().getName()
                   + "/"
                   + name
                   + " and "
                   + c.getParentFile().getName()
                   + "/"
                   + name);
         }
         polygonFiles.put(c.getParentFile().getName() + "/" + name, c);
       }
     }
   }
 }
 @Override
 public List<File> loadInBackground() {
   if (path == null || !path.isDirectory()) return Collections.emptyList();
   final File[] listed_files = path.listFiles();
   if (listed_files == null) return Collections.emptyList();
   final List<File> dirs = new ArrayList<File>();
   final List<File> files = new ArrayList<File>();
   for (final File file : listed_files) {
     if (!file.canRead() || file.isHidden()) {
       continue;
     }
     if (file.isDirectory()) {
       dirs.add(file);
     } else if (file.isFile()) {
       final String name = file.getName();
       final int idx = name.lastIndexOf(".");
       if (extensions == null
           || extensions.length == 0
           || idx == -1
           || idx > -1 && extensions_regex.matcher(name.substring(idx + 1)).matches()) {
         files.add(file);
       }
     }
   }
   Collections.sort(dirs, NAME_COMPARATOR);
   Collections.sort(files, NAME_COMPARATOR);
   final List<File> list = new ArrayList<File>();
   final File parent = path.getParentFile();
   if (path.getParentFile() != null) {
     list.add(parent);
   }
   list.addAll(dirs);
   list.addAll(files);
   return list;
 }
 public static File getCacheFile(String fileName) {
   File file = new File(cacheDir, fileName);
   if (!file.getParentFile().exists()) {
     file.getParentFile().mkdirs();
   }
   return file;
 }
Beispiel #10
0
  /**
   * Returns the path of the installation of the directory server. Note that this method assumes
   * that this code is being run locally.
   *
   * @return the path of the installation of the directory server.
   */
  static String getInstallPathFromClasspath() {
    String installPath = DirectoryServer.getServerRoot();
    if (installPath != null) {
      return installPath;
    }

    /* Get the install path from the Class Path */
    final String sep = System.getProperty("path.separator");
    final String[] classPaths = System.getProperty("java.class.path").split(sep);
    String path = getInstallPath(classPaths);
    if (path != null) {
      final File f = new File(path).getAbsoluteFile();
      final File librariesDir = f.getParentFile();

      /*
       * Do a best effort to avoid having a relative representation (for
       * instance to avoid having ../../../).
       */
      try {
        installPath = librariesDir.getParentFile().getCanonicalPath();
      } catch (IOException ioe) {
        // Best effort
        installPath = librariesDir.getParent();
      }
    }
    return installPath;
  }
  @Test
  public void testCopyScriptsInTargetDirectory() throws IOException {

    File f = new File(this.folder.newFolder(), "toto.properties");
    Utils.writeStringInto("id: tid\nprop: value\nhandler: h", f);

    TestApplicationTemplate appT = new TestApplicationTemplate();
    Utils.writeStringInto(
        "#!/bin/bash\necho Bonjour le monde cruel > toto.txt",
        new File(f.getParentFile(), "toto.sh"));
    Utils.writeStringInto("#!/bin/bash\ntouch titi.txt", new File(f.getParentFile(), "titi.sh"));
    Utils.writeStringInto(
        "#!/bin/bash\necho tototo", new File(f.getParentFile(), "toto-script.sh"));

    File targetDir =
        new File(this.configurationMngr.getWorkingDirectory(), ConfigurationUtils.TARGETS + "/tid");
    Assert.assertFalse(targetDir.exists());

    String targetId = this.mngr.createTarget(f, appT);
    Assert.assertEquals("tid", targetId);
    Assert.assertTrue(targetDir.exists());
    Assert.assertEquals(4, targetDir.list().length);

    File toto = new File(targetDir, "toto.sh");
    File titi = new File(targetDir, "titi.sh");
    File totoMain = new File(targetDir, "toto-script.sh");
    Assert.assertTrue(toto.exists());
    Assert.assertFalse(titi.exists());
    Assert.assertTrue(totoMain.exists());
  }
 private void exportColorPaletteDef() {
   final ImageInfo imageInfo = getFormModel().getModifiedImageInfo();
   if (imageInfo == null) {
     // Normally this code is unreachable because, the export Button should be
     // disabled if the color manipulation form has no ImageInfo.
     return;
   }
   final SnapFileChooser fileChooser = new SnapFileChooser();
   fileChooser.setDialogTitle("Export Colour Palette"); /*I18N*/
   fileChooser.setFileFilter(getOrCreateColorPaletteDefinitionFileFilter());
   fileChooser.setCurrentDirectory(getIODir().toFile());
   final int result = fileChooser.showSaveDialog(getToolViewPaneControl());
   File file = fileChooser.getSelectedFile();
   if (file != null && file.getParentFile() != null) {
     setIODir(file.getParentFile());
   }
   if (result == JFileChooser.APPROVE_OPTION) {
     if (file != null) {
       if (Boolean.TRUE.equals(SnapDialogs.requestOverwriteDecision(titlePrefix, file))) {
         file = FileUtils.ensureExtension(file, FILE_EXTENSION);
         try {
           final ColorPaletteDef colorPaletteDef = imageInfo.getColorPaletteDef();
           ColorPaletteDef.storeColorPaletteDef(colorPaletteDef, file);
         } catch (IOException e) {
           showErrorDialog("Failed to export colour palette:\n" + e.getMessage()); /*I18N*/
         }
       }
     }
   }
 }
 private void importColorPaletteDef() {
   final ImageInfo targetImageInfo = getFormModel().getModifiedImageInfo();
   if (targetImageInfo == null) {
     // Normally this code is unreachable because, the export Button
     // is disabled if the _contrastStretchPane has no ImageInfo.
     return;
   }
   final SnapFileChooser fileChooser = new SnapFileChooser();
   fileChooser.setDialogTitle("Import Colour Palette"); /*I18N*/
   fileChooser.setFileFilter(getOrCreateColorPaletteDefinitionFileFilter());
   fileChooser.setCurrentDirectory(getIODir().toFile());
   final int result = fileChooser.showOpenDialog(getToolViewPaneControl());
   final File file = fileChooser.getSelectedFile();
   if (file != null && file.getParentFile() != null) {
     setIODir(file.getParentFile());
   }
   if (result == JFileChooser.APPROVE_OPTION) {
     if (file != null && file.canRead()) {
       try {
         final ColorPaletteDef colorPaletteDef = ColorPaletteDef.loadColorPaletteDef(file);
         colorPaletteDef.getFirstPoint().setLabel(file.getName());
         applyColorPaletteDef(colorPaletteDef, getFormModel().getRaster(), targetImageInfo);
         getFormModel().setModifiedImageInfo(targetImageInfo);
         childForm.updateFormModel(getFormModel());
         updateMultiApplyState();
       } catch (IOException e) {
         showErrorDialog("Failed to import colour palette:\n" + e.getMessage());
       }
     }
   }
 }
Beispiel #14
0
  public CodeServerGui() {
    super("XApi Codeserver");
    BorderLayout layout = new BorderLayout(5, 5);
    setLayout(layout);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 300);
    //    setAlwaysOnTop(true);
    test = new SingleFileSelector("Set Work Directory");
    test.setToolTipText(
        "The working directory where gwt codeserver will write compiles.  Defaults to "
            + tmpConfig.getParent());
    test.setChooserType(JFileChooser.DIRECTORIES_ONLY);
    try {
      test.setFile(tmpConfig.getParentFile());
    } catch (Exception e) {
      X_Log.warn(getClass(), "Error loading file ", tmpConfig.getParentFile(), e);
    }
    add(test, BorderLayout.NORTH);
    controls =
        new CodeServerControls(
            new Runnable() {
              @Override
              public void run() {
                launchServer(isUseTestSources(), "JS", getLogLevel());
              }
            });
    add(controls, BorderLayout.SOUTH);
    logger =
        new ProcessLog() {
          Runnable recalc;

          @Override
          public void invalidate() {
            super.invalidate();
            if (null == recalc) {
              recalc =
                  new Runnable() {
                    @Override
                    public void run() {
                      recalc = null;
                      CodeServerGui.this.validate();
                    }
                  };
              SwingUtilities.invokeLater(recalc);
            }
          }
        };
    sources = new SourcesSelector("Gwt Sources", logger);
    JScrollPane wrap =
        new JScrollPane(
            logger,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitter.setLeftComponent(sources);
    splitter.setRightComponent(wrap);
    splitter.setResizeWeight(0.5);
    add(splitter, BorderLayout.CENTER);
    //    add(logger,BorderLayout.EAST);
  }
Beispiel #15
0
  public synchronized TopLevelItem createProjectFromXML(String name, InputStream xml)
      throws IOException {
    acl.checkPermission(Job.CREATE);

    Jenkins.getInstance().getProjectNamingStrategy().checkName(name);
    // place it as config.xml
    File configXml = Items.getConfigFile(getRootDirFor(name)).getFile();
    configXml.getParentFile().mkdirs();
    try {
      IOUtils.copy(xml, configXml);

      // load it
      TopLevelItem result;
      Items.updatingByXml.set(true);
      try {
        result = (TopLevelItem) Items.load(parent, configXml.getParentFile());
      } finally {
        Items.updatingByXml.set(false);
      }
      add(result);

      ItemListener.fireOnCreated(result);
      Jenkins.getInstance().rebuildDependencyGraph();

      return result;
    } catch (IOException e) {
      // if anything fails, delete the config file to avoid further confusion
      Util.deleteRecursive(configXml.getParentFile());
      throw e;
    }
  }
  /** Generates a manifest file to be included in the .hpi file */
  protected void generateManifest(MavenArchiveConfiguration archive, File manifestFile)
      throws MojoExecutionException {
    // create directory if it doesn't exist yet
    if (!manifestFile.getParentFile().exists()) manifestFile.getParentFile().mkdirs();

    getLog().info("Generating " + manifestFile);

    MavenArchiver ma = new MavenArchiver();
    ma.setOutputFile(manifestFile);

    PrintWriter printWriter = null;
    try {
      Manifest mf = ma.getManifest(project, archive.getManifest());
      Section mainSection = mf.getMainSection();
      setAttributes(mainSection);

      printWriter =
          new PrintWriter(new OutputStreamWriter(new FileOutputStream(manifestFile), "UTF-8"));
      mf.write(printWriter);
    } catch (ManifestException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } catch (IOException e) {
      throw new MojoExecutionException("Error preparing the manifest: " + e.getMessage(), e);
    } finally {
      IOUtil.close(printWriter);
    }
  }
Beispiel #17
0
  /**
   * Method to write the contents of the picture to a file with the passed name
   *
   * @param fileName the name of the file to write the picture to
   */
  public void writeOrFail(String fileName) throws IOException {
    String extension = this.extension; // the default is current

    // create the file object
    File file = new File(fileName);
    File fileLoc = file.getParentFile(); // directory name

    // if there is no parent directory use the current media dir
    if (fileLoc == null) {
      fileName = FileChooser.getMediaPath(fileName);
      file = new File(fileName);
      fileLoc = file.getParentFile();
    }

    // check that you can write to the directory
    if (!fileLoc.canWrite()) {
      throw new IOException(
          fileName + " could not be opened. Check to see if you can write to the directory.");
    }

    // get the extension
    int posDot = fileName.indexOf('.');
    if (posDot >= 0) extension = fileName.substring(posDot + 1);

    // write the contents of the buffered image to the file
    ImageIO.write(bufferedImage, extension, file);
  }
Beispiel #18
0
  /**
   * Finds all test resources and returns the information that JUnit needs to dynamically create the
   * corresponding test cases.
   *
   * @return the test data needed to dynamically create the test cases
   */
  @Parameters(name = "test {index}: {5}: {6}")
  public static List<Object[]> data() {

    String filter = System.getProperty("okapi.symbol.test");

    String backend = "uk.org.okapibarcode.backend";
    Reflections reflections = new Reflections(backend);
    Set<Class<? extends Symbol>> symbols = reflections.getSubTypesOf(Symbol.class);

    List<Object[]> data = new ArrayList<>();
    for (Class<? extends Symbol> symbol : symbols) {
      String symbolName = symbol.getSimpleName().toLowerCase();
      if (filter == null || filter.equals(symbolName)) {
        String dir = "src/test/resources/" + backend.replace('.', '/') + "/" + symbolName;
        for (File file : getPropertiesFiles(dir)) {
          String fileBaseName = file.getName().replaceAll(".properties", "");
          File codewordsFile = new File(file.getParentFile(), fileBaseName + ".codewords");
          File pngFile = new File(file.getParentFile(), fileBaseName + ".png");
          File errorFile = new File(file.getParentFile(), fileBaseName + ".error");
          data.add(
              new Object[] {
                symbol, file, codewordsFile, pngFile, errorFile, symbolName, fileBaseName
              });
        }
      }
    }

    return data;
  }
 @NotNull
 public static String getProjectRepresentationName(
     @NotNull String targetProjectPath, @Nullable String rootProjectPath) {
   if (rootProjectPath == null) {
     File rootProjectDir = new File(targetProjectPath);
     if (rootProjectDir.isFile()) {
       rootProjectDir = rootProjectDir.getParentFile();
     }
     return rootProjectDir.getName();
   }
   File rootProjectDir = new File(rootProjectPath);
   if (rootProjectDir.isFile()) {
     rootProjectDir = rootProjectDir.getParentFile();
   }
   File targetProjectDir = new File(targetProjectPath);
   if (targetProjectDir.isFile()) {
     targetProjectDir = targetProjectDir.getParentFile();
   }
   StringBuilder buffer = new StringBuilder();
   for (File f = targetProjectDir;
       f != null && !FileUtil.filesEqual(f, rootProjectDir);
       f = f.getParentFile()) {
     buffer.insert(0, f.getName()).insert(0, ":");
   }
   buffer.insert(0, rootProjectDir.getName());
   return buffer.toString();
 }
Beispiel #20
0
  /**
   * The current commit's passed in storedFiles is now directly saved into this commit's stored
   * Files as well as the .gitlet + commitID folder; Uses the same method as the above
   * copyfileHelper java utility FileInputStream
   */
  private boolean save(String direc) throws IOException {
    for (String f : storedFiles.keySet()) {
      File source = new File(f);
      File dest = new File(direc + "/" + f);

      if (dest.getParentFile() != null) {
        dest.getParentFile().mkdirs();
      }
      FileInputStream in = null;
      FileOutputStream out = null;
      try {
        in = new FileInputStream(source);
        out = new FileOutputStream(dest);
        int c;
        while ((c = in.read()) != -1) {
          out.write(c);
        }
        storedFiles.put(f, direc);
      } finally {
        if (in != null && out != null) {
          in.close();
          out.close();
        }
      }
    }
    return true;
  }
Beispiel #21
0
 /**
  * 获取工程路径
  *
  * @return
  */
 public static String getProjectPath() {
   // 如果配置了工程路径,则直接返回,否则自动获取。
   String projectPath = Global.getConfig("projectPath");
   if (StringUtils.isNotBlank(projectPath)) {
     return projectPath;
   }
   try {
     File file = new DefaultResourceLoader().getResource("").getFile();
     if (file != null) {
       while (true) {
         File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
         if (f == null || f.exists()) {
           break;
         }
         if (file.getParentFile() != null) {
           file = file.getParentFile();
         } else {
           break;
         }
       }
       projectPath = file.toString();
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return projectPath;
 }
  /**
   * Check if the resource is an eDoc.
   *
   * @param uri - the resource's URI.
   * @return true if the resource is an (KOBV) eDoc.
   */
  public static boolean isEDoc(String uri) {
    // test local file system
    File f = new File(uri);

    if (f.getParentFile().getName().equals("pdf")
        && new File(f.getParentFile().getParentFile(), "index.html").exists()) {
      return true;
    } else { // test HTTP
      try {
        URL url = new URL(uri);
        int pos = url.toExternalForm().lastIndexOf("/pdf");
        if (pos != -1) {
          String newUrl = url.toExternalForm().substring(0, pos) + "/index.html";

          URL indexUrl = new URL(newUrl);
          @SuppressWarnings("unused")
          URLConnection conn = indexUrl.openConnection();

          return true;
        }
        return false;
      } catch (MalformedURLException e) {
        return false;
      } catch (IOException e) {
        return false;
      }
    }
  }
 @SuppressWarnings("rawtypes")
 public Set getResourcePaths(String path) {
   path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
   File src = ResourceUtil.getResourceAsFile(".");
   File root = src.getParentFile();
   if (root.getName().equalsIgnoreCase("WEB-INF")) {
     root = root.getParentFile();
   }
   File file = new File(root, adjustPath(path));
   if (!file.exists()) {
     int pos = path.lastIndexOf('/');
     if (pos != -1) {
       path = path.substring(pos + 1);
     }
     do {
       file = new File(root, path);
       root = root.getParentFile();
     } while (!file.exists() && root != null);
     path = "/" + path;
   }
   if (file.isDirectory()) {
     int len = file.getAbsolutePath().length();
     Set<String> paths = new HashSet<String>();
     File[] files = file.listFiles();
     if (files != null) {
       for (int i = 0; i < files.length; ++i) {
         String replace = files[i].getAbsolutePath().substring(len).replace('\\', '/');
         paths.add(path + replace);
       }
       return paths;
     }
   }
   return null;
 }
        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
          String[] mFilterDirs = getResources().getStringArray(R.array.filter_out_dirs);
          if (data != null) {
            List<Image> images = new ArrayList<Image>();
            int count = data.getCount();
            if (count > 0) {
              data.moveToFirst();
              do {
                String path = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                String name = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));
                long dateTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                Image image = new Image(path, name, dateTime);
                File file = new File(path);
                if (file.exists()) {
                  String imageParentName = file.getParentFile().getName();
                  if (!isFilterOutDir(imageParentName, mFilterDirs)) {
                    images.add(image);
                  }
                }
                if (!hasFolderGened) {
                  // 获取文件夹名称
                  File imageFile = new File(path);
                  if (imageFile.exists()) {
                    File folderFile = imageFile.getParentFile();
                    Folder folder = new Folder();
                    folder.name = folderFile.getName();
                    folder.path = folderFile.getAbsolutePath();
                    folder.cover = image;
                    if (!mResultFolder.contains(folder)) {
                      List<Image> imageList = new ArrayList<Image>();
                      if (!isFilterOutDir(folder.name, mFilterDirs)) {
                        imageList.add(image);
                        folder.images = imageList;
                        mResultFolder.add(folder);
                      }
                    } else {
                      // 更新
                      Folder f = mResultFolder.get(mResultFolder.indexOf(folder));
                      if (!isFilterOutDir(folder.name, mFilterDirs)) {
                        f.images.add(image);
                      }
                    }
                  }
                }

              } while (data.moveToNext());

              mImageAdapter.setData(images);

              // 设定默认选择
              if (resultList != null && resultList.size() > 0) {
                mImageAdapter.setDefaultSelected(resultList);
              }

              mFolderAdapter.setData(mResultFolder);
              hasFolderGened = true;
            }
          }
        }
 public static File appDirectory() {
   File app, dir;
   try {
     app =
         new File(
             Application.getInstance()
                 .getClass()
                 .getProtectionDomain()
                 .getCodeSource()
                 .getLocation()
                 .toURI());
     dir = app.getParentFile();
   } catch (Exception e) {
     app =
         new File(
             Application.getInstance()
                 .getClass()
                 .getProtectionDomain()
                 .getCodeSource()
                 .getLocation()
                 .getPath()
                 .replaceAll("%20", " "));
     dir = app.getParentFile();
   }
   return dir;
 }
Beispiel #26
0
 public static boolean createFile(String destFileName) {
   File file = new File(destFileName);
   if (!file.getParentFile().exists()) {
     // 如果目标文件所在的目录不存在,则创建父目录
     if (!file.getParentFile().mkdirs()) {
       return false;
     }
   }
   if (destFileName.endsWith(File.separator)) {
     return false;
   }
   // 判断目标文件所在的目录是否存在
   // 创建目标文件
   if (file.exists()) {
     return true;
   }
   try {
     if (file.createNewFile()) {
       return true;
     } else {
       return false;
     }
   } catch (IOException e) {
     e.printStackTrace();
     return false;
   }
 }
Beispiel #27
0
 /**
  * Copies a file to a new location.
  *
  * <p>This method copies the contents of the specified source file to the specified destination
  * file. The directory holding the destination file is created if it does not exist. If the
  * destination file exists, then this method will overwrite it.
  *
  * @param srcFile an existing file to copy, must not be <code>null</code>
  * @param destFile the new file, must not be <code>null</code>
  * @param preserveFileDate true if the file date of the copy should be the same as the original
  * @throws NullPointerException if source or destination is <code>null</code>
  * @throws IOException if source or destination is invalid
  * @throws IOException if an IO error occurs during copying
  * @see #copyFileToDirectory(File, File, boolean)
  */
 public static void copyFile(File srcFile, File destFile) throws IOException {
   if (srcFile == null) {
     throw new NullPointerException("Source must not be null");
   }
   if (destFile == null) {
     throw new NullPointerException("Destination must not be null");
   }
   if (srcFile.exists() == false) {
     throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
   }
   if (srcFile.isDirectory()) {
     throw new IOException("Source '" + srcFile + "' exists but is a directory");
   }
   if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
     throw new IOException(
         "Source '" + srcFile + "' and destination '" + destFile + "' are the same");
   }
   if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
     if (destFile.getParentFile().mkdirs() == false) {
       throw new IOException("Destination '" + destFile + "' directory cannot be created");
     }
   }
   if (destFile.exists() && destFile.canWrite() == false) {
     throw new IOException("Destination '" + destFile + "' exists but is read-only");
   }
   doCopyFile(srcFile, destFile);
 }
Beispiel #28
0
  /**
   * 创建单个文件
   *
   * @param descFileName 文件名,包含路径
   * @return 如果创建成功,则返回true,否则返回false
   */
  public static boolean createFile(String descFileName) {
    File file = new File(descFileName);
    if (file.exists()) {
      log.debug("文件 " + descFileName + " 已存在!");
      return false;
    }
    if (descFileName.endsWith(File.separator)) {
      log.debug(descFileName + " 为目录,不能创建目录!");
      return false;
    }
    if (!file.getParentFile().exists()) {
      // 如果文件所在的目录不存在,则创建目录
      if (!file.getParentFile().mkdirs()) {
        log.debug("创建文件所在的目录失败!");
        return false;
      }
    }

    // 创建文件
    try {
      if (file.createNewFile()) {
        log.debug(descFileName + " 文件创建成功!");
        return true;
      } else {
        log.debug(descFileName + " 文件创建失败!");
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace();
      log.debug(descFileName + " 文件创建失败!");
      return false;
    }
  }
Beispiel #29
0
 /**
  * Gets the root (or project) directory of a project. The working-directory can be any of the
  * modules.
  *
  * @param workingDirectory the working-directory.
  * @return the root-directory.
  */
 public static File getRoot(final File workingDirectory) {
   File ref = workingDirectory;
   while (ref.getParentFile() != null && new File(ref.getParentFile(), POM_FILE).exists()) {
     ref = ref.getParentFile();
   }
   return ref;
 }
  @Override
  public void kill(DataSegment segment) throws SegmentLoadingException {
    final File path = getPath(segment);
    log.info("killing segment[%s] mapped to path[%s]", segment.getIdentifier(), path);

    try {
      if (path.getName().endsWith(".zip")) {

        // path format -- > .../dataSource/interval/version/partitionNum/xxx.zip
        File partitionNumDir = path.getParentFile();
        FileUtils.deleteDirectory(partitionNumDir);

        // try to delete other directories if possible
        File versionDir = partitionNumDir.getParentFile();
        if (versionDir.delete()) {
          File intervalDir = versionDir.getParentFile();
          if (intervalDir.delete()) {
            File dataSourceDir = intervalDir.getParentFile();
            dataSourceDir.delete();
          }
        }
      } else {
        throw new SegmentLoadingException("Unknown file type[%s]", path);
      }
    } catch (IOException e) {
      throw new SegmentLoadingException(e, "Unable to kill segment");
    }
  }