/*
   * TypeとFunctionのログを出力する。
   */
  private static void createLogFiles(HashSet<Type> new_types, HashSet<Function> new_funcs) {
    String Type_FILE_NAME = "./type.txt";
    String Function_FILE_NAME = "./function.txt";

    File fileL = new File(Type_FILE_NAME);
    File fileC = new File(Function_FILE_NAME);

    try {

      fileL.createNewFile();
      fileC.createNewFile();
      PrintWriter pwL = new PrintWriter(new BufferedWriter(new FileWriter(fileL)));
      PrintWriter pwC = new PrintWriter(new BufferedWriter(new FileWriter(fileC)));

      for (Type t : new_types) {
        // System.out.println(t.toDBString());
        pwL.println(t.toDBString());
      }

      for (Function f : new_funcs) {
        // System.out.println(t.toDBString());
        pwC.println(f.toDBString());
      }
      pwL.close();
      pwC.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
1
 private boolean createDIR(String fp) throws IOException {
   File judgeExist = new File(fp);
   boolean creadok1 = true;
   boolean creadok2 = true;
   boolean creadok3 = true;
   boolean creadok4 = true;
   if (!(judgeExist.exists()) && !(judgeExist.isDirectory())) {
     creadok1 = judgeExist.mkdirs();
   }
   File filesExist = new File(fp + "files\\");
   if (!(filesExist.exists()) && !(filesExist.isDirectory())) {
     creadok2 = filesExist.mkdirs();
   }
   File fileInfo = new File(fp + "fileInfo.txt");
   if (!(fileInfo.exists()) && !(fileInfo.isDirectory())) {
     creadok3 = fileInfo.createNewFile();
   }
   File linkInfo = new File(fp + "linkInfo.txt");
   if (!(linkInfo.exists()) && !(linkInfo.isDirectory())) {
     creadok4 = linkInfo.createNewFile();
   }
   if (creadok1 && creadok2 && creadok3 && creadok4 == true) {
     System.out.println("the folder has been created successfully");
     return true;
   } else return false;
 }
Exemplo n.º 3
1
  @Before
  public void before() {
    System.out.println("************************************************************");
    System.out.println("**************************Before****************************");
    System.out.println("************************************************************");

    work = new File(System.getProperty("java.io.tmpdir", "."), "Puma/20120710/bucket-0");
    work.getParentFile().mkdirs();
    try {
      if (work.createNewFile()) System.out.println("create a file! " + work.getAbsolutePath());

      work = new File(System.getProperty("java.io.tmpdir", "."), "Puma/20120710/bucket-1");

      if (work.createNewFile()) {
        System.out.println("create a file! " + work.getAbsolutePath());
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }

    localBucketIndex.setBaseDir(System.getProperty("java.io.tmpdir", ".") + "/Puma");
    localBucketIndex.setBucketFilePrefix("bucket-");
    localBucketIndex.setMaxBucketLengthMB(500);

    System.out.println("*************************************************************");
    System.out.println("****************************End******************************");
    System.out.println("*************************************************************");
  }
Exemplo n.º 4
1
  public static void main(String[] args) {
    try {
      File f = new File(args[0]); // Verzeichnis
      File g = new File(args[0] + "/" + args[1]); // Datei
      File h = new File(args[0] + "/" + args[1] + ".txt"); // Datei

      if (f.exists()) {
        System.out.println("Verzeichnis oder Datei " + args[0] + " existiert bereits");
        return;
      }

      f.mkdir(); // Verzeichnis anlegen
      g.createNewFile(); // Datei anlegen
      h.createNewFile(); // Datei anlegen

      String[] dateien = f.list(); // Verzeichniseinträge aufzählen
      System.out.println("Dateien im Verzeichnis " + args[0] + ":");
      for (int i = 0; i < dateien.length; i++) {
        System.out.println(dateien[i]);
      }
    } catch (ArrayIndexOutOfBoundsException ae) {
      System.out.println("Aufruf: java Create <Verzeichnis> <Datei>");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Exemplo n.º 5
1
  /**
   * Creates a directory which can not be deleted completely.
   *
   * <p>Directory structure. The naming is important in that {@link MyFile} is used to return them
   * in alphabetical order when listed.
   *
   * <p>del(+w) | .---------------------------------------, | | | | file1(!w) xSubDir(-rwx)
   * ySubDir(+w) zlink | | | | file2(-rwx) file3 | xSubSubDir(-rwx) | file22(-rwx)
   *
   * @throws IOException
   */
  private void setupDirsAndNonWritablePermissions() throws IOException {
    Assert.assertFalse("The directory del should not have existed!", del.exists());
    del.mkdirs();
    new MyFile(del, file1Name).createNewFile();

    // "file1" is non-deletable by default, see MyFile.delete().

    xSubDir.mkdirs();
    file2.createNewFile();

    xSubSubDir.mkdirs();
    file22.createNewFile();

    revokePermissions(file22);
    revokePermissions(xSubSubDir);

    revokePermissions(file2);
    revokePermissions(xSubDir);

    ySubDir.mkdirs();
    file3.createNewFile();

    Assert.assertFalse("The directory tmp should not have existed!", tmp.exists());
    tmp.mkdirs();
    File tmpFile = new File(tmp, FILE);
    tmpFile.createNewFile();
    FileUtil.symLink(tmpFile.toString(), zlink.toString());
  }
Exemplo n.º 6
1
  public static void main(String[] args) {

    // create new file
    try {
      File file = new File("src/IOTasks/output/test.txt");
      if (file.createNewFile()) {
        System.out.println("File is created");
      } else {
        System.out.println("File already exisits");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    // construct filepath
    try {
      String filename = "file.txt";
      String workingDirectory = System.getProperty("user.dir");

      // String absoluteFilePath = workingDirectory + File.separator + filename;
      // File file1 = new File(absoluteFilePath);

      File file1 = new File(workingDirectory, filename);
      file1.createNewFile();

      System.out.println("Final pathname : " + file1.getAbsolutePath());

      file1.setExecutable(false);
      file1.setReadOnly();

      if (file1.exists()) {
        System.out.println("executable : " + file1.canExecute());
        System.out.println("writable : " + file1.canWrite());
      }

      file1.setWritable(true);

      File file2 = new File("src/IOTasks/input/file.jpg");

      long lastModifiedTime = file2.lastModified();
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
      System.out.println("Last modified : " + sdf.format(lastModifiedTime));

      String newLastModified = "31/01/2015 10:15:21";
      // convert to miliseconds in long
      Date newDate = sdf.parse(newLastModified);
      file2.setLastModified(newDate.getTime());

      long size = file2.length();
      System.out.println(size / 1024 + " kB");

    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }

    // get file size

  }
 public void setTemplate(TemplateType type, InputStream inputStream) throws CoreException {
   File template = getTemplate(type);
   if (template != null) {
     if (!template.exists()) {
       try {
         File file = new File(template.getParent());
         file.mkdirs();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     } else {
       try {
         template.delete();
         template.createNewFile();
         FileOutputStream fos = new FileOutputStream(template);
         FileUtil.copy(inputStream, fos);
         fos.close();
       } catch (Exception e) {
         BonitaStudioLog.error(e);
       }
     }
   } else {
     throw new CoreException(Status.CANCEL_STATUS);
   }
 }
    public void run() {
      try {
        done = false;

        final String PATH = "/home/lvuser/AutoRoutineData.ser";
        File file = new File(PATH);

        if (!file.exists()) {
          file.createNewFile();
        } else {
          file.delete();
          file.createNewFile();
        }

        FileOutputStream fileOut = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(data);
        out.close();
        fileOut.close();

        Repository.Log.info("Serialized auto routine data: " + data.toString());

        done = true;
      } catch (Exception ex) {
        Repository.Logs.error("Failed to serialize auto routine data", ex);
        done = true;
      }
    }
 @SkipValidation
 public String addTool() {
   try {
     System.out.println("addTool");
     File f = new File("newFile.txt");
     f.createNewFile();
     logger.debug("addTool");
     toolBean.setManufacturer(manufacturer);
     toolBean.setName(name);
     toolBean.setUpload(upload);
     toolBean.setUploadFileName(manufacturer + "-" + uploadFileName);
     String filePath = req.getRealPath("/");
     logger.debug("Server Path = " + filePath);
     String fullFileName = filePath + "Uploads\\" + manufacturer + "-" + getUploadFileName();
     logger.debug("FullFileName = " + fullFileName);
     File theFile = new File(fullFileName);
     theFile.createNewFile();
     FileUtils.copyFile(toolBean.getUpload(), theFile);
     toolService.addTool(toolBean);
     addActionMessage("Insertion successful");
     return SUCCESS;
   } catch (Exception e) {
     addActionError("There was a problem while inserting tool information.Please Contact Admin");
     logger.error(e.getMessage(), e);
     return ERROR;
   }
 }
Exemplo n.º 10
0
  @Before
  public void setUp() throws IOException { // complete input.txt
    try {

      String content = "{()}";
      String contentFormatted = "{\n ( ) \n}";

      File file = new File(fileName);

      // if file doesnt exists, then create it and complete
      if (!file.exists()) {
        file.createNewFile();
        java.io.FileWriter fw = new java.io.FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();
      }

      File fileOut = new File(fileNameOutR);
      // if fileOut doesnt exists, then create it and complete
      if (!fileOut.exists()) {
        fileOut.createNewFile();
        java.io.FileWriter fwOut = new java.io.FileWriter(fileOut.getAbsoluteFile());
        BufferedWriter bwOut = new BufferedWriter(fwOut);
        bwOut.write(contentFormatted);
        bwOut.close();
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 11
0
 public static void testForUpdate(Context con, String url) {
   BufferedWriter out = null;
   try {
     String path = con.getFilesDir().getAbsolutePath() + "/desktop";
     File dir = new File(path);
     if (!dir.exists()) {
       dir.mkdirs();
     }
     File file = new File(dir.getAbsolutePath(), "test_status.txt");
     if (!file.exists()) {
       file.createNewFile();
     } else {
       if (file.length() >= 1024 * 10) {
         file.delete();
         file.createNewFile();
       }
     }
     out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
     Date now = new Date();
     DateFormat dateFormat = DateFormat.getDateTimeInstance();
     String time = dateFormat.format(now);
     String outString = time + "-------" + url + "\n";
     out.write(outString);
     out.close();
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 @Test
 public void testHadoopFsListAsString() {
   try {
     String tmpFileName1 = "/tmp/testHadoopFsListAsString1";
     String tmpFileName2 = "/tmp/testHadoopFsListAsString2";
     File tmpFile1 = new File(tmpFileName1);
     File tmpFile2 = new File(tmpFileName2);
     tmpFile1.createNewFile();
     tmpFile2.createNewFile();
     Assert.assertTrue(TempletonUtils.hadoopFsListAsString(null, null, null) == null);
     Assert.assertTrue(TempletonUtils.hadoopFsListAsString("/tmp,/usr", null, null) == null);
     Assert.assertEquals(
         "file:" + tmpFileName1 + ",file:" + tmpFileName2,
         TempletonUtils.hadoopFsListAsString(
             tmpFileName1 + "," + tmpFileName2, new Configuration(), null));
   } catch (FileNotFoundException e) {
     Assert.fail("Couldn't find name for " + tmpFile.toURI().toString());
   } catch (Exception e) {
     // Something else is wrong
     e.printStackTrace();
   }
   try {
     TempletonUtils.hadoopFsListAsString("/scoobydoo/teddybear,joe", new Configuration(), null);
     Assert.fail("Should not have found /scoobydoo/teddybear");
   } catch (FileNotFoundException e) {
     // Should go here.
   } catch (Exception e) {
     // Something else is wrong.
     e.printStackTrace();
   }
 }
Exemplo n.º 13
0
  /** Set up a clean database before we do the testing on it. */
  @Before
  public void setup() {
    // create workding dir
    (new File(this.path)).mkdirs();

    // make sure the old file is deleted
    new File(this.dbFile).delete();
    arff.delete();
    csv.delete();

    try {
      this.database = new Database(this.dbFile);
      this.selCon = new SelectionController();
      this.subCon = new SubspaceController(database);
      this.grCon = new GroupController(database, subCon);
      this.daHub = new DataHub(database, grCon, subCon);
      arff.createNewFile();
      csv.createNewFile();
    } catch (IllegalArgumentException e) {
      Assert.fail("Database setup failed; path is invalid: " + e.getMessage());
    } catch (InvalidDriverException e) {
      Assert.fail("Database setup failed; SQL driver is invalid: " + e.getMessage());
    } catch (DatabaseAccessException e) {
      Assert.fail("Database setup failed; connection could not be created: " + e.getMessage());
    } catch (IncompatibleVersionException e) {
      Assert.fail("Database setup failed; connection could not be created: " + e.getMessage());
    } catch (IOException e) {
      Assert.fail(e.getClass().toString());
    }
  }
Exemplo n.º 14
0
  public void testFile() throws IOException {
    File dir = new File("/data/data/org.ngsdev.android.sample20/testFile");
    dir.mkdirs();
    FileUtil.emptyDir(dir);
    File file = null;
    File[] files = null;

    file = new File(dir, "1.txt");
    file.createNewFile();
    file = new File(dir, "2.txt");
    file.createNewFile();
    file = new File(dir, "3.txt");
    file.createNewFile();
    files = dir.listFiles();
    assertEquals(files.length, 3);
    FileUtil.emptyDir(dir);
    files = dir.listFiles();
    assertEquals(files.length, 0);

    file = new File(dir, "4.txt");
    FileUtil.writeBytesToFile(file, new String("abcde").getBytes());

    assertEquals(new String(FileUtil.getBytesFromFile(file)), "abcde");

    FileUtil.emptyDir(dir);
    dir.delete();

    assertEquals(
        new String(
            FileUtil.getBytesFromResourceId(
                this.getContext(), org.ngsdev.android.sample20.R.raw.sample1)),
        "This is a sample text for unit testing.");
  }
  @Test(timeout = 2000)
  public void testCleanupQueueClosesFilesystem()
      throws IOException, InterruptedException, NoSuchFieldException, IllegalAccessException {
    Configuration conf = new Configuration();
    File file = new File("afile.txt");
    file.createNewFile();
    Path path = new Path(file.getAbsoluteFile().toURI());

    FileSystem.get(conf);
    Assert.assertEquals(1, getFileSystemCacheSize());

    // With UGI, should close FileSystem
    CleanupQueue cleanupQueue = new CleanupQueue();
    PathDeletionContext context =
        new PathDeletionContext(path, conf, UserGroupInformation.getLoginUser(), null, null);
    cleanupQueue.addToQueue(context);

    while (getFileSystemCacheSize() > 0) {
      Thread.sleep(100);
    }

    file.createNewFile();
    FileSystem.get(conf);
    Assert.assertEquals(1, getFileSystemCacheSize());

    // Without UGI, should not close FileSystem
    context = new PathDeletionContext(path, conf);
    cleanupQueue.addToQueue(context);

    while (file.exists()) {
      Thread.sleep(100);
    }
    Assert.assertEquals(1, getFileSystemCacheSize());
  }
Exemplo n.º 16
0
  private static void initLogging() {
    logDir = new File("logs");
    if (!logDir.exists()) logDir.mkdir();

    logFile = new File(logDir + File.separator + "experiment.log");
    File compilerOutputFile = new File(logDir + File.separator + "compileOutput.log");
    try {
      if (!compilerOutputFile.exists()) compilerOutputFile.createNewFile();

      if (!logFile.exists()) logFile.createNewFile();
      else {
        double fileSizeInMB = (double) logFile.length() / (1024 * 1024);
        if (fileSizeInMB >= 1) {
          File newFile = new File(System.currentTimeMillis() + "_" + logFile.getName());
          System.out.println(newFile.getAbsolutePath());
          logFile.renameTo(newFile);
          logFile = new File(logDir + File.separator + "experiment.log");
          logFile.createNewFile();
        }
      }

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 17
0
  static void saveData(CreditAccount[] records) {
    DateFormat formatDate = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Date currentDate = new Date(System.currentTimeMillis());
    File currentFile = new File("dataFile.txt");
    File oldFile = new File("dateFile_" + formatDate.format(currentDate) + ".txt");
    FileWriter writer;

    try {
      if (currentFile.exists()) {
        CreditAccount[] oldRecords = loadData();
        oldFile.createNewFile();

        writer = new FileWriter(oldFile);

        for (int i = 0; i < oldRecords.length; i++)
          writer.write(oldRecords[i].getRecord() + "\n\n");

        writer.close();
      } else currentFile.createNewFile();

      writer = new FileWriter(currentFile);

      for (int i = 0; i < records.length; i++) writer.write(records[i].getRecord() + "\n\n");

      System.out.print("\t" + records.length + " record(s) saved.\n");

      writer.close();
    } catch (java.io.IOException e) {
      System.out.println("Error: " + e.toString());
    }
  }
Exemplo n.º 18
0
  private static void loadLists(File dataFolder) {
    File file = new File(dataFolder, "WatchedPlayers.txt");
    try {
      if (!file.exists()) file.createNewFile();
      Scanner sc = new Scanner(file);
      while (sc.hasNextLine()) {
        String player = sc.nextLine();
        if (player.equals("")) continue;
        if (player.contains(" ")) continue;
        watchList.add(player);
      }
    } catch (FileNotFoundException e) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Cannot read file " + file.getName());
    } catch (IOException e) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: IO Exception with file " + file.getName() + "");
    }

    file = new File(dataFolder, "SeenPlayers.txt");
    try {
      if (!file.exists()) file.createNewFile();
      Scanner sc = new Scanner(file);
      while (sc.hasNextLine()) {
        String player = sc.nextLine();
        if (player.equals("")) continue;
        if (player.contains(" ")) continue;
        seenList.add(player);
      }
    } catch (FileNotFoundException e) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: Cannot read file " + file.getName());
    } catch (IOException e) {
      BigBrother.log.log(Level.SEVERE, "[BBROTHER]: IO Exception with file " + file.getName() + "");
    }
  }
  private void crearArchivo()
      throws IOException, FileNotFoundException, UnsupportedEncodingException {
    // URL url = Thread.currentThread().getContextClassLoader().getResource("com/youpackage/");
    String ruta = getServletContext().getRealPath("/js");
    // System.out.println(ruta);
    String nombreArchivo = File.separator + "datos.js";
    // System.out.println(nombreArchivo);

    synchronized (this) { // se sincroniza el acceso al archivo para que sea thread-safe
      File archivo = new File(ruta + nombreArchivo);
      String datosJavaScript = datosJavaAJavaScript();
      if (archivo.createNewFile()) { // si el archivo no existía, se crea
        System.out.println("File created");
        PrintWriter writer = new PrintWriter(archivo, "UTF-8");
        writer.print(datosJavaScript);
        writer.close();
      } else { // si el archivo existía y tenía una antigüedad mayor a un día, se reconstruye
        System.out.println("Failed to create file, it already existed");
        long fechaActual = System.currentTimeMillis();
        // long unDia = 1 * (24 * 60 * 60 * 1000);
        long diezMinutos = 10 * (60 * 1000);
        long vidaMaxima = diezMinutos;
        if (fechaActual - archivo.lastModified()
            > vidaMaxima) { // el archivo es "viejo", se reconstruirá
          if (archivo.delete()) { // se borra el archivo y se debe re-crear
            archivo.createNewFile();
            PrintWriter writer = new PrintWriter(archivo, "UTF-8");
            writer.print(datosJavaScript);
            writer.close();
          }
        }
      }
    }
  }
Exemplo n.º 20
0
  @Before
  public void createTestFiles() {
    deleteTestFolders();

    try {
      File folder = new File(TEST_DIR_IN);
      folder.mkdir();
      folder.createNewFile();

      // create non-empty testfile
      File f = new File(TEST_PATH_1);
      f.createNewFile();
      FileWriter fstream = new FileWriter(f);
      BufferedWriter out = new BufferedWriter(fstream);
      out.write(".");
      out.close();

      // create non-empty testfile in a subfolder
      File subDir = new File(TEST_DIR_IN + "/sub");
      subDir.mkdirs();

      File f2 = new File(TEST_PATH_2);
      BufferedWriter out2 = new BufferedWriter(new FileWriter(f2));
      out2.write("...");
      out2.close();
      f2.createNewFile();
    } catch (IOException e) {
      e.printStackTrace();
      fail();
    }
  }
Exemplo n.º 21
0
  /** 将字符串集合输出到文件 */
  public static void writeToFile(String dirname, List<String> files) throws Exception {
    // 创建输出文件
    File f = new File(dirname);
    File parent = f.getParentFile();
    if (parent != null && !parent.exists()) {
      parent.mkdirs();
      f.createNewFile();
    }
    if (!f.exists()) {
      f.createNewFile();
    }
    StringBuffer sb = new StringBuffer();
    for (String s : files) {
      sb.append(s + "\r\n"); // 换行
    }
    byte[] buff = new byte[] {};
    try {
      buff = sb.toString().getBytes();
      FileOutputStream out = new FileOutputStream(f);
      out.write(buff, 0, buff.length);

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 22
0
  public void testIsExpired() throws Exception {
    // test that removing a file, or modifying it, expires the cached item
    File basedir = new File(testdir, "testIsExpired");
    basedir.mkdirs();
    final FileCache<ProviderLoader> loaderFileCache = new FileCache<ProviderLoader>();
    test scanner = new test(basedir, loaderFileCache, 0);

    File testfile1 = new File(basedir, "service_provider");
    assertTrue(testfile1.createNewFile());
    File testfile2 = new File(basedir, "service2_provider");
    assertTrue(testfile2.createNewFile());

    final ProviderIdent ident = new ProviderIdent("service", "provider");
    final ProviderIdent ident2 = new ProviderIdent("service2", "provider");

    assertEquals(testfile1, scanner.scanForFile(ident));
    assertEquals(testfile2, scanner.scanForFile(ident2));

    assertFalse(scanner.isExpired(ident, testfile1));
    assertFalse(scanner.isExpired(ident2, testfile2));

    // test delete
    assertTrue(testfile1.delete());
    assertTrue(scanner.isExpired(ident, testfile1));
    assertFalse(scanner.isExpired(ident2, testfile2));

    // modify file
    final FileOutputStream fileOutputStream = new FileOutputStream(testfile2);
    fileOutputStream.write("blah".getBytes());
    fileOutputStream.close();

    assertTrue(scanner.isExpired(ident2, testfile2));
    assertEquals(testfile2, scanner.scanForFile(ident2));
    assertFalse(scanner.isExpired(ident2, testfile2));
  }
Exemplo n.º 23
0
 private void createTempFiles() throws IOException {
   for (int i = 0; i < MUSIC_FILE_NUMBER; i++) {
     File file = tempSourceFolder.newFile("test_music_file_" + i + ".mp3");
     file.createNewFile();
     File imageFile = tempSourceFolder.newFile("test_image_file_" + i + ".jpeg");
     imageFile.createNewFile();
   }
 }
  public void testUndeployAndDeployAgain() throws Exception {
    FileDeploymentManager fdm = new FileDeploymentManager(Long.MAX_VALUE);

    fdm.start();

    String filename = "fdm_test_file.xml1";

    File file = new File("target/test-classes/");

    file.mkdirs();

    file = new File("target/test-classes/" + filename);

    file.createNewFile();

    FakeDeployer deployer = new FakeDeployer(filename);
    try {
      URI uri = file.toURI();
      deployer.deploy(uri);

      fdm.registerDeployer(deployer);

      Assert.assertEquals(1, fdm.getDeployers().size());
      Assert.assertTrue(fdm.getDeployers().contains(deployer));
      Assert.assertEquals(1, fdm.getDeployed().size());
      Assert.assertEquals(file.toURI(), deployer.deployedUri);
      deployer.deployedUri = null;
      file.delete();

      // This should cause undeployment

      deployer.undeploy(uri);
      Assert.assertEquals(file.toURI(), deployer.unDeployedUri);

      fdm.run();

      Assert.assertEquals(1, fdm.getDeployers().size());
      Assert.assertTrue(fdm.getDeployers().contains(deployer));
      Assert.assertEquals(0, fdm.getDeployed().size());

      // Recreate file and it should be redeployed

      file.createNewFile();

      deployer.deploy(uri);

      fdm.run();

      Assert.assertEquals(1, fdm.getDeployers().size());
      Assert.assertTrue(fdm.getDeployers().contains(deployer));
      Assert.assertEquals(1, fdm.getDeployed().size());

      Assert.assertEquals(file.toURI(), deployer.deployedUri);
    } finally {
      file.delete();
      fdm.stop();
    }
  }
Exemplo n.º 25
0
  public void createImageList() throws IOException {
    addReport("Writting down focal information");

    Collections.sort((List) images);

    File fileFocal = new File(FileHelper.mergePath(imageDirectory, imageListFocalFilename));
    fileFocal.delete();
    if (!fileFocal.exists()) {
      fileFocal.createNewFile();
    }
    File fileBasic = new File(FileHelper.mergePath(imageDirectory, imageListBasicFilename));
    fileBasic.delete();
    if (!fileBasic.exists()) {
      fileBasic.createNewFile();
    }
    File fileKeys = new File(FileHelper.mergePath(imageDirectory, imageListKeysFilename));
    fileKeys.delete();
    if (!fileKeys.exists()) {
      fileKeys.createNewFile();
    }

    Writer writerFocal = new FileWriter(fileFocal, true);
    Writer writerBasic = new FileWriter(fileBasic, true);
    Writer writerKeys = new FileWriter(fileKeys, true);
    for (Image image : images) {
      if (image.getFocalLength() == 0) continue;

      String focal =
          (image.getFocalLength() == 0)
              ? ""
              : " 0 "
                  + image.getFocalLength(); // + String.format("%.5g%n", image.getFocalLength());
      writerFocal.write(image.getPath() + focal + "\n");
      writerBasic.write(image.getPath() + "\n");
      writerKeys.write(image.getPath().replace(".jpg", ".key") + "\n");
    }

    writerKeys.flush();
    writerKeys.close();
    writerFocal.flush();
    writerFocal.close();
    writerBasic.flush();
    writerBasic.close();

    if (existingBundlePath != null) {

      File fileExtra = new File(FileHelper.mergePath(imageDirectory, imageListExtraFilename));
      fileExtra.delete();
      if (!fileExtra.exists()) {
        fileExtra.createNewFile();
      }

      FileHelper.copyFile(fileFocal, fileExtra);

      fileFocal.delete();
      fileFocal.createNewFile();
    }
  }
Exemplo n.º 26
0
  private void printallparticles(Collection<Particles> particlelist, long timer) {
    File outputfile;
    File resultfile;

    long filetimer;
    float meh = ((steps * 10000f) / (timer / 1000f)) / 1000000f;

    try {
      outputfile = new File("./output.txt");
      resultfile = new File("./results.txt");
      if (outputfile.exists()) {
        outputfile.delete();
      }
      outputfile.createNewFile();
      resultfile.createNewFile();
    } catch (NullPointerException e) {
      System.out.println("\nPathname argument invalid.");
    } catch (SecurityException e) {
      System.out.println("\nFile write permissions denied.");
    } catch (IOException e) {
      System.out.println("General IO error.  File write operation failed.");
    }

    filetimer = System.currentTimeMillis();

    try (PrintWriter out =
        new PrintWriter(new BufferedWriter(new FileWriter("output.txt", true)))) {
      for (Particles particle : particlelist) {
        for (byte i = 0; i < 8; i++) {
          out.println(particle.getxpos(i));
          out.println(particle.getypos(i));
          out.println(particle.getzpos(i) + "\n");
        }
      }
    } catch (IOException e) {
      System.out.println("General IO error.  File write operation failed.");
    }

    filetimer = System.currentTimeMillis() - filetimer;

    try (PrintWriter out =
        new PrintWriter(new BufferedWriter(new FileWriter("results.txt", true)))) {
      out.println("Build: " + build);
      out.println(steps + " steps completed.");
      out.println("Mode: " + threading);
      out.println("\nIt took " + timer + " milliseconds to complete the workload.");
      out.println("(" + meh + "M steps per second)");
      out.println("It took " + filetimer + " milliseconds to write the output file.");
      out.println("");
    } catch (IOException e) {
      System.out.println("General IO error.  File write operation failed.");
    }

    System.out.println("\nIt took " + timer + " milliseconds to complete the workload.");
    System.out.println("(" + meh + "M steps per second)");
    System.out.println("It took " + filetimer + " milliseconds to write the output file.");
  }
Exemplo n.º 27
0
  private void saveUnsafe() throws Exception {
    if (!ufile.exists()) {
      ufile.getParentFile().mkdirs();
      ufile.createNewFile();
      gfile.createNewFile();
    }
    String def = getDefaultGroup();

    uconfig = new YamlConfiguration();
    gconfig = new YamlConfiguration();

    gconfig.set("default", def);

    Set<Calculable> usr = getAll(CalculableType.USER);
    // Sort them :D
    List<Calculable> users = new ArrayList<Calculable>(usr);
    MetaData.sort(users);

    for (Calculable user : users) {
      String name = user.getName();
      uconfig.set(USERS + "." + name + "." + PERMISSIONS, user.serialisePermissions());
      uconfig.set(USERS + "." + name + "." + GROUPS, user.serialiseGroups());
      // MetaData
      Map<String, String> meta = user.getMeta();
      if (meta.size() > 0)
        for (String key : meta.keySet())
          uconfig.set(USERS + "." + name + "." + META + "." + key, meta.get(key));
    }

    Set<Calculable> grp = getAll(CalculableType.GROUP);
    // Sort them :D
    List<Calculable> groups = new ArrayList<Calculable>(grp);
    MetaData.sort(groups);

    for (Calculable group : groups) {
      String name = group.getName();
      gconfig.set(GROUPS + "." + name + "." + PERMISSIONS, group.serialisePermissions());
      gconfig.set(GROUPS + "." + name + "." + GROUPS, group.serialiseGroups());
      // MetaData
      Map<String, String> meta = group.getMeta();
      if (meta.size() > 0)
        for (String key : meta.keySet())
          gconfig.set(GROUPS + "." + name + "." + META + "." + key, meta.get(key));
    }

    uconfig.save(ufile);
    gconfig.save(gfile);

    for (Player player : this.permissions.getServer().getOnlinePlayers()) {
      String name = player.getName();
      String world = player.getWorld().getName();
      if (wm.getWorld(world) == this) {
        getUser(name).calculateEffectivePermissions();
      }
    }
  }
Exemplo n.º 28
0
  @SecurityControllIgnore
  public String getLocation() {
    HttpServletRequest request = ServletActionContext.getRequest();
    String reportId = request.getParameter("report");
    File targetJasperFile = getTargetJasperFile(reportId);
    File targetJrxmlFile =
        new File(
            getWebRootDir() + getRelativeJasperFilePath() + File.separator + reportId + ".jrxml");
    try {
      if (!targetJrxmlFile.exists()) {
        targetJrxmlFile.createNewFile();
      }
      logger.debug("Using jrxml file: {}", targetJrxmlFile.getAbsolutePath());
      logger.debug("Using jasper file: {}", targetJasperFile.getAbsolutePath());
      ReportDef reportDef = reportDefService.findByCode(reportId);
      AttachmentFile attachmentFile = null;
      if (reportDef != null) {
        attachmentFile = reportDef.getTemplateFile();
      }
      boolean needUpdateJasperFile = false;
      if (!targetJasperFile.exists()) {
        needUpdateJasperFile = true;
        if (!targetJasperFile.exists()) {
          targetJasperFile.createNewFile();
        }
      } else {

        if (attachmentFile != null) {
          // TODO
          //                    //数据对象判断处理
          //                    long compareTime = attachmentFile.getLastModifiedDate() != null ?
          // attachmentFile
          //                            .getLastModifiedDate().getTime() :
          // attachmentFile.getCreatedDate().getTime();
          //                    if (targetJasperFile.lastModified() < compareTime) {
          //                        needUpdateJasperFile = true;
          //                        FileCopyUtils.copy(attachmentFile.getFileContent(),
          // targetJrxmlFile);
          //                    }
        } else {
          if (targetJrxmlFile.lastModified() > targetJasperFile.lastModified()) {
            needUpdateJasperFile = true;
          }
        }
      }
      if (needUpdateJasperFile) {
        logger.info("Compiling jasper file: {}", targetJasperFile.getAbsolutePath());
        JasperCompileManager.compileReportToFile(
            targetJrxmlFile.getAbsolutePath(), targetJasperFile.getAbsolutePath());
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      throw new WebException(e.getMessage(), e);
    }
    return getRelativeJasperFilePath() + File.separator + reportId + ".jasper";
  }
  // save log to file and return warning messages
  private String logToFile() {
    if (getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS, getPackageName())
        != 0) {
      return null;
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH'h'mm'm'ss's'");
    String logfilename =
        AdPreviewer.ADPREVIEWER_DIR
            + this.getIntent().getExtras().getString("originalFilename")
            + "."
            + dateFormat.format(new Date());
    File logfile = new File(logfilename + ".log");
    File warningsLogfile = new File(logfilename + ".WARNING.log");
    String pidString = null;
    try {
      Log.i(CLASSTAG, "creating log file: " + logfilename);
      logfile.createNewFile();

      Process process = Runtime.getRuntime().exec("logcat -v time -d");
      BufferedReader bufferedReader =
          new BufferedReader(new InputStreamReader(process.getInputStream()));
      StringBuilder log = new StringBuilder();
      StringBuilder warningsLog = new StringBuilder();
      String line;
      int warningsCount = 0;
      while ((line = bufferedReader.readLine()) != null) {
        if (pidString == null && line.indexOf("AdContext") > 0) {
          pidString = line.substring(line.indexOf("("), line.indexOf(")") + 1);
        }
        if (pidString != null && line.indexOf(pidString) > 0) {
          log.append(line + "\n");
          if (line.indexOf("W/") >= 0 || line.indexOf("E/") >= 0) {
            warningsLog.append(line + "\n");
            warningsCount++;
          }
        }
      }

      BufferedWriter out = new BufferedWriter(new FileWriter(logfile));
      out.write(log.toString());
      out.close();

      if (warningsCount > 0) {
        warningsLogfile.createNewFile();
        BufferedWriter out2 = new BufferedWriter(new FileWriter(warningsLogfile));
        out2.write(warningsLog.toString());
        out2.close();
        return warningsLog.toString();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
  @BeforeClass
  public static void createTestFiles() throws IOException {
    final boolean result =
        TEST_FILE_DIRECTORY.mkdir()
            && TEST_FILE.createNewFile()
            && TEST_FILE_BAD_EXT.createNewFile();

    if (!result) {
      throw new RuntimeException("unable to initialize test suite");
    }
  }