예제 #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();
      }
    }
  }
예제 #2
0
 /**
  * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_
  * indexed images. Images are cached: loading an image with the same name twice will get the
  * cached image the second time. If you want to remove an image from the cache, use purgeImage.
  * Throws JGError when there was an error.
  */
 @SuppressWarnings({"deprecation", "unchecked"})
 public JGImage loadImage(String imgfile) {
   Image img = (Image) loadedimages.get(imgfile);
   if (img == null) {
     URL imgurl = getClass().getResource(imgfile);
     if (imgurl == null) {
       try {
         File imgf = new File(imgfile);
         if (imgf.canRead()) {
           imgurl = imgf.toURL();
         } else {
           imgurl = new URL(imgfile);
           // throw new JGameError(
           //	"File "+imgfile+" not found.",true);
         }
       } catch (MalformedURLException e) {
         // e.printStackTrace();
         throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true);
       }
     }
     img = output_comp.getToolkit().createImage(imgurl);
     loadedimages.put(imgfile, img);
   }
   try {
     ensureLoaded(img);
   } catch (Exception e) {
     // e.printStackTrace();
     throw new JGameError("Error loading image " + imgfile);
   }
   return new JREImage(img);
 }
예제 #3
0
 /**
  * Get the test suite specifications from the suite file, apply the options to all, and report any
  * messages to the holder.
  *
  * @param suitePath the String path to the harness suite file
  * @param options the String[] options for the tests - may be null
  * @param holder the IMessageHolder for any messages - may be null
  * @return AjcTest.Suite.Spec test descriptions (non-null but empty if some error)
  */
 public static AjcTest.Suite.Spec getSuiteSpec(
     String suitePath, String[] options, IMessageHolder holder) {
   if (null == suitePath) {
     MessageUtil.fail(holder, "null suitePath");
     return EmptySuite.ME;
   }
   File suiteFile = new File(suitePath);
   if (!suiteFile.canRead() || !suiteFile.isFile()) {
     MessageUtil.fail(holder, "unable to read file " + suitePath);
     return EmptySuite.ME;
   }
   try {
     AjcTest.Suite.Spec tempSpec;
     AbstractRunSpec.RT runtime = new AbstractRunSpec.RT();
     tempSpec = AjcSpecXmlReader.getReader().readAjcSuite(suiteFile);
     tempSpec.setSuiteDirFile(suiteFile.getParentFile());
     if (null == options) {
       options = new String[0];
     }
     runtime.setOptions(options);
     boolean skip = !tempSpec.adoptParentValues(runtime, holder);
     if (skip) {
       tempSpec = EmptySuite.ME;
     }
     return tempSpec;
   } catch (IOException e) {
     MessageUtil.abort(holder, "IOException", e);
     return EmptySuite.ME;
   }
 }
예제 #4
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
예제 #5
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.");
  }
예제 #6
0
  /** Retourne le stream associé à une URL, d'abord teste le réseau et sinon le cache */
  public InputStream getWithBackup(String url) throws Exception {
    // Cache non accessible, on retourne directement l'appel distant
    if (!isAvailable()) return Util.openStream(url);

    Exception eBackup = null;
    InputStream is = null;

    // Tentative d'accès direct par le réseau
    try {
      is = Util.openStream(url);
      if (is == null) throw new Exception("cache openStream error");
    } catch (Exception e) {
      is = null;
      eBackup = e;
    }

    String id = codage(url);
    File f = new File(dir + Util.FS + id);

    // Ca a marché en direct !
    if (is != null) {
      // Devrais-je tenter de remettre à jour le cache
      if (!f.isFile() || outOfDate(f)) add(url);
      return is;
    }

    // Ca n'a pas marché en direct, peut être présent dans le cache ?
    if (f.isFile() && f.canRead() && f.length() > 0) {
      aladin.trace(3, "[" + url + "] backup from cache !");
      return new FileInputStream(f);
    }

    // Bon, pas d'autre solution
    throw eBackup;
  }
예제 #7
0
  /**
   * 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++;
    }
  }
 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()));
     }
   }
 }
예제 #9
0
  public Bundle(File dir) throws IOException {
    if (!dir.exists()) {
      throw new IllegalArgumentException(String.format("%s does not exist", dir.getAbsolutePath()));
    }
    if (!dir.canRead()) {
      throw new IllegalArgumentException(String.format("%s cannot be read", dir.getAbsolutePath()));
    }
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(
          String.format("%s is not a directory", dir.getAbsolutePath()));
    }

    this.dir = dir;

    config = new BundleConfig(new File(dir, "Config.pl"));

    dataFiles = new ArrayList<File>();

    dataFiles.addAll(
        Arrays.asList(
            dir.listFiles(
                new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                    String upper = name.toUpperCase();
                    return (upper.endsWith(".rdf")
                            || upper.endsWith(".owl")
                            || upper.endsWith(".n3")
                            || upper.endsWith(".ttl"))
                        && new File(dir, name).canRead();
                  }
                })));
  }
예제 #10
0
  /**
   * Traverses a directory and populates the mappings in memory
   *
   * @param directory the directory to traverse.
   * @param prefix the LFN prefix to be applied
   */
  private void traverse(File directory, String prefix) {
    // sanity check, if we can read it
    if (!directory.canRead()) {
      // warn and return
      System.err.println("Ignoring. Unable to read directory " + directory);
      return;
    }

    for (File f : directory.listFiles()) {
      StringBuffer lfn = new StringBuffer();
      String name = f.getName();
      if (mConstructFlatLFN || prefix == null || prefix.isEmpty()) {
        lfn.append(name);
      } else {
        lfn.append(prefix).append(File.separator).append(name);
      }

      if (f.isDirectory()) {
        // the lfn is the prefix now
        traverse(f, lfn.toString());
      } else {
        // we have a mapping to populate
        String pfn = this.mURLPrefix + f.getAbsolutePath();
        // System.out.println( lfn + " => " + pfn );
        insert(lfn.toString(), new ReplicaCatalogEntry(pfn, mSiteHandle));
      }
    }

    return;
  }
예제 #11
0
 public synchronized boolean reload(boolean force) {
   long now = System.currentTimeMillis();
   if (force == false && now < last_check + 3000) return false;
   last_check = now;
   File file = getPropertyFile();
   if (file.lastModified() == last_load_time) {
     return false;
   }
   last_load_time = file.lastModified();
   Properties temp = new Properties();
   if (file.canRead()) {
     FileInputStream in = null;
     try {
       in = new FileInputStream(file);
       temp.load(in);
     } catch (Exception e) {
       e.printStackTrace();
     } finally {
       FileUtil.close(in);
     }
   }
   property = ConfigValueUtil.replaceSysProp(temp);
   apply();
   ConfObserver.run();
   return true;
 }
예제 #12
0
파일: RunGen.java 프로젝트: ejconlon/jerial
  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;
    }
  }
예제 #13
0
  public void uploadAttachments(JiraTickets tickets)
      throws ExecutionException, InterruptedException, IOException {
    for (JiraTicket t : tickets) {
      Promise<Issue> issuePromise = issueRestClient.getIssue(t.getId());
      Issue i = issuePromise.get();
      File rollback = t.getRollback();
      File hotfix = t.getHotfix();

      if (rollback != null && rollback.canRead()) {
        issueRestClient.addAttachment(
            i.getAttachmentsUri(), FileUtils.openInputStream(rollback), rollback.getName());
      }

      if (hotfix != null && hotfix.canRead()) {
        issueRestClient.addAttachment(
            i.getAttachmentsUri(), FileUtils.openInputStream(hotfix), hotfix.getName());
      }
    }
  }
예제 #14
0
파일: RC.java 프로젝트: qlongyinqw/thredds
  public boolean load(String abspath) {
    abspath = abspath.replace('\\', '/');
    File rcFile = new File(abspath);
    if (!rcFile.exists() || !rcFile.canRead()) {
      return false;
    }
    if (showlog) log.debug("Loading rc file: " + abspath);
    try (BufferedReader rdr =
        new BufferedReader(new InputStreamReader(new FileInputStream(rcFile), CDM.UTF8))) {
      for (int lineno = 1; ; lineno++) {
        URL url = null;
        String line = rdr.readLine();
        if (line == null) break;
        // trim leading blanks
        line = line.trim();
        if (line.length() == 0) continue; // empty line
        if (line.charAt(0) == '#') continue; // check for comment
        // parse the line
        if (line.charAt(0) == LTAG) {
          int rindex = line.indexOf(RTAG);
          if (rindex < 0) return false;
          if (showlog) log.error("Malformed [url] at " + abspath + "." + lineno);
          String surl = line.substring(1, rindex);
          try {
            url = new URL(surl);
          } catch (MalformedURLException mue) {
            if (showlog) log.error("Malformed [url] at " + abspath + "." + lineno);
          }
          line = line.substring(rindex + 1);
          // trim again
          line = line.trim();
        }
        // Get the key,value part
        String[] pieces = line.split("\\s*=\\s*");
        assert (pieces.length == 1 || pieces.length == 2);
        // Create the triple
        String value = "1";
        if (pieces.length == 2) value = pieces[1].trim();
        Triple triple = new Triple(pieces[0].trim(), value, url);
        List<Triple> list = triplestore.get(triple.key);
        if (list == null) list = new ArrayList<Triple>();
        Triple prev = addtriple(list, triple);
        triplestore.put(triple.key, list);
      }

    } catch (FileNotFoundException fe) {
      if (showlog) log.debug("Loading rc file: " + abspath);
      return false;

    } catch (IOException ioe) {
      if (showlog) log.error("File " + abspath + ": IO exception: " + ioe.getMessage());
      return false;
    }
    return true;
  }
예제 #15
0
 // harvest a dir/file
 public void harvest(File f) throws Exception {
   String name = f.getName();
   if (name.startsWith(".")) return;
   if (!f.canRead()) {
     System.out.println("Unreadable: " + f);
     return;
   }
   if (f.isDirectory()) harvestDir(f);
   else if (name.endsWith(".mod")) harvestMod(f);
   else if (name.endsWith(".proj")) harvestProj(f);
 }
 protected InputStream getInputStream(String configFileName) throws FileNotFoundException {
   InputStream configInputStream = null;
   File f = new File(configDirectory, configFileName);
   if (f.canRead()) {
     ConfigLogImplementation.logMethods.info("Found configuration file: " + f);
     configInputStream = new FileInputStream(f);
   } else {
     ConfigLogImplementation.logMethods.info(
         "Could not " + (f.exists() ? "read" : "find") + " configuration file: " + f);
   }
   return configInputStream;
 }
예제 #17
0
  public static boolean isBundle(File dir) {
    if (!dir.exists()) {
      return false;
    }
    if (!dir.canRead()) {
      return false;
    }
    if (!dir.isDirectory()) {
      return false;
    }
    File config = new File(dir, "Config.pl");

    if (!config.exists()) {
      return false;
    }
    if (!config.canRead()) {
      return false;
    }

    return true;
  }
예제 #18
0
  /**
   * 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);
    }
  }
예제 #19
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);
 }
예제 #20
0
파일: Q2.java 프로젝트: rlishtaba/jPOS
 private void initSystemLogger() {
   File loggerConfig = new File(deployDir, LOGGER_CONFIG);
   if (loggerConfig.canRead()) {
     hasSystemLogger = true;
     try {
       register(loggerConfig);
       deploy();
     } catch (Exception e) {
       getLog().warn("init-system-logger", e);
     }
   }
   getLog().info("Q2 started, deployDir=" + deployDir.getAbsolutePath());
 }
예제 #21
0
  /** This method will process each argument and assign new varibles */
  public void processArgs(String[] args) {
    Pattern pat = Pattern.compile("-[a-z]");
    File dir = null;
    for (int i = 0; i < args.length; i++) {
      String lcArg = args[i].toLowerCase();
      Matcher mat = pat.matcher(lcArg);
      if (mat.matches()) {
        char test = args[i].charAt(1);
        try {
          switch (test) {
            case 'f':
              dir = new File(args[i + 1]);
              i++;
              break;
            case 'v':
              genomeVersion = args[i + 1];
              i++;
              break;
            case 's':
              strand = args[++i];
              break;
            case 't':
              stairStep = true;
              break;
            case 'h':
              printDocs();
              System.exit(0);
            default:
              Misc.printExit("\nError: unknown option! " + mat.group());
          }
        } catch (Exception e) {
          Misc.printExit(
              "\nSorry, something doesn't look right with this parameter: -" + test + "\n");
        }
      }
    }
    if (dir == null || dir.canRead() == false)
      Misc.printExit("\nError: cannot find or read your sgr file/ directory.\n");
    File[][] tot = new File[3][];
    tot[0] = IO.extractFiles(dir, ".sgr");
    tot[1] = IO.extractFiles(dir, ".sgr.zip");
    tot[2] = IO.extractFiles(dir, ".sgr.gz");
    sgrFiles = IO.collapseFileArray(tot);

    if (sgrFiles == null || sgrFiles.length == 0)
      Misc.printExit("\nError: cannot find your xxx.sgr.zip file(s)");
    if (genomeVersion == null)
      Misc.printExit(
          "\nError: you must supply a genome version. Goto http://genome.ucsc.edu/cgi-"
              + "bin/hgGateway load your organism to find the associated genome version.\n");
  }
예제 #22
0
 /** Directory is valid if it exists, does not represent a file, and can be read. */
 private static void validateDirectory(File aDirectory) throws FileNotFoundException {
   if (aDirectory == null) {
     throw new IllegalArgumentException("Directory should not be null.");
   }
   if (!aDirectory.exists()) {
     throw new FileNotFoundException("Directory does not exist: " + aDirectory);
   }
   if (!aDirectory.isDirectory()) {
     throw new IllegalArgumentException("Is not a directory: " + aDirectory);
   }
   if (!aDirectory.canRead()) {
     throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
   }
 }
예제 #23
0
파일: C.java 프로젝트: Mityai/nncworkspaces
 public static void main(String[] args) throws IOException {
   InputStream input = System.in;
   PrintStream output = System.out;
   File file = new File("c.in");
   if (file.exists() && file.canRead()) {
     input = new FileInputStream(file);
     output = new PrintStream("c.out");
   }
   br = new BufferedReader(new InputStreamReader(input));
   out = new PrintWriter(output);
   solve();
   out.close();
   br.close();
 }
예제 #24
0
 /** Play a sound file (in .wav or .au format) in a background thread. */
 public static void play(String filename) {
   prePlay();
   URL url = null;
   try {
     File file = new File(filename);
     if (file.canRead()) url = file.toURI().toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   // URL url = StdAudio.class.getResource(filename);
   if (url == null) throw new RuntimeException("audio " + filename + " not found");
   AudioClip clip = Applet.newAudioClip(url);
   clip.play();
 }
  private boolean loadFileProps(File f) {
    if (!f.exists() || !f.canRead()) return false;

    try {
      FileInputStream ins = new FileInputStream(f);
      loadFromXML(ins);
      prop_file = f;
      return true;
    } catch (IOException e) {
      BoardLog.logE("BOARD", "Problem reading property file: " + e);
    }

    return false;
  }
예제 #26
0
 /**
  * Converts a dir string to a linked dir string
  *
  * @param dir the directory string (e.g. /usr/local/httpd)
  * @param browserLink web-path to Browser.jsp
  */
 public static String dir2linkdir(String dir, String browserLink, int sortMode) {
   File f = new File(dir);
   StringBuffer buf = new StringBuffer();
   while (f.getParentFile() != null) {
     if (f.canRead()) {
       String encPath = URLEncoder.encode(f.getAbsolutePath());
       buf.insert(
           0,
           "<a href=\""
               + browserLink
               + "?sort="
               + sortMode
               + "&amp;dir="
               + encPath
               + "\">"
               + conv2Html(f.getName())
               + File.separator
               + "</a>");
     } else buf.insert(0, conv2Html(f.getName()) + File.separator);
     f = f.getParentFile();
   }
   if (f.canRead()) {
     String encPath = URLEncoder.encode(f.getAbsolutePath());
     buf.insert(
         0,
         "<a href=\""
             + browserLink
             + "?sort="
             + sortMode
             + "&amp;dir="
             + encPath
             + "\">"
             + conv2Html(f.getAbsolutePath())
             + "</a>");
   } else buf.insert(0, f.getAbsolutePath());
   return buf.toString();
 }
예제 #27
0
 /**
  * Add to the class-search path.
  *
  * @param file is the jar or class root.
  */
 public synchronized void addToClassPath(final File file) throws ManifoldCFException {
   if (file.canRead()) {
     addDirsToClassPath(
         new File[] {file.getParentFile()},
         new FileFilter[] {
           new FileFilter() {
             public boolean accept(final File pathname) {
               return pathname.equals(file);
             }
           }
         });
   } else
     throw new ManifoldCFException(
         "Path '" + file.toString() + "' does not exist or is not readable");
 }
예제 #28
0
 /**
  * Constructs an instance.
  *
  * @param pathname the name of a file
  */
 FileInfo(String pathname) {
   mPathname = pathname;
   File file = new File(pathname);
   // Cope with directory indexes for now
   // FIXME: [2003-05-09 bloch] is this the right place
   // for this?
   if (file.isDirectory()) {
     file = new File(pathname + File.separator + "library.lzx");
   }
   // Truncate to an seconds
   mLastMod = ((long) (file.lastModified() / 1000L)) * 1000L;
   mCanRead = file.canRead();
   // mLogger.debug("lm: " + mLastMod);
   mLength = file.length();
 }
예제 #29
0
  public static int checkFiles(String[] filenames) {
    int errors = 0;

    for (String filename : filenames) {
      File file = new File(filename);
      if (!file.exists()) {
        System.err.println("error: file not found: " + file);
        ++errors;
      } else if (!file.canRead()) {
        System.err.println("error: file not readable: " + file);
        ++errors;
      }
    }

    return errors;
  }
예제 #30
0
 /** Loop a sound file (in .wav or .au format) in a background thread. */
 public static void loop(String filename) {
   if (muted) {
     return;
   }
   URL url = null;
   try {
     File file = new File(filename);
     if (file.canRead()) url = file.toURI().toURL();
   } catch (MalformedURLException e) {
     e.printStackTrace();
   }
   // URL url = StdAudio.class.getResource(filename);
   if (url == null) throw new RuntimeException("audio " + filename + " not found");
   AudioClip clip = Applet.newAudioClip(url);
   clip.loop();
   notifyListeners(new AudioEvent(AudioEvent.Type.LOOP));
 }