示例#1
0
  private Response respond(Map<String, String> headers, String uri) {
    // Remove URL arguments
    uri = uri.trim().replace(File.separatorChar, '/');
    if (uri.indexOf('?') >= 0) {
      uri = uri.substring(0, uri.indexOf('?'));
    }

    // Prohibit getting out of current directory
    if (uri.contains("../")) {
      return createResponse(
          Response.Status.FORBIDDEN,
          NanoHTTPD.MIME_PLAINTEXT,
          "FORBIDDEN: Won't serve ../ for security reasons.");
    }

    File f = new File(webRoot, uri);
    if (!f.exists()) {
      return createResponse(
          Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.");
    }

    // Browsers get confused without '/' after the directory, send a
    // redirect.
    if (f.isDirectory() && !uri.endsWith("/")) {
      uri += "/";
      Response res =
          createResponse(
              Response.Status.REDIRECT,
              NanoHTTPD.MIME_HTML,
              "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
      res.addHeader("Location", uri);
      return res;
    }

    if (f.isDirectory()) {
      // First look for index files (index.html, index.htm, etc) and if
      // none found, list the directory if readable.
      String indexFile = findIndexFileInDirectory(f);
      if (indexFile == null) {
        if (f.canRead()) {
          // No index file, list the directory if it is readable
          return createResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, listDirectory(uri, f));
        } else {
          return createResponse(
              Response.Status.FORBIDDEN,
              NanoHTTPD.MIME_PLAINTEXT,
              "FORBIDDEN: No directory listing.");
        }
      } else {
        return respond(headers, uri + indexFile);
      }
    }

    Response response = null;
    response = serveFile(uri, headers, f, getMimeTypeForFile(uri));
    return response != null
        ? response
        : createResponse(
            Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.");
  }
  /**
   * helper: recursively scan given directory.
   *
   * @return list of files found (might be empty)
   */
  private ArrayList<File> scanDirectory(File path) {
    Debug.trace("scanning directory " + path.getAbsolutePath());

    ArrayList<File> scan_result = new ArrayList<File>();

    if (!path.isDirectory()) {
      return scan_result;
    }

    File[] entries = path.listFiles();

    for (File file : entries) {
      if (file == null) {
        continue;
      }

      if (file.isDirectory()) {
        scan_result.addAll(scanDirectory(file));
      } else if ((file.isFile()) && (file.getName().toLowerCase().endsWith(".java"))) {
        scan_result.add(file);
      }
    }

    return scan_result;
  }
  /**
   * Recursively scans given directory and load all found files by loader.
   *
   * @param clsLdr Loader that could load class from given file.
   * @param dir Directory which should be scanned.
   * @param rsrcs Set which will be filled in.
   */
  @SuppressWarnings({"UnusedCatchParameter"})
  private static void findResourcesInDirectory(
      GridUriDeploymentFileResourceLoader clsLdr,
      File dir,
      Set<Class<? extends GridTask<?, ?>>> rsrcs) {
    assert dir.isDirectory() == true;

    for (File file : dir.listFiles()) {
      if (file.isDirectory()) {
        // Recurse down into directories.
        findResourcesInDirectory(clsLdr, file, rsrcs);
      } else {
        Class<? extends GridTask<?, ?>> rsrc = null;

        try {
          rsrc = clsLdr.createResource(file.getAbsolutePath(), true);
        } catch (GridSpiException e) {
          // Must never happen because we use 'ignoreUnknownRsrc=true'.
          assert false;
        }

        if (rsrc != null) {
          rsrcs.add(rsrc);
        }
      }
    }
  }
示例#4
0
 public int compare(Object o1, Object o2) {
   File f1 = (File) o1;
   File f2 = (File) o2;
   if (f1.isDirectory()) {
     if (f2.isDirectory()) {
       switch (mode) {
           // Filename or Type
         case 1:
         case 4:
           return sign
               * f1.getAbsolutePath()
                   .toUpperCase()
                   .compareTo(f2.getAbsolutePath().toUpperCase());
           // Filesize
         case 2:
           return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
           // Date
         case 3:
           return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
         default:
           return 1;
       }
     } else return -1;
   } else if (f2.isDirectory()) return 1;
   else {
     switch (mode) {
       case 1:
         return sign
             * f1.getAbsolutePath().toUpperCase().compareTo(f2.getAbsolutePath().toUpperCase());
       case 2:
         return sign * (new Long(f1.length()).compareTo(new Long(f2.length())));
       case 3:
         return sign * (new Long(f1.lastModified()).compareTo(new Long(f2.lastModified())));
       case 4:
         { // Sort by extension
           int tempIndexf1 = f1.getAbsolutePath().lastIndexOf('.');
           int tempIndexf2 = f2.getAbsolutePath().lastIndexOf('.');
           if ((tempIndexf1 == -1) && (tempIndexf2 == -1)) { // Neither have an extension
             return sign
                 * f1.getAbsolutePath()
                     .toUpperCase()
                     .compareTo(f2.getAbsolutePath().toUpperCase());
           }
           // f1 has no extension
           else if (tempIndexf1 == -1) return -sign;
           // f2 has no extension
           else if (tempIndexf2 == -1) return sign;
           // Both have an extension
           else {
             String tempEndf1 = f1.getAbsolutePath().toUpperCase().substring(tempIndexf1);
             String tempEndf2 = f2.getAbsolutePath().toUpperCase().substring(tempIndexf2);
             return sign * tempEndf1.compareTo(tempEndf2);
           }
         }
       default:
         return 1;
     }
   }
 }
示例#5
0
 private static void removeFiles(File file) throws IOException {
   if (file.exists() && file.isDirectory()) {
     for (File f : file.listFiles()) {
       removeFiles(f);
     }
   } else if (file.exists() && !file.isDirectory()) {
     if (!file.delete()) throw new IOException();
   }
 }
    public void valueChanged(ListSelectionEvent evt) {
      if (!evt.getValueIsAdjusting()) {
        JFileChooser chooser = getFileChooser();
        FileSystemView fsv = chooser.getFileSystemView();
        JList list = (JList) evt.getSource();

        int fsm = chooser.getFileSelectionMode();
        boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY);

        if (chooser.isMultiSelectionEnabled()) {
          File[] files = null;
          Object[] objects = list.getSelectedValues();
          if (objects != null) {
            if (objects.length == 1
                && ((File) objects[0]).isDirectory()
                && chooser.isTraversable(((File) objects[0]))
                && (useSetDirectory || !fsv.isFileSystem(((File) objects[0])))) {
              setDirectorySelected(true);
              setDirectory(((File) objects[0]));
            } else {
              ArrayList<File> fList = new ArrayList<File>(objects.length);
              for (Object object : objects) {
                File f = (File) object;
                boolean isDir = f.isDirectory();
                if ((chooser.isFileSelectionEnabled() && !isDir)
                    || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) {
                  fList.add(f);
                }
              }
              if (fList.size() > 0) {
                files = fList.toArray(new File[fList.size()]);
              }
              setDirectorySelected(false);
            }
          }
          chooser.setSelectedFiles(files);
        } else {
          File file = (File) list.getSelectedValue();
          if (file != null
              && file.isDirectory()
              && chooser.isTraversable(file)
              && (useSetDirectory || !fsv.isFileSystem(file))) {

            setDirectorySelected(true);
            setDirectory(file);
            if (usesSingleFilePane) {
              chooser.setSelectedFile(null);
            }
          } else {
            setDirectorySelected(false);
            if (file != null) {
              chooser.setSelectedFile(file);
            }
          }
        }
      }
    }
示例#7
0
  public void innerExecute() throws IOException, JerializerException {
    // first arg - schema dir, second arg - dest dir
    // TODO write schemas

    File schemas = new File(schemaDir);
    assert schemas.isDirectory() && schemas.canRead();

    File dest = new File(destDir);
    assert !dest.exists();
    dest.mkdir();
    assert dest.isDirectory() && dest.canWrite();

    Set<Klass> genKlasses = new TreeSet<Klass>();

    JsonParser parser = new JsonParser();
    for (File schema : schemas.listFiles()) {
      BufferedReader reader = new BufferedReader(new FileReader(schema));
      JThing thing = parser.parse(reader);
      System.out.println(thing);
      String rootString = schemas.toURI().toString();
      if (!rootString.endsWith("/")) rootString = rootString + "/";
      String klassName =
          KlassContext.capitalize(schema.toURI().toString().substring(rootString.length()));
      String packageName = basePackage + "." + klassName.toLowerCase();

      GenWritable writable = parseSchemaThing(klassName, packageName, thing);

      Map<String, String> m = writable.makeClassToTextMap();

      final File dir = new File(destDir + "/" + klassName.toLowerCase());
      dir.mkdirs();
      for (Map.Entry<String, String> entry : m.entrySet()) {
        final String fullClass = entry.getKey();
        final String contents = entry.getValue();
        final String relName = fullClass.substring(fullClass.lastIndexOf(".") + 1) + ".java";
        final File f = new File(dir, relName);
        FileWriter writer = new FileWriter(f);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(contents, 0, contents.length());
        bufferedWriter.close();
      }

      genKlasses.add(new Klass(klassName, packageName));
    }

    RegistryGen registryGen =
        new RegistryGen(new Klass("GenschemaRegistryFactory", basePackage), genKlasses);
    final File g = new File(destDir + "/GenschemaRegistryFactory.java");
    for (Map.Entry<String, String> entry : registryGen.makeClassToTextMap().entrySet()) {
      final String contents = entry.getValue();
      FileWriter writer = new FileWriter(g);
      BufferedWriter bufferedWriter = new BufferedWriter(writer);
      bufferedWriter.write(contents, 0, contents.length());
      bufferedWriter.close();
      break;
    }
  }
示例#8
0
  /**
   * Return either (a) the children files in a directory, or (b) files listed in the input, assuming
   * inputFileOrDir is a text file with 1 file listing per line.
   *
   * @param inputFileOrDir
   * @return
   */
  private List<File> getFilesFromDirOrList(File inputFileOrDir) {

    if (inputFileOrDir.isDirectory()) {
      File[] files = inputFileOrDir.listFiles();
      Arrays.sort(
          files,
          new Comparator<File>() {
            public int compare(File file, File file1) {
              return file.getName().compareTo(file1.getName());
            }
          });
      return Arrays.asList(files);
    } else {
      // Must be a "list" file
      BufferedReader br = null;
      try {
        ArrayList<File> files = new ArrayList<File>();
        br = new BufferedReader(new FileReader(inputFileOrDir));
        File parentDirectory = inputFileOrDir.getParentFile();
        String nextLine;
        while ((nextLine = br.readLine()) != null) {
          File f = new File(nextLine);
          if (f.exists()) {
            if (f.isDirectory()) {
              continue; // Skip directories
            }
            files.add(f);
          } else {
            // Might be relative path
            f = new File(parentDirectory, nextLine);
            if (f.exists()) {
              files.add(f);
            } else {
              System.out.println("File not found: " + nextLine);
            }
          }
        }
        return files;
      } catch (Exception e) {
        // todo -- someday create reasonable excpetion classes.  Althought, this one works
        e.printStackTrace();
        throw new RuntimeException(
            "Error parsing input file: " + inputFileOrDir.getAbsolutePath() + " " + e.getMessage());
      } finally {
        if (br != null)
          try {
            br.close();
          } catch (IOException e) {
            e
                .printStackTrace(); // To change body of catch statement use File | Settings | File
                                    // Templates.
          }
      }
    }
  }
  private void setupHomeDir(String homeString) {
    if (homeString == null) {
      homeString = sysProps.getProperty("swingri.home");
    }

    if (homeString != null) {
      dataDir = new File(homeString);
    } else {
      userHome = new File(sysProps.getProperty("user.home"));
      String dataDirStr = props.getString("application.datadir", DEFAULT_HOME_DIR);
      dataDir = new File(userHome, dataDirStr);
    }

    if (!dataDir.isDirectory()) {
      String path = dataDir.getAbsolutePath();
      boolean create;
      if (props.hasUserRejectedCreatingLocalDataDir()) {
        create = false;
      } else if (getBoolean("application.showLocalStorageDialogs", true)) {
        create =
            Resources.showConfirmDialog(
                null,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.createNewDirectory",
                path);
        if (!create) props.setUserRejectedCreatingLocalDataDir();
      } else {
        // Always create local-storage directory if show user prompt dialog setting is false.
        create = true;
      }

      if (!create) {
        dataDir = null;
      } else {
        dataDir.mkdirs();
        if (!dataDir.isDirectory()) {
          // check to make sure that dialog should be shown on the error.
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.failedCreation",
                dataDir.getAbsolutePath());
          }
          dataDir = null;
        }
      }
    }
  }
示例#10
0
  /**
   * Extracts next entry from JAR file, creating directories as needed. If the entry is for a
   * directory which doesn't exist prior to this invocation, returns that entry, otherwise returns
   * null.
   */
  ZipEntry extractFile(InputStream is, ZipEntry e) throws IOException {
    ZipEntry rc = null;
    String name = e.getName();
    File f = new File(e.getName().replace('/', File.separatorChar));
    if (e.isDirectory()) {
      if (f.exists()) {
        if (!f.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        }
      } else {
        if (!f.mkdirs()) {
          throw new IOException(formatMsg("error.create.dir", f.getPath()));
        } else {
          rc = e;
        }
      }

      if (vflag) {
        output(formatMsg("out.create", name));
      }
    } else {
      if (f.getParent() != null) {
        File d = new File(f.getParent());
        if (!d.exists() && !d.mkdirs() || !d.isDirectory()) {
          throw new IOException(formatMsg("error.create.dir", d.getPath()));
        }
      }
      try {
        copy(is, f);
      } finally {
        if (is instanceof ZipInputStream) ((ZipInputStream) is).closeEntry();
        else is.close();
      }
      if (vflag) {
        if (e.getMethod() == ZipEntry.DEFLATED) {
          output(formatMsg("out.inflated", name));
        } else {
          output(formatMsg("out.extracted", name));
        }
      }
    }
    if (!useExtractionTime) {
      long lastModified = e.getTime();
      if (lastModified != -1) {
        f.setLastModified(lastModified);
      }
    }
    return rc;
  }
示例#11
0
  /**
   * Estimage the number of lines in the given file, or all files in the given directory, or all
   * files referenced in a ".list" file.
   *
   * @param file a file or directory.
   * @return
   */
  private int estimateLineCount(File file) {

    int nLines = 0;
    if (file.isDirectory() || file.getName().endsWith(".list")) {
      List<File> files = getFilesFromDirOrList(file);
      for (File f : files) {
        if (!f.isDirectory()) {
          nLines += ParsingUtils.estimateLineCount(f.getAbsolutePath());
        }
      }
    } else {
      nLines = ParsingUtils.estimateLineCount(file.getAbsolutePath());
    }
    return nLines;
  }
示例#12
0
  /** Like mkdirs but but using openide filesystems (firing events) */
  public static FileObject mkfolders(File file) throws IOException {
    file = FileUtil.normalizeFile(file);
    if (file.isDirectory()) return FileUtil.toFileObject(file);

    File parent = file.getParentFile();

    String path = file.getName();
    while (parent.isDirectory() == false) {
      path = parent.getName() + "/" + path; // NOI18N
      parent = parent.getParentFile();
    }

    FileObject fo = FileUtil.toFileObject(parent);
    return FileUtil.createFolder(fo, path);
  }
  /**
   * Load classes from given file. File could be either directory or JAR file.
   *
   * @param clsLdr Class loader to load files.
   * @param file Either directory or JAR file which contains classes or references to them.
   * @return Set of found and loaded classes or empty set if file does not exist.
   * @throws GridSpiException Thrown if given JAR file references to none existed class or
   *     IOException occurred during processing.
   */
  static Set<Class<? extends GridTask<?, ?>>> getClasses(ClassLoader clsLdr, File file)
      throws GridSpiException {
    Set<Class<? extends GridTask<?, ?>>> rsrcs = new HashSet<Class<? extends GridTask<?, ?>>>();

    if (file.exists() == false) {
      return rsrcs;
    }

    GridUriDeploymentFileResourceLoader fileRsrcLdr =
        new GridUriDeploymentFileResourceLoader(clsLdr, file);

    if (file.isDirectory()) {
      findResourcesInDirectory(fileRsrcLdr, file, rsrcs);
    } else {
      try {
        for (JarEntry entry : U.asIterable(new JarFile(file.getAbsolutePath()).entries())) {
          Class<? extends GridTask<?, ?>> rsrc = fileRsrcLdr.createResource(entry.getName(), false);

          if (rsrc != null) {
            rsrcs.add(rsrc);
          }
        }
      } catch (IOException e) {
        throw new GridSpiException(
            "Failed to discover classes in file: " + file.getAbsolutePath(), e);
      }
    }

    return rsrcs;
  }
  /**
   * Add fully-resolved directories (with filters) to the current class path.
   *
   * @param baseList is the list of library directories.
   * @param filterList is the corresponding list of filters.
   */
  protected void addDirsToClassPath(File[] baseList, FileFilter[] filterList)
      throws ManifoldCFException {
    int i = 0;
    while (i < baseList.length) {
      File base = baseList[i];
      FileFilter filter;
      if (filterList != null) filter = filterList[i];
      else filter = null;

      if (base.canRead() && base.isDirectory()) {
        File[] files = base.listFiles(filter);

        if (files != null && files.length > 0) {
          int j = 0;
          while (j < files.length) {
            File file = files[j++];
            currentClasspath.add(file);
            // Invalidate the current classloader
            classLoader = null;
          }
        }
      } else
        throw new ManifoldCFException(
            "Supposed directory '"
                + base.toString()
                + "' is either not a directory, or is unreadable.");
      i++;
    }
  }
示例#15
0
  private static void index_h(String prefix, File file, IndexWriter indexWriter)
      throws IOException {
    Document doc = null;

    if (file.isDirectory()) {
      File files[] = file.listFiles();
      for (File file1 : files) {
        index_h(prefix + FILE_SEPARATOR + file.getName(), file1, indexWriter);
      }
    } else {
      String content = FileUtils.readFileToString(file, "utf-8");

      System.out.println("==============================================================");
      System.out.println("index_h " + content);
      System.out.println("==============================================================");

      String filename = prefix + FILE_SEPARATOR + file.getName();
      String path = file.getAbsolutePath();

      doc = new Document();
      doc.add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED));
      doc.add(new Field("relative_path", filename, Field.Store.YES, Field.Index.NOT_ANALYZED));
      indexWriter.addDocument(doc);
    }
  }
示例#16
0
  public static void copyDirectory(
      File source, File destination, boolean hardLinks, FileFilter filter) {
    if (source.exists() && source.isDirectory()) {
      if (!destination.exists()) {
        destination.mkdirs();
      }

      File[] fileArray = filter != null ? source.listFiles(filter) : source.listFiles();

      for (int i = 0; i < fileArray.length; i++) {
        if (fileArray[i].getName().endsWith("xml")) {
          String name = fileArray[i].getName();
          Logger.info(FileUtil.class, "copy " + name);
        }

        if (fileArray[i].isDirectory()) {
          copyDirectory(
              fileArray[i],
              new File(destination.getPath() + File.separator + fileArray[i].getName()),
              hardLinks,
              filter);
        } else {
          copyFile(
              fileArray[i],
              new File(destination.getPath() + File.separator + fileArray[i].getName()),
              hardLinks);
        }
      }
    }
  }
示例#17
0
 /** svg image on sdcard */
 public static void unpackOnSdCard(AssetManager assetManager) throws IOException {
   if (Environment.getExternalStorageState().compareTo(Environment.MEDIA_MOUNTED) == 0) {
     File sdcard = Environment.getExternalStorageDirectory();
     String irrlichtPath = sdcard.getAbsoluteFile() + "/Irrlicht/";
     File irrlichtDir = new File(irrlichtPath);
     if (irrlichtDir.exists() && !irrlichtDir.isDirectory()) {
       throw new IOException("Irrlicht exists and is not a directory on SD Card");
     } else if (!irrlichtDir.exists()) {
       irrlichtDir.mkdirs();
     }
     // Note: /sdcard/irrlicht dir exists
     String[] filenames = assetManager.list("data");
     for (String filename : filenames) {
       InputStream inputStream = assetManager.open("data/" + filename);
       OutputStream outputStream = new FileOutputStream(irrlichtPath + "/" + filename);
       // copy
       byte[] buffer = new byte[4096];
       int length;
       while ((length = inputStream.read(buffer)) > 0) {
         outputStream.write(buffer, 0, length);
       }
       outputStream.flush();
       outputStream.close();
       inputStream.close();
     }
   } else {
     throw new IOException("SD Card not available");
   }
 }
 public boolean accept(File pathname) {
   if (pathname.isDirectory()) {
     return true;
   } else {
     return pattern.matcher(pathname.getName()).matches();
   }
 }
示例#19
0
  public static File[] listFileHandles(File dir, Boolean includeSubDirs) throws IOException {

    if (!dir.exists() || !dir.isDirectory()) {
      return new File[0];
    }

    FileFilter fileFilter =
        new FileFilter() {
          public boolean accept(File file) {
            return file.isDirectory();
          }
        };

    File[] subFolders = dir.listFiles(fileFilter);

    List<File> files = new ArrayList<File>();

    List<File> fileArray =
        new ArrayList<File>(
            FileUtils.listFiles(
                dir, TrueFileFilter.INSTANCE, includeSubDirs ? TrueFileFilter.INSTANCE : null));

    for (File file : fileArray) {
      if (file.isFile()) {
        if (includeSubDirs && containsParentFolder(file, subFolders)) {
          files.add(file);
        } else {
          files.add(file);
        }
      }
    }

    return (File[]) files.toArray(new File[0]);
  }
示例#20
0
文件: Macro.java 项目: bramk/bnd
  String ls(String args[], boolean relative) {
    if (args.length < 2)
      throw new IllegalArgumentException(
          "the ${ls} macro must at least have a directory as parameter");

    File dir = domain.getFile(args[1]);
    if (!dir.isAbsolute())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter is not absolute: " + dir);

    if (!dir.exists())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter does not exist: " + dir);

    if (!dir.isDirectory())
      throw new IllegalArgumentException(
          "the ${ls} macro directory parameter points to a file instead of a directory: " + dir);

    Collection<File> files = new ArrayList<File>(new SortedList<File>(dir.listFiles()));

    for (int i = 2; i < args.length; i++) {
      Instructions filters = new Instructions(args[i]);
      files = filters.select(files, true);
    }

    List<String> result = new ArrayList<String>();
    for (File file : files) result.add(relative ? file.getName() : file.getAbsolutePath());

    return Processor.join(result, ",");
  }
 /**
  * Called by the JFileChooser, checks if a file has to be displayed or not.
  *
  * @param f the File to check.
  */
 public boolean accept(File f) {
   if (f.isDirectory()) {
     return true;
   }
   String nomfic = f.getName();
   return nomfic.endsWith(this.extension);
 }
示例#22
0
  public static void testBumpSubBuilders() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-sub");
      project.setTrace(true);

      assertNull(project.getProperty("Bundle-Version"));

      project.bump("=+0");

      assertNull(project.getProperty("Bundle-Version"));

      for (Builder b : project.getSubBuilders()) {
        assertEquals(new Version(1, 1, 0), new Version(b.getVersion()));
      }
    } finally {
      IO.deleteWithException(tmp);
    }
  }
  private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
    Class marker =
        isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;

    File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

    if (!classDirOrJar.isDirectory()) {
      return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
    }

    // it's a classes directory, we are in development mode.
    File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
    tempFile.deleteOnExit();

    ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
    try {
      ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

      if (isMaven3) {
        File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

        String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
        ZipUtil.addDirToZipRecursively(
            zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
      }
    } finally {
      zipOutput.close();
    }

    return tempFile.getAbsolutePath();
  }
示例#24
0
  public static void testBumpIncludeFile() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-included");
      project.setTrace(true);
      Version old = new Version(project.getProperty("Bundle-Version"));
      assertEquals(new Version(1, 0, 0), old);
      project.bump("=+0");

      Processor processor = new Processor();
      processor.setProperties(project.getFile("include.txt"));

      Version newv = new Version(processor.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(1, newv.getMajor());
      assertEquals(1, newv.getMinor());
      assertEquals(0, newv.getMicro());
    } finally {
      IO.deleteWithException(tmp);
    }
  }
  public void run() {
    try {
      File f2 = new File(MATCH_LOG_FILE);
      if (f2.exists() && !f2.isDirectory()) {
        matchReader = new BufferedReader(new FileReader(MATCH_LOG_FILE));
        String sCurrentLine;

        for (int i = 0; i < logCount; i++) {
          matchReader.readLine();
        }

        while ((sCurrentLine = matchReader.readLine()) != null) {
          if (sendToBackOffice(sCurrentLine)) {
            System.out.println("Updating log count");
            logWriter = new PrintWriter(new FileWriter("c:\\temp\\countBackOffice.log"));
            logWriter.print(++logCount);
            logWriter.close();
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (matchReader != null) matchReader.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
 @Override
 public boolean accept(File path) {
   if (path.isDirectory()) return true;
   String name = path.getName();
   if (name.endsWith(".py") || name.endsWith(".PY")) return true;
   return false;
 }
示例#27
0
 /**
  * Determines the sticky information for a given file. If the file is new then it returns its
  * parent directory's sticky info, if any.
  *
  * @param file file to examine
  * @return String sticky information for a file (without leading N, D or T specifier) or null
  */
 public static String getSticky(File file) {
   if (file == null) return null;
   FileInformation info = CvsVersioningSystem.getInstance().getStatusCache().getStatus(file);
   if (info.getStatus() == FileInformation.STATUS_NOTVERSIONED_NEWLOCALLY) {
     return getSticky(file.getParentFile());
   } else if (info.getStatus() == FileInformation.STATUS_NOTVERSIONED_EXCLUDED) {
     return null;
   }
   if (file.isDirectory()) {
     String std =
         CvsVersioningSystem.getInstance().getAdminHandler().getStickyTagForDirectory(file);
     if (std != null) {
       std = std.substring(1);
     }
     return std;
   }
   Entry entry = info.getEntry(file);
   if (entry != null) {
     String stickyInfo = null;
     if (entry.getTag() != null) stickyInfo = entry.getTag(); // NOI18N
     else if (entry.getDate() != null) stickyInfo = entry.getDateFormatted(); // NOI18N
     return stickyInfo;
   }
   return null;
 }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
 public static void copyDir(
     @NotNull File fromDir, @NotNull File toDir, @Nullable final FileFilter filter)
     throws IOException {
   ensureExists(toDir);
   if (isAncestor(fromDir, toDir, true)) {
     LOG.error(fromDir.getAbsolutePath() + " is ancestor of " + toDir + ". Can't copy to itself.");
     return;
   }
   File[] files = fromDir.listFiles();
   if (files == null)
     throw new IOException(
         CommonBundle.message("exception.directory.is.invalid", fromDir.getPath()));
   if (!fromDir.canRead())
     throw new IOException(
         CommonBundle.message("exception.directory.is.not.readable", fromDir.getPath()));
   for (File file : files) {
     if (filter != null && !filter.accept(file)) {
       continue;
     }
     if (file.isDirectory()) {
       copyDir(file, new File(toDir, file.getName()), filter);
     } else {
       copy(file, new File(toDir, file.getName()));
     }
   }
 }
示例#30
0
  public static void testBump() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("p1");
      int size = project.getProperties().size();
      Version old = new Version(project.getProperty("Bundle-Version"));
      System.err.println("Old version " + old);
      project.bump("=+0");
      Version newv = new Version(project.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(old.getMajor(), newv.getMajor());
      assertEquals(old.getMinor() + 1, newv.getMinor());
      assertEquals(0, newv.getMicro());
      assertEquals(size, project.getProperties().size());
      assertEquals("sometime", newv.getQualifier());
    } finally {
      IO.deleteWithException(tmp);
    }
  }