Beispiel #1
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();
      }
    }
  }
 public static void setReadOnlyAttribute(@NotNull String path, boolean readOnlyFlag) {
   final boolean writableFlag = !readOnlyFlag;
   final File file = new File(path);
   if (!file.setWritable(writableFlag) && file.canWrite() != writableFlag) {
     LOG.warn("Can't set writable attribute of '" + path + "' to " + readOnlyFlag);
   }
 }
Beispiel #3
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;
    }
  }
  public IncrementalJUnit4Runner() {
    File testRunFile = new File("testRun.properties");

    if (testRunFile.exists() && !testRunFile.canWrite()) {
      throw new IllegalStateException();
    }

    coverageMap = new Properties();
    testMethods = new HashMap<Method, Boolean>();
  }
  private void commonInitializer(File file) throws IOException {
    File parent = file.getParentFile();
    if (parent == null) parent = new File(System.getProperty("user.dir"));
    if (!parent.canWrite()) {
      String msg = Logging.getMessage("generic.FolderNoWritePermission", parent.getAbsolutePath());
      Logging.logger().severe(msg);
      throw new IllegalArgumentException(msg);
    }

    this.targetFile = new RandomAccessFile(file, "rw");
    this.theChannel = this.targetFile.getChannel();
  }
  /**
   * GET SMIC WIP FILEs
   *
   * @throws IOException
   */
  public void GetCpYieldFiles() {

    try {
      logger.debug("fileInUrl " + fileInUrl.getPath());
      List fileList = Methods.getFiles(fileInUrl);
      fileList = null != fileList ? fileList : new ArrayList();

      for (int i = 0; i < fileList.size(); i++) {
        File txtFile = (File) fileList.get(i);
        String fileName = txtFile.getName();
        // 1.0 Check File Status can read, write
        if (txtFile.canRead() && txtFile.canWrite()) {}

        // if (file_name.substring(4, 5).equals("B")) {
        // System.out.println(file_name+" is Bump's File");
        if (this.parserCpYieldTxt(txtFile) == false) {
          logger.info(fileName + " is Parser false");
          // alert.setSubject(SystemContext.getConfig("config.himax.mail.subject") + " - " +
          // fileName + " is Parser false");
          // alert.sendNoFile("CP Yield Parser fail:" + txtFile);
          Methods.copyFile(txtFile, new File(fileErrorUrl + "\\" + fileName));
          txtFile.delete();
        } else {

          // logger.info(fileName + " is Parser complete");
          // Methods.copyFile(txtFile, new File(fileOutUrl + "\\" + fileName));
          // txtFile.delete();
        }
        /*} else {
            logger.info(file_name + " is not Bump's File");
            alert.sendNoFile("ECOA This File is not Bump's File:" + excelFile);
            mod.copyFile(excelFile, new File(fileErrorUrl + "\\" + file_name));
            excelFile.delete();

            logger.info(file_name+" is not BUMP's File");
        }*/
      }
    } catch (Exception e) {
      StackTraceElement[] messages = e.getStackTrace();

      int length = messages.length;
      String error = "";
      alert.setSubject(
          SystemContext.getConfig("config.himax.mail.subject") + " - " + e.getMessage());
      for (int i = 0; i < length; i++) {
        error = error + "toString:" + messages[i].toString() + "\r\n";
      }
      alert.sendNoFile(error);
      e.printStackTrace();
      logger.error(error);
    }
  }
Beispiel #7
0
 /**
  * debug
  *
  * @param filename look for this file
  * @throws java.io.IOException if read error
  */
 static void make(String filename) throws IOException {
   File want = DiskCache.getCacheFile(filename);
   System.out.println("make=" + want.getPath() + "; exists = " + want.exists());
   if (!want.exists()) want.createNewFile();
   System.out.println(
       " canRead= "
           + want.canRead()
           + " canWrite = "
           + want.canWrite()
           + " lastMod = "
           + new Date(want.lastModified()));
   System.out.println(" original=" + filename);
 }
  /**
   * Checks whether <tt>path</tt> is a valid directory for recording (creates it if necessary).
   *
   * @param path the path to the directory to check.
   * @return <tt>true</tt> if the directory <tt>path</tt> can be used for media recording,
   *     <tt>false</tt> otherwise.
   */
  private boolean checkRecordingDirectory(String path) {
    if (path == null || "".equals(path)) return false;

    File dir = new File(path);

    if (!dir.exists()) {
      dir.mkdir();
      if (!dir.exists()) return false;
    }
    if (!dir.isDirectory() || !dir.canWrite()) return false;

    return true;
  }
Beispiel #9
0
 private void initOutStreamEtc() throws Exception {
   if (!destDir.exists()) {
     System.err.println("Destination directory " + destDir.getAbsolutePath() + " does not exist!");
     System.exit(1);
   }
   if (!destDir.canWrite()) {
     System.err.println(
         "Destination directory " + destDir.getAbsolutePath() + " cannot be written to!");
     System.exit(1);
   }
   if (verbose) printAST(model, 0);
   outFile = new File(destDir, outFilename);
   // destDir and outFilename are initialized either in the constructor or in parseArgs,
   // which is called from parse
   outStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outFile)));
 }
  private static boolean canWrite(File installDir) {
    if (!installDir.canWrite()) return false;

    if (!installDir.isDirectory()) return false;

    File fileTest = null;
    try {
      fileTest = File.createTempFile("writtableArea", null, installDir); // $NON-NLS-1$
    } catch (IOException e) {
      // If an exception occured while trying to create the file, it means that it is not writtable
      return false;
    } finally {
      if (fileTest != null) fileTest.delete();
    }
    return true;
  }
  /** {@inheritDoc} */
  public void initialize(WikiEngine engine, Properties props)
      throws NoRequiredPropertyException, IOException {
    m_engine = engine;

    m_luceneDirectory = engine.getWorkDir() + File.separator + LUCENE_DIR;

    int initialDelay =
        TextUtil.getIntegerProperty(props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY);
    int indexDelay =
        TextUtil.getIntegerProperty(props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY);

    m_analyzerClass = TextUtil.getStringProperty(props, PROP_LUCENE_ANALYZER, m_analyzerClass);
    // FIXME: Just to be simple for now, we will do full reindex
    // only if no files are in lucene directory.

    File dir = new File(m_luceneDirectory);

    log.info("Lucene enabled, cache will be in: " + dir.getAbsolutePath());

    try {
      if (!dir.exists()) {
        dir.mkdirs();
      }

      if (!dir.exists() || !dir.canWrite() || !dir.canRead()) {
        log.error("Cannot write to Lucene directory, disabling Lucene: " + dir.getAbsolutePath());
        throw new IOException("Invalid Lucene directory.");
      }

      String[] filelist = dir.list();

      if (filelist == null) {
        throw new IOException(
            "Invalid Lucene directory: cannot produce listing: " + dir.getAbsolutePath());
      }
    } catch (IOException e) {
      log.error("Problem while creating Lucene index - not using Lucene.", e);
    }

    // Start the Lucene update thread, which waits first
    // for a little while before starting to go through
    // the Lucene "pages that need updating".
    LuceneUpdater updater = new LuceneUpdater(m_engine, this, initialDelay, indexDelay);
    updater.start();
  }
Beispiel #12
0
  private void execCmdIdentifyDrive() {
    if (this.curDisk != null) {
      Arrays.fill(this.ioBuf, 0, SECTOR_SIZE, (byte) 0);
      setIOBufWord(0, 0x015A);
      setIOBufWord(2, this.curDisk.getCylinders());
      setIOBufWord(6, this.curDisk.getHeads());
      setIOBufWord(8, this.curDisk.getSectorsPerTrack() * SECTOR_SIZE);
      setIOBufWord(10, SECTOR_SIZE);
      setIOBufWord(12, this.curDisk.getSectorsPerTrack());
      setIOBufASCII(20, Main.VERSION, 20);
      setIOBufWord(42, 1); // 1 Sektor Puffer
      setIOBufASCII(46, "JKCEMU", 8);

      String model = this.curDisk.getDiskModel();
      if (model != null) {
        if (model.isEmpty()) {
          model = null;
        }
      }
      if (model == null) {
        model =
            String.format(
                "Sonstige (%dx%dx%d)",
                this.curDisk.getCylinders(),
                this.curDisk.getHeads(),
                this.curDisk.getSectorsPerTrack());
      }
      setIOBufASCII(54, model, 40);
      File file = this.curDisk.getFile();
      if (file != null) {
        if (!file.canWrite()) {
          setIOBufWord(98, 1); // schreibgeschuetzt
        }
      }
      this.ioBufPos = 0;
      this.pendingCmd = Command.IDENTIFY_DISK;
      this.statusReg |= STATUS_DATA_REQUEST;
      fireInterrupt();
    }
  }
Beispiel #13
0
  public void fileUpload() throws IOException {
    Seller seller = (Seller) getRequest().getSession().getAttribute(FrontContainer.SELLER_INFO);
    if (seller == null) {
      return;
    }
    String user_id = seller.getId();
    // 文件保存本地目录路径
    // String savePath = "d:/JJShop/attached/";
    // String savePath =
    // getRequest().getSession().getServletContext().getRealPath("/")+"/attached/";

    // 文件保存目录URL
    // String saveUrl = getRequest().getContextPath() +
    // savePath.substring(2);
    // String saveUrl = getRequest().getContextPath() + "/attached/";
    SystemSetting systemSetting = SystemManager.systemSetting;
    // 根目录路径,可以指定绝对路径,比如 /var/www/attached/
    String savePath = getRequest().getServletContext().getRealPath("/") + "attached/";
    // String rootPath =
    // "D:\\workspace\\myshop\\web\\attached\\";//pageContext.getServletContext().getRealPath("/")
    // + "attached/";
    // 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
    String saveUrl = systemSetting.getImageRootPath() + "/attached/"; // request.getContextPath()
    // +
    // "/attached/";
    // 定义允许上传的文件扩展名
    HashMap<String, String> extMap = new HashMap<String, String>();
    extMap.put("image", "gif,jpg,jpeg,png,bmp");
    extMap.put("flash", "swf,flv");
    extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
    extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

    // 允许最大上传文件大小 struts.xml struts.multipart.maxSize=3G
    long maxSize = 3000000l;

    getResponse().setContentType("text/html; charset=UTF-8");

    if (!ServletFileUpload.isMultipartContent(getRequest())) {
      getResponse().getWriter().write(getError("请选择文件。"));
      return;
    }
    // 检查目录
    File uploadDir = new File(savePath);
    if (!uploadDir.isDirectory()) {
      getResponse().getWriter().write(getError("上传目录不存在。"));
      return;
    }
    // 检查目录写权限
    if (!uploadDir.canWrite()) {
      getResponse().getWriter().write(getError("上传目录没有写权限。"));
      return;
    }

    String dirName = getRequest().getParameter("dir"); // image
    if (dirName == null) {
      dirName = "image";
    }
    if (!extMap.containsKey(dirName)) {
      getResponse().getWriter().write(getError("目录名不正确。"));
      return;
    }
    // 创建文件夹
    savePath += dirName + "/" + user_id + "/";
    saveUrl += dirName + "/" + user_id + "/";
    File saveDirFile = new File(savePath);
    if (!saveDirFile.exists()) {
      saveDirFile.mkdirs();
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String ymd = sdf.format(new Date());
    savePath += ymd + "/";
    saveUrl += ymd + "/";
    File dirFile = new File(savePath);
    if (!dirFile.exists()) {
      dirFile.mkdirs();
    }
    if (!dirFile.isDirectory()) {
      getResponse().getWriter().write(getError("上传目录不存在 。"));
      return;
    }
    // 检查目录写入权限
    if (!dirFile.canWrite()) {
      getResponse().getWriter().write(getError("上传目录没有写入权限。"));
      return;
    }

    // Struts2 请求 包装过滤器
    MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) getRequest();
    // 获得上传的文件名
    String fileName = wrapper.getFileNames("imgFile")[0]; // imgFile,imgFile,imgFile
    // 获得文件过滤器
    File file = wrapper.getFiles("imgFile")[0];

    // 检查扩展名
    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
      getResponse()
          .getWriter()
          .write(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
      return;
    }
    // 检查文件大小
    if (file.length() > maxSize) {
      getResponse().getWriter().write(getError("上传文件大小超过限制。"));
      return;
    }

    // 重构上传图片的名称
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
    String newImgName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
    byte[] buffer = new byte[1024];
    // 获取文件输出流
    FileOutputStream fos = new FileOutputStream(savePath + "/" + newImgName);
    // 获取内存中当前文件输入流
    InputStream in = new FileInputStream(file);
    try {
      int num = 0;
      while ((num = in.read(buffer)) > 0) {
        fos.write(buffer, 0, num);
      }
    } catch (Exception e) {
      e.printStackTrace(System.err);
    } finally {
      in.close();
      fos.close();
    }
    // 发送给 KE
    JSONObject obj = new JSONObject();
    obj.put("error", 0);
    obj.put("url", saveUrl + "/" + newImgName);
    getResponse().getWriter().write(obj.toJSONString());
    return;
  }
  /**
   * Callback method to process modifications in the common ConfigOptions panel. ConfigOptions was
   * developed to be common to many applications (even though we only have three modes), so it does
   * not have any knowledge of how we are using it within this dialog box. So ConfigOptions just
   * sends updates to registered Observers whenever anything changes. We can receive those
   * notifications here, and decide whether we have enough information to enable the "Connect"
   * button of the dialog box.
   */
  public void update(Observable o, Object arg) {
    // we are going to ignore the Observable object, since we are only
    // observing one object. All we are interested in is the argument.

    if (!(arg instanceof OptionUpdate)) {
      log.log(
          Level.WARNING,
          "DatabaseLocationDialog received update type: " + arg,
          new IllegalArgumentException());
      return;
    }

    OptionUpdate optionUpdate = (OptionUpdate) arg;

    // load saved configuration
    SavedConfiguration config = SavedConfiguration.getSavedConfiguration();

    switch (optionUpdate.getUpdateType()) {
      case DB_LOCATION_CHANGED:
        location = (String) optionUpdate.getPayload();
        if (configOptions.getApplicationMode() == ApplicationMode.STANDALONE_CLIENT) {
          File f = new File(location);
          if (f.exists() && f.canRead() && f.canWrite()) {
            validDb = true;
            log.info("File chosen " + location);
            config.setParameter(SavedConfiguration.DATABASE_LOCATION, location);
          } else {
            log.warning("Invalid file " + location);
          }
        } else {
          try {
            if (location.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) {
              // location given matches 4 '.' separated numbers
              // regex could be improved by limiting each quad to
              // no more than 3 digits.
              String[] quads = location.split("\\.");
              byte[] address = new byte[quads.length];
              for (int i = 0; i < quads.length; i++) {
                address[i] = new Integer(quads[i]).byteValue();
              }
              InetAddress.getByAddress(address);
            } else {
              InetAddress.getAllByName(location);
            }
            log.info("Server specified " + location);
            validDb = true;
            config.setParameter(SavedConfiguration.SERVER_ADDRESS, location);
          } catch (UnknownHostException uhe) {
            log.warning("Unknown host: " + location);
            validDb = false;
          }
        }
        break;
      case PORT_CHANGED:
        port = (String) optionUpdate.getPayload();
        int p = Integer.parseInt(port);

        if (p >= LOWEST_PORT && p < HIGHEST_PORT) {
          if (p < SYSTEM_PORT_BOUNDARY) {
            log.info("User chose System port " + port);
          } else if (p < IANA_PORT_BOUNDARY) {
            log.info("User chose IANA port " + port);
          } else {
            log.info("User chose dynamic port " + port);
          }
          validPort = true;
          config.setParameter(SavedConfiguration.SERVER_PORT, port);
        } else {
          validPort = false;
        }
        break;
      case NETWORK_CHOICE_MADE:
        networkType = (ConnectionType) optionUpdate.getPayload();
        switch (networkType) {
          case SOCKET:
            log.info("Server connection via Sockets");
            break;
          case RMI:
            log.info("Server connection via RMI");
            break;
          default:
            log.info("Unknown connection type: " + networkType);
            break;
        }
        config.setParameter(SavedConfiguration.NETWORK_TYPE, "" + networkType);
        validCnx = true;
        break;
      default:
        log.warning("Unknown update: " + optionUpdate);
        break;
    }

    boolean allValid = validDb && validPort && validCnx;
    connectButton.setEnabled(allValid);
  }
Beispiel #15
0
 public void run(String arg) {
   if (arg.equals("menus")) {
     updateMenus();
     return;
   }
   if (IJ.getApplet() != null) return;
   URL url = getClass().getResource("/ij/IJ.class");
   String ij_jar = url == null ? null : url.toString().replaceAll("%20", " ");
   if (ij_jar == null || !ij_jar.startsWith("jar:file:")) {
     error("Could not determine location of ij.jar");
     return;
   }
   int exclamation = ij_jar.indexOf('!');
   ij_jar = ij_jar.substring(9, exclamation);
   if (IJ.debugMode) IJ.log("Updater (jar loc): " + ij_jar);
   File file = new File(ij_jar);
   if (!file.exists()) {
     error("File not found: " + file.getPath());
     return;
   }
   if (!file.canWrite()) {
     String msg = "No write access: " + file.getPath();
     error(msg);
     return;
   }
   String[] list = openUrlAsList(IJ.URL + "/download/jars/list.txt");
   int count = list.length + 3;
   String[] versions = new String[count];
   String[] urls = new String[count];
   String uv = getUpgradeVersion();
   if (uv == null) return;
   versions[0] = "v" + uv;
   urls[0] = IJ.URL + "/upgrade/ij.jar";
   if (versions[0] == null) return;
   for (int i = 1; i < count - 2; i++) {
     String version = list[i - 1];
     versions[i] = version.substring(0, version.length() - 1); // remove letter
     urls[i] =
         IJ.URL + "/download/jars/ij" + version.substring(1, 2) + version.substring(3, 6) + ".jar";
   }
   versions[count - 2] = "daily build";
   urls[count - 2] = IJ.URL + "/ij.jar";
   versions[count - 1] = "previous";
   urls[count - 1] = IJ.URL + "/upgrade/ij2.jar";
   int choice = showDialog(versions);
   if (choice == -1 || !Commands.closeAll()) return;
   // System.out.println("choice: "+choice);
   // for (int i=0; i<urls.length; i++) System.out.println("  "+i+" "+urls[i]);
   byte[] jar = null;
   if ("daily build".equals(versions[choice]) && notes != null && notes.contains(" </title>"))
     jar = getJar("http://wsr.imagej.net/download/daily-build/ij.jar");
   if (jar == null) jar = getJar(urls[choice]);
   if (jar == null) {
     error("Unable to download ij.jar from " + urls[choice]);
     return;
   }
   Prefs.savePreferences();
   // System.out.println("saveJar: "+file);
   saveJar(file, jar);
   if (choice < count - 2) // force macro Function Finder to download fresh list
   new File(IJ.getDirectory("macros") + "functions.html").delete();
   System.exit(0);
 }
Beispiel #16
0
 public void run(String arg) {
   if (arg.equals("menus")) {
     updateMenus();
     return;
   }
   if (IJ.getApplet() != null) return;
   // File file = new File(Prefs.getHomeDir() + File.separator + "ij.jar");
   // if (isMac() && !file.exists())
   //	file = new File(Prefs.getHomeDir() + File.separator +
   // "ImageJ.app/Contents/Resources/Java/ij.jar");
   URL url = getClass().getResource("/ij/IJ.class");
   String ij_jar = url == null ? null : url.toString().replaceAll("%20", " ");
   if (ij_jar == null || !ij_jar.startsWith("jar:file:")) {
     error("Could not determine location of ij.jar");
     return;
   }
   int exclamation = ij_jar.indexOf('!');
   ij_jar = ij_jar.substring(9, exclamation);
   if (IJ.debugMode) IJ.log("Updater: " + ij_jar);
   File file = new File(ij_jar);
   if (!file.exists()) {
     error("File not found: " + file.getPath());
     return;
   }
   if (!file.canWrite()) {
     String msg = "No write access: " + file.getPath();
     if (IJ.isVista()) msg += Prefs.vistaHint;
     error(msg);
     return;
   }
   String[] list = openUrlAsList(IJ.URL + "/download/jars/list.txt");
   int count = list.length + 2;
   String[] versions = new String[count];
   String[] urls = new String[count];
   String uv = getUpgradeVersion();
   if (uv == null) return;
   versions[0] = "v" + uv;
   urls[0] = IJ.URL + "/upgrade/ij.jar";
   if (versions[0] == null) return;
   for (int i = 1; i < count - 1; i++) {
     String version = list[i - 1];
     versions[i] = version.substring(0, version.length() - 1); // remove letter
     urls[i] =
         IJ.URL + "/download/jars/ij" + version.substring(1, 2) + version.substring(3, 6) + ".jar";
   }
   versions[count - 1] = "daily build";
   urls[count - 1] = IJ.URL + "/ij.jar";
   int choice = showDialog(versions);
   if (choice == -1) return;
   if (!versions[choice].startsWith("daily")
       && versions[choice].compareTo("v1.39") < 0
       && Menus.getCommands().get("ImageJ Updater") == null) {
     String msg =
         "This command is not available in versions of ImageJ prior\n"
             + "to 1.39 so you will need to install the plugin version at\n"
             + "<"
             + IJ.URL
             + "/plugins/imagej-updater.html>.";
     if (!IJ.showMessageWithCancel("Update ImageJ", msg)) return;
   }
   byte[] jar = getJar(urls[choice]);
   // file.renameTo(new File(file.getParent()+File.separator+"ij.bak"));
   if (version().compareTo("1.37v") >= 0) Prefs.savePreferences();
   // if (!renameJar(file)) return; // doesn't work on Vista
   saveJar(file, jar);
   if (choice < count - 1) // force macro Function Finder to download fresh list
   new File(IJ.getDirectory("macros") + "functions.html").delete();
   System.exit(0);
 }
Beispiel #17
0
  /**
   * Constructs a new MultipartRequest to handle the specified request, saving any uploaded files to
   * the given directory, and limiting the upload size to the specified length. If the content is
   * too large, an IOException is thrown. This constructor actually parses the
   * <tt>multipart/form-data</tt> and throws an IOException if there's any problem reading or
   * parsing the request.
   *
   * <p>To avoid file collisions, this constructor takes an implementation of the FileRenamePolicy
   * interface to allow a pluggable rename policy.
   *
   * @param request the servlet request.
   * @param saveDirectory the directory in which to save any uploaded files.
   * @param maxPostSize the maximum size of the POST content.
   * @param encoding the encoding of the response, such as ISO-8859-1
   * @param policy a pluggable file rename policy
   * @exception IOException if the uploaded content is larger than <tt>maxPostSize</tt> or there's a
   *     problem reading or parsing the request.
   */
  public MultipartRequest(
      HttpServletRequest request,
      String saveDirectory,
      int maxPostSize,
      String encoding,
      FileRenamePolicy policy)
      throws IOException {
    // Sanity check values
    if (request == null) throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null) throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
      throw new IllegalArgumentException("maxPostSize must be positive");
    }

    // Save the dir
    File dir = new File(saveDirectory);

    // Check saveDirectory is truly a directory
    if (!dir.isDirectory()) throw new IllegalArgumentException("Not a directory: " + saveDirectory);

    // Check saveDirectory is writable
    if (!dir.canWrite()) throw new IllegalArgumentException("Not writable: " + saveDirectory);

    // Parse the incoming multipart, storing files in the dir provided,
    // and populate the meta objects which describe what we found
    MultipartParser parser = new MultipartParser(request, maxPostSize, true, true, encoding);

    // Some people like to fetch query string parameters from
    // MultipartRequest, so here we make that possible.  Thanks to
    // Ben Johnson, [email protected], for the idea.
    if (request.getQueryString() != null) {
      // Let HttpUtils create a name->String[] structure
      Hashtable queryParameters = HttpUtils.parseQueryString(request.getQueryString());
      // For our own use, name it a name->Vector structure
      Enumeration queryParameterNames = queryParameters.keys();
      while (queryParameterNames.hasMoreElements()) {
        Object paramName = queryParameterNames.nextElement();
        String[] values = (String[]) queryParameters.get(paramName);
        Vector newValues = new Vector();
        for (int i = 0; i < values.length; i++) {
          newValues.add(values[i]);
        }
        parameters.put(paramName, newValues);
      }
    }

    Part part;
    while ((part = parser.readNextPart()) != null) {
      String name = part.getName();
      if (name == null) {
        throw new IOException("Malformed input: parameter name missing (known Opera 7 bug)");
      }
      if (part.isParam()) {
        // It's a parameter part, add it to the vector of values
        ParamPart paramPart = (ParamPart) part;
        String value = paramPart.getStringValue();
        Vector existingValues = (Vector) parameters.get(name);
        if (existingValues == null) {
          existingValues = new Vector();
          parameters.put(name, existingValues);
        }
        existingValues.addElement(value);
      } else if (part.isFile()) {
        // It's a file part
        FilePart filePart = (FilePart) part;
        String fileName = filePart.getFileName();
        if (fileName != null) {
          filePart.setRenamePolicy(policy); // null policy is OK
          // The part actually contained a file
          filePart.writeTo(dir);
          files.put(
              name,
              new UploadedFile(
                  dir.toString(), filePart.getFileName(), fileName, filePart.getContentType()));
        } else {
          // The field did not contain a file
          files.put(name, new UploadedFile(null, null, null, null));
        }
      }
    }
  }
Beispiel #18
0
  /** Does install of JRE */
  public static void install() {

    // Hide the JNLP Clients installer window and show own
    Config.getInstallService().hideStatusWindow();
    showInstallerWindow();

    // Make sure the destination exists.
    String path = Config.getInstallService().getInstallPath();
    if (Config.isWindowsInstall()) {
      String defaultLocation = "C:\\Program Files\\Java\\j2re" + Config.getJavaVersion() + "\\";
      File defaultDir = new File(defaultLocation);
      if (!defaultDir.exists()) {
        defaultDir.mkdirs();
      }
      if (defaultDir.exists() && defaultDir.canWrite()) {
        path = defaultLocation; // use default if you can
      }
    }

    File installDir = new File(path);

    if (!installDir.exists()) {
      installDir.mkdirs();
      if (!installDir.exists()) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("couldntCreateDirectory", null);
        return;
      }
    }

    // Show license if neccesary
    enableStep(STEP_LICENSE);
    if (!showLicensing()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Licensing was not accepted", null);
    }
    ;

    // Make sure that the data JAR is downloaded
    enableStep(STEP_DOWNLOAD);
    if (!downloadInstallerComponent()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to download data component", null);
    }

    String nativeLibName = Config.getNativeLibName();
    File installerFile = null;

    try {
      // Load native library into process if found
      if (nativeLibName != null && !Config.isSolarisInstall()) {
        System.loadLibrary(nativeLibName);
      }

      // Unpack installer
      enableStep(STEP_UNPACK);
      String installResource = Config.getInstallerResource();
      Config.trace("Installer resource: " + installResource);
      installerFile = unpackInstaller(installResource);

      // To clean-up downloaded files
      Config.trace("Unpacked installer to: " + installerFile);
      if (installerFile == null) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not unpack installer components", null);
        return;
      }

      enableStep(STEP_INSTALL);
      setStepText(STEP_INSTALL, Config.getWindowStepWait(STEP_INSTALL));

      boolean success = false;
      if (Config.isSolarisInstall()) {
        success = runSolarisInstaller(path, installerFile);
      } else {
        success = runWindowsInstaller(path, installerFile);
      }

      if (!success) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not run installer", null);
        return;
      }
    } catch (UnsatisfiedLinkError ule) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to load library: " + nativeLibName, null);
      return;
    } finally {
      if (installerFile != null) {
        installerFile.delete();
      }
    }

    setStepText(STEP_INSTALL, Config.getWindowStep(STEP_INSTALL));
    enableStep(STEP_DONE);

    String execPath = path + Config.getJavaPath();
    Config.trace(execPath);

    /** Remove installer JAR from cache */
    removeInstallerComponent();

    // If we're running anything after 1.0.1 or not on Windows, just call
    // finishedInstall.  Otherwise, deny ExitVM permission so that we can
    // return here and do a reboot.  We have to do this because we need to
    // call ExtensionInstallerService.finishedInstall(), which registers
    // that our extension (the JRE) is installed.  Unfortunately pre-1.2 it
    // also does not understand that we are requesting a reboot, and calls
    // System.exit().  So for pre 1.2 we want to deny the permission to
    // exit the VM so we can return here and perform a reboot.
    boolean ispre12 = false;
    String version = Config.getJavaWSVersion();
    // get first tuple
    String v = version.substring(version.indexOf('-') + 1);
    int i2 = v.indexOf('.');
    int v1 = Integer.parseInt(v.substring(0, i2));
    // get second tuple
    v = v.substring(i2 + 1);
    i2 = v.indexOf('.');
    if (i2 == -1) i2 = v.indexOf('-');
    if (i2 == -1) i2 = v.indexOf('[');
    if (i2 == -1) i2 = v.length();
    int v2 = Integer.parseInt(v.substring(0, i2));
    // are we pre 1.2?
    if (v1 < 1 || (v1 == 1 && v2 < 2)) ispre12 = true;

    if (Config.isWindowsInstall() && ispre12 && Config.isHopper()) {
      // deny ExitVM permission then call finishedInstall
      ProtectionDomain pd = (new Object()).getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      AllPermissionExceptExitVM perm = new AllPermissionExceptExitVM();
      PermissionCollection newpc = perm.newPermissionCollection();
      newpc.add(perm);

      // run finishedInstall within the new context which excluded
      // just the ExitVM permission
      ProtectionDomain newpd = new ProtectionDomain(cs, newpc);
      AccessControlContext newacc = new AccessControlContext(new ProtectionDomain[] {newpd});
      final String fExecPath = execPath;
      try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction() {
              public Object run() throws SecurityException {
                finishedInstall(fExecPath);
                return null;
              }
            },
            newacc);
      } catch (PrivilegedActionException pae) {
        // swallow the exception because we want ExitVM to fail silent
      } catch (SecurityException se) {
        // swallow the exception because we want ExitVM to fail silent
      }
    } else {
      // just call finished Install
      finishedInstall(execPath);
    }

    if (Config.isWindowsInstall() && WindowsInstaller.IsRebootNecessary()) {
      // reboot
      if (!WindowsInstaller.askUserForReboot()) System.exit(0);
    } else {
      System.exit(0);
    }
  }
  public void deinit(Appendable out, boolean force) throws Exception {
    Settings settings = new Settings(platform.getConfigFile());

    if (!force) {
      Justif justify = new Justif(80, 40);
      StringBuilder sb = new StringBuilder();
      Formatter f = new Formatter(sb);

      try {
        String list = listFiles(platform.getGlobal());
        if (list != null) {
          f.format("In global default environment:%n");
          f.format(list);
        }

        list = listFiles(platform.getLocal());
        if (list != null) {
          f.format("In local default environment:%n");
          f.format(list);
        }

        if (settings.containsKey(JPM_CACHE_GLOBAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_GLOBAL)));
          if (list != null) {
            f.format("In global configured environment:%n");
            f.format(list);
          }
        }

        if (settings.containsKey(JPM_CACHE_LOCAL)) {
          list = listFiles(IO.getFile(settings.get(JPM_CACHE_LOCAL)));
          if (list != null) {
            f.format("In local configured environment:%n");
            f.format(list);
          }
        }

        list = listSupportFiles();
        if (list != null) {
          f.format("jpm support files:%n");
          f.format(list);
        }

        f.format("%n%n");

        f.format(
            "All files listed above will be deleted if deinit is run with the force flag set"
                + " (\"jpm deinit -f\" or \"jpm deinit --force\"%n%n");
        f.flush();

        justify.wrap(sb);
        out.append(sb.toString());
      } finally {
        f.close();
      }
    } else { // i.e. if(force)
      int count = 0;
      File[] caches = {platform.getGlobal(), platform.getLocal(), null, null};
      if (settings.containsKey(JPM_CACHE_LOCAL)) {
        caches[2] = IO.getFile(settings.get(JPM_CACHE_LOCAL));
      }
      if (settings.containsKey(JPM_CACHE_GLOBAL)) {
        caches[3] = IO.getFile(settings.get(JPM_CACHE_GLOBAL));
      }
      ArrayList<File> toDelete = new ArrayList<File>();

      for (File cache : caches) {
        if (cache == null || !cache.exists()) {
          continue;
        }
        listFiles(cache, toDelete);
        if (toDelete.size() > count) {
          count = toDelete.size();
          if (!cache.canWrite()) {
            reporter.error(PERMISSION_ERROR + " (" + cache + ")");
            return;
          }
          toDelete.add(cache);
        }
      }
      listSupportFiles(toDelete);

      for (File f : toDelete) {
        if (f.exists() && !f.canWrite()) {
          reporter.error(PERMISSION_ERROR + " (" + f + ")");
        }
      }
      if (reporter.getErrors().size() > 0) {
        return;
      }

      for (File f : toDelete) {
        if (f.exists()) {
          IO.deleteWithException(f);
        }
      }
    }
  }
  public boolean hasAccess() {
    assert (binDir != null);
    assert (homeDir != null);

    return binDir.canWrite() && homeDir.canWrite();
  }
Beispiel #21
0
  private static String validateLogFile(String logFileName, String scriptName) {
    String strippedDownScriptName = null;

    if (scriptName != null) {
      File scriptFile = new File(scriptName);
      if (!scriptFile.isDirectory()) {
        String scriptFileAbsPath;
        try {
          scriptFileAbsPath = scriptFile.getCanonicalPath();
        } catch (IOException ioe) {
          throw new AssertionError(
              "Could not compute canonical path to the script file " + ioe.getMessage());
        }
        strippedDownScriptName = getFileFromCanonicalPath(scriptFileAbsPath);
      }
    }

    String defaultLogFileName =
        (strippedDownScriptName == null ? "pig_" : strippedDownScriptName)
            + new Date().getTime()
            + ".log";
    File logFile;

    if (logFileName != null) {
      logFile = new File(logFileName);

      // Check if the file name is a directory
      // append the default file name to the file
      if (logFile.isDirectory()) {
        if (logFile.canWrite()) {
          try {
            logFileName = logFile.getCanonicalPath() + File.separator + defaultLogFileName;
          } catch (IOException ioe) {
            throw new AssertionError(
                "Could not compute canonical path to the log file " + ioe.getMessage());
          }
          return logFileName;
        } else {
          throw new AssertionError(
              "Need write permission in the directory: " + logFileName + " to create log file.");
        }
      } else {
        // we have a relative path or an absolute path to the log file
        // check if we can write to the directory where this file is/will be stored

        if (logFile.exists()) {
          if (logFile.canWrite()) {
            try {
              logFileName = new File(logFileName).getCanonicalPath();
            } catch (IOException ioe) {
              throw new AssertionError(
                  "Could not compute canonical path to the log file " + ioe.getMessage());
            }
            return logFileName;
          } else {
            // do not have write permissions for the log file
            // bail out with an error message
            throw new AssertionError(
                "Cannot write to file: " + logFileName + ". Need write permission.");
          }
        } else {
          logFile = logFile.getParentFile();

          if (logFile != null) {
            // if the directory is writable we are good to go
            if (logFile.canWrite()) {
              try {
                logFileName = new File(logFileName).getCanonicalPath();
              } catch (IOException ioe) {
                throw new AssertionError(
                    "Could not compute canonical path to the log file " + ioe.getMessage());
              }
              return logFileName;
            } else {
              throw new AssertionError(
                  "Need write permission in the directory: " + logFile + " to create log file.");
            }
          } // end if logFile != null else is the default in fall through
        } // end else part of logFile.exists()
      } // end else part of logFile.isDirectory()
    } // end if logFileName != null

    // file name is null or its in the current working directory
    // revert to the current working directory
    String currDir = System.getProperty("user.dir");
    logFile = new File(currDir);
    logFileName =
        currDir + File.separator + (logFileName == null ? defaultLogFileName : logFileName);
    if (logFile.canWrite()) {
      return logFileName;
    }
    throw new RuntimeException("Cannot write to log file: " + logFileName);
  }
 private void checkConfigFileWritableIfExists(File configToWrite) throws ConfigManagerException {
   if (configToWrite.exists() && !configToWrite.canWrite()) {
     throw new ConfigManagerException("Cannot write to config file " + configToWrite);
   }
 }