Exemplo n.º 1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
  public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = null;
    is = new FileInputStream(file);
    long length = file.length();

    if (length > Integer.MAX_VALUE) {
      is.close();
      return null; // File is too large
    }

    byte[] bytes = new byte[(int) length];

    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
        && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += numRead;
    }

    if (offset < bytes.length) {
      is.close();
      throw new IOException("Could not completely read file " + file.getName());
    }
    is.close();
    return bytes;
  }
Exemplo n.º 3
1
    /** Returns true if the two InputStreams differ. */
    private static boolean differs(InputStream oldIS, InputStream newIS) throws IOException {
      int newSize = 0;
      int oldSize;
      int total = 0;
      boolean retVal = false;

      try {
        while (newSize != -1) {
          newSize = newIS.read(newBytes);
          oldSize = oldIS.read(oldBytes);

          if (newSize != oldSize) {
            if (_debug) {
              System.out.println(
                  "\tread sizes differ: " + newSize + " " + oldSize + " total " + total);
            }
            retVal = true;
            break;
          }
          if (newSize > 0) {
            while (--newSize >= 0) {
              total++;
              if (newBytes[newSize] != oldBytes[newSize]) {
                if (_debug) {
                  System.out.println("\tbytes differ at " + total);
                }
                retVal = true;
                break;
              }
              if (retVal) {
                // Jump out
                break;
              }
              newSize = 0;
            }
          }
        }
      } catch (IOException ioE) {
        throw ioE;
      } finally {
        try {
          oldIS.close();
        } catch (IOException e) {
          // Ignore
        }
        try {
          newIS.close();
        } catch (IOException e) {
          // Ignore
        }
      }
      return retVal;
    }
Exemplo n.º 4
1
  public void publicizeResources(File arscFile) throws AndrolibException {
    byte[] data = new byte[(int) arscFile.length()];

    InputStream in = null;
    OutputStream out = null;
    try {
      in = new FileInputStream(arscFile);
      in.read(data);

      publicizeResources(data);

      out = new FileOutputStream(arscFile);
      out.write(data);
    } catch (IOException ex) {
      throw new AndrolibException(ex);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException ex) {
        }
      }
      if (out != null) {
        try {
          out.close();
        } catch (IOException ex) {
        }
      }
    }
  }
Exemplo n.º 5
1
 /**
  * Construct a frequency table from an InputStream. This will create a temporary file to copy the
  * InputStream in.
  *
  * @param source the Input Stream
  * @return an InputStream which is a copy of the source Stream, provided to re-Read the same Bytes
  *     for the actual compression process.
  */
 public InputStream constructTable(InputStream source, boolean copy) {
   freq = new int[TABLESIZE];
   try {
     File file = null;
     FileOutputStream fos = null;
     if (copy == true) {
       file = File.createTempFile("huf", "tmp");
       file.deleteOnExit();
       fos = new FileOutputStream(file);
     }
     while (source.available() != 0) {
       int c = source.read();
       freq[c]++;
       if (copy) fos.write(c);
     }
     source.close();
     if (copy) {
       fos.close();
       return new FileInputStream(file);
     }
     return null;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
 public void close() {
   try {
     stream.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 7
0
  /** prepares Lua state and some bookkeeping */
  protected void prepareState() throws IOException {
    ui.debugMsg("Creating state...\n");
    state = new LuaState(System.out);

    /*write("Registering base libs...\n");
    BaseLib.register(state);
    MathLib.register(state);
    StringLib.register(state);
    CoroutineLib.register(state);
    OsLib.register(state);*/

    ui.debugMsg("Building javafunc map...\n");
    savegame.buildJavafuncMap(state.getEnvironment());

    ui.debugMsg("Loading stdlib...");
    InputStream stdlib = getClass().getResourceAsStream("/cz/matejcik/openwig/stdlib.lbc");
    LuaClosure closure = LuaPrototype.loadByteCode(stdlib, state.getEnvironment());
    ui.debugMsg("calling...\n");
    state.call(closure, null, null, null);
    stdlib.close();
    stdlib = null;

    ui.debugMsg("Registering WIG libs...\n");
    WherigoLib.register(state);

    ui.debugMsg("Building event queue...\n");
    eventRunner = new BackgroundRunner(true);
    eventRunner.setQueueListener(
        new Runnable() {
          public void run() {
            ui.refresh();
          }
        });
  }
Exemplo n.º 8
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

    File outFile = new File(sGREDir, name);
    if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize())
      return false;

    File dir = outFile.getParentFile();
    if (!dir.exists()) dir.mkdirs();

    InputStream fileStream;
    fileStream = zip.getInputStream(fileEntry);

    OutputStream outStream = new FileOutputStream(outFile);

    while (fileStream.available() > 0) {
      int read = fileStream.read(buf, 0, buf.length);
      outStream.write(buf, 0, read);
    }

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
Exemplo n.º 9
0
 static KeyStore getKeyStore() throws Exception {
   InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks"));
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, password);
   in.close();
   return ks;
 }
 public static void main(String[] args) {
   Random r = new Random();
   int n;
   if (args.length == 1) {
     n = Integer.parseInt(args[0]);
   } else {
     n = r.nextInt(10000) + 1;
   }
   try {
     OutputStream ofs = new FileOutputStream("scores.txt");
     ObjectOutputStream oos = new ObjectOutputStream(ofs);
     for (int i = 0; i < n; ++i) {
       int testNum = r.nextInt(21);
       String name = randString(r.nextInt(6) + 5);
       while (testNum-- > 0) {
         oos.writeUTF(name);
         oos.writeInt(r.nextInt(101));
       }
     }
     ofs.close();
   } catch (Exception e) {
     System.out.println("Error creating scores.txt: " + e.getMessage());
   }
   try {
     InputStream ifs = new FileInputStream("scores.txt");
     String name = findStudentWithTopThreeAverageScores(ifs);
     System.out.println("top student is " + name);
     ifs.close();
   } catch (Exception e) {
     System.out.println("Error reading scores.txt: " + e.getMessage());
   }
 }
Exemplo n.º 11
0
 byte[] getJar(String address) {
   // System.out.println("getJar: "+address);
   byte[] data;
   try {
     URL url = new URL(address);
     IJ.showStatus("Connecting to " + IJ.URL);
     URLConnection uc = url.openConnection();
     int len = uc.getContentLength();
     if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len);
     if (len <= 0) return null;
     String name = address.contains("wsr") ? "daily build (" : "ij.jar (";
     IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)");
     InputStream in = uc.getInputStream();
     data = new byte[len];
     int n = 0;
     while (n < len) {
       int count = in.read(data, n, len - n);
       if (count < 0) throw new EOFException();
       n += count;
       IJ.showProgress(n, len);
     }
     in.close();
   } catch (IOException e) {
     if (IJ.debugMode) IJ.log("" + e);
     return null;
   }
   if (IJ.debugMode) IJ.wait(6000);
   return data;
 }
  // get drivername, user, pw & server, and return connection id
  public void serve(InputStream i, OutputStream o) throws IOException {
    // TODOServiceList.getSingleInstance();
    initialize();
    NameListMessage nameListMessage = null;

    try {
      // read input to know which target panel is required
      ObjectInputStream input = new ObjectInputStream(i);
      nameListMessage = (NameListMessage) input.readObject();

      // parse the required panel
      parseSqlFile(nameListMessage);

    } catch (ClassNotFoundException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      nameListMessage.errorMessage = ex.toString();
    }

    // send object to the caller
    ObjectOutputStream output = new ObjectOutputStream(o);
    output.writeObject(nameListMessage);

    // end socket connection
    o.close();
    i.close();
  }
  private void loadTerminologyFromXML(String filename) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    InputStream input = this.getClass().getResourceAsStream(filename);
    try {
      Document doc = builder.build(input);
      Element root = doc.getRootElement();
      List codesets = root.getChildren("codeset");
      codeSetList.clear();
      groupList.clear();

      for (Iterator it = codesets.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        codeSetList.add(loadCodeSet(element));
      }

      List groups = root.getChildren("group");
      for (Iterator it = groups.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        groupList.add(loadGroup(element));
      }
    } finally {
      if (input != null) {
        input.close();
      }
    }
  }
  protected void load(ZipFile zipfile) throws IOException {
    Enumeration entries = zipfile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) entries.nextElement();

      fireBeginFile(entry.getName());

      Logger.getLogger(getClass())
          .debug("Starting file " + entry.getName() + " (" + entry.getSize() + " bytes)");

      byte[] bytes = null;
      InputStream in = null;
      try {
        in = zipfile.getInputStream(entry);
        bytes = readBytes(in);
      } finally {
        if (in != null) {
          try {
            in.close();
          } catch (IOException ex) {
            // Ignore
          }
        }
      }

      Logger.getLogger(getClass())
          .debug("Passing up file " + entry.getName() + " (" + bytes.length + " bytes)");
      getLoader().load(entry.getName(), new ByteArrayInputStream(bytes));

      fireEndFile(entry.getName());
    }
  }
Exemplo n.º 15
0
 private void initConfigDecorator() {
   InputStream in =
       Q2.class
           .getClassLoader()
           .getResourceAsStream("META-INF/org/jpos/config/Q2-decorator.properties");
   try {
     if (in != null) {
       PropertyResourceBundle bundle = new PropertyResourceBundle(in);
       String ccdClass = bundle.getString("config-decorator-class");
       if (log != null) log.info("Initializing config decoration provider: " + ccdClass);
       decorator =
           (ConfigDecorationProvider) Q2.class.getClassLoader().loadClass(ccdClass).newInstance();
       decorator.initialize(getDeployDir());
     }
   } catch (IOException e) {
   } catch (Exception e) {
     if (log != null) log.error(e);
     else {
       e.printStackTrace();
     }
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException e) {
       }
     }
   }
 }
Exemplo n.º 16
0
  /* Heck there's no getenv, we have to roll one ourselves! */
  public static Hashtable getenv() throws Throwable {
    Process p;
    if (File.separator.equals("\\")) {
      p = Runtime.getRuntime().exec("cmd /c set");
    } else {
      p = Runtime.getRuntime().exec("printenv");
    }

    InputStream in = p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    Hashtable table = new Hashtable();

    while ((line = reader.readLine()) != null) {
      int i = line.indexOf('=');
      if (i > 0) {
        String name = line.substring(0, i);
        String value = line.substring(i + 1);
        table.put(name, value);
      }
    }

    in.close();
    p.waitFor();
    return table;
  }
Exemplo n.º 17
0
 private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException {
   if (processedLinks.contains(url)) {
     return false;
   } else {
     processedLinks.add(url);
   }
   URLConnection connection = url.openConnection();
   InputStream in = new BufferedInputStream(connection.getInputStream());
   ArrayList list = processPage(in, baseDir, url);
   if ((status != null) && (list.size() > 0)) {
     status.setMaximum(list.size());
   }
   for (int i = 0; i < list.size(); i++) {
     if (status != null) {
       status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i);
     }
     if ((!((String) list.get(i)).startsWith("RUN"))
         && (!((String) list.get(i)).startsWith("SAVE"))
         && (!((String) list.get(i)).startsWith("LOAD"))) {
       processURL(
           new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)),
           baseDir,
           status);
     }
   }
   in.close();
   return true;
 }
Exemplo n.º 18
0
 /** Load from the named resource. */
 private MimeTypeFile loadResource(String name) {
   InputStream clis = null;
   try {
     clis = SecuritySupport.getResourceAsStream(this.getClass(), name);
     if (clis != null) {
       MimeTypeFile mf = new MimeTypeFile(clis);
       if (LogSupport.isLoggable())
         LogSupport.log("MimetypesFileTypeMap: successfully " + "loaded mime types file: " + name);
       return mf;
     } else {
       if (LogSupport.isLoggable())
         LogSupport.log("MimetypesFileTypeMap: not loading " + "mime types file: " + name);
     }
   } catch (IOException e) {
     if (LogSupport.isLoggable()) LogSupport.log("MimetypesFileTypeMap: can't load " + name, e);
   } catch (SecurityException sex) {
     if (LogSupport.isLoggable()) LogSupport.log("MimetypesFileTypeMap: can't load " + name, sex);
   } finally {
     try {
       if (clis != null) clis.close();
     } catch (IOException ex) {
     } // ignore it
   }
   return null;
 }
Exemplo n.º 19
0
  private void uploadFile(String relPath, Path fullPath) throws DropboxException, IOException {
    if (!fullPath.toFile().exists()) return;

    /*if(api.metadata(relPath, 1, null, false, null).rev == MetaHandler.getRev(relPath)){
    	logger.debug("File "+relPath+" not changed");
    	return;
    }*/

    VOSync.debug("Uploading " + relPath);

    String rev = MetaHandler.getRev(relPath);

    InputStream inp = new FileInputStream(fullPath.toFile());
    Entry fileEntry = api.putFile(relPath, inp, fullPath.toFile().length(), rev, null);
    inp.close();

    Path destFilePath =
        FileSystems.getDefault()
            .getPath(fullPath.toFile().getParentFile().getPath(), fileEntry.fileName());

    MetaHandler.setFile(relPath, destFilePath.toFile(), fileEntry.rev);

    logger.debug(relPath + " put to db");

    // if the file was renamed, move the file on disk and download the current from server
    if (!fileEntry.fileName().equals(fullPath.toFile().getName())) {
      logger.error(fileEntry.fileName() + " != " + fullPath.toFile().getName());
      fullPath.toFile().renameTo(destFilePath.toFile());
    }
  }
Exemplo n.º 20
0
    public static void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection) {
        JarFile jarFile;
        try {
            jarFile = jarConnection.getJarFile();
        } catch (Exception e) {
            _.die("Failed to get jar file)");
            return;
        }

        Enumeration<JarEntry> em = jarFile.entries();
        while (em.hasMoreElements()) {
            JarEntry entry = em.nextElement();
            if (entry.getName().startsWith(jarConnection.getEntryName())) {
                String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
                if (!fileName.equals("/")) {  // exclude the directory
                    InputStream entryInputStream = null;
                    try {
                        entryInputStream = jarFile.getInputStream(entry);
                        FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
                    } catch (Exception e) {
                        die("Failed to copy resource: " + fileName);
                    } finally {
                        if (entryInputStream != null) {
                            try {
                                entryInputStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 21
0
  /**
   * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file.
   *
   * @param f The jar file to extract from.
   * @return a temporary file to which the plugin.xml file has been copied.
   */
  public static File unpackPluginXML(File f) {
    InputStream in = null;
    OutputStream out = null;

    try {
      JarFile jar = new JarFile(f);
      ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE);
      if (entry == null) {
        return null;
      }
      File dest = File.createTempFile("jabref_plugin", ".xml");
      dest.deleteOnExit();

      in = new BufferedInputStream(jar.getInputStream(entry));
      out = new BufferedOutputStream(new FileOutputStream(dest));
      byte[] buffer = new byte[2048];
      for (; ; ) {
        int nBytes = in.read(buffer);
        if (nBytes <= 0) break;
        out.write(buffer, 0, nBytes);
      }
      out.flush();
      return dest;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    } finally {
      try {
        if (out != null) out.close();
        if (in != null) in.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
Exemplo n.º 22
0
  /**
   * Callback method from _scanKeychain. If a trusted certificate is found, this method will be
   * called.
   */
  private void createTrustedCertEntry(
      String alias, long keychainItemRef, long creationDate, byte[] derStream) {
    TrustedCertEntry tce = new TrustedCertEntry();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream input = new ByteArrayInputStream(derStream);
      X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
      input.close();
      tce.cert = cert;
      tce.certRef = keychainItemRef;

      // Make a creation date.
      if (creationDate != 0) tce.date = new Date(creationDate);
      else tce.date = new Date();

      int uniqueVal = 1;
      String originalAlias = alias;

      while (entries.containsKey(alias.toLowerCase())) {
        alias = originalAlias + " " + uniqueVal;
        uniqueVal++;
      }

      entries.put(alias.toLowerCase(), tce);
    } catch (Exception e) {
      // The certificate will be skipped.
      System.err.println("KeychainStore Ignored Exception: " + e);
    }
  }
  public static Map<String, String> readProperties(InputStream inputStream) {
    Map<String, String> propertiesMap = null;
    try {
      propertiesMap = new LinkedHashMap<String, String>();

      Properties properties = new Properties();
      properties.load(inputStream);

      Enumeration<?> enumeration = properties.propertyNames();
      while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        String value = (String) properties.get(key);
        propertiesMap.put(key, value);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return propertiesMap;
  }
Exemplo n.º 24
0
  public static String getResTxtContent(ClassLoader cl, String p) throws IOException {
    String s = res2txt_cont.get(p);
    if (s != null) return s;

    InputStream is = null;
    try {
      is = cl.getResourceAsStream(p);
      // is = this.getClass().getResourceAsStream(p);
      if (is == null) return null;

      byte[] buf = new byte[1024];
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int len;
      while ((len = is.read(buf)) >= 0) {
        baos.write(buf, 0, len);
      }

      byte[] cont = baos.toByteArray();
      s = new String(cont, "UTF-8");

      res2txt_cont.put(p, s);
      return s;
    } finally {
      if (is != null) is.close();
    }
  }
Exemplo n.º 25
0
 public static String visitWeb(String urlStr) {
   URL url = null;
   HttpURLConnection httpConn = null;
   InputStream in = null;
   try {
     url = new URL(urlStr);
     httpConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection.setFollowRedirects(true);
     httpConn.setRequestMethod("GET");
     httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)");
     in = httpConn.getInputStream();
     return convertStreamToString(in);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       in.close();
       httpConn.disconnect();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return null;
 }
 private static void loadPlatformZipPropertiesFromFile() {
   File installLocation = getInstallLocation();
   if (installLocation != null) {
     // parent will be "eclipse" and the parent's parent will be "eclipse-testing"
     File parent = installLocation.getParentFile();
     if (parent != null) {
       parent = parent.getParentFile();
       if (parent != null) {
         File propertiesFile = new File(parent, "equinoxp2tests.properties");
         if (!propertiesFile.exists()) return;
         archiveAndRepositoryProperties = new Properties();
         try {
           InputStream is = null;
           try {
             is = new BufferedInputStream(new FileInputStream(propertiesFile));
             archiveAndRepositoryProperties.load(is);
           } finally {
             is.close();
           }
         } catch (IOException e) {
           return;
         }
       }
     }
   }
 }
Exemplo n.º 27
0
 /** svg image on sdcard */
 public static void unpackOnSdCard(AssetManager assetManager) throws IOException {
   if (Environment.getExternalStorageState().compareTo(Environment.MEDIA_MOUNTED) == 0) {
     File sdcard = Environment.getExternalStorageDirectory();
     String irrlichtPath = sdcard.getAbsoluteFile() + "/Irrlicht/";
     File irrlichtDir = new File(irrlichtPath);
     if (irrlichtDir.exists() && !irrlichtDir.isDirectory()) {
       throw new IOException("Irrlicht exists and is not a directory on SD Card");
     } else if (!irrlichtDir.exists()) {
       irrlichtDir.mkdirs();
     }
     // Note: /sdcard/irrlicht dir exists
     String[] filenames = assetManager.list("data");
     for (String filename : filenames) {
       InputStream inputStream = assetManager.open("data/" + filename);
       OutputStream outputStream = new FileOutputStream(irrlichtPath + "/" + filename);
       // copy
       byte[] buffer = new byte[4096];
       int length;
       while ((length = inputStream.read(buffer)) > 0) {
         outputStream.write(buffer, 0, length);
       }
       outputStream.flush();
       outputStream.close();
       inputStream.close();
     }
   } else {
     throw new IOException("SD Card not available");
   }
 }
Exemplo n.º 28
0
  private Image getImage(String str) throws IOException {
    String url = "http://" + controller.selectedCity.URL + "/cameras/images/" + str + ".jpg";
    System.out.println(url);
    InputStream iStrm = (InputStream) Connector.openInputStream(url);
    Image im = null;

    try {
      ByteArrayOutputStream bStrm = new ByteArrayOutputStream();

      int ch;
      while ((ch = iStrm.read()) != -1) bStrm.write(ch);

      // Place into image array
      byte imageData[] = bStrm.toByteArray();

      // Create the image from the byte array
      im = Image.createImage(imageData, 0, imageData.length);

    } finally {
      // Clean up
      if (iStrm != null) iStrm.close();
    }

    return (im == null ? null : im);
  }
 @Nullable
 private DataInputStream createFSDataStream(File dataStorageRoot) {
   if (myInitialFSDelta == null) {
     // this will force FS rescan
     return null;
   }
   try {
     final File file = new File(dataStorageRoot, FS_STATE_FILE);
     final InputStream fs = new FileInputStream(file);
     byte[] bytes;
     try {
       bytes = FileUtil.loadBytes(fs, (int) file.length());
     } finally {
       fs.close();
     }
     final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
     final int version = in.readInt();
     if (version != FSState.VERSION) {
       return null;
     }
     final long savedOrdinal = in.readLong();
     if (savedOrdinal + 1L != myInitialFSDelta.getOrdinal()) {
       return null;
     }
     return in;
   } catch (FileNotFoundException ignored) {
   } catch (Throwable e) {
     LOG.error(e);
   }
   return null;
 }
Exemplo n.º 30
0
 /**
  * A static convience method for decoding an object from a String.
  *
  * <p>All exceptions are logged using LogMgr internally and then rethrown as GlueException with
  * the same message as written to the log.
  *
  * @param title The name to be given to the object when decoded.
  * @param bytes The Glue formated data to be decoded.
  * @throws GlueException If unable to decode the string.
  */
 public static Object decodeBytes(String title, byte bytes[]) throws GlueException {
   try {
     GlueDecoderImpl gd = new GlueDecoderImpl();
     InputStream in = null;
     try {
       in = new ByteArrayInputStream(bytes);
       GlueParser parser = new GlueParser(in);
       return parser.Decode(gd, gd.getState());
     } catch (ParseException ex) {
       throw new GlueException(ex);
     } catch (TokenMgrError ex) {
       throw new GlueException(ex);
     } finally {
       in.close();
     }
   } catch (GlueException ex) {
     String msg = ("Unable to Glue decode: " + title + "\n" + "  " + ex.getMessage());
     LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg);
     throw new GlueException(msg);
   } catch (Exception ex) {
     String msg = Exceptions.getFullMessage("INTERNAL ERROR:", ex, true, true);
     LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg);
     throw new GlueException(msg);
   }
 }