/**
   * Download a gzipped file using an HttpURLConnection, and gunzip it to the given destination.
   *
   * @param url URL to download from
   * @param destinationFile File to save the download as, including path
   * @return True if response received, destinationFile opened, and unzip successful
   * @throws IOException
   */
  private boolean downloadGzippedFileHttp(URL url, File destinationFile) throws IOException {
    // Send an HTTP GET request for the file
    Log.d(TAG, "Sending GET request to " + url + "...");
    publishProgress("Downloading data for " + languageName + "...", "0");
    HttpURLConnection urlConnection = null;
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();
    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      Log.e(TAG, "Did not get HTTP_OK response.");
      Log.e(TAG, "Response code: " + urlConnection.getResponseCode());
      Log.e(TAG, "Response message: " + urlConnection.getResponseMessage().toString());
      return false;
    }
    int fileSize = urlConnection.getContentLength();
    InputStream inputStream = urlConnection.getInputStream();
    File tempFile = new File(destinationFile.toString() + ".gz.download");

    // Stream the file contents to a local file temporarily
    Log.d(TAG, "Streaming download to " + destinationFile.toString() + ".gz.download...");
    final int BUFFER = 8192;
    FileOutputStream fileOutputStream = null;
    Integer percentComplete;
    int percentCompleteLast = 0;
    try {
      fileOutputStream = new FileOutputStream(tempFile);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Exception received when opening FileOutputStream.", e);
    }
    int downloaded = 0;
    byte[] buffer = new byte[BUFFER];
    int bufferLength = 0;
    while ((bufferLength = inputStream.read(buffer, 0, BUFFER)) > 0) {
      fileOutputStream.write(buffer, 0, bufferLength);
      downloaded += bufferLength;
      percentComplete = (int) ((downloaded / (float) fileSize) * 100);
      if (percentComplete > percentCompleteLast) {
        publishProgress("Downloading data for " + languageName + "...", percentComplete.toString());
        percentCompleteLast = percentComplete;
      }
    }
    fileOutputStream.close();
    if (urlConnection != null) {
      urlConnection.disconnect();
    }

    // Uncompress the downloaded temporary file into place, and remove the temporary file
    try {
      Log.d(TAG, "Unzipping...");
      gunzip(tempFile, new File(tempFile.toString().replace(".gz.download", "")));
      return true;
    } catch (FileNotFoundException e) {
      Log.e(TAG, "File not available for unzipping.");
    } catch (IOException e) {
      Log.e(TAG, "Problem unzipping file.");
    }
    return false;
  }
Esempio n. 2
0
 public void appendToFile(String toAppend, File file) throws IJunitException {
   logger.debug("Entered in ResourceFileWriter.appendToFile()");
   BufferedWriter writer = null;
   try {
     if (!file.exists()) {
       file.createNewFile();
     }
     writer = new BufferedWriter(new java.io.FileWriter(file));
     writer.write(toAppend);
     writer.flush();
     logger.debug("Exited from ResourceFileWriter.enclosing_method()");
   } catch (IOException e) {
     logger.error(
         ErrorMessageParser.getMessage(
             IExceptionCodes.FILEWRITER_EXP, new String[] {file.toString()}),
         e);
     throw new IJunitException(
         ErrorMessageParser.getMessage(
             IExceptionCodes.FILEWRITER_EXP, new String[] {file.toString()}),
         e);
   } finally {
     try {
       if (writer != null) {
         writer.close();
       }
     } catch (IOException e) {
       logger.error(
           "In ResourceFileWriter.appendToFile "
               + ErrorMessageParser.getMessage(IExceptionCodes.GENERIC_EXP),
           e);
     }
   }
 }
  @SuppressWarnings("deprecation")
  public CoronaJobTrackerRunner(
      TaskTracker.TaskInProgress tip,
      Task task,
      TaskTracker tracker,
      JobConf ttConf,
      CoronaSessionInfo info,
      String originalPath,
      String releasePath)
      throws IOException {
    super(tip, task, tracker, ttConf);
    this.coronaSessionInfo = info;
    this.originalPath = originalPath;
    this.releasePath = releasePath;
    LocalDirAllocator lDirAlloc = new LocalDirAllocator("mapred.local.dir");

    workDir =
        new File(
            lDirAlloc
                .getLocalPathForWrite(
                    TaskTracker.getLocalTaskDir(
                            task.getJobID().toString(),
                            task.getTaskID().toString(),
                            task.isTaskCleanupTask())
                        + Path.SEPARATOR
                        + MRConstants.WORKDIR,
                    conf)
                .toString());
    if (!workDir.mkdirs()) {
      if (!workDir.isDirectory()) {
        throw new IOException("Mkdirs failed to create " + workDir.toString());
      }
    }
    localizeTaskConfiguration(tracker, ttConf, workDir.toString(), task, task.getJobID());
  }
Esempio n. 4
0
  /**
   * 删除目录(包括:目录里的所有文件)
   *
   * @param fileName
   * @return
   */
  public static boolean deleteDirectory(String fileName) {
    boolean status;
    SecurityManager checker = new SecurityManager();

    if (!fileName.equals("")) {

      // File path = Environment.getExternalStorageDirectory();
      File newPath = new File(fileName);
      checker.checkDelete(newPath.toString());
      if (newPath.isDirectory()) {
        String[] listfile = newPath.list();
        // delete all files within the specified directory and then
        // delete the directory
        try {
          for (int i = 0; i < listfile.length; i++) {
            File deletedFile = new File(newPath.toString() + "/" + listfile[i].toString());
            deletedFile.delete();
          }
          newPath.delete();
          Log.i(TAG, "DirectoryManager deleteDirectory:" + fileName);
          status = true;
        } catch (Exception e) {
          e.printStackTrace();
          status = false;
        }

      } else status = false;
    } else status = false;
    return status;
  }
Esempio n. 5
0
 /**
  * A refactored method for populating all the command line arguments based on the user-specified
  * attributes.
  */
 private void populateAttributes() {
   commandline.createArgument().setValue("-o");
   commandline.createArgument().setValue(outputDirectory.toString());
   if (superGrammar != null) {
     commandline.createArgument().setValue("-glib");
     commandline.createArgument().setValue(superGrammar.toString());
   }
   if (html) {
     commandline.createArgument().setValue("-html");
   }
   if (diagnostic) {
     commandline.createArgument().setValue("-diagnostic");
   }
   if (trace) {
     commandline.createArgument().setValue("-trace");
   }
   if (traceParser) {
     commandline.createArgument().setValue("-traceParser");
   }
   if (traceLexer) {
     commandline.createArgument().setValue("-traceLexer");
   }
   if (traceTreeWalker) {
     if (is272()) {
       commandline.createArgument().setValue("-traceTreeParser");
     } else {
       commandline.createArgument().setValue("-traceTreeWalker");
     }
   }
   if (debug) {
     commandline.createArgument().setValue("-debug");
   }
 }
Esempio n. 6
0
  /**
   * Send a message to an Object.
   *
   * @param engine The engine.
   * @param msg The message that is sent.
   * @param ob The object receiving the message.
   * @return The result of the message being sent.
   */
  public String sendMessageToObject(Engine engine, String msg, OObject ob) {
    if (msg.equalsIgnoreCase(Keyword.FILE_CHECK_EXISTENCE)) {
      File f = new File(ob.getSimpleValue());
      if (f.exists()) return Keyword.TRUE;
      else return Keyword.FALSE;
    } else if (msg.equalsIgnoreCase(Keyword.FILE_READ)) {
      File f = new File(ob.getSimpleValue());
      if (f.exists()) {
        String data = TextFileLoader.loadFile(f.toString());
        OObject childData = ob.getBucket().findChildByName(Keyword.CHILD_DATA);
        if (childData != null) childData.setSimpleValue(data);
        return data;
      }
    } else if (msg.equalsIgnoreCase(Keyword.FILE_WRITE)) {
      File f = new File(ob.getSimpleValue());

      OObject childData = ob.getBucket().findChildByName(Keyword.CHILD_DATA);
      if (childData != null) {
        TextFileWriter.writeFile(f.toString(), childData.getSimpleValue());
      }
      if (f.exists()) return Keyword.TRUE;
      else return Keyword.FALSE;
    } else if (msg.equalsIgnoreCase(Keyword.FILE_DELETE)) {
      File f = new File(ob.getSimpleValue());
      if (f.exists()) {
        if (f.delete()) return Keyword.TRUE;
      }
      return Keyword.FALSE;
    }

    return "";
  }
  @Override
  protected void onHandleIntent(Intent intent) {
    File output =
        new File(
            this.defaultLocation,
            new SimpleDateFormat("'Document 'yyyy-MM-dd' 'HHmmss'.'").format(new Date())
                + intent.getStringExtra(EXTRA_OUTPUT_FILE_EXTENSION));

    getNotificationManager()
        .notify(
            ConversionService.class.getName(),
            1,
            new NotificationCompat.Builder(this)
                .setContentTitle("Converting documents")
                .setContentText(defaultLocation.toString())
                .setSmallIcon(R.drawable.ic_launcher)
                .setOngoing(true)
                .build());

    InputStream is = null;
    try {
      is = getContentResolver().openInputStream(intent.getData());
      Document doc = new Document(is);
      App.closeStream(is);
      doc.save(output.toString(), intent.getIntExtra(EXTRA_SAVE_FORMAT, -1));

      getNotificationManager()
          .notify(
              ConversionService.class.getName(),
              2,
              new NotificationCompat.Builder(this)
                  .setContentTitle("Document converted")
                  .setContentText(output.toString())
                  .setSmallIcon(R.drawable.ic_launcher)
                  .setContentIntent(
                      PendingIntent.getActivity(
                          ConversionService.this,
                          0,
                          new Intent(Intent.ACTION_VIEW)
                              .setDataAndType(
                                  Uri.fromFile(output), intent.getStringExtra(EXTRA_OUTPUT_MIME)),
                          PendingIntent.FLAG_CANCEL_CURRENT))
                  .build());

    } catch (Exception x) {
      getNotificationManager()
          .notify(
              ConversionService.class.getName(),
              3,
              new NotificationCompat.Builder(this)
                  .setContentTitle("Document conversion failed")
                  .setContentText(x.getMessage())
                  .setSmallIcon(R.drawable.ic_launcher)
                  .build());
    } finally {
      App.closeStream(is);
    }

    getNotificationManager().cancel(ConversionService.class.getName(), 1);
  }
Esempio n. 8
0
  /**
   * Builds the configuration ZIP file.
   *
   * @param configName the configuration name
   * @param parentDir the parent directory
   * @return the file
   */
  public static File buildConfigZip(final String configName, final File parentDir) {
    if (!parentDir.isDirectory()) {
      throw new RuntimeException(MSGS.format(CONFIG_NOT_DIR_1, parentDir.toString()));
    }

    final File zipFile = createEmptyZipFile(configName);
    final ZipOutputStream out;
    try {
      out = new ZipOutputStream(new FileOutputStream(zipFile));
    } catch (final FileNotFoundException e) {
      throw new RuntimeException(MSGS.format(ERROR_ZIPPING_1, parentDir.toString()), e);
    }

    try {
      addFilesToZip(parentDir, out, parentDir);
      return zipFile;
    } catch (final IOException e) {
      throw new RuntimeException(MSGS.format(ERROR_ZIPPING_1, parentDir.toString()), e);
    } finally {
      try {
        if (out != null) {
          out.close();
        }
      } catch (final IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
Esempio n. 9
0
 private String createCacheDir(File baseDir, String subDir) {
   String cacheDirName = null;
   if (baseDir.isDirectory()) {
     if (baseDir.canWrite()) {
       if (subDir != null) {
         baseDir = new File(baseDir, subDir);
         baseDir.mkdir();
       }
       if (baseDir.exists() && baseDir.canWrite()) {
         File cacheDir = new File(baseDir, "cache");
         if (cacheDir.exists() || cacheDir.mkdirs()) {
           if (cacheDir.canWrite()) {
             cacheDirName = cacheDir.getAbsolutePath();
             CR3_SETTINGS_DIR_NAME = baseDir.getAbsolutePath();
           }
         }
       }
     } else {
       log.i(baseDir.toString() + " is read only");
     }
   } else {
     log.i(baseDir.toString() + " is not found");
   }
   return cacheDirName;
 }
Esempio n. 10
0
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   switch (requestCode) {
     case TAKE_PICTURE:
       if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
         //                    dataList = new ArrayList<ImageItem>();
         String fileName = String.valueOf(System.currentTimeMillis());
         //                    String a=tempFile.toString();
         //                    System.out.println(a);
         //                    Bitmap bm = (Bitmap) data.getExtras().get("data");
         BitmapFactory.Options opts = new BitmapFactory.Options();
         opts.inJustDecodeBounds = true;
         Bitmap bm = BitmapFactory.decodeFile(tempFile.toString(), opts);
         try {
           File file = FileUtils.saveBitmap(bm, fileName, tempFile.toString());
           ImageItem takePhoto = new ImageItem();
           takePhoto.setImagePath(file.toString());
           takePhoto.setBitmap(bm);
           Bimp.tempSelectBitmap.add(takePhoto);
         } catch (Exception e) {
           Toast.makeText(ReplyPhoto.this, "手机可运行内存不足,照片保存失败,请清理后操作", Toast.LENGTH_SHORT).show();
         }
       }
       break;
   }
 }
  private static void processFile(File next, Path inputDirectory, Path outputDirectory) {
    try {
      String fileContents = IOUtils.toString(new FileInputStream(next));
      fileContents = fileContents.replaceAll("\\.json", ".yaml");

      final JsonNode jsonNode =
          DeserializationUtils.deserializeIntoTree(fileContents, next.toString());

      final String yamlOutput =
          Yaml.mapper().writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);

      final String relativePath =
          "./" + next.toString().replace(inputDirectory.toString(), "").replace(".json", ".yaml");

      final Path outputFile = outputDirectory.resolve(relativePath).normalize();
      LOGGER.debug("output file: " + outputFile);

      final File file = outputFile.toAbsolutePath().toFile();
      FileUtils.forceMkdir(outputFile.getParent().toFile());
      FileUtils.write(file, yamlOutput);

    } catch (IOException e) {
      throw new RuntimeException("Could not process file " + next, e);
    }
  }
Esempio n. 12
0
  private void createThumbnail(ContentValues map) throws IOException {
    File videoFile = fileFromResourceMap(map);

    Log.d("Creating thumbnail from video file " + videoFile.toString());

    Bitmap bitmap =
        ThumbnailUtils.createVideoThumbnail(
            videoFile.toString(), MediaStore.Video.Thumbnails.MINI_KIND);
    if (bitmap == null) {
      Log.w("Error creating thumbnail");
      return;
    }

    String filename = (String) map.get(Resources.FILENAME);
    if (TextUtils.isEmpty(filename)) {
      throw new IOException("Must specify FILENAME when inserting Resource");
    }
    Uri thumbnailUri = Resources.buildThumbnailUri(filename + THUMBNAIL_EXT);
    OutputStream ostream;
    try {
      ostream = getContext().getContentResolver().openOutputStream(thumbnailUri);
    } catch (FileNotFoundException e) {
      Log.d("Could not open output stream for thumbnail storage: " + e.getLocalizedMessage());
      return;
    }

    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
    ostream.flush();
    IOUtilities.closeStream(ostream);

    map.put(Resources.THUMBNAIL, thumbnailUri.toString());
  }
Esempio n. 13
0
  /**
   * Construct a {@link SubProcessHeavy SubProcessHeavy} instance which when executed will fulfill
   * the given action agenda.
   *
   * <p>
   *
   * @param agenda The agenda to be accomplished by the action.
   * @param outFile The file to which all STDOUT output is redirected.
   * @param errFile The file to which all STDERR output is redirected.
   * @return The SubProcess which will fulfill the agenda.
   * @throws PipelineException If unable to prepare a SubProcess due to illegal, missing or
   *     imcompatable information in the action agenda or a general failure of the prep method code.
   */
  public SubProcessHeavy prep(ActionAgenda agenda, File outFile, File errFile)
      throws PipelineException {
    /* create the process to run the action */
    try {
      ArrayList<String> args = new ArrayList<String>();

      for (File file : agenda.getPrimaryTarget().getFiles()) args.add(file.toString());

      for (FileSeq fseq : agenda.getSecondaryTargets()) {
        for (File file : fseq.getFiles()) args.add(file.toString());
      }

      return new SubProcessHeavy(
          agenda.getNodeID().getAuthor(),
          getName() + "-" + agenda.getJobID(),
          "touch",
          args,
          agenda.getEnvironment(),
          agenda.getWorkingDir(),
          outFile,
          errFile);
    } catch (Exception ex) {
      throw new PipelineException(
          "Unable to generate the SubProcess to perform this Action!\n" + ex.getMessage());
    }
  }
Esempio n. 14
0
  // Mostly for setting up the symlinks. Note that when we setup the distributed
  // cache, we didn't create the symlinks. This is done on a per task basis
  // by the currently executing task.
  public static void setupWorkDir(JobConf conf) throws IOException {
    File workDir = new File(".").getAbsoluteFile();
    FileUtil.fullyDelete(workDir);
    if (DistributedCache.getSymlink(conf)) {
      URI[] archives = DistributedCache.getCacheArchives(conf);
      URI[] files = DistributedCache.getCacheFiles(conf);
      Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
      Path[] localFiles = DistributedCache.getLocalCacheFiles(conf);
      if (archives != null) {
        for (int i = 0; i < archives.length; i++) {
          String link = archives[i].getFragment();
          if (link != null) {
            link = workDir.toString() + Path.SEPARATOR + link;
            File flink = new File(link);
            if (!flink.exists()) {
              FileUtil.symLink(localArchives[i].toString(), link);
            }
          }
        }
      }
      if (files != null) {
        for (int i = 0; i < files.length; i++) {
          String link = files[i].getFragment();
          if (link != null) {
            link = workDir.toString() + Path.SEPARATOR + link;
            File flink = new File(link);
            if (!flink.exists()) {
              FileUtil.symLink(localFiles[i].toString(), link);
            }
          }
        }
      }
    }
    File jobCacheDir = null;
    if (conf.getJar() != null) {
      jobCacheDir = new File(new Path(conf.getJar()).getParent().toString());
    }

    // create symlinks for all the files in job cache dir in current
    // workingdir for streaming
    try {
      DistributedCache.createAllSymlink(conf, jobCacheDir, workDir);
    } catch (IOException ie) {
      // Do not exit even if symlinks have not been created.
      LOG.warn(StringUtils.stringifyException(ie));
    }
    // add java.io.tmpdir given by mapred.child.tmp
    String tmp = conf.get("mapred.child.tmp", "./tmp");
    Path tmpDir = new Path(tmp);

    // if temp directory path is not absolute
    // prepend it with workDir.
    if (!tmpDir.isAbsolute()) {
      tmpDir = new Path(workDir.toString(), tmp);
      FileSystem localFs = FileSystem.getLocal(conf);
      if (!localFs.mkdirs(tmpDir) && !localFs.getFileStatus(tmpDir).isDir()) {
        throw new IOException("Mkdirs failed to create " + tmpDir.toString());
      }
    }
  }
Esempio n. 15
0
  private static File shortenFileName(File fileName, String dir) {
    if ((fileName == null) || (fileName.length() == 0)) {
      return fileName;
    }
    if (!fileName.isAbsolute() || (dir == null)) {
      return fileName;
    }

    String longName;
    if (OS.WINDOWS) {
      // case-insensitive matching on Windows
      longName = fileName.toString().toLowerCase();
      dir = dir.toLowerCase();
    } else {
      longName = fileName.toString();
    }

    if (!dir.endsWith(System.getProperty("file.separator"))) {
      dir = dir.concat(System.getProperty("file.separator"));
    }

    if (longName.startsWith(dir)) {
      // result is based on original name, not on lower-cased name
      String newName = fileName.toString().substring(dir.length());
      return new File(newName);
    } else {
      return fileName;
    }
  }
 public void testWorks() throws Exception {
   try (TestDirectory dir = new TestDirectory("sdf2fasta")) {
     final File xd = new File(dir, "sdf");
     final ArrayList<InputStream> al = new ArrayList<>();
     al.add(
         new ByteArrayInputStream(
             ">test\nacgt\n>bob\ntagt\naccc\n>cat\ncat\n>dog\nccc".getBytes()));
     final FastaSequenceDataSource ds = new FastaSequenceDataSource(al, new DNAFastaSymbolTable());
     final SequencesWriter sw = new SequencesWriter(ds, xd, 300000, PrereadType.UNKNOWN, false);
     sw.processSequences();
     File x;
     SequencesReader sr = SequencesReaderFactory.createDefaultSequencesReader(xd);
     try {
       x = new File(dir, "junitmy.fasta");
       checkMainInitOk("-i", xd.toString(), "-o", x.toString(), "-Z");
       checkContent1(x);
     } finally {
       sr.close();
     }
     sr = SequencesReaderFactory.createDefaultSequencesReader(xd);
     try {
       checkMainInitOk("-i", xd.toString(), "-o", x.toString(), "-l", "3", "-Z");
       checkContent2(x);
     } finally {
       sr.close();
     }
   }
 }
Esempio n. 17
0
    public Drawable loadImageFromUrl(Context context, String imageUrl) {
      Drawable drawable = null;

      if (imageUrl == null) return null;
      String fileName = "";

      // 获取url中图片的文件名与后缀
      if (imageUrl != null && imageUrl.length() != 0) {
        fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
      }

      File file = new File(context.getCacheDir(), fileName);

      if (!file.exists() && !file.isDirectory()) {
        try {
          FileOutputStream fos = new FileOutputStream(file);
          InputStream is = new URL(imageUrl).openStream();
          int data = is.read();
          while (data != -1) {
            fos.write(data);
            data = is.read();
          }
          fos.close();
          is.close();

          drawable = Drawable.createFromPath(file.toString());
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        // System.out.println(file.isDirectory() + " " + file.getName());
        drawable = Drawable.createFromPath(file.toString());
      }
      return drawable;
    }
Esempio n. 18
0
  boolean defineAllTestcases(String root, String server) {
    ClientTest.root = root;
    ClientTest.server = server;
    File testpath = new File(root + "/" + TESTINPUTDIR);
    File basepath = new File(root + "/" + BASELINEDIR);
    if (!basepath.exists() || !basepath.isDirectory() || !basepath.canRead())
      return report("Base directory not readable: " + basepath.toString());
    if (!testpath.exists() || !testpath.isDirectory() || !testpath.canRead())
      return report("Test directory not readable: " + testpath.toString());
    // Generate the testcases from the located .dmr files
    // This assumes that the set of files and the set of
    // files thru the sourceurl are the same
    File[] filelist = testpath.listFiles(new TestFilter(DEBUG));
    for (int i = 0; i < filelist.length; i++) {
      File file = filelist[i];
      // remove the extension
      String name = file.getName();
      if (name == null) continue;
      int index = name.lastIndexOf("." + TESTEXTENSION);
      assert (index > 0);
      name = name.substring(0, index);
      if (!isDisabledTest(name)) {
        ClientTest ct = new ClientTest(name, true, isXfailTest(name));
        this.alltestcases.add(ct);
      }
    }

    return true;
  }
  /**
   * Before downloading a file for map icons (see "retrieveMapImageForIcon" below), first remove any
   * existing .img and .img.* files
   *
   * <p>e.g. delete all that start with (DataFile name) + ".img"
   *
   * @param mapLayerMetadata
   * @return
   * @throws IOException
   */
  private boolean deleteOlderMapThumbnails(MapLayerMetadata mapLayerMetadata) {
    if (mapLayerMetadata == null) {
      logger.warning("mapLayerMetadata is null");
      return false;
    }

    // Retrieve the data file
    //
    DataFile df = mapLayerMetadata.getDataFile();

    try {
      DataFileIO dataAccess = df.getAccessObject();

      if (dataAccess == null || !dataAccess.isLocalFile()) {
        return false;
      }
      // Get the parent directory
      //
      Path fileDirname = dataAccess.getFileSystemPath().getParent();
      if (fileDirname == null) {
        logger.warning(
            "DataFile directory has null path.  Directory path: "
                + dataAccess.getFileSystemPath().toString());
        return false;
      }

      // Verify that the directory exists
      //
      File fileDirectory = new File(fileDirname.normalize().toString());
      if (!(fileDirectory.isDirectory())) {
        logger.warning(
            "DataFile directory is not actuall a directory.  Directory path: "
                + fileDirectory.toString());
        return false;
      }

      /* Iterate through directory and delete any ".img" files for this DataFile

          Example:
          Datafile name: 14a5e4abf7d-e7eebfb6474d
          Types of files that would be deleted (if they exist):
              14a5e4abf7d-e7eebfb6474d.img
              14a5e4abf7d-e7eebfb6474d.img.thumb64
              14a5e4abf7d-e7eebfb6474d.img.thumb400
      */
      String iconBaseFilename = dataAccess.getFileSystemPath().toString() + ".img";

      for (File singleFile : fileDirectory.listFiles()) {
        if (singleFile.toString().startsWith(iconBaseFilename)) {
          // logger.info("file found: " + singleFile.toString());
          singleFile.delete();
          // results.add(file.getName());
        }
      }
    } catch (IOException ioEx) {
      return false;
    }

    return true;
  }
  /**
   * Save the blog category.
   *
   * @param blogUser {@link BlogUser}
   * @throws BlojsomException If there is an error saving the category
   * @since blojsom 2.22
   */
  public void save(BlogUser blogUser) throws BlojsomException {
    _blogUser = blogUser;
    Blog blog = blogUser.getBlog();
    File blogCategory = new File(blog.getBlogHome() + BlojsomUtils.removeInitialSlash(_category));

    // If the category does not exist, try and create it
    if (!blogCategory.exists()) {
      if (!blogCategory.mkdirs()) {
        _logger.error("Could not create new blog category at: " + blogCategory.toString());

        return;
      }
    }

    // We know the category exists so try and save its meta-data
    String propertiesExtension = blog.getBlogPropertiesExtensions()[0];
    File categoryMetaDataFile = new File(blogCategory, "blojsom" + propertiesExtension);
    Properties categoryMetaData = BlojsomUtils.mapToProperties(_metadata, BlojsomConstants.UTF8);
    try {
      FileOutputStream fos = new FileOutputStream(categoryMetaDataFile);
      categoryMetaData.store(fos, null);
      fos.close();
    } catch (IOException e) {
      _logger.error(e);
      throw new BlojsomException("Unable to save blog category", e);
    }

    _logger.debug("Saved blog category: " + blogCategory.toString());
  }
 public static boolean copy(File src, File dest, CopyProgressListener l, boolean overwrite)
     throws IOException {
   if (dest.exists()) {
     if (!dest.isFile()) {
       throw new IOException("impossible to copy: destination is not a file: " + dest);
     }
     if (overwrite) {
       if (!dest.canWrite()) {
         dest.delete();
       } // if dest is writable, the copy will overwrite it without requiring a delete
     } else {
       Message.verbose(dest + " already exists, nothing done");
       return false;
     }
   }
   copy(new FileInputStream(src), dest, l);
   long srcLen = src.length();
   long destLen = dest.length();
   if (srcLen != destLen) {
     dest.delete();
     throw new IOException(
         "size of source file "
             + src.toString()
             + "("
             + srcLen
             + ") differs from size of dest file "
             + dest.toString()
             + "("
             + destLen
             + ") - please retry");
   }
   dest.setLastModified(src.lastModified());
   return true;
 }
Esempio n. 22
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    photo = new File(Environment.getExternalStorageDirectory() + "/Frutarre_NoFrames");
    Log.d("GCM", photo.toString());
    boolean success = false;
    if (!photo.exists()) {
      success = photo.mkdirs();
    }
    // if (!success)
    {
      Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
      photo =
          new File(
              Environment.getExternalStorageDirectory() + "/Frutarre_NoFrames",
              Commons.getTodaysDate() + ".jpg");
      Log.d("GCM", photo.toString());
      intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
      Uri imageUir = Uri.fromFile(photo);
      startActivityForResult(intent, REQUEST_CODE);
      // finish();
    }
  }
Esempio n. 23
0
 @Override
 public void onGetCurrentMap(Bitmap map) {
   File sdcard = Environment.getExternalStorageDirectory();
   File dir = new File(sdcard.toString() + "/vehicle");
   if (dir.exists() == false) {
     dir.mkdir();
   }
   appData.lastId++;
   File file = new File(dir.toString() + "/cut" + appData.lastId + ".png");
   try {
     file.createNewFile();
   } catch (IOException e) {
     Log.v("file", "create fail");
     return;
   }
   FileOutputStream fOut = null;
   try {
     fOut = new FileOutputStream(file);
   } catch (FileNotFoundException e) {
     Log.v("file", "find fail");
     return;
   }
   map.compress(Bitmap.CompressFormat.PNG, 100, fOut);
   Log.v("file", "succeed write: cut" + appData.lastId + ".png");
   try {
     fOut.flush();
     fOut.close();
   } catch (IOException e) {
     Log.v("file", "end fail");
     return;
   }
 }
Esempio n. 24
0
  public void run() throws Exception {
    File rtDir = new File("rt.dir");
    File javaHome = new File(System.getProperty("java.home"));
    if (javaHome.getName().equals("jre")) javaHome = javaHome.getParentFile();
    File rtJar = new File(new File(new File(javaHome, "jre"), "lib"), "rt.jar");
    expand(rtJar, rtDir);

    String[] rtDir_opts = {
      "-bootclasspath", rtDir.toString(),
      "-classpath", "",
      "-sourcepath", "",
      "-extdirs", ""
    };
    test(rtDir_opts, "HelloPathWorld");

    if (isJarFileSystemAvailable()) {
      String[] rtJar_opts = {
        "-bootclasspath", rtJar.toString(),
        "-classpath", "",
        "-sourcepath", "",
        "-extdirs", ""
      };
      test(rtJar_opts, "HelloPathWorld");

      String[] default_opts = {};
      test(default_opts, "HelloPathWorld");

      // finally, a non-trivial program
      test(default_opts, "CompileTest");
    } else System.err.println("jar file system not available: test skipped");
  }
Esempio n. 25
0
  /** Perform an unified diff between to directory. Only Java file are compared */
  public static void main(String[] args) throws Exception {
    if (args.length != 2) {
      usageAndExit();
    }

    File dir1 = new File(args[0]);
    File dir2 = new File(args[1]);

    if (!directoryExist(dir1) || !directoryExist(dir2)) {
      System.exit(1);
    }

    List<File> files = exploreDirectory(dir1);
    boolean diffFound = false;

    for (File file : files) {
      String file2 = file.toString().replaceFirst(dir1.toString(), dir2.toString());
      if (!new File(file2).exists()) {
        System.err.println(file2 + " does not exist in " + dir2);
        diffFound = true;
        continue;
      }

      if (DiffPrint.printUnifiedDiff(file.toString(), file2)) {
        diffFound = true;
      }
    }

    if (diffFound) {
      System.exit(1);
    }
  }
  /**
   * Test for the SystemUtils.createTempDir() and SystemUtils.deleteDirectory() methods.
   *
   * @throws Exception
   */
  @Test
  public void testCreateDeleteTempDir() throws Exception {

    /* create a temporary directory, making sure that it exists after it's created */
    File dir1 = SystemUtils.createTempDir();
    assertTrue(dir1.exists());

    /* create a second temporary directory, making sure it's different from the first */
    File dir2 = SystemUtils.createTempDir();
    assertTrue(dir1.exists());
    assertNotSame(dir1.toString(), dir2.toString());

    /* store some additional files/directories in the first temp directory */
    File subdir1 = new File(dir1, "subdir1");
    File subdir2 = new File(dir1, "subdir2");
    assertTrue(subdir1.mkdir());
    assertTrue(subdir2.mkdir());
    assertTrue(new File(dir1, "file1").createNewFile());
    assertTrue(new File(dir1, "file2").createNewFile());
    assertTrue(new File(subdir1, "file3").createNewFile());
    assertTrue(new File(subdir1, "file4").createNewFile());

    /* delete the second temp dir */
    assertTrue(SystemUtils.deleteDirectory(dir2));

    /* delete the first temp dir */
    assertTrue(SystemUtils.deleteDirectory(dir1));
  }
Esempio n. 27
0
 /** Serialize to an XML File. */
 public void writeXML(File f) {
   OutputStream out = null;
   try {
     Marshaller marshaller = ctx.createMarshaller();
     OvalNamespacePrefixMapper.configure(marshaller, OvalNamespacePrefixMapper.URI.RES);
     out = new FileOutputStream(f);
     marshaller.marshal(getOvalResults(), out);
   } catch (JAXBException e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
   } catch (FactoryConfigurationError e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
   } catch (FileNotFoundException e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
   } catch (OvalException e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         logger.warn(JOVALMsg.ERROR_FILE_CLOSE, e.toString());
       }
     }
   }
 }
Esempio n. 28
0
 public void writeXML(File f) {
   OutputStream out = null;
   try {
     Marshaller marshaller = ctx.createMarshaller();
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
     out = new FileOutputStream(f);
     marshaller.marshal(getOvalVariables(), out);
   } catch (JAXBException e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
     logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
   } catch (FactoryConfigurationError e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
     logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
   } catch (FileNotFoundException e) {
     logger.warn(JOVALMsg.ERROR_FILE_GENERATE, f.toString());
     logger.warn(JOVALMsg.getMessage(JOVALMsg.ERROR_EXCEPTION), e);
   } finally {
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
         logger.warn(JOVALMsg.ERROR_FILE_CLOSE, f.toString());
       }
     }
   }
 }
  private static Instance[] initializeInstances(String dataFile, String labelFile) {

    // DataSetReader dsr = new CSVDataSetReader(new File("").getAbsolutePath() + "/src/opt/test/" +
    // dataFile);
    // DataSetReader lsr = new CSVDataSetReader(new File("").getAbsolutePath() + "/src/opt/test/" +
    // labelFile);

    URL d_path = IndepenentComponentAnalysisMyDataTest.class.getResource(dataFile);
    File df = new File(d_path.getFile());
    URL l_path = IndepenentComponentAnalysisMyDataTest.class.getResource(dataFile);
    File lf = new File(l_path.getFile());

    DataSetReader dsr = new CSVDataSetReader(df.toString());
    DataSetReader lsr = new CSVDataSetReader(lf.toString());
    DataSet ds;
    DataSet labs;

    try {
      ds = dsr.read();
      labs = lsr.read();
      Instance[] instances = ds.getInstances();
      Instance[] labels = labs.getInstances();

      //            for(int i = 0; i < instances.length; i++) {
      //                instances[i].setLabel(new Instance(labels[i].getData().get(0)));
      //            	//instances[i].setLabel(new Instance(labels[i].getData()));
      //            }

      return instances;
    } catch (Exception e) {
      System.out.println("Failed to read input file");
      return null;
    }
  }
  private void generateSource(
      Generator.TemplateType mgrType, String template, String recordType, String outputPath)
      throws MojoFailureException {
    InputStream is = getClass().getClassLoader().getResourceAsStream(template);
    if (is == null) {
      throw new MojoFailureException("template '" + template + "' not found in classpath");
    }

    StringBuilder sb = new StringBuilder();
    File outputFile = new File(outputPath + File.separator + recordType + template);

    try {
      getLog().info("generating " + outputFile.toString());

      Generator.generateSource(mgrType, packageName, typeMap.get(recordType), is, sb, debug);
      is.close();

      FileWriter outWriter = new FileWriter(outputFile);
      outWriter.write(sb.toString());
      outWriter.close();
    } catch (Exception ex) {
      getLog().error(ex);
      throw new MojoFailureException("failed to generate " + outputFile.toString());
    }
  }