Ejemplo n.º 1
1
 static void initWords(int size, Object[] key, Object[] abs) {
   String fileName = "testwords.txt";
   int ki = 0;
   int ai = 0;
   try {
     FileInputStream fr = new FileInputStream(fileName);
     BufferedInputStream in = new BufferedInputStream(fr);
     while (ki < size || ai < size) {
       StringBuffer sb = new StringBuffer();
       for (; ; ) {
         int c = in.read();
         if (c < 0) {
           if (ki < size) randomWords(key, ki, size);
           if (ai < size) randomWords(abs, ai, size);
           in.close();
           return;
         }
         if (c == '\n') {
           String s = sb.toString();
           if (ki < size) key[ki++] = s;
           else abs[ai++] = s;
           break;
         }
         sb.append((char) c);
       }
     }
     in.close();
   } catch (IOException ex) {
     System.out.println("Can't read words file:" + ex);
     throw new Error(ex);
   }
 }
Ejemplo n.º 2
0
  /**
   * Takes a packed-stream InputStream, and writes to a JarOutputStream. Internally the entire
   * buffer must be read, it may be more efficient to read the packed-stream to a file and pass the
   * File object, in the alternate method described below.
   *
   * <p>Closes its input but not its output. (The output can accumulate more elements.)
   *
   * @param in an InputStream.
   * @param out a JarOutputStream.
   * @exception IOException if an error is encountered.
   */
  public void unpack(InputStream in0, JarOutputStream out) throws IOException {
    assert (Utils.currentInstance.get() == null);
    TimeZone tz = (_props.getBoolean(Utils.PACK_DEFAULT_TIMEZONE)) ? null : TimeZone.getDefault();

    try {
      Utils.currentInstance.set(this);
      if (tz != null) TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
      final int verbose = _props.getInteger(Utils.DEBUG_VERBOSE);
      BufferedInputStream in = new BufferedInputStream(in0);
      if (Utils.isJarMagic(Utils.readMagic(in))) {
        if (verbose > 0) Utils.log.info("Copying unpacked JAR file...");
        Utils.copyJarFile(new JarInputStream(in), out);
      } else if (_props.getBoolean(Utils.DEBUG_DISABLE_NATIVE)) {
        (new DoUnpack()).run(in, out);
        in.close();
        Utils.markJarFile(out);
      } else {
        (new NativeUnpack(this)).run(in, out);
        in.close();
        Utils.markJarFile(out);
      }
    } finally {
      _nunp = null;
      Utils.currentInstance.set(null);
      if (tz != null) TimeZone.setDefault(tz);
    }
  }
Ejemplo n.º 3
0
  /** Renvoi la chaine correspondant au hash md5 du fichier */
  private String computeHash() {
    try {
      FileInputStream reader_tmp = new FileInputStream(this);
      BufferedInputStream reader = new BufferedInputStream(reader_tmp);

      byte[] buffer = new byte[2048];
      MessageDigest hash = MessageDigest.getInstance("MD5");
      int count;
      do {
        count = reader.read(buffer);
        if (count > 0) {
          hash.update(buffer, 0, count);
        }

      } while (count != -1);
      byte[] b = hash.digest();

      reader.close();

      String result = "";
      for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
      }

      return result;
    } catch (Exception e) {
      System.out.println("Unable to compute key for complete file");
      e.printStackTrace();
    }
    return new String();
  }
Ejemplo n.º 4
0
 public Properties loadUpdateProperties() {
   File propertiesDirectory;
   Properties updateProperties = new Properties();
   // First we look at local configuration directory
   propertiesDirectory = new File(System.getProperty("user.home"), PROPERTIES_DIRECTORY_NAME);
   if (!propertiesDirectory.exists()) {
     // Second we look at tangara binary path
     propertiesDirectory = getTangaraPath().getParentFile();
   }
   BufferedInputStream input = null;
   try {
     input =
         new BufferedInputStream(
             new FileInputStream(
                 new File(propertiesDirectory, getProperty("checkUpdate.fileName"))));
     updateProperties.load(input);
     input.close();
     return updateProperties;
   } catch (IOException e) {
     LOG.warn("Error trying to load update properties");
   } finally {
     IOUtils.closeQuietly(input);
   }
   return null;
 }
Ejemplo n.º 5
0
 /**
  * Load UTF8withBOM or any ansi text file.
  *
  * @param filename
  * @return
  * @throws java.io.IOException
  */
 public static String loadFileAsString(String filename) throws java.io.IOException {
   final int BUFLEN = 1024;
   BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN);
   try {
     ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN);
     byte[] bytes = new byte[BUFLEN];
     boolean isUTF8 = false;
     int read, count = 0;
     while ((read = is.read(bytes)) != -1) {
       if (count == 0
           && bytes[0] == (byte) 0xEF
           && bytes[1] == (byte) 0xBB
           && bytes[2] == (byte) 0xBF) {
         isUTF8 = true;
         baos.write(bytes, 3, read - 3); // drop UTF8 bom marker
       } else {
         baos.write(bytes, 0, read);
       }
       count += read;
     }
     return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
   } finally {
     try {
       is.close();
     } catch (Exception ex) {
     }
   }
 }
Ejemplo n.º 6
0
  private void sendFile(String filePath) {

    try {
      File fileToSend = new File(filePath);
      FileInputStream fileInputStream = new FileInputStream(fileToSend);
      BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
      OutputStream outputStream = clientSocket.getOutputStream();

      // Writer:
      byte[] writerBuffer = new byte[(int) fileToSend.length()];
      bufferedInputStream.read(writerBuffer, 0, writerBuffer.length);

      System.out.println("Sending " + filePath + "(" + writerBuffer.length + " bytes)");
      outputStream.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
      // System.out.println("Writing: "+new String(writerBuffer));
      outputStream.write(writerBuffer, 0, writerBuffer.length);
      outputStream.flush();

      System.out.println("Done.");

      // inputStream.close();
      fileInputStream.close();
      bufferedInputStream.close();
      outputStream.close();
    } catch (IOException e) {
      // report exception somewhere.
      e.printStackTrace();
    }
  }
Ejemplo n.º 7
0
 /**
  * Returns the dev.properties as a property store.
  *
  * @return properties
  */
 protected static Properties getDevProperties() {
   if (fgIsDev) {
     if (fgDevProperties == null) {
       fgDevProperties = new Properties();
       if (fgDevPropertiesURL != null) {
         try {
           URL url = new URL(fgDevPropertiesURL);
           String path = url.getFile();
           if (path != null && path.length() > 0) {
             File file = new File(path);
             if (file.exists()) {
               BufferedInputStream stream = null;
               try {
                 stream = new BufferedInputStream(new FileInputStream(file));
                 fgDevProperties.load(stream);
               } catch (FileNotFoundException e) {
                 PDECore.log(e);
               } catch (IOException e) {
                 PDECore.log(e);
               } finally {
                 if (stream != null) stream.close();
               }
             }
           }
         } catch (MalformedURLException e) {
           PDECore.log(e);
         } catch (IOException e) {
           PDECore.log(e);
         }
       }
     }
     return fgDevProperties;
   }
   return null;
 }
Ejemplo n.º 8
0
 public static TaggedDictionary loadFrom(File f) throws Exception {
   FileInputStream fi = null;
   BufferedInputStream bi = null;
   ObjectInputStream oin = null;
   TaggedDictionary result = null;
   try {
     fi = new FileInputStream(f);
     bi = new BufferedInputStream(fi, 1000000);
     oin = new ObjectInputStream(bi);
     result = new TaggedDictionary();
     result.readFrom(oin);
   } finally {
     try {
       oin.close();
     } catch (Exception exx) {
     }
     try {
       bi.close();
     } catch (Exception exx) {
     }
     try {
       fi.close();
     } catch (Exception exx) {
     }
   }
   return result;
 }
Ejemplo n.º 9
0
 public static WordClass[] loadWordClassesFrom(File f) throws Exception {
   FileInputStream fi = null;
   BufferedInputStream bi = null;
   ObjectInputStream oin = null;
   WordClass result[];
   try {
     fi = new FileInputStream(f);
     bi = new BufferedInputStream(fi, 1000000);
     oin = new ObjectInputStream(bi);
     result = (WordClass[]) oin.readObject();
   } finally {
     try {
       oin.close();
     } catch (Exception exx) {
     }
     try {
       bi.close();
     } catch (Exception exx) {
     }
     try {
       fi.close();
     } catch (Exception exx) {
     }
   }
   return result;
 }
Ejemplo n.º 10
0
  /**
   * each entry represents a bitstream....
   *
   * @param c
   * @param i
   * @param path
   * @param fileName
   * @param bundleName
   * @throws SQLException
   * @throws IOException
   * @throws AuthorizeException
   */
  private void processContentFileEntry(
      Context c, Item i, String path, String fileName, String bundleName, boolean primary)
      throws SQLException, IOException, AuthorizeException {
    String fullpath = path + File.separatorChar + fileName;

    // get an input stream
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fullpath));

    Bitstream bs = null;
    String newBundleName = bundleName;

    if (bundleName == null) {
      // is it license.txt?
      if ("license.txt".equals(fileName)) {
        newBundleName = "LICENSE";
      } else {
        // call it ORIGINAL
        newBundleName = "ORIGINAL";
      }
    }

    if (!isTest) {
      // find the bundle
      Bundle[] bundles = i.getBundles(newBundleName);
      Bundle targetBundle = null;

      if (bundles.length < 1) {
        // not found, create a new one
        targetBundle = i.createBundle(newBundleName);
      } else {
        // put bitstreams into first bundle
        targetBundle = bundles[0];
      }

      // now add the bitstream
      bs = targetBundle.createBitstream(bis);

      bs.setName(fileName);

      // Identify the format
      // FIXME - guessing format guesses license.txt incorrectly as a text
      // file format!
      BitstreamFormat bf = FormatIdentifier.guessFormat(c, bs);
      bs.setFormat(bf);

      // Is this a the primary bitstream?
      if (primary) {
        targetBundle.setPrimaryBitstreamID(bs.getID());
        targetBundle.update();
      }

      bs.update();
    }

    bis.close();
  }
Ejemplo n.º 11
0
  /** Download resource to the given file */
  private boolean download(URL target, File file) {

    _log.addDebug("JarDiffHandler:  Doing download");

    boolean ret = true;
    boolean delete = false;
    // use bufferedstream for better performance
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      in = new BufferedInputStream(target.openStream());
      out = new BufferedOutputStream(new FileOutputStream(file));
      int read = 0;
      int totalRead = 0;
      byte[] buf = new byte[BUF_SIZE];
      while ((read = in.read(buf)) != -1) {
        out.write(buf, 0, read);
        totalRead += read;
      }

      _log.addDebug("total read: " + totalRead);
      _log.addDebug("Wrote URL " + target.toString() + " to file " + file);

    } catch (IOException ioe) {

      _log.addDebug("Got exception while downloading resource: " + ioe);

      ret = false;

      if (file != null) delete = true;

    } finally {

      try {
        in.close();
        in = null;
      } catch (IOException ioe) {
        _log.addDebug("Got exception while downloading resource: " + ioe);
      }

      try {
        out.close();
        out = null;
      } catch (IOException ioe) {
        _log.addDebug("Got exception while downloading resource: " + ioe);
      }

      if (delete) {
        file.delete();
      }
    }
    return ret;
  }
Ejemplo n.º 12
0
  /**
   * Downloads a Bundle file for a given bundle id.
   *
   * @param request HttpRequest
   * @param response HttpResponse
   * @throws IOException If fails sending back to the user response information
   */
  public void downloadBundle(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    try {
      if (!APILocator.getLayoutAPI()
          .doesUserHaveAccessToPortlet("EXT_CONTENT_PUBLISHING_TOOL", getUser())) {
        response.sendError(401);
        return;
      }
    } catch (DotDataException e1) {
      Logger.error(RemotePublishAjaxAction.class, e1.getMessage(), e1);
      response.sendError(401);
      return;
    }
    Map<String, String> map = getURIParams();
    response.setContentType("application/x-tgz");

    String bid = map.get("bid");

    PublisherConfig config = new PublisherConfig();
    config.setId(bid);
    File bundleRoot = BundlerUtil.getBundleRoot(config);

    ArrayList<File> list = new ArrayList<File>(1);
    list.add(bundleRoot);
    File bundle =
        new File(bundleRoot + File.separator + ".." + File.separator + config.getId() + ".tar.gz");
    if (!bundle.exists()) {
      response.sendError(500, "No Bundle Found");
      return;
    }

    response.setHeader("Content-Disposition", "attachment; filename=" + config.getId() + ".tar.gz");
    BufferedInputStream in = null;
    try {
      in = new BufferedInputStream(new FileInputStream(bundle));
      byte[] buf = new byte[4096];
      int len;

      while ((len = in.read(buf, 0, buf.length)) != -1) {
        response.getOutputStream().write(buf, 0, len);
      }
    } catch (Exception e) {
      Logger.warn(this.getClass(), "Error Downloading Bundle.", e);
    } finally {
      try {
        in.close();
      } catch (Exception ex) {
        Logger.warn(this.getClass(), "Error Closing Stream.", ex);
      }
    }
    return;
  }
Ejemplo n.º 13
0
  /**
   * Copies a file or directory
   *
   * @param src the file or directory to copy
   * @param dest where copy
   * @throws IOException
   */
  public static void copyFile(File src, File dest) throws IOException {
    if (!src.exists()) throw new IOException("File not found '" + src.getAbsolutePath() + "'");
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));

    byte[] read = new byte[4096];
    int len;
    while ((len = in.read(read)) > 0) out.write(read, 0, len);

    out.flush();
    out.close();
    in.close();
  }
 /**
  * Given a DICOM object encoded as an XML document in a named file convert it to a list of
  * attributes.
  *
  * @param name the input file containing the XML document
  * @return the list of DICOM attributes
  * @exception IOException
  * @exception SAXException
  * @exception DicomException
  */
 public AttributeList getAttributeList(String name)
     throws IOException, SAXException, DicomException {
   InputStream fi = new FileInputStream(name);
   BufferedInputStream bi = new BufferedInputStream(fi);
   AttributeList list = null;
   try {
     list = getAttributeList(bi);
   } finally {
     bi.close();
     fi.close();
   }
   return list;
 }
Ejemplo n.º 15
0
  private final String getFileAsString(String filename) throws IOException {
    File file = new File(filename);

    if (!file.exists()) {
      logger.log(Level.ERROR, "template file " + filename + " does not exist");
      System.exit(1);
    }
    final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    final byte[] bytes = new byte[(int) file.length()];
    bis.read(bytes);
    bis.close();
    return new String(bytes);
  }
Ejemplo n.º 16
0
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
Ejemplo n.º 17
0
 private String readFileAsString(File file) throws java.io.IOException {
   byte[] buffer = new byte[(int) file.length()];
   BufferedInputStream bis = null;
   try {
     bis = new BufferedInputStream(new FileInputStream(file));
     bis.read(buffer);
   } finally {
     if (bis != null)
       try {
         bis.close();
       } catch (IOException ignored) {
       }
   }
   return new String(buffer);
 }
 /*.................................................................................................................*/
 public void cipresDownload(HttpClient httpclient, String URL, String filePath) {
   HttpGet httpget = new HttpGet(URL);
   httpget.addHeader("cipres-appkey", CIPRESkey);
   try {
     HttpResponse response = httpclient.execute(httpget);
     HttpEntity responseEntity = response.getEntity();
     BufferedInputStream bis = new BufferedInputStream(responseEntity.getContent());
     BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
     int inByte;
     while ((inByte = bis.read()) != -1) bos.write(inByte);
     bis.close();
     bos.close();
     EntityUtils.consume(response.getEntity());
   } catch (IOException e) {
     Debugg.printStackTrace(e);
   }
 }
Ejemplo n.º 19
0
 public BytecodeBuffer(String filename) throws IOException {
   BufferedInputStream in = null;
   try {
     in = new BufferedInputStream(new FileInputStream(filename));
     bytecodes = new byte[in.available()];
     in.read(bytecodes);
     size = bytecodes.length;
     pos = 0;
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ex) {
       }
     }
   }
 }
Ejemplo n.º 20
0
  /**
   * Funcion que transforma el archivo suministrado en un arreglo de bytes para transferir al
   * servidor de archivos
   *
   * @param nombreArchivo el nombre del archivo a comprobar
   * @return True si encuentra el archivo
   * @throws Exception Al ocurrir un error en transformar el archivo a bytes
   */
  public static byte[] formatearArchivo(String nombreArchivo) {

    try {

      // Crear un arreglo de bytes con el tamaño del archivo
      File archivo = new File(nombreArchivo);
      byte buffer[] = new byte[(int) archivo.length()];
      BufferedInputStream input = new BufferedInputStream(new FileInputStream(nombreArchivo));
      input.read(buffer, 0, buffer.length);
      input.close();
      return (buffer);
    } catch (Exception e) {
      String error = "- Error - Problema al transformar el archivo " + "en un arreglo de bytes";
      System.out.print(error);
      return (null);
    }
  }
Ejemplo n.º 21
0
  public void upload() throws Exception {
    boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
    if (!isMultipart) {
      this.state = this.errorInfo.get("NOFILE");
      return;
    }

    if (this.inputStream == null) {
      this.state = this.errorInfo.get("FILE");
      return;
    }

    // 存储title
    this.title = this.getParameter("pictitle");

    try {
      String savePath = this.getFolder(this.savePath);

      if (!this.checkFileType(this.originalName)) {
        this.state = this.errorInfo.get("TYPE");
        return;
      }

      this.fileName = this.getName(this.originalName);
      this.type = this.getFileExt(this.fileName);
      this.url = savePath + "/" + this.fileName;

      FileOutputStream fos = new FileOutputStream(this.getPhysicalPath(this.url));
      BufferedInputStream bis = new BufferedInputStream(this.inputStream);
      byte[] buff = new byte[128];
      int count = -1;

      while ((count = bis.read(buff)) != -1) {

        fos.write(buff, 0, count);
      }

      bis.close();
      fos.close();

      this.state = this.errorInfo.get("SUCCESS");
    } catch (Exception e) {
      e.printStackTrace();
      this.state = this.errorInfo.get("IO");
    }
  }
  private static void addFileToJar(
      @NotNull JarOutputStream jar,
      @NotNull File file,
      @NotNull File rootDirectory,
      boolean packRClasses)
      throws IOException {

    if (file.isDirectory()) {
      for (File child : file.listFiles()) {
        addFileToJar(jar, child, rootDirectory, packRClasses);
      }
    } else if (file.isFile()) {
      if (!FileUtil.getExtension(file.getName()).equals("class")) {
        return;
      }

      if (!packRClasses && R_PATTERN.matcher(file.getName()).matches()) {
        return;
      }

      final String rootPath = rootDirectory.getAbsolutePath();

      String path = file.getAbsolutePath();
      path = FileUtil.toSystemIndependentName(path.substring(rootPath.length()));
      if (path.charAt(0) == '/') {
        path = path.substring(1);
      }

      final JarEntry entry = new JarEntry(path);
      entry.setTime(file.lastModified());
      jar.putNextEntry(entry);

      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
      try {
        final byte[] buffer = new byte[1024];
        int count;
        while ((count = bis.read(buffer)) != -1) {
          jar.write(buffer, 0, count);
        }
        jar.closeEntry();
      } finally {
        bis.close();
      }
    }
  }
Ejemplo n.º 23
0
 private void loadCommentTemplates() {
   IPath pluginStateLocation =
       CVSUIPlugin.getPlugin().getStateLocation().append(COMMENT_TEMPLATES_FILE);
   File file = pluginStateLocation.toFile();
   if (!file.exists()) return;
   try {
     BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
     try {
       readCommentTemplates(is);
     } finally {
       is.close();
     }
   } catch (IOException e) {
     CVSUIPlugin.log(IStatus.ERROR, CVSUIMessages.RepositoryManager_ioException, e);
   } catch (TeamException e) {
     CVSUIPlugin.log(e);
   }
 }
Ejemplo n.º 24
0
  public static void saveUrl(String filename, String urlString)
      throws MalformedURLException, IOException {
    BufferedInputStream in = null;
    FileOutputStream fout = null;
    try {
      in = new BufferedInputStream(new URL(urlString).openStream());
      fout = new FileOutputStream(filename);

      byte data[] = new byte[1024];
      int count;
      while ((count = in.read(data, 0, 1024)) != -1) {
        fout.write(data, 0, count);
      }
    } finally {
      if (in != null) in.close();
      if (fout != null) fout.close();
    }
  }
Ejemplo n.º 25
0
  public static void copy(String srcFileName, String dstFileName) {
    try {
      BufferedInputStream in = new BufferedInputStream(new FileInputStream(srcFileName));
      BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dstFileName));
      byte[] bytes = new byte[1024];

      int nb = in.read(bytes, 0, bytes.length);
      while (nb > 0) {
        out.write(bytes, 0, nb);
        nb = in.read(bytes, 0, bytes.length);
      }
      in.close();
      out.close();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(1);
    }
  }
Ejemplo n.º 26
0
  /**
   * Get binary data of a source file.
   *
   * @param path The canonical path of source file.
   * @return Source file data.
   */
  public byte[] read(String path) {
    if (!binaryCache.containsKey(path)) {
      try {
        BufferedInputStream bf = new BufferedInputStream(new FileInputStream(new File(path)));
        try {
          byte[] data = new byte[bf.available()];
          bf.read(data);
          detectBOM(data, path);
          binaryCache.put(path, data);
        } finally {
          bf.close();
        }
      } catch (IOException e) {
        App.exit(e);
      }
    }

    return binaryCache.get(path);
  }
Ejemplo n.º 27
0
 /**
  * Reads GIF image from stream
  *
  * @param BufferedInputStream containing GIF file.
  * @return read status code (0 = no errors)
  */
 public int read(BufferedInputStream is) {
   init();
   if (is != null) {
     in = is;
     readHeader();
     if (!err()) {
       readContents();
       if (frameCount < 0) {
         status = STATUS_FORMAT_ERROR;
       }
     }
   } else {
     status = STATUS_OPEN_ERROR;
   }
   try {
     is.close();
   } catch (IOException e) {
   }
   return status;
 }
Ejemplo n.º 28
0
 /**
  * Loads from specified file
  *
  * @param file
  * @param mnemo the name for the text file
  */
 private void addToCache(File file, String mnemo) {
   BufferedInputStream fis;
   try {
     fis = new BufferedInputStream(new FileInputStream(file));
   } catch (FileNotFoundException e) {
     System.out.println("Warning! File '" + file + "' not found!");
     return;
   }
   String text = "";
   byte[] buf = new byte[4096];
   int i = 0;
   try {
     while ((i = fis.read(buf)) != -1) {
       text += new String(buf, 0, i);
     }
     fis.close();
   } catch (IOException ignored) {
   }
   helpcache.put(mnemo, text);
 }
Ejemplo n.º 29
0
  public static int copyPlugin(JFrame frame, File source, String destFileName) {
    if (destFileName == null) destFileName = source.getName();
    if (!PluginCore.userPluginDir.exists()) {
      boolean created = PluginCore.userPluginDir.mkdirs();
      if (!created) {
        return UNABLE_TO_CREATE_DIR;
      }
    }
    File destFile = new File(PluginCore.userPluginDir, destFileName);
    BufferedInputStream in = null;
    BufferedOutputStream out = null;
    try {
      in = new BufferedInputStream(new FileInputStream(source));
      out = new BufferedOutputStream(new FileOutputStream(destFile));
      byte[] buf = new byte[1024];
      int count;
      while ((count = in.read(buf, 0, buf.length)) > 0) {
        out.write(buf, 0, count);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      return UNABLE_TO_COPY_FILE;
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }

      if (out != null) {
        try {
          out.close();
        } catch (IOException ignore) {
          // UNABLE_TO_COPY_FILE;
        }
      }
    }
    return SUCCESS;
  }
Ejemplo n.º 30
0
 /**
  * Reads data from a file and writes it to an index.
  *
  * @param indexWriter the index to write to.
  * @param inputFile the input data for the process.
  * @throws IOException
  * @throws InstantiationException
  * @throws IllegalAccessException
  * @throws ClassNotFoundException
  */
 private void readFile(IndexWriter indexWriter, File inputFile)
     throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
   BufferedInputStream in = new BufferedInputStream(new FileInputStream(inputFile));
   byte[] tempInt = new byte[4];
   int tmp, tmpFeature, count = 0;
   byte[] temp = new byte[100 * 1024];
   // read file hashFunctionsFileName length:
   while (in.read(tempInt, 0, 4) > 0) {
     Document d = new Document();
     tmp = SerializationUtils.toInt(tempInt);
     // read file hashFunctionsFileName:
     in.read(temp, 0, tmp);
     String filename = new String(temp, 0, tmp);
     // normalize Filename to full path.
     filename =
         inputFile
                 .getCanonicalPath()
                 .substring(0, inputFile.getCanonicalPath().lastIndexOf(inputFile.getName()))
             + filename;
     d.add(new StringField(DocumentBuilder.FIELD_NAME_IDENTIFIER, filename, Field.Store.YES));
     //            System.out.print(filename);
     while ((tmpFeature = in.read()) < 255) {
       //                System.out.print(", " + tmpFeature);
       LireFeature f = (LireFeature) Class.forName(Extractor.features[tmpFeature]).newInstance();
       // byte[] length ...
       in.read(tempInt, 0, 4);
       tmp = SerializationUtils.toInt(tempInt);
       // read feature byte[]
       in.read(temp, 0, tmp);
       f.setByteArrayRepresentation(temp, 0, tmp);
       addToDocument(f, d, Extractor.featureFieldNames[tmpFeature]);
       //                d.add(new StoredField(Extractor.featureFieldNames[tmpFeature],
       // f.getByteArrayRepresentation()));
     }
     if (run == 2) indexWriter.addDocument(d);
     docCount++;
     //            if (count%1000==0) System.out.print('.');
     //            if (count%10000==0) System.out.println(" " + count);
   }
   in.close();
 }