Пример #1
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) {
        }
      }
    }
  }
Пример #2
1
  /**
   * Load a system library from a stream. Copies the library to a temp file and loads from there.
   *
   * @param libname name of the library (just used in constructing the library name)
   * @param is InputStream pointing to the library
   */
  private void loadLibraryFromStream(String libname, InputStream is) {
    try {
      File tempfile = createTempFile(libname);
      OutputStream os = new FileOutputStream(tempfile);

      logger.debug("tempfile.getPath() = " + tempfile.getPath());

      long savedTime = System.currentTimeMillis();

      // Leo says 8k block size is STANDARD ;)
      byte buf[] = new byte[8192];
      int len;
      while ((len = is.read(buf)) > 0) {
        os.write(buf, 0, len);
      }

      os.flush();
      InputStream lock = new FileInputStream(tempfile);
      os.close();

      double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;
      logger.debug("Copying took " + seconds + " seconds.");

      logger.debug("Loading library from " + tempfile.getPath() + ".");
      System.load(tempfile.getPath());

      lock.close();
    } catch (IOException io) {
      logger.error("Could not create the temp file: " + io.toString() + ".\n");
    } catch (UnsatisfiedLinkError ule) {
      logger.error("Couldn't load copied link file: " + ule.toString() + ".\n");
      throw ule;
    }
  }
Пример #3
0
    /**
     * Do a http operation
     *
     * @param urlConnection the HttpURLConnection to be used
     * @param inputData if not null,will be written to the urlconnection.
     * @param hasOutput if true, read content back from the urlconnection
     * @return Response
     */
    private Response doOperation(
        HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) {
      Response response = null;
      InputStream inputStream = null;
      OutputStream outputStream = null;
      byte[] payload = null;
      try {
        if (inputData != null) {
          urlConnection.setDoOutput(true);
          outputStream = urlConnection.getOutputStream();
          outputStream.write(inputData);
        }
        if (hasOutput) {
          inputStream = urlConnection.getInputStream();
          payload = Util.readFileContents(urlConnection.getInputStream());
        }
        response =
            new Response(urlConnection.getHeaderFields(), urlConnection.getResponseCode(), payload);

      } catch (IOException e) {
        log.error("Error calling service", e);
      } finally {
        Util.close(inputStream);
        Util.close(outputStream);
      }
      return response;
    }
Пример #4
0
  public void secondRun() throws Exception {
    // Read the JSESSIONID from the previous run
    FileInputStream fis = new FileInputStream(JSESSIONID);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String jsessionId = br.readLine();
    new File(JSESSIONID).delete();

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    String cookie = "Cookie: " + jsessionId + "\n";
    os.write(cookie.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    boolean found = false;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      if (line.contains(EXPECTED_RESPONSE)) {
        found = true;
        break;
      }
    }

    if (found) {
      stat.addStatus(TEST_NAME, stat.PASS);
    } else {
      throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found");
    }
  }
Пример #5
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
Пример #6
0
 /**
  * ** Writes the specified byte array to the specified socket's output stream ** @param socket The
  * socket which's output stream to write to ** @param b The byte array to write to the socket
  * output stream ** @throws IOException if an error occurs
  */
 protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException {
   if ((socket != null) && (b != null)) {
     OutputStream output = socket.getOutputStream();
     output.write(b);
     output.flush();
   }
 }
Пример #7
0
 public static TByteArrayList transformByExternalCommand(
     final String command, final InputStream input) throws IOException {
   final Process process = Runtime.getRuntime().exec(command);
   final InputStream in = process.getInputStream();
   final OutputStream out = process.getOutputStream();
   final TByteArrayList bytes = new TByteArrayList(100500);
   final byte[] buffer = new byte[1024 * 1024];
   try {
     int read;
     while ((read = input.read(buffer)) > 0) {
       out.write(buffer, 0, read);
       if (in.available() > 0) {
         read = in.read(buffer);
         bytes.add(buffer, 0, read);
       }
     }
     out.close();
     while ((read = in.read(buffer)) > 0) {
       bytes.add(buffer, 0, read);
     }
     in.close();
   } catch (IOException ioe) {
     System.err.println(readByteStream(process.getErrorStream()));
     LOG.error(ioe);
     throw ioe;
   }
   return bytes;
 }
Пример #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;
  }
Пример #9
0
 /**
  * @param src 源文件
  * @param dst 目标位置
  */
 private static void copy(File src, File dst) {
   InputStream in = null;
   OutputStream out = null;
   try {
     in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
     out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
     byte[] buffer = new byte[BUFFER_SIZE];
     int len = 0;
     while ((len = in.read(buffer)) > 0) {
       out.write(buffer, 0, len);
     }
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     if (null != in) {
       try {
         in.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     if (null != out) {
       try {
         out.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
Пример #10
0
  private void generateValuesFile(ResValuesFile valuesFile, Directory out, ExtXmlSerializer serial)
      throws AndrolibException {
    try {
      OutputStream outStream = out.getFileOutput(valuesFile.getPath());
      serial.setOutput((outStream), null);
      serial.startDocument(null, null);
      serial.startTag(null, "resources");

      for (ResResource res : valuesFile.listResources()) {
        if (valuesFile.isSynthesized(res)) {
          continue;
        }
        ((ResValuesXmlSerializable) res.getValue()).serializeToResValuesXml(serial, res);
      }

      serial.endTag(null, "resources");
      serial.newLine();
      serial.endDocument();
      serial.flush();
      outStream.close();
    } catch (IOException ex) {
      throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex);
    } catch (DirectoryException ex) {
      throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex);
    }
  }
Пример #11
0
  private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial)
      throws AndrolibException {
    try {
      OutputStream outStream = out.getFileOutput("values/public.xml");
      serial.setOutput(outStream, null);
      serial.startDocument(null, null);
      serial.startTag(null, "resources");

      for (ResResSpec spec : pkg.listResSpecs()) {
        serial.startTag(null, "public");
        serial.attribute(null, "type", spec.getType().getName());
        serial.attribute(null, "name", spec.getName());
        serial.attribute(null, "id", String.format("0x%08x", spec.getId().id));
        serial.endTag(null, "public");
      }

      serial.endTag(null, "resources");
      serial.endDocument();
      serial.flush();
      outStream.close();
    } catch (IOException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    } catch (DirectoryException ex) {
      throw new AndrolibException("Could not generate public.xml file", ex);
    }
  }
Пример #12
0
  public static void main(String[] args) {
    try {

      File fileName = File.createTempFile("d:/1.txt", null);
      OutputStream outputStream = new FileOutputStream(fileName);
      InputStream inputStream = new FileInputStream(fileName);

      ClassWithStatic classWithStatic = new ClassWithStatic();
      classWithStatic.i = 3;
      classWithStatic.j = 4;
      classWithStatic.save(outputStream);
      outputStream.flush();

      ClassWithStatic loadedObject = new ClassWithStatic();
      ClassWithStatic.staticString = "something";
      loadedObject.i = 6;
      loadedObject.j = 7;

      loadedObject.load(inputStream);
      System.out.println(ClassWithStatic.staticString);

      outputStream.close();
      inputStream.close();

    } catch (IOException e) {
      e.printStackTrace();
      System.out.println("Oops, something wrong with my file");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Oops, something wrong with save/load method");
    }
  }
Пример #13
0
  private static void moveVoicemail(String strContact, String strID, String strTempVMTS) {
    System.out.println(strContact + " " + strID + " " + strTempVMTS);

    try {
      File fSrc = new File(strSrcVMDir + "/" + strID + ".amr");
      File fDest = new File(strDestVMDir + strContact + "/" + strTempVMTS + ".amr");
      InputStream isSrc = new FileInputStream(fSrc);

      OutputStream osDest = new FileOutputStream(fDest);

      byte[] buf = new byte[1024];
      int len;
      while ((len = isSrc.read(buf)) > 0) {
        osDest.write(buf, 0, len);
      }
      isSrc.close();
      osDest.close();
      System.out.println("File copied.");
    } catch (Exception e) {
      System.err.println(e.getLocalizedMessage());
      System.err.println();
      System.err.println(e.getStackTrace());
      System.exit(0);
    }
  }
Пример #14
0
 private void downloadInternal(URI address, File destination) throws Exception {
   OutputStream out = null;
   URLConnection conn;
   InputStream in = null;
   try {
     URL url = address.toURL();
     out = new BufferedOutputStream(new FileOutputStream(destination));
     conn = url.openConnection();
     final String userAgentValue = calculateUserAgent();
     conn.setRequestProperty("User-Agent", userAgentValue);
     in = conn.getInputStream();
     byte[] buffer = new byte[BUFFER_SIZE];
     int numRead;
     long progressCounter = 0;
     while ((numRead = in.read(buffer)) != -1) {
       progressCounter += numRead;
       if (progressCounter / PROGRESS_CHUNK > 0) {
         System.out.print(".");
         progressCounter = progressCounter - PROGRESS_CHUNK;
       }
       out.write(buffer, 0, numRead);
     }
   } finally {
     System.out.println("");
     if (in != null) {
       in.close();
     }
     if (out != null) {
       out.close();
     }
   }
 }
 private static void writeTokenToFile(String file, TBase token) {
   if (file != null && file.equals("stdout")) {
     System.out.println(token);
   } else {
     OutputStream os = null;
     try {
       os = new FileOutputStream(new File(file));
       os.write(new TSerializer().serialize(token));
     } catch (FileNotFoundException e) {
       System.err.println("Output file not found: " + file + " error: " + e.getMessage());
     } catch (IOException e) {
       System.err.println("Error writing to output file: " + file + " error: " + e.getMessage());
     } catch (TException e) {
       System.err.println("Unable to serialize token to file: " + e.getMessage());
     } finally {
       if (os != null) {
         try {
           os.close();
         } catch (IOException e) {
           // ignore
         }
       }
     }
   }
 }
Пример #16
0
  public static void main(String[] args) {
    // you can find your_file_name.tmp in your TMP directory or fix outputStream/inputStream
    // according to your real file location
    // вы можете найти your_file_name.tmp в папке TMP или исправьте outputStream/inputStream в
    // соответствии с путем к вашему реальному файлу
    try {
      File your_file_name = File.createTempFile("your_file_name", null);
      OutputStream outputStream = new FileOutputStream(your_file_name);
      InputStream inputStream = new FileInputStream(your_file_name);

      JavaRush javaRush = new JavaRush();
      // initialize users field for the javaRush object here - инициализируйте поле users для
      // объекта javaRush тут
      javaRush.save(outputStream);
      outputStream.flush();

      JavaRush loadedObject = new JavaRush();
      loadedObject.load(inputStream);
      // check here that javaRush object equals to loadedObject object - проверьте тут, что javaRush
      // и loadedObject равны

      outputStream.close();
      inputStream.close();

    } catch (IOException e) {
      // e.printStackTrace();
      System.out.println("Oops, something wrong with my file");
    } catch (Exception e) {
      // e.printStackTrace();
      System.out.println("Oops, something wrong with save/load method");
    }
  }
Пример #17
0
  public static void copyFile(String filenameIn, String filenameOut, boolean buffer)
      throws IOException {
    long lenIn = new File(filenameIn).length();
    if (debug) System.out.println("read " + filenameIn + " len = " + lenIn);

    InputStream in = new FileInputStream(filenameIn);
    if (buffer) new BufferedInputStream(in, 10000);

    OutputStream out = new FileOutputStream(filenameOut);
    if (buffer) out = new BufferedOutputStream(out, 1000);

    long start = System.currentTimeMillis();
    IO.copyB(in, out, 10000);
    out.flush();
    double took = .001 * (System.currentTimeMillis() - start);

    out.close();
    in.close();

    long lenOut = new File(filenameOut).length();
    if (debug) System.out.println(" write file= " + filenameOut + " len = " + lenOut);

    double rate = lenIn / took / (1000 * 1000);
    String name = buffer ? "buffer" : "no buffer";
    System.out.println(" copy (" + name + ") took = " + took + " sec; rate = " + rate + "Mb/sec");
  }
  public static void main(String[] args) throws IOException {
    final int BUFF_SIZE = 4;
    final byte[] DATA_IN = {0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1};

    // Создаем файл 1
    try (OutputStream file =
        new FileOutputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/1.txt")) {
      file.write(DATA_IN);
    } catch (IOException e) {
      System.out.println("Ой!");
    }
    // Сортируем данные файла 1 и записываем в файл java_out
    try (InputStream src =
            new FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/1.txt");
        OutputStream out =
            new FileOutputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt")) {
      filterArray(src, out, BUFF_SIZE);
    } catch (IOException e) {
      System.out.println("Ой!!!");
    }
    // Печатаем из java_out в консоль
    //        byte[] arr = new byte[10];
    //        try (InputStream in = new
    // FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt")){
    //            in.read(arr);
    //        }
    try (ByteArrayOutputStream buff = new ByteArrayOutputStream();
        InputStream in =
            new FileInputStream("/home/aleks/Java/JavaITCourses-master/tmp_files/java_out.txt"); ) {
      copy(in, buff);
      System.out.println(Arrays.toString(buff.toByteArray()));
    }
  }
Пример #19
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();
      }
    }
  }
Пример #20
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();
    }
  }
  static void filterArray(InputStream in, OutputStream out, int buffSize) throws IOException {
    final int ZERO_STATE = 0;
    final int NUMBER_STATE = 1;
    byte[] buff = new byte[buffSize];
    int count;

    while ((count = in.read(buff)) != -1) {
      int state = ZERO_STATE;
      int previousIndex = 0;
      for (int index = 0; index < count; index++) {
        switch (state) {
          case ZERO_STATE:
            if (buff[index] == 0) state = ZERO_STATE;
            else {
              previousIndex = index;
              state = NUMBER_STATE;
            }
            break;
          case NUMBER_STATE:
            if (buff[index] == 0) {
              out.write(buff, previousIndex, index - previousIndex);
              state = ZERO_STATE;
            } else {
              state = NUMBER_STATE;
            }
            break;
        }
      }
      if (state == ZERO_STATE) {
        state = ZERO_STATE;
      } else out.write(buff, previousIndex, count - previousIndex);
    }
  }
Пример #22
0
  public void firstRun() throws Exception {

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    // Get the JSESSIONID from the response
    String line = null;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) {
        break;
      }
    }

    if (line == null) {
      throw new Exception("Missing Set-Cookie response header");
    }

    String jsessionId = getSessionIdFromCookie(line, JSESSIONID);

    // Store the JSESSIONID in a file
    FileOutputStream fos = new FileOutputStream(JSESSIONID);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    osw.write(jsessionId);
    osw.close();

    stat.addStatus(TEST_NAME, stat.PASS);
  }
 public static void save(Properties properties, File file) throws IOException {
   Assert.notNull(properties, "存储的属性为空!");
   OutputStream outputStream = new FileOutputStream(file);
   properties.store(outputStream, "saved on " + DateHelper.getStringDate());
   outputStream.flush();
   outputStream.close();
 }
Пример #24
0
  public Server() {
    try {
      ServerSocket ss = new ServerSocket(SERVER_PORT);

      Socket s = ss.accept();

      InputStream is = s.getInputStream();
      OutputStream out = s.getOutputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String sss = br.readLine();
      System.out.println(sss);

      PrintWriter pw = new PrintWriter(out);
      pw.print("hello,我是服务器。");

      pw.close();
      br.close();
      isr.close();
      out.close();
      is.close();
      s.close();
      ss.close();
    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (IOException oe) {
      oe.printStackTrace();
    }
  }
    @Override
    public InputStream sendXmlRpc(byte[] request) throws IOException {
      // Create a trust manager that does not validate certificate for this connection
      TrustManager[] trustAllCerts = new TrustManager[] {new PyPITrustManager()};

      try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());

        final HttpConfigurable settings = HttpConfigurable.getInstance();
        con = settings.openConnection(PYPI_LIST_URL);
        if (con instanceof HttpsURLConnection) {
          ((HttpsURLConnection) con).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        if (auth != null) {
          con.setRequestProperty("Authorization", "Basic " + auth);
        }
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        out.close();
        return con.getInputStream();
      } catch (NoSuchAlgorithmException e) {
        LOG.warn(e.getMessage());
      } catch (KeyManagementException e) {
        LOG.warn(e.getMessage());
      }
      return super.sendXmlRpc(request);
    }
Пример #26
0
  public static void write(String path, String content) {
    String s1 = new String();
    try {
      File f = new File(path);
      if (f.exists()) {
        System.out.println("文件存在");
      } else {
        System.out.println("文件不存在,正在创建....");
        if (f.createNewFile()) {
          System.out.println("文件创建成功!");
        } else {
          System.out.println("文件创建失败!");
        }
      }

      s1 = "\n" + content;

      OutputStream outPut = new FileOutputStream(path, true);
      byte[] b = s1.getBytes();
      outPut.write(b, 0, b.length);
      outPut.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #27
0
 public static Reader communicate(final String urlStr, final CharSequence toSend) {
   OutputStream outputStream = null;
   try {
     final URL url = new URL(urlStr);
     final URLConnection urlConnection = url.openConnection();
     urlConnection.setDoOutput(true);
     urlConnection.setDoInput(true);
     outputStream = urlConnection.getOutputStream();
     final OutputStreamWriter writer =
         new OutputStreamWriter(outputStream, DEFAULT_CHARSET.name());
     writer.append(toSend);
     writer.close();
     return new InputStreamReader(urlConnection.getInputStream(), DEFAULT_CHARSET.name());
   } catch (IOException e) {
     LOG.warn("exception caught", e);
   } finally {
     if (outputStream != null) {
       try {
         outputStream.close();
       } catch (IOException e) {
         LOG.warn("exception caught", e);
       }
     }
   }
   return null;
 }
Пример #28
0
 /**
  * Decode Base64 encoded data from one file to the other. Characters in the Base64 alphabet, white
  * space and equals sign are expected to be in urlencoded data. The presence of other characters
  * could be a sign that the data is corrupted.
  *
  * @param fIn File to be decoded.
  * @param fOut File to which the results should be written (may be the same as fIn).
  * @param throwExceptions Whether to throw exceptions when unexpected data is encountered.
  * @throws IOException if an IO error occurs.
  * @throws Base64DecodingException if unexpected data is encountered when throwExceptions is
  *     specified.
  * @since ostermillerutils 1.00.00
  */
 public static void decode(File fIn, File fOut, boolean throwExceptions) throws IOException {
   File temp = null;
   InputStream in = null;
   OutputStream out = null;
   try {
     in = new BufferedInputStream(new FileInputStream(fIn));
     temp = File.createTempFile("Base64", null, null);
     out = new BufferedOutputStream(new FileOutputStream(temp));
     decode(in, out, throwExceptions);
     in.close();
     in = null;
     out.flush();
     out.close();
     out = null;
     FileHelper.move(temp, fOut, true);
   } finally {
     if (in != null) {
       try {
         in.close();
       } catch (IOException ignore) {
         if (throwExceptions) throw ignore;
       }
       in = null;
     }
     if (out != null) {
       try {
         out.flush();
         out.close();
       } catch (IOException ignore) {
         if (throwExceptions) throw ignore;
       }
       out = null;
     }
   }
 }
 @Override
 public void run() {
   int count;
   try {
     while (!Thread.currentThread().isInterrupted() && !isComplete) {
       URL url = new URL(urlStr);
       URLConnection conection = url.openConnection();
       conection.connect();
       int lenghtOfFile = conection.getContentLength();
       InputStream input = new BufferedInputStream(url.openStream(), 8192);
       File file =
           createNameFile(
               Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                   + "/"
                   + this.tile,
               type);
       OutputStream output = new FileOutputStream(file);
       byte data[] = new byte[1024];
       long start = System.currentTimeMillis();
       long total = 0;
       while ((count = input.read(data)) != -1) {
         total += count;
         output.write(data, 0, count);
         updateProgress((int) ((total * 100) / lenghtOfFile));
       }
       output.flush();
       output.close();
       input.close();
       isComplete = true;
     }
   } catch (Exception e) {
     isComplete = false;
   }
 }
 @Override
 public void aroundWriteTo(WriterInterceptorContext responseCtx)
     throws IOException, WebApplicationException {
   RequestDetails requestDetails = (RequestDetails) responseCtx.getProperty(TMP_REQDETAILS);
   if (requestDetails.principal != null) {
     ByteArrayOutputStream content = new ByteArrayOutputStream();
     OutputStream oldStream = responseCtx.getOutputStream();
     responseCtx.setOutputStream(content);
     responseCtx.proceed();
     byte[] contentData = content.toByteArray();
     RESTResponseSigner responseSigner =
         new RESTResponseSigner(
             requestDetails.nonce,
             requestDetails.signature,
             requestDetails.statusCode,
             contentData);
     try {
       responseCtx
           .getHeaders()
           .add(
               RESTRequestSigner.HEADER_SIGNATURE,
               signResponse(requestDetails.principal, responseSigner.getDataToSign()));
     } catch (InvalidKeyException e) {
       logServerError(
           "Invalid key for identity " + requestDetails.identity + " : " + e.getMessage(),
           e,
           null);
       throw new WebApplicationException(INTERNAL_SERVER_ERROR);
     } catch (BackendAccessException e) {
       logServerError("Unexpected BackendAccessException" + e.getMessage(), e, null);
       throw new WebApplicationException(INTERNAL_SERVER_ERROR);
     }
     oldStream.write(contentData);
   }
 }