// System-dependent portion of ProcessBuilder.start()
  static Process start(
      String cmdarray[],
      java.util.Map<String, String> environment,
      String dir,
      ProcessBuilder.Redirect[] redirects,
      boolean redirectErrorStream)
      throws IOException {
    String envblock = ProcessEnvironment.toEnvironmentBlock(environment);

    FileInputStream f0 = null;
    FileOutputStream f1 = null;
    FileOutputStream f2 = null;

    try {
      long[] stdHandles;
      if (redirects == null) {
        stdHandles = new long[] {-1L, -1L, -1L};
      } else {
        stdHandles = new long[3];

        if (redirects[0] == Redirect.PIPE) stdHandles[0] = -1L;
        else if (redirects[0] == Redirect.INHERIT)
          stdHandles[0] = fdAccess.getHandle(FileDescriptor.in);
        else {
          f0 = new FileInputStream(redirects[0].file());
          stdHandles[0] = fdAccess.getHandle(f0.getFD());
        }

        if (redirects[1] == Redirect.PIPE) stdHandles[1] = -1L;
        else if (redirects[1] == Redirect.INHERIT)
          stdHandles[1] = fdAccess.getHandle(FileDescriptor.out);
        else {
          f1 = newFileOutputStream(redirects[1].file(), redirects[1].append());
          stdHandles[1] = fdAccess.getHandle(f1.getFD());
        }

        if (redirects[2] == Redirect.PIPE) stdHandles[2] = -1L;
        else if (redirects[2] == Redirect.INHERIT)
          stdHandles[2] = fdAccess.getHandle(FileDescriptor.err);
        else {
          f2 = newFileOutputStream(redirects[2].file(), redirects[2].append());
          stdHandles[2] = fdAccess.getHandle(f2.getFD());
        }
      }

      return new ProcessImpl(cmdarray, envblock, dir, stdHandles, redirectErrorStream);
    } finally {
      // In theory, close() can throw IOException
      // (although it is rather unlikely to happen here)
      try {
        if (f0 != null) f0.close();
      } finally {
        try {
          if (f1 != null) f1.close();
        } finally {
          if (f2 != null) f2.close();
        }
      }
    }
  }
 protected void add(Object value) {
   File f = null;
   FileOutputStream fos = null;
   try {
     f = createTempFile("S", dir);
     fos = new FileOutputStream(f);
     ObjectOutputStream fout = new ObjectOutputStream(new BufferedOutputStream(fos));
     fout.writeObject(value);
     fout.flush();
     fos.getFD().sync();
   } catch (Exception e) {
     throw new SpaceError(e);
   } finally {
     if (fos != null) {
       try {
         fos.close();
       } catch (Exception e) {
         throw new SpaceError(e);
       }
     }
   }
   stored.add(f.getAbsolutePath());
   /* fill cache */
   if (cacheSize > data.size()) if ((data.size() + 1) == stored.size()) data.add(value);
 }
 /**
  * {@inheritDoc}
  *
  * @see
  *     com.continuent.tungsten.common.file.FileIO#write(com.continuent.tungsten.common.file.FilePath,
  *     java.lang.String, java.lang.String, boolean)
  */
 @Override
 public void write(FilePath path, String value, String charset, boolean fsync)
     throws FileIOException {
   // Write the value and flush to storage. This overwrites any
   // previous version.
   FileOutputStream fos = null;
   try {
     fos = getOutputStream(path);
     BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos, charset));
     bw.write(value);
     bw.flush();
     if (fsync) {
       fos.getFD().sync();
     }
   } catch (IOException e) {
     throw new FileIOException(
         "Unable to write data to file: file="
             + path.toString()
             + " value="
             + safeSynopsis(value, 20),
         e);
   } finally {
     if (fos != null) {
       try {
         fos.close();
       } catch (IOException e) {
       }
     }
   }
 }
  private File downloadMemberPhoto(Host profileInfo, String targetFilePath) {
    File targetFile = new File(targetFilePath);
    if (targetFile.exists()) {
      targetFile.delete();
    }
    HttpURLConnection c = null;
    FileOutputStream fos = null;
    BufferedOutputStream out = null;
    try {
      c = (HttpURLConnection) new URL(profileInfo.getProfilePictureLarge()).openConnection();
      fos = new FileOutputStream(targetFilePath);
      out = new BufferedOutputStream(fos);

      InputStream in = c.getInputStream();
      byte[] buffer = new byte[16384];
      int len = 0;
      while ((len = in.read(buffer)) > 0) {
        fos.write(buffer, 0, len);
      }
      fos.flush();

    } catch (Exception e) {
      Log.i(TAG, "Error: " + e);
    } finally {
      try {
        fos.getFD().sync();
        out.close();
        c.disconnect();
      } catch (Exception e) {
        // Don't worry about these?
      }
    }
    return targetFile;
  }
Exemple #5
0
  public static void witeObjectToFile(Object object, File file) {

    ObjectOutputStream objectOut = null;
    FileOutputStream fileOut = null;
    try {
      if (!file.exists()) {
        file.createNewFile();
      }
      fileOut = new FileOutputStream(file, false);
      objectOut = new ObjectOutputStream(fileOut);
      objectOut.writeObject(object);
      fileOut.getFD().sync();

    } catch (IOException e) {
      e.printStackTrace();
    } catch (NullPointerException e) {
      e.printStackTrace();
    } finally {
      if (objectOut != null) {
        try {
          objectOut.close();
        } catch (IOException e) {
          // do nowt
        }
      }
      if (fileOut != null) {
        try {
          fileOut.close();
        } catch (IOException e) {
          // do nowt
        }
      }
    }
  }
 public void saveCache(
     JMXInstrumentedCache<K, V> cache, File savedCachePath, Function<K, byte[]> converter)
     throws IOException {
   long start = System.currentTimeMillis();
   String msgSuffix = " " + savedCachePath.getName() + " for " + cfname + " of " + ksname;
   logger.debug("saving" + msgSuffix);
   int count = 0;
   File tmpFile =
       File.createTempFile(savedCachePath.getName(), null, savedCachePath.getParentFile());
   FileOutputStream fout = new FileOutputStream(tmpFile);
   ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fout));
   FileDescriptor fd = fout.getFD();
   for (K key : cache.getKeySet()) {
     byte[] bytes = converter.apply(key);
     out.writeInt(bytes.length);
     out.write(bytes);
     ++count;
   }
   out.flush();
   fd.sync();
   out.close();
   if (!tmpFile.renameTo(savedCachePath))
     throw new IOException("Unable to rename cache to " + savedCachePath);
   if (logger.isDebugEnabled())
     logger.debug(
         "saved "
             + count
             + " keys in "
             + (System.currentTimeMillis() - start)
             + " ms from"
             + msgSuffix);
 }
  private static void unzip(File src, File dest) throws IOException {
    InputStream is = new FileInputStream(src);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    ZipEntry ze;

    dest.mkdirs();

    while ((ze = zis.getNextEntry()) != null) {
      byte[] buffer = new byte[16384];
      int count;
      FileOutputStream fos = new FileOutputStream(new File(dest, ze.getName()));
      BufferedOutputStream out = new BufferedOutputStream(fos);

      try {
        while ((count = zis.read(buffer)) != -1) {
          out.write(buffer, 0, count);
        }
        out.flush();
      } finally {
        fos.getFD().sync();
        out.close();
      }

      zis.closeEntry();
    }

    zis.close();
  }
Exemple #8
0
 /** Copy data from a source stream to destFile. Return true if succeed, return false if failed. */
 public static boolean copyToFile(InputStream inputStream, File destFile) {
   try {
     if (destFile.exists()) {
       destFile.delete();
     }
     FileOutputStream out = new FileOutputStream(destFile);
     try {
       byte[] buffer = new byte[4096];
       int bytesRead;
       while ((bytesRead = inputStream.read(buffer)) >= 0) {
         out.write(buffer, 0, bytesRead);
       }
     } finally {
       out.flush();
       try {
         out.getFD().sync();
       } catch (IOException e) {
       }
       out.close();
     }
     return true;
   } catch (IOException e) {
     return false;
   }
 }
  private File download(String url) throws MalformedURLException, IOException {
    File output = new File(getFilesDir(), UPDATE_FILENAME);

    if (output.exists()) {
      output.delete();
    }

    HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
    FileOutputStream fos = new FileOutputStream(output.getPath());
    BufferedOutputStream out = new BufferedOutputStream(fos);

    try {
      InputStream in = c.getInputStream();
      byte[] buffer = new byte[16384];
      int len = 0;

      while ((len = in.read(buffer)) > 0) {
        out.write(buffer, 0, len);
      }

      out.flush();
    } finally {
      fos.getFD().sync();
      out.close();
      c.disconnect();
    }

    return (output);
  }
Exemple #10
0
  private synchronized void saveProperties(final Properties nifiProps, final Logger logger)
      throws IOException {
    final File statusFile = getStatusFile(logger);
    if (statusFile.exists() && !statusFile.delete()) {
      logger.warn("Failed to delete {}", statusFile);
    }

    if (!statusFile.createNewFile()) {
      throw new IOException("Failed to create file " + statusFile);
    }

    try {
      final Set<PosixFilePermission> perms = new HashSet<>();
      perms.add(PosixFilePermission.OWNER_READ);
      perms.add(PosixFilePermission.OWNER_WRITE);
      Files.setPosixFilePermissions(statusFile.toPath(), perms);
    } catch (final Exception e) {
      logger.warn(
          "Failed to set permissions so that only the owner can read status file {}; "
              + "this may allows others to have access to the key needed to communicate with NiFi. "
              + "Permissions should be changed so that only the owner can read this file",
          statusFile);
    }

    try (final FileOutputStream fos = new FileOutputStream(statusFile)) {
      nifiProps.store(fos, null);
      fos.getFD().sync();
    }

    logger.debug("Saved Properties {} to {}", new Object[] {nifiProps, statusFile});
  }
Exemple #11
0
 public static void convertTableSaveFile(
     char delimiter, Integer[] partitions, final File outfile, final File infile)
     throws FileNotFoundException, IOException, InterruptedException, SyncFailedException {
   final FileOutputStream fos = new FileOutputStream(outfile, true);
   try {
     final CSVTableSaveFile converter = new CSVTableSaveFile(infile, delimiter, partitions);
     try {
       while (true) {
         final byte bytes[] = converter.read();
         if (bytes.length == 0) {
           break;
         }
         fos.write(bytes);
       }
     } finally {
       try {
         converter.close();
       } finally {
         fos.getFD().sync();
       }
     }
   } finally {
     fos.close();
   }
 }
 private static boolean sync(FileOutputStream paramFileOutputStream) {
   if (paramFileOutputStream != null) {}
   try {
     paramFileOutputStream.getFD().sync();
     return true;
   } catch (IOException paramFileOutputStream) {
   }
   return false;
 }
Exemple #13
0
 /**
  * Write the file content to the target file.
  *
  * @param content The file content.
  * @param target The file to write to.
  */
 public static void writeContentTo(String content, File target) {
   try (FileOutputStream fos = new FileOutputStream(target);
       BufferedOutputStream out = new BufferedOutputStream(fos)) {
     out.write(content.getBytes(UTF_8));
     out.flush();
     fos.getFD().sync();
   } catch (IOException e) {
     throw new UncheckedIOException(e);
   }
 }
 /**
  * Perform an fsync on the given FileOutputStream. The stream at this point must be flushed but
  * not yet closed.
  */
 public static boolean sync(FileOutputStream stream) {
   try {
     if (stream != null) {
       stream.getFD().sync();
     }
     return true;
   } catch (IOException e) {
   }
   return false;
 }
Exemple #15
0
  public static void createJarFileEntries(File jarFile, LinkedHashMap entries) throws Exception {
    JarOutputStream jarStream = null;
    FileOutputStream fileStream = null;

    if (jarFile != null) {
      logger.debug("Creating jar file " + jarFile.getAbsolutePath());

      try {
        fileStream = new FileOutputStream(jarFile);
        jarStream = new JarOutputStream(fileStream);

        if (entries != null && !entries.isEmpty()) {
          Iterator iter = entries.keySet().iterator();
          while (iter.hasNext()) {
            String jarFilePath = (String) iter.next();
            Object content = entries.get(jarFilePath);

            JarEntry entry = new JarEntry(jarFilePath);
            jarStream.putNextEntry(entry);

            logger.debug("Adding jar entry " + jarFilePath + " to " + jarFile.getAbsolutePath());

            if (content instanceof String) {
              writeJarEntry(jarStream, ((String) content).getBytes());
            } else if (content instanceof byte[]) {
              writeJarEntry(jarStream, (byte[]) content);
            } else if (content instanceof File) {
              writeJarEntry(jarStream, (File) content);
            }
          }
        }

        jarStream.flush();
        fileStream.getFD().sync();
      } catch (Exception jarCreationFailure) {
        throw jarCreationFailure;
      } finally {
        if (jarStream != null) {
          try {
            jarStream.close();
          } catch (Exception jarNotClosed) {
            logger.debug(jarNotClosed);
          }
        }
        if (fileStream != null) {
          try {
            fileStream.close();
          } catch (Exception fileNotClosed) {
            logger.debug(fileNotClosed);
          }
        }
      }
    }
  }
Exemple #16
0
 /**
  * Perform an fsync on the given FileOutputStream. The stream at this point must be flushed but
  * not yet closed.
  */
 private static boolean sync(FileOutputStream stream) {
   //noinspection EmptyCatchBlock
   try {
     if (stream != null) {
       stream.getFD().sync();
     }
     return true;
   } catch (IOException e) {
   }
   return false;
 }
 int truncate(FileDescriptor fd, long size) throws IOException {
     if (append) {
         // HACK in append mode we're not allowed to truncate, so we try to reopen the file and truncate that
         try (FileOutputStream fos = new FileOutputStream(((FileStream)fd.getStream()).get_Name())) {
             fos.getFD().setLength(size);
         }
     } else {
         fd.setLength(size);
     }
     return 0;
 }
  public static void main(String[] args) throws IOException {
    RandomAccessFile raf = new RandomAccessFile("classes/test/FileDescriptors.java", "r");
    testDescriptorValidity(raf, raf.getFD());

    FileInputStream fs1 = new FileInputStream("classes/test/FileDescriptors.java");
    testDescriptorValidity(fs1, fs1.getFD());

    File temp = File.createTempFile("Doppio-FileDescriptorsTest", ".txt");
    FileOutputStream fs2 = new FileOutputStream(temp);
    testDescriptorValidity(fs2, fs2.getFD());
    temp.delete(); // we don't support deleteOnExit either
  }
  @Override
  protected void onHandleIntent(Intent intent) {

    Uri imageUri = intent.getData();
    String imageFileName = imageUri.getLastPathSegment();
    String imageURL = imageUri.toString();
    String fileLocation;

    try {
      // Create a File directory
      File dir =
          Environment.getExternalStoragePublicDirectory(
              Environment.DIRECTORY_DCIM + "/SampleIntentService");
      // Make the directories if needed
      dir.mkdirs();
      // Create the image file
      File imageFile = new File(dir, imageFileName);
      // Delete the image file if already exists
      if (imageFile.exists()) {
        imageFile.delete();
      }
      // Convert URL from String to URL object
      URL url = new URL(imageURL);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

      FileOutputStream fileOutputStream = new FileOutputStream(imageFile.getPath());
      BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

      try {
        InputStream inputStream = httpURLConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int length = 0;

        while ((length = inputStream.read(buffer)) >= 0) {
          bufferedOutputStream.write(buffer, 0, length);
        }

        bufferedOutputStream.flush();

      } finally {
        fileOutputStream.getFD().sync();
        bufferedOutputStream.close();
        fileLocation = imageFile.getAbsolutePath();
        httpURLConnection.disconnect();
      }

      notifyDownloadFinished(fileLocation);

    } catch (IOException e) {
      Log.e(LOG_TAG, "Error in downloading image file", e);
    }
  }
  /**
   * Prepares the recorder to begin capturing and encoding data. This method must be called after
   * setting up the desired audio and video sources, encoders, file format, etc., but before
   * start().
   *
   * @throws IllegalStateException if it is called after start() or before setOutputFormat().
   * @throws IOException if prepare fails otherwise.
   */
  public void prepare() throws IllegalStateException, IOException {
    if (mPath != null) {
      FileOutputStream fos = new FileOutputStream(mPath);
      try {
        _setOutputFile(fos.getFD(), 0, 0);
      } finally {
        fos.close();
      }
    } else if (mFd != null) {
      _setOutputFile(mFd, 0, 0);
    } else {
      throw new IOException("No valid output file");
    }

    _prepare();
  }
  private void save(FileOutputStream os) throws IOException {
    // write the version number
    os.write(KEYRING_FILE_VERSION);

    CipherOutputStream cos = new CipherOutputStream(os, password);
    ObjectOutputStream oos = new ObjectOutputStream(cos);
    // write the data
    try {
      oos.writeObject(authorizationInfo);
      oos.writeObject(protectionSpace);
      os.flush();
      os.getFD().sync();
    } finally {
      oos.close();
    }
  }
Exemple #22
0
  /**
   * @param context Context required to write the object
   * @param object The object to write
   * @param filename the filename to write to
   * @throws IOException
   */
  public static void witeObjectToFile(Context context, Object object, String filename)
      throws IOException {

    ObjectOutputStream objectOut = null;
    try {

      // create output stream
      FileOutputStream fileOut = context.openFileOutput(filename, Activity.MODE_PRIVATE);
      objectOut = new ObjectOutputStream(fileOut);

      // write the object
      objectOut.writeObject(object);
      fileOut.getFD().sync();

    } finally {
      if (objectOut != null) objectOut.close();
    }
  }
Exemple #23
0
 private void writeMessage(FileOutputStream stream, String message, boolean forceTimestamp) {
   try {
     if (forceTimestamp || includeTimestampForMessages) {
       writeTimeStamp(stream);
     }
     stream.write(message.getBytes(CharsetSupport.getCharset()));
     stream.write('\n');
     stream.flush();
     if (syncAfterWrite) {
       stream.getFD().sync();
     }
   } catch (IOException e) {
     // QFJ-459: no point trying to log the error in the file if we had an IOException
     // we will end up with a java.lang.StackOverflowError
     System.err.println("error writing message to log : " + message);
     e.printStackTrace(System.err);
   }
 }
  // save / read file
  public static void writeToFile(Context ctx, String[] list) {
    FileOutputStream stream = null;

    try {
      /* you should declare private and final FILENAME_CITY */
      stream =
          new FileOutputStream(
              new File(Environment.getExternalStorageDirectory().getPath() + "/LvivRoutes.txt"));
      ObjectOutputStream dout = new ObjectOutputStream(stream);
      dout.writeObject(list);

      dout.flush();
      stream.getFD().sync();
      stream.close();
    } catch (IOException e) {

    }
  }
Exemple #25
0
  @Override
  public void onHandleIntent(Intent i) {
    try {
      File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

      root.mkdirs();

      File output = new File(root, i.getData().getLastPathSegment());

      if (output.exists()) {
        output.delete();
      }

      URL url = new URL(i.getData().toString());
      HttpURLConnection c = (HttpURLConnection) url.openConnection();

      c.setRequestMethod("GET");
      c.setReadTimeout(15000);
      c.connect();

      FileOutputStream fos = new FileOutputStream(output.getPath());
      BufferedOutputStream out = new BufferedOutputStream(fos);

      try {
        InputStream in = c.getInputStream();
        byte[] buffer = new byte[8192];
        int len = 0;

        while ((len = in.read(buffer)) > 0) {
          out.write(buffer, 0, len);
        }

        out.flush();
      } finally {
        fos.getFD().sync();
        out.close();
      }

      sendBroadcast(new Intent(ACTION_COMPLETE));
    } catch (IOException e2) {
      Log.e(getClass().getName(), "Exception in download", e2);
    }
  }
Exemple #26
0
  /** Write a byte[] array to file */
  private void writeToFile(byte[] data, String filePath) {
    Log.i(TAG, "Write data " + (new String(data)));

    // Write byte[] to file
    try {
      FileOutputStream out = new FileOutputStream(filePath);

      Log.i(TAG, "Flush & syn");
      out.write(data);
      out.flush();
      out.getFD().sync();
      out.close();

      Log.i(TAG, "Close stream");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #27
0
  /**
   * Copy a resource to the target directory. The resource file retains it's name.
   *
   * @param resource The resource path.
   * @param dir Target directory.
   */
  public static void copyResourceTo(String resource, File dir) {
    if (!dir.exists()) {
      fail("Trying to copy resource " + resource + " to non-existing directory: " + dir);
    }
    if (dir.isFile()) {
      fail("Trying to copy resource " + resource + " to file: " + dir + ", directory required");
    }
    int i = resource.lastIndexOf('/');
    File file = new File(dir, resource.substring(i + 1));

    try (FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream out = new BufferedOutputStream(fos);
        InputStream in = getResourceAsStream(resource)) {
      IOUtils.copy(in, out);
      out.flush();
      fos.getFD().sync();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
  private void writeFile(TimerImpl timer) {
    final File file = fileName(timer.getTimedObjectId(), timer.getId());

    // if the timer is expired or cancelled delete the file
    if (timer.getState() == TimerState.CANCELED || timer.getState() == TimerState.EXPIRED) {
      if (file.exists()) {
        file.delete();
      }
      return;
    }

    final TimerEntity entity;
    if (timer instanceof CalendarTimer) {
      entity = new CalendarTimerEntity((CalendarTimer) timer);
    } else {
      entity = new TimerEntity(timer);
    }

    FileOutputStream fileOutputStream = null;
    try {
      fileOutputStream = new FileOutputStream(file, false);
      final Marshaller marshaller = factory.createMarshaller(configuration);
      marshaller.start(new OutputStreamByteOutput(fileOutputStream));
      marshaller.writeObject(entity);
      marshaller.finish();
      fileOutputStream.flush();
      fileOutputStream.getFD().sync();
    } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      if (fileOutputStream != null) {
        try {
          fileOutputStream.close();
        } catch (IOException e) {
          ROOT_LOGGER.failToCloseFile(e);
        }
      }
    }
  }
  private void closeCurrentOutputStream() throws IOException {
    if (outputStream == null) {
      return;
    }

    boolean success = false;
    try {
      outputStream.flush();
      outputStream.getFD().sync();
      success = true;
    } finally {
      Util.closeQuietly(outputStream);
      if (success) {
        cache.commitFile(file);
      } else {
        file.delete();
      }
      outputStream = null;
      file = null;
    }
  }
Exemple #30
0
 public long open(String path, String mode) throws IOException {
   if (!("r".equals(mode) || "w".equals(mode) || "rw".equals(mode))) {
     throw new IllegalArgumentException();
   }
   try {
     FileDescriptor fileFD;
     File file;
     if (mode.equals("w")) {
       FileOutputStream f = new FileOutputStream(path);
       fileFD = f.getFD();
       file = new OutputStreamFile(f, kem);
     } else {
       RandomAccessFile f = new RandomAccessFile(fileUtil.resolveWorkingDirectory(path), mode);
       fileFD = f.getFD();
       file = new RandomAccessFileFile(f);
     }
     long fd = fdCounter++;
     descriptors.put(fd, fileFD);
     files.put(fileFD, file);
     return fd;
   } catch (FileNotFoundException e) {
     try {
       processFileNotFoundException(e);
     } catch (IOException ioe) {
       if (ioe.getMessage().equals("EISDIR") && mode.equals("r")) {
         // man 2 open says you can open a directory in readonly mode with open, but
         // java has no support for it. So we throw an UnsupportedOperationException
         // instead of failing with EISDIR
         kem.registerInternalWarning(
             "Unsupported file system behavior: tried to open a directory."
                 + " If you are interested in this behavior, please file an issue on github.");
         throw new UnsupportedOperationException();
       }
       throw ioe;
     }
     throw e; // unreachable
   }
 }