Exemplo n.º 1
0
  /**
   * This method will read the standard input and save the content to a temporary. source file since
   * the source file will be parsed mutiple times. The HTML source file is parsed and checked for
   * Charset in HTML tags at first time, then source file is parsed again for the converting The
   * temporary file is read from standard input and saved in current directory and will be deleted
   * after the conversion has completed.
   *
   * @return the vector of the converted temporary source file name
   */
  public Vector getStandardInput() throws FileAccessException {
    byte[] buf = new byte[2048];
    int len = 0;
    FileInputStream fis = null;
    FileOutputStream fos = null;
    File tempSourceFile;
    String tmpSourceName = ".tmpSource_stdin";

    File outFile = new File(tmpSourceName);

    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (!tempSourceFile.exists()) {
      try {
        fis = new FileInputStream(FileDescriptor.in);
        fos = new FileOutputStream(outFile);
        while ((len = fis.read(buf, 0, 2048)) != -1) fos.write(buf, 0, len);
      } catch (IOException e) {
        System.out.println(ResourceHandler.getMessage("plugin_converter.write_permission"));
        return null;
      }
    } else {
      throw new FileAccessException(ResourceHandler.getMessage("plugin_converter.overwrite"));
    }
    tempSourceFile = new File(System.getProperty("user.dir") + sep + tmpSourceName);
    if (tempSourceFile.exists()) {
      fileSpecs.add(tmpSourceName);
      return fileSpecs;
    } else {
      throw new FileAccessException(
          ResourceHandler.getMessage("plugin_converter.write_permission"));
    }
  }
Exemplo n.º 2
0
  /**
   * This method will take in a string which will be a directory. It will make sure that the
   * directory exists and return the absolute path
   *
   * @return the value of the absolute directory
   */
  private String doesExistAndAbsolute(String dir) {

    File tempDirFile = new File(dir);
    try {
      if (tempDirFile.exists()) {
        if (tempDirFile.isAbsolute()) {
          return dir;
        } else {
          tempDirFile = new File(System.getProperty("user.dir") + sep + dir);
          if (tempDirFile.exists()) {
            return tempDirFile.getAbsolutePath();
          } else {
            throw new NotDirectoryException(
                ResourceHandler.getMessage("caption.reldirnotfound")
                    + ":  "
                    + tempDirFile.getAbsolutePath());
          }
        }
      } else {
        throw new NotDirectoryException(
            ResourceHandler.getMessage("caption.absdirnotfound")
                + ":  "
                + tempDirFile.getAbsolutePath());
      }

    } catch (NotDirectoryException e) {
      System.out.println(
          ResourceHandler.getMessage("caption.absdirnotfound")
              + ":  "
              + tempDirFile.getAbsolutePath());
      return null; // this is just so it would compile
    }
  }
Exemplo n.º 3
0
  public void doSort(String ifile, String ofile, String tmpDirName, int maxRecords) {

    System.out.println("Sorting " + ifile + "  -> " + ofile);
    File inputFile = new File(ifile);
    File outputFile = new File(ofile);
    Sorter sorter = Sorter.getSorter(inputFile, outputFile);
    if (tmpDirName != null && tmpDirName.trim().length() > 0) {
      File tmpDir = new File(tmpDirName);
      if (!tmpDir.exists()) {
        System.err.println(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
        throw new PreprocessingException(
            "Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
      }
      sorter.setTmpDir(tmpDir);
    }

    sorter.setMaxRecords(maxRecords);
    try {
      sorter.run();
    } catch (Exception e) {
      e.printStackTrace();
      // Delete output file as its probably corrupt
      if (outputFile.exists()) {
        outputFile.delete();
      }
    }
    System.out.println("Done");
    System.out.flush();
  }
  private void saveConfiguration(
      BundleInfo[] configuration, File outputFile, URI installArea, boolean backup)
      throws IOException {
    if (backup && outputFile.exists()) {
      File backupFile = Utils.getSimpleDataFormattedFile(outputFile);
      if (!outputFile.renameTo(backupFile)) {
        throw new IOException("Fail to rename from (" + outputFile + ") to (" + backupFile + ")");
      }
    }

    org.eclipse.equinox.internal.simpleconfigurator.utils.BundleInfo[] simpleInfos =
        convertBundleInfos(configuration, installArea);

    // if empty remove the configuration file
    if (simpleInfos == null || simpleInfos.length == 0) {
      if (outputFile.exists()) {
        outputFile.delete();
      }
      File parentDir = outputFile.getParentFile();
      if (parentDir.exists()) {
        parentDir.delete();
      }
      return;
    }
    SimpleConfiguratorManipulatorUtils.writeConfiguration(simpleInfos, outputFile);
    if (CONFIG_LIST.equals(outputFile.getName())
        && installArea != null
        && isSharedInstallSetup(URIUtil.toFile(installArea), outputFile))
      rememberSharedBundlesInfoTimestamp(installArea, outputFile.getParentFile());
  }
Exemplo n.º 5
0
  private void _loadConfig() {
    try {

      _configScope.set("__instance__", this);

      _loadConfigFromCloudObject(getSiteObject());
      _loadConfigFromCloudObject(getEnvironmentObject());

      File f;
      if (!_admin) {
        f = getFileSafe("_config.js");
        if (f == null || !f.exists()) f = getFileSafe("_config");
      } else
        f =
            new File(
                Module.getModule("core-modules/admin").getRootFile(getVersionForLibrary("admin")),
                "_config.js");

      _libraryLogger.info("config file [" + f + "] exists:" + f.exists());

      if (f == null || !f.exists()) return;

      Convert c = new Convert(f);
      JSFunction func = c.get();
      func.setUsePassedInScope(true);
      func.call(_configScope);

      _logger.debug("config things " + _configScope.keySet());
    } catch (Exception e) {
      throw new RuntimeException("couldn't load config", e);
    }
  }
Exemplo n.º 6
0
  /** Maintain the versions of the file we are about to for writing. */
  private static boolean shuffleVersions(String file) {
    File f = new File(file);

    if (!f.exists()) {
      return true;
    }
    int version = 99;

    boolean found = false;

    do {
      String fileVersion = file + String.format("_%02d", version);
      File vf = new File(fileVersion);

      if (vf.exists()) {
        found = true;
      } else {
        version--;
      }

    } while (!found && version >= 0);

    version++;

    String fileVersion = file + String.format("_%02d", version);

    File newf = new File(fileVersion);

    return f.renameTo(newf);
  }
 protected int runEclipse(String message, File location, String[] args, File extensions) {
   File root = new File(Activator.getBundleContext().getProperty("java.home"));
   root = new File(root, "bin");
   File exe = new File(root, "javaw.exe");
   if (!exe.exists()) exe = new File(root, "java");
   assertTrue("Java executable not found in: " + exe.getAbsolutePath(), exe.exists());
   List<String> command = new ArrayList<String>();
   Collections.addAll(
       command,
       new String[] {
         (new File(location == null ? output : location, getExeFolder() + "eclipse"))
             .getAbsolutePath(),
         "--launcher.suppressErrors",
         "-nosplash",
         "-vm",
         exe.getAbsolutePath()
       });
   Collections.addAll(command, args);
   Collections.addAll(command, new String[] {"-vmArgs", "-Dosgi.checkConfiguration=true"});
   // command-line if you want to run and allow a remote debugger to connect
   if (debug)
     Collections.addAll(
         command,
         new String[] {
           "-Xdebug", "-Xnoagent", "-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8787"
         });
   int result = run(message, command.toArray(new String[command.size()]));
   // 13 means that we wrote something out in the log file.
   // so try and parse it and fail via that message if we can.
   if (result == 13) parseExitdata(message);
   return result;
 }
Exemplo n.º 8
0
 public boolean convertMapFormat(String s, IProgressUpdate iprogressupdate) {
   iprogressupdate.setLoadingProgress(0);
   ArrayList arraylist = new ArrayList();
   ArrayList arraylist1 = new ArrayList();
   ArrayList arraylist2 = new ArrayList();
   ArrayList arraylist3 = new ArrayList();
   File file = new File(field_22180_a, s);
   File file1 = new File(file, "DIM-1");
   System.out.println("Scanning folders...");
   func_22183_a(file, arraylist, arraylist1);
   if (file1.exists()) {
     func_22183_a(file1, arraylist2, arraylist3);
   }
   int i = arraylist.size() + arraylist2.size() + arraylist1.size() + arraylist3.size();
   System.out.println(
       (new StringBuilder()).append("Total conversion count is ").append(i).toString());
   func_22181_a(file, arraylist, 0, i, iprogressupdate);
   func_22181_a(file1, arraylist2, arraylist.size(), i, iprogressupdate);
   WorldInfo worldinfo = func_22173_b(s);
   worldinfo.setSaveVersion(19132);
   ISaveHandler isavehandler = getSaveLoader(s, false);
   isavehandler.saveWorldInfo(worldinfo);
   func_22182_a(arraylist1, arraylist.size() + arraylist2.size(), i, iprogressupdate);
   if (file1.exists()) {
     func_22182_a(
         arraylist3, arraylist.size() + arraylist2.size() + arraylist1.size(), i, iprogressupdate);
   }
   return true;
 }
Exemplo n.º 9
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");
   }
 }
Exemplo n.º 10
0
  synchronized void migrateData(DataStore targetStore) {
    ForceLoadAllClaims(this);
    targetStore.ClearInventoryOnJoinPlayers = ClearInventoryOnJoinPlayers;
    // migrate claims
    for (Claim c : this.claims) {
      GriefPrevention.AddLogEntry("Migrating Claim #" + c.getID());
      targetStore.addClaim(c);
    }

    // migrate groups
    Iterator<String> groupNamesEnumerator = this.permissionToBonusBlocksMap.keySet().iterator();
    while (groupNamesEnumerator.hasNext()) {
      String groupName = groupNamesEnumerator.next();
      targetStore.saveGroupBonusBlocks(groupName, this.permissionToBonusBlocksMap.get(groupName));
    }

    // migrate players
    for (PlayerData pdata : getAllPlayerData()) {

      targetStore.playerNameToPlayerDataMap.put(pdata.playerName, pdata);
      targetStore.savePlayerData(pdata.playerName, pdata);
    }

    // migrate next claim ID
    if (this.nextClaimID > targetStore.nextClaimID) {
      targetStore.setNextClaimID(this.nextClaimID);
    }

    // rename player and claim data folders so the migration won't run again
    int i = 0;
    File claimsBackupFolder;
    File playersBackupFolder;
    do {
      String claimsFolderBackupPath = claimDataFolderPath;
      if (i > 0) claimsFolderBackupPath += String.valueOf(i);
      claimsBackupFolder = new File(claimsFolderBackupPath);

      String playersFolderBackupPath = playerDataFolderPath;
      if (i > 0) playersFolderBackupPath += String.valueOf(i);
      playersBackupFolder = new File(playersFolderBackupPath);
      i++;
    } while (claimsBackupFolder.exists() || playersBackupFolder.exists());

    File claimsFolder = new File(claimDataFolderPath);
    File playersFolder = new File(playerDataFolderPath);

    claimsFolder.renameTo(claimsBackupFolder);
    playersFolder.renameTo(playersBackupFolder);

    GriefPrevention.AddLogEntry(
        "Backed your file system data up to "
            + claimsBackupFolder.getName()
            + " and "
            + playersBackupFolder.getName()
            + ".");
    GriefPrevention.AddLogEntry(
        "If your migration encountered any problems, you can restore those data with a quick copy/paste.");
    GriefPrevention.AddLogEntry(
        "When you're satisfied that all your data have been safely migrated, consider deleting those folders.");
  }
Exemplo n.º 11
0
  // Look through the http-import directory and process all
  // the files there, oldest first. Note that these are actual
  // files, not queue elements.
  private void processHttpImportFiles() {
    File importDirFile = new File(TrialConfig.basepath + TrialConfig.httpImportDir);
    if (!importDirFile.exists()) return;
    File[] files = importDirFile.listFiles();
    for (int k = 0; k < files.length; k++) {
      File next = files[k];
      if (next.canRead() && next.canWrite()) {
        FileObject fileObject = FileObject.getObject(next);
        if (preprocess(fileObject)) {
          process(fileObject);
          if (!queueForDatabase(fileObject))
            Log.message(Quarantine.file(next, processorServiceName));
          else Log.message(processorServiceName + ": Processing complete: " + next.getName());
        }

        // If the file still exists, then there must be a bug
        // somewhere; log it and quarantine the file so we don't
        // fall into an infinite loop.
        if (next.exists()) {
          logger.warn(
              "File still in queue after processing:\n" + next + "The file will be quarantined.");
          Log.message(Quarantine.file(next, processorServiceName));
        }
        Thread.currentThread().yield();
      }
    }
  }
Exemplo n.º 12
0
  /**
   * Constructor. The name of the properties file can be passed as parameter. If the filename is
   * null, it will look for a properties file, based on <code>&lt;classname&gt;.properties</code>.
   *
   * @param propertiesFilename The name of the properties file. Can be null.
   * @param classname The full name of the class using this class.
   */
  public Util(String propertiesFilename, String classname) {
    propFile = null;
    prop = new Properties();

    if (propertiesFilename == null) {
      propertiesFilename = getDefaultPropertiesFilename(classname);
      propFile = new File(propertiesFilename);
    } else {
      propFile = new File(propertiesFilename);
      if (propFile.exists() == false) {
        System.out.println("Util(): Cannot find properties file '" + propFile + "'.");

        propertiesFilename = getDefaultPropertiesFilename(classname);
        propFile = new File(propertiesFilename);
      }
    }

    if (propFile.exists() == true) {
      loadPropfile(propFile);
    } else {
      propFile = null;
      System.out.println(
          "Util(): Cannot find properties file '" + propFile + "'. Will use default properties.");
    }
  }
Exemplo n.º 13
0
 JavacState(Options op, boolean removeJavacState, PrintStream o, PrintStream e) {
   options = op;
   out = o;
   err = e;
   numCores = options.getNumCores();
   theArgs = options.getStateArgsString();
   binDir = Util.pathToFile(options.getDestDir());
   gensrcDir = Util.pathToFile(options.getGenSrcDir());
   headerDir = Util.pathToFile(options.getHeaderDir());
   stateDir = Util.pathToFile(options.getStateDir());
   javacState = new File(stateDir, "javac_state");
   if (removeJavacState && javacState.exists()) {
     javacState.delete();
   }
   newJavacState = false;
   if (!javacState.exists()) {
     newJavacState = true;
     // If there is no javac_state then delete the contents of all the artifact dirs!
     // We do not want to risk building a broken incremental build.
     // BUT since the makefiles still copy things straight into the bin_dir et al,
     // we avoid deleting files here, if the option --permit-unidentified-classes was supplied.
     if (!options.areUnidentifiedArtifactsPermitted()) {
       deleteContents(binDir);
       deleteContents(gensrcDir);
       deleteContents(headerDir);
     }
     needsSaving = true;
   }
   prev = new BuildState();
   now = new BuildState();
   taintedPackages = new HashSet<>();
   recompiledPackages = new HashSet<>();
   packagesWithChangedPublicApis = new HashSet<>();
 }
 /*
  * Set up the platform binary download and get it ready to run the tests.
  * This method is not intended to be called by clients, it will be called
  * automatically when the clients use a ReconcilerTestSuite. If the executable isn't
  * found on the file-system after the call, then we fail.
  */
 public void initialize() throws Exception {
   initialized = false;
   File file = getPlatformZip();
   output = getUniqueFolder();
   toRemove.add(output);
   // for now we will exec to un-tar archives to keep the executable bits
   if (file.getName().toLowerCase().endsWith(".zip")) {
     try {
       FileUtils.unzipFile(file, output);
     } catch (IOException e) {
       fail("0.99", e);
     }
   } else {
     untar("1.0", file);
   }
   File exe = new File(output, getExeFolder() + "eclipse.exe");
   if (!exe.exists()) {
     exe = new File(output, getExeFolder() + "eclipse");
     if (!exe.exists())
       fail(
           "Executable file: "
               + exe.getAbsolutePath()
               + "(or .exe) not found after extracting: "
               + file.getAbsolutePath()
               + " to: "
               + output);
   }
   initialized = true;
 }
Exemplo n.º 15
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);
        }
      }
    }
  }
Exemplo n.º 16
0
  private static void setupJurisdictionPolicies() throws Exception {
    String javaHomeDir = System.getProperty("java.home");
    String sep = File.separator;
    String pathToPolicyJar = javaHomeDir + sep + "lib" + sep + "security" + sep;

    File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
    File importJar = new File(pathToPolicyJar, "local_policy.jar");
    URL jceCipherURL = ClassLoader.getSystemResource("javax/crypto/Cipher.class");

    if ((jceCipherURL == null) || !exportJar.exists() || !importJar.exists()) {
      throw new SecurityException("Cannot locate policy or framework files!");
    }

    // Read jurisdiction policies.
    CryptoPermissions defaultExport = new CryptoPermissions();
    CryptoPermissions exemptExport = new CryptoPermissions();
    loadPolicies(exportJar, defaultExport, exemptExport);

    CryptoPermissions defaultImport = new CryptoPermissions();
    CryptoPermissions exemptImport = new CryptoPermissions();
    loadPolicies(importJar, defaultImport, exemptImport);

    // Merge the export and import policies for default applications.
    if (defaultExport.isEmpty() || defaultImport.isEmpty()) {
      throw new SecurityException("Missing mandatory jurisdiction " + "policy files");
    }
    defaultPolicy = defaultExport.getMinimum(defaultImport);

    // Merge the export and import policies for exempt applications.
    if (exemptExport.isEmpty()) {
      exemptPolicy = exemptImport.isEmpty() ? null : exemptImport;
    } else {
      exemptPolicy = exemptExport.getMinimum(exemptImport);
    }
  }
Exemplo n.º 17
0
 private void fixConfigSchema() {
   File configFile;
   File ctpDir = new File(directory, "CTP");
   if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml");
   else configFile = new File(directory, "config.xml");
   if (configFile.exists()) {
     try {
       Document doc = getDocument(configFile);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       moveAttributes(server, sslAttrs, "SSL");
       moveAttributes(server, proxyAttrs, "ProxyServer");
       moveAttributes(server, ldapAttrs, "LDAP");
       if (programName.equals("ISN")) fixRSNAROOT(server);
       if (isMIRC(root)) fixFileServiceAnonymizerID(root);
       setFileText(configFile, toString(doc));
     } catch (Exception ex) {
       cp.appendln(Color.red, "\nUnable to convert the config file schema.");
       cp.appendln(Color.black, "");
     }
   } else {
     cp.appendln(Color.red, "\nUnable to find the config file to check the schema.");
     cp.appendln(Color.black, "");
   }
 }
Exemplo n.º 18
0
  /**
   * Maps a servlet-like URI to a jxp file.
   *
   * @param f File to check
   * @return new File with <root>.jxp if exists, orig file if not
   * @example /wiki/geir -> maps to wiki.jxp if exists
   */
  File tryServlet(File f) {
    if (f.exists()) return f;

    String uri = f.toString();

    if (uri.startsWith(_rootFile.toString())) uri = uri.substring(_rootFile.toString().length());

    if (_core != null && uri.startsWith(_core._base.toString()))
      uri = "/~~" + uri.substring(_core._base.toString().length());

    while (uri.startsWith("/")) uri = uri.substring(1);

    int start = 0;
    while (true) {

      int idx = uri.indexOf("/", start);
      if (idx < 0) break;
      String foo = uri.substring(0, idx);

      File temp = getFileSafe(foo + ".jxp");

      if (temp != null && temp.exists()) f = temp;

      start = idx + 1;
    }

    return f;
  }
Exemplo n.º 19
0
 public static void receive_abort(Client client) throws IOException {
   File tempDir = getTempReceiveDir(client);
   File trashDir = getTrashReceiveDir(client);
   synchronized (ClientCatalog.class) {
     if (tempDir.exists()) FileUtils.deleteDirectory(tempDir);
     if (trashDir.exists()) FileUtils.deleteDirectory(trashDir);
   }
 }
Exemplo n.º 20
0
 private static void checkPackageInfoFiles(
     Project project, String packageName, boolean expectPackageInfo, boolean expectPackageInfoJava)
     throws Exception {
   File pkgInfo = IO.getFile(project.getSrc(), packageName + "/packageinfo");
   File pkgInfoJava = IO.getFile(project.getSrc(), packageName + "/package-info.java");
   assertEquals(expectPackageInfo, pkgInfo.exists());
   assertEquals(expectPackageInfoJava, pkgInfoJava.exists());
 }
Exemplo n.º 21
0
  /**
   * Tries to find the given file, assuming that it's missing the ".jxp" extension
   *
   * @param f File to check
   * @return same file if not found to be missing the .jxp, or a new File w/ the .jxp appended
   */
  File tryNoJXP(File f) {
    if (f.exists()) return f;

    if (f.getName().indexOf(".") >= 0) return f;

    File temp = new File(f.toString() + ".jxp");
    return temp.exists() ? temp : f;
  }
Exemplo n.º 22
0
  protected static void initSystemProperties(MoquiStart cl, boolean useProperties)
      throws IOException {
    Properties moquiInitProperties = new Properties();
    URL initProps = cl.getResource("MoquiInit.properties");
    if (initProps != null) {
      InputStream is = initProps.openStream();
      moquiInitProperties.load(is);
      is.close();
    }

    // before doing anything else make sure the moqui.runtime system property exists (needed for
    // config of various things)
    String runtimePath = System.getProperty("moqui.runtime");
    if (runtimePath != null && runtimePath.length() > 0)
      System.out.println("Determined runtime from system property: " + runtimePath);
    if (useProperties && (runtimePath == null || runtimePath.length() == 0)) {
      runtimePath = moquiInitProperties.getProperty("moqui.runtime");
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from MoquiInit.properties file: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      // see if runtime directory under the current directory exists, if not default to the current
      // directory
      File testFile = new File("runtime");
      if (testFile.exists()) runtimePath = "runtime";
      if (runtimePath != null && runtimePath.length() > 0)
        System.out.println("Determined runtime from existing runtime directory: " + runtimePath);
    }
    if (runtimePath == null || runtimePath.length() == 0) {
      runtimePath = ".";
      System.out.println("Determined runtime by defaulting to current directory: " + runtimePath);
    }
    File runtimeFile = new File(runtimePath);
    runtimePath = runtimeFile.getCanonicalPath();
    System.out.println("Canonicalized runtimePath: " + runtimePath);
    if (runtimePath.endsWith("/")) runtimePath = runtimePath.substring(0, runtimePath.length() - 1);
    System.setProperty("moqui.runtime", runtimePath);

    /* Don't do this here... loads as lower-level that WEB-INF/lib jars and so can't have dependencies on those,
        and dependencies on those are necessary
    // add runtime/lib jar files to the class loader
    File runtimeLibFile = new File(runtimePath + "/lib");
    for (File jarFile: runtimeLibFile.listFiles()) {
        if (jarFile.getName().endsWith(".jar")) cl.jarFileList.add(new JarFile(jarFile));
    }
    */

    // moqui.conf=conf/development/MoquiDevConf.xml
    String confPath = System.getProperty("moqui.conf");
    if (confPath == null || confPath.length() == 0) {
      confPath = moquiInitProperties.getProperty("moqui.conf");
    }
    if (confPath == null || confPath.length() == 0) {
      File testFile = new File(runtimePath + "/" + defaultConf);
      if (testFile.exists()) confPath = defaultConf;
    }
    if (confPath != null) System.setProperty("moqui.conf", confPath);
  }
Exemplo n.º 23
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();
   }
 }
Exemplo n.º 24
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.
          }
      }
    }
  }
Exemplo n.º 25
0
  /** Loads the script at the given URL. */
  private String loadSource(String sourceUrl) {
    String source = null;
    int hash = sourceUrl.indexOf('#');
    if (hash >= 0) {
      sourceUrl = sourceUrl.substring(0, hash);
    }
    try {
      InputStream is;
      openStream:
      {
        if (sourceUrl.indexOf(':') < 0) {
          // Can be a file name
          try {
            if (sourceUrl.startsWith("~/")) {
              String home = SecurityUtilities.getSystemProperty("user.home");
              if (home != null) {
                String pathFromHome = sourceUrl.substring(2);
                File f = new File(new File(home), pathFromHome);
                if (f.exists()) {
                  is = new FileInputStream(f);
                  break openStream;
                }
              }
            }
            File f = new File(sourceUrl);
            if (f.exists()) {
              is = new FileInputStream(f);
              break openStream;
            }
          } catch (SecurityException ex) {
          }
          // No existing file, assume missed http://
          if (sourceUrl.startsWith("//")) {
            sourceUrl = "http:" + sourceUrl;
          } else if (sourceUrl.startsWith("/")) {
            sourceUrl = "http://127.0.0.1" + sourceUrl;
          } else {
            sourceUrl = "http://" + sourceUrl;
          }
        }

        is = (new URL(sourceUrl)).openStream();
      }

      try {
        source = Kit.readReader(new InputStreamReader(is));
      } finally {
        is.close();
      }
    } catch (IOException ex) {
      System.err.println("Failed to load source from " + sourceUrl + ": " + ex);
    }
    return source;
  }
Exemplo n.º 26
0
  /**
   * Returns the index.jxp for the File argument if it's an existing directory, and the index.jxp
   * file exists
   *
   * @param f directory to check
   * @return new File for index.jxp in that directory, or same file object if not
   */
  File tryIndex(File f) {

    if (!(f.isDirectory() && f.exists())) return f;

    for (int i = 0; i < JSFileLibrary._srcExtensions.length; i++) {
      File temp = new File(f, "index" + JSFileLibrary._srcExtensions[i]);
      if (temp.exists()) return temp;
    }

    return f;
  }
Exemplo n.º 27
0
  private void checkAndLaunchUpdate() {
    Log.i(LOG_FILE_NAME, "Checking for an update");

    int statusCode = 8; // UNEXPECTED_ERROR
    File baseUpdateDir = null;
    if (Build.VERSION.SDK_INT >= 8)
      baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");

    File updateDir = new File(new File(baseUpdateDir, "updates"), "0");

    File updateFile = new File(updateDir, "update.apk");
    File statusFile = new File(updateDir, "update.status");

    if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return;

    if (!updateFile.exists()) return;

    Log.i(LOG_FILE_NAME, "Update is available!");

    // Launch APK
    File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk");
    try {
      if (updateFile.renameTo(updateFileToRun)) {
        String amCmd =
            "/system/bin/am start -a android.intent.action.VIEW "
                + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://"
                + updateFileToRun.getPath();
        Log.i(LOG_FILE_NAME, amCmd);
        Runtime.getRuntime().exec(amCmd);
        statusCode = 0; // OK
      } else {
        Log.i(LOG_FILE_NAME, "Cannot rename the update file!");
        statusCode = 7; // WRITE_ERROR
      }
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error launching installer to update", e);
    }

    // Update the status file
    String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n";

    OutputStream outStream;
    try {
      byte[] buf = status.getBytes("UTF-8");
      outStream = new FileOutputStream(statusFile);
      outStream.write(buf, 0, buf.length);
      outStream.close();
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error writing status file", e);
    }

    if (statusCode == 0) System.exit(0);
  }
  public void remove(String filePath) throws IOException, FileNotFoundException {
    File f = new File(filePath);

    if (f.exists() == false || f.isDirectory()) {
      return;
    }

    if (f.exists() && f.isFile()) {
      f.delete();
    }
  }
Exemplo n.º 29
0
  /** Create a new dfs name directory. Caution: this destroys all files in this filesystem. */
  public static void format(File dir, Configuration conf) throws IOException {
    File image = new File(dir, "image");
    File edits = new File(dir, "edits");

    if (!((!image.exists() || FileUtil.fullyDelete(image, conf))
        && (!edits.exists() || edits.delete())
        && image.mkdirs())) {

      throw new IOException("Unable to format: " + dir);
    }
  }
Exemplo n.º 30
0
  protected static DefaultFontMapper getMapper() {
    if (mapper == null) {
      //      long t = System.currentTimeMillis();
      mapper = new DefaultFontMapper();

      if (PApplet.platform == PApplet.MACOSX) {
        try {
          String homeLibraryFonts = System.getProperty("user.home") + "/Library/Fonts";
          mapper.insertDirectory(homeLibraryFonts);
        } catch (Exception e) {
          // might be a security issue with getProperty() and user.home
          // if this sketch is running from the web
        }
        // add the system font paths
        mapper.insertDirectory("/System/Library/Fonts");
        mapper.insertDirectory("/Library/Fonts");

      } else if (PApplet.platform == PApplet.WINDOWS) {
        // how to get the windows fonts directory?
        // could be c:\winnt\fonts or c:\windows\fonts or not even c:
        // maybe do a Runtime.exec() on echo %WINDIR% ?
        // Runtime.exec solution might be a mess on systems where the
        // the backslash/colon characters not really used (i.e. JP)

        // find the windows fonts folder
        File roots[] = File.listRoots();
        for (int i = 0; i < roots.length; i++) {
          if (roots[i].toString().startsWith("A:")) {
            // Seems to be a problem with some machines that the A:
            // drive is returned as an actual root, even if not available.
            // This won't fix the issue if the same thing happens with
            // other removable drive devices, but should fix the
            // initial/problem as cited by the bug report:
            // http://dev.processing.org/bugs/show_bug.cgi?id=478
            // If not, will need to use the other fileExists() code below.
            continue;
          }

          File folder = new File(roots[i], "WINDOWS/Fonts");
          if (folder.exists()) {
            mapper.insertDirectory(folder.getAbsolutePath());
            break;
          }
          folder = new File(roots[i], "WINNT/Fonts");
          if (folder.exists()) {
            mapper.insertDirectory(folder.getAbsolutePath());
            break;
          }
        }
      }
      //      System.out.println("mapping " + (System.currentTimeMillis() - t));
    }
    return mapper;
  }