Пример #1
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
Пример #2
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);
   }
 }
Пример #3
1
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
Пример #4
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;
 }
Пример #5
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);
    }
  }
Пример #6
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;
 }
Пример #7
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();
  }
 public TestType1CFont(InputStream is) throws IOException {
   super();
   setPreferredSize(new Dimension(800, 800));
   addKeyListener(this);
   BufferedInputStream bis = new BufferedInputStream(is);
   int count = 0;
   ArrayList<byte[]> al = new ArrayList<byte[]>();
   byte b[] = new byte[32000];
   int len;
   while ((len = bis.read(b, 0, b.length)) >= 0) {
     byte[] c = new byte[len];
     System.arraycopy(b, 0, c, 0, len);
     al.add(c);
     count += len;
     b = new byte[32000];
   }
   data = new byte[count];
   len = 0;
   for (int i = 0; i < al.size(); i++) {
     byte from[] = al.get(i);
     System.arraycopy(from, 0, data, len, from.length);
     len += from.length;
   }
   pos = 0;
   //	printData();
   parse();
   // TODO: free up (set to null) unused structures (data, subrs, stack)
 }
Пример #9
0
 public static boolean download(
     URL url, String file, int prefix, int totalFilesize, IProgressUpdater updater) {
   File fFile = new File(new File(file).getParentFile().getPath());
   if (!fFile.exists()) fFile.mkdirs();
   boolean downloaded = true;
   BufferedInputStream in = null;
   FileOutputStream out = null;
   BufferedOutputStream bout = null;
   try {
     int count;
     int totalCount = 0;
     byte data[] = new byte[BUFFER];
     in = new BufferedInputStream(url.openStream());
     out = new FileOutputStream(file);
     bout = new BufferedOutputStream(out);
     while ((count = in.read(data, 0, BUFFER)) != -1) {
       bout.write(data, 0, count);
       totalCount += count;
       if (updater != null) updater.update(prefix + totalCount, totalFilesize);
     }
   } catch (Exception e) {
     e.printStackTrace();
     Utils.logger.log(Level.SEVERE, "Download error!");
     downloaded = false;
   } finally {
     try {
       close(in);
       close(bout);
       close(out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return downloaded;
 }
Пример #10
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;
 }
Пример #11
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) {
     }
   }
 }
Пример #12
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;
 }
Пример #13
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();
    }
  }
Пример #14
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
Пример #15
0
  /** @throws IOException If failed. */
  private void initFavicon() throws IOException {
    assert favicon == null;

    InputStream in = getClass().getResourceAsStream("favicon.ico");

    if (in != null) {
      BufferedInputStream bis = new BufferedInputStream(in);

      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      try {
        byte[] buf = new byte[2048];

        while (true) {
          int n = bis.read(buf);

          if (n == -1) break;

          bos.write(buf, 0, n);
        }

        favicon = bos.toByteArray();
      } finally {
        U.closeQuiet(bis);
      }
    }
  }
Пример #16
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();
  }
Пример #17
0
 private static InputStream detect(InputStream input) throws IOException {
   BufferedInputStream reader = new BufferedInputStream(input, 1024 * 1024);
   reader.mark(1000);
   try {
     return new GZIPInputStream(reader);
   } catch (Exception e) {;
   }
   reader.reset();
   return reader;
 }
Пример #18
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
 @Transactional
 public DeviceTestData parseAndSaveBBIFile(
     InputStream inputStream, String verificationID, String originalFileName)
     throws IOException, DecoderException {
   BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
   bufferedInputStream.mark(inputStream.available());
   DeviceTestData deviceTestData =
       bbiFileService.parseBbiFile(bufferedInputStream, originalFileName);
   bufferedInputStream.reset();
   calibratorService.uploadBbi(bufferedInputStream, verificationID, originalFileName);
   return deviceTestData;
 }
Пример #20
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;
  }
Пример #21
0
  /**
   * Read file input stream to string value.
   *
   * @param inputStream
   * @return
   * @throws IOException
   */
  public static String readToString(InputStream inputStream) throws IOException {
    BufferedInputStream reader = new BufferedInputStream(inputStream);
    StringBuilder builder = new StringBuilder();

    byte[] contents = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = reader.read(contents)) != -1) {
      builder.append(new String(contents, 0, bytesRead));
    }

    return builder.toString();
  }
Пример #22
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;
  }
Пример #23
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;
 }
  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);
  }
Пример #26
0
 /**
  * Sends an input stream to the server.
  *
  * @param input xml input
  * @throws IOException I/O exception
  */
 private void send(final InputStream input) throws IOException {
   final BufferedInputStream bis = new BufferedInputStream(input);
   final BufferedOutputStream bos = new BufferedOutputStream(out);
   for (int b; (b = bis.read()) != -1; ) {
     // 0x00 and 0xFF will be prefixed by 0xFF
     if (b == 0x00 || b == 0xFF) bos.write(0xFF);
     bos.write(b);
   }
   bos.write(0);
   bos.flush();
   info = receive();
   if (!ok()) throw new IOException(info);
 }
Пример #27
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;
 }
 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);
 }
Пример #29
0
  private String readLine4Big() throws Exception {
    byte[] b = new byte[1024 * 256];

    int i = 0;
    int readLen = 0;
    while ((readLen = bis.read(b, 0, 1024 * 256)) != -1) {

      if (readLen == 1) {
        if (b[0] == 10) {
          break;
        } else if (b[0] != 13) {
          this.bos.write(b, 0, readLen);
        }
      } else if (b[readLen - 2] != 13 && b[readLen - 1] != 10) {
        this.bos.write(b, 0, readLen);
      } else if (b[readLen - 1] == 10) {
        if (b[readLen - 2] == 13) {
          this.bos.write(b, 0, (readLen - 2));
        } else {
          this.bos.write(b, 0, (readLen - 1));
        }
        break;
      }
    }

    String ret = this.bos.toString();
    this.bos.reset();
    return ret;
  }
Пример #30
0
  /**
   * Reads color table as 256 RGB integer values
   *
   * @param ncolors int number of colors to read
   * @return int array containing 256 colors (packed ARGB with full alpha)
   */
  protected int[] readColorTable(int ncolors) {
    int nbytes = 3 * ncolors;
    int[] tab = null;
    byte[] c = new byte[nbytes];
    int n = 0;
    try {
      n = in.read(c);
    } catch (IOException e) {
    }
    if (n < nbytes) {
      status = STATUS_FORMAT_ERROR;
    } else {
      tab = new int[256]; // max size to avoid bounds checks

      int i = 0;
      int j = 0;
      while (i < ncolors) {
        int r = ((int) c[j++]) & 0xff;
        int g = ((int) c[j++]) & 0xff;
        int b = ((int) c[j++]) & 0xff;
        tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
      }
    }
    return tab;
  }