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) {
        }
      }
    }
  }
Example #2
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 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;
  }
Example #4
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;
  }
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
 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;
 }
Example #7
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();
      }
    }
  }
Example #8
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());
    }
  }
Example #9
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
  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());
    }
  }
Example #11
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) {
       }
     }
   }
 }
  public AuthenticatedSocket(InetAddress ia, int port, MessageDigest md, byte[] secret)
      throws IOException, AuthenticationException {
    super(ia, port);

    try {
      OutputStream output = this.getOutputStream();
      InputStream input = this.getInputStream();

      // Get challenge length
      byte[] challengeSize = new byte[4];
      input.read(challengeSize);

      // Receive random challenge string
      byte[] challenge = new byte[Bytes.toInt(challengeSize)];
      input.read(challenge);

      // Generate MD5 hash
      byte[] append = Bytes.append(challenge, secret);
      byte[] hash = md.digest(append);

      // Send time and hash strings
      output.write(hash);
    } catch (Exception e) {
      throw new AuthenticationException("Authentication failed: " + e.getMessage());
    }
  }
Example #13
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();
          }
        });
  }
Example #14
0
  private void getTrafficSpots() {
    controller.showProgressBar();
    String uploadWebsite =
        "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43";
    String[] ArrayOfData = null;
    StreamConnection c = null;
    InputStream s = null;
    StringBuffer b = new StringBuffer();

    String url = uploadWebsite;
    System.out.print(url);
    try {
      c = (StreamConnection) Connector.open(url);
      s = c.openDataInputStream();
      int ch;
      int k = 0;
      while ((ch = s.read()) != -1) {
        System.out.print((char) ch);
        b.append((char) ch);
      }
      // System.out.println("b"+b);
      try {
        JSONObject ff1 = new JSONObject(b.toString());
        String data1 = ff1.getString("locations");
        JSONArray jsonArray1 = new JSONArray(data1);
        Vector TrafficStatus = new Vector();
        for (int i = 0; i < jsonArray1.length(); i++) {

          System.out.println(jsonArray1.getJSONArray(i).getString(3));
          double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1));
          double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2));
          System.out.println(aDoubleLat + " " + aDoubleLon);
          TrafficStatus.addElement(
              new LocationPointer(
                  jsonArray1.getJSONArray(i).getString(3),
                  (float) aDoubleLon,
                  (float) aDoubleLat,
                  1,
                  true));
        }
        controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus));
      } catch (Exception E) {
        controller.setCurrentScreen(traf);
        new Thread() {
          public void run() {
            controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
          }
        }.start();
      }

    } catch (Exception e) {

      controller.setCurrentScreen(traf);
      new Thread() {
        public void run() {
          controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO);
        }
      }.start();
    }
  }
Example #15
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);
  }
Example #16
0
  /**
   * Gives the same basic functionality of File.exists but can be used to look for removable media
   * without showing a system dialog if the media is not present. Workaround pulled from the <A
   * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on
   * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start
   * requiring Java 6.
   */
  protected static boolean fileExists(File file) {
    try {
      Process process =
          Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()});

      // We need to consume all available output or the process will block.
      boolean haveExitCode = false;
      int exitCode = -1;
      InputStream out = process.getInputStream();
      InputStream err = process.getErrorStream();

      while (!haveExitCode) {
        while (out.read() >= 0) {}
        while (err.read() >= 0) {}

        try {
          exitCode = process.exitValue();
          haveExitCode = true;
        } catch (IllegalThreadStateException e) {
          // Not yet complete.
          Thread.sleep(100);
        }
      }
      // int exitCode = process.waitFor();
      return exitCode == 0;

    } catch (IOException e) {
      System.out.println("Unable to check for file: " + file + " : " + e);
      return false;

    } catch (InterruptedException e) {
      System.out.println("Unable to check for file.  Interrupted: " + file + " : " + e);
      return false;
    }
  }
 @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;
 }
  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();
      }
    }
  }
 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());
   }
 }
 /** 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;
 }
 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;
 }
Example #22
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) {
                            }
                        }
                    }
                }
            }
        }
    }
Example #23
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;
 }
Example #24
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);
    }
  }
Example #25
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;
  }
Example #26
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");
   }
 }
Example #27
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;
 }
Example #28
0
  public static void ensureExists(File thing, String resource) {
    System.err.println("configfile = " + thing);
    if (!thing.exists()) {
      try {
        System.err.println("Creating: " + thing + " from " + resource);
        if (resource.indexOf("/") != 0) {
          resource = "/" + resource;
        }

        InputStream is = Config.class.getResourceAsStream(resource);
        if (is == null) {
          throw new NullPointerException("Can't find resource: " + resource);
        }
        getParentFile(thing).mkdirs();
        OutputStream os = new FileOutputStream(thing);

        for (int next = is.read(); next != -1; next = is.read()) {
          os.write(next);
        }

        os.flush();
        os.close();
      } catch (FileNotFoundException fnfe) {
        throw new Error("Can't create resource: " + fnfe.getMessage());
      } catch (IOException ioe) {
        throw new Error("Can't create resource: " + ioe.getMessage());
      }
    }
  }
Example #29
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();
    }
  }
 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;
         }
       }
     }
   }
 }