Exemplo n.º 1
0
  public void record(Document doc) throws IOException {
    // System.out.println("Recording Entities");
    Path currentRelativePath = Paths.get("");
    String s = currentRelativePath.toAbsolutePath().toString();
    // System.out.println("Current relative path is: " + s);

    Path targetPath = currentRelativePath.resolve(writeOutLocation);

    if (Files.notExists(targetPath)) {
      Files.createDirectory(targetPath);
      Files.createDirectory(targetPath.resolve("location"));
      Files.createDirectory(targetPath.resolve("date"));
    }

    boolean isNew = true;
    for (String entity : entityTypes) {
      StringBuilder sb = new StringBuilder();
      TagTokenizer tok = new TagTokenizer();
      tok.addField(entity);
      tok.tokenize(doc);
      if (entity.equals("date")) sb = findDates(doc, sb);
      else if (entity.equals("location")) sb = findLocations(doc, sb);

      String docName = doc.name.split("_")[0];
      String outputName = writeOutLocation + entity + "/" + docName + ".txt";
      isNew = Files.notExists(Paths.get(outputName));
      // if the name is not new, then append rather than start a new file
      BufferedWriter bw = new BufferedWriter(new FileWriter(outputName, !isNew));
      bw.write(sb.toString());
      bw.close();
    }
  }
 private static String getFirefoxDriverDefaultPath() {
   if (OsUtils.isWindows()) {
     if (OsUtils.is64Bit()
         && (Files.exists(Paths.get("./drivers/geckodriver-windows-64bit"))
             || Files.notExists(Paths.get("./drivers/geckodriver-windows-32bit")))) {
       return "drivers/geckodriver-windows-64bit.exe";
     } else {
       return "drivers/geckodriver-windows-32bit.exe";
     }
   } else if (OsUtils.isMac()) {
     if (OsUtils.is64Bit()
         && (Files.exists(Paths.get("./drivers/geckodriver-mac-64bit"))
             || Files.notExists(Paths.get("./drivers/geckodriver-mac-32bit")))) {
       return "drivers/geckodriver-mac-64bit";
     } else {
       return "drivers/geckodriver-mac-32bit";
     }
   } else if (OsUtils.isLinux()) {
     if (OsUtils.is64Bit()
         && (Files.exists(Paths.get("./drivers/geckodriver-linux-64bit"))
             || Files.notExists(Paths.get("./drivers/geckodriver-linux-32bit")))) {
       return "drivers/geckodriver-linux-64bit";
     } else {
       return "drivers/geckodriver-linux-32bit";
     }
   }
   return null;
 }
Exemplo n.º 3
0
  public void split() throws IOException {
    List<ObjectPath> pathTable = asset.getPaths();
    TypeTree typeTree = asset.getTypeTree();

    // assets with just one object can't be split any further
    if (pathTable.size() == 1) {
      L.warning("Asset doesn't contain sub-assets!");
      return;
    }

    for (ObjectPath path : pathTable) {
      // skip filtered classes
      if (cf != null && !cf.accept(path)) {
        continue;
      }

      String className = ClassID.getNameForID(path.getClassID(), true);

      AssetFile subAsset = new AssetFile();
      subAsset.getHeader().setFormat(asset.getHeader().getFormat());

      ObjectPath subFieldPath = new ObjectPath();
      subFieldPath.setClassID1(path.getClassID1());
      subFieldPath.setClassID2(path.getClassID2());
      subFieldPath.setLength(path.getLength());
      subFieldPath.setOffset(0);
      subFieldPath.setPathID(1);
      subAsset.getPaths().add(subFieldPath);

      TypeTree subTypeTree = subAsset.getTypeTree();
      subTypeTree.setEngineVersion(typeTree.getEngineVersion());
      subTypeTree.setVersion(-2);
      subTypeTree.setFormat(typeTree.getFormat());
      subTypeTree.getFields().put(path.getClassID(), typeTree.getFields().get(path.getClassID()));

      subAsset.setDataBuffer(asset.getPathBuffer(path));

      Path subAssetDir = outputDir.resolve(className);
      if (Files.notExists(subAssetDir)) {
        Files.createDirectories(subAssetDir);
      }

      // probe asset name
      String subAssetName = getObjectName(asset, path);
      if (subAssetName != null) {
        // remove any chars that could cause troubles on various file systems
        subAssetName = FilenameSanitizer.sanitizeName(subAssetName);
      } else {
        // use numeric names
        subAssetName = String.format("%06d", path.getPathID());
      }
      subAssetName += ".asset";

      Path subAssetFile = subAssetDir.resolve(subAssetName);
      if (Files.notExists(subAssetFile)) {
        L.log(Level.INFO, "Writing {0}", subAssetFile);
        subAsset.save(subAssetFile);
      }
    }
  }
  private void bringUpDeadNodeAndEnsureNoReplication(
      CloudJettyRunner nodeToBringUp, boolean disableFingerprint) throws Exception {
    // disable fingerprint check if needed
    System.setProperty("solr.disableFingerprint", String.valueOf(disableFingerprint));

    indexInBackground(50);

    // bring back dead node and ensure it recovers
    ChaosMonkey.start(nodeToBringUp.jetty);

    nodesDown.remove(nodeToBringUp);

    waitTillNodesActive();
    waitForThingsToLevelOut(30);

    Set<CloudJettyRunner> jetties = new HashSet<>();
    jetties.addAll(shardToJetty.get("shard1"));
    jetties.removeAll(nodesDown);
    assertEquals(getShardCount() - nodesDown.size(), jetties.size());

    long cloudClientDocs = cloudClient.query(new SolrQuery("*:*")).getResults().getNumFound();
    assertEquals(docId, cloudClientDocs);

    // if there was no replication, we should not have replication.properties file
    String replicationProperties =
        nodeToBringUp.jetty.getSolrHome()
            + "/cores/"
            + DEFAULT_TEST_COLLECTION_NAME
            + "/data/replication.properties";
    assertTrue(
        "PeerSync failed. Had to fail back to replication",
        Files.notExists(Paths.get(replicationProperties)));
  }
Exemplo n.º 5
0
  public void run() throws Throwable {
    if (Files.notExists(jdkMods)) {
      return;
    }

    if (!CompilerUtils.compile(src, classes)) {
      throw new AssertionError("Compilation failure. See log.");
    }

    String modName = "test";
    Files.createDirectories(jmods);
    Files.createDirectories(jars);
    Path jarfile = jars.resolve("test.jar");
    JarUtils.createJarFile(jarfile, classes);

    Path image = Paths.get("mysmallimage");
    runJmod(jarfile.toString(), modName);
    runJlink(image, modName, "--compress", "2");
    execute(image, modName);

    Files.delete(jmods.resolve(modName + ".jmod"));

    image = Paths.get("myimage");
    runJmod(classes.toString(), modName);
    runJlink(image, modName);
    execute(image, modName);
  }
Exemplo n.º 6
0
  public static SyncFile addFolderSyncFile(
      Path filePath, long parentFolderId, long repositoryId, long syncAccountId) throws Exception {

    // Local sync file

    if (Files.notExists(filePath)) {
      return null;
    }

    String name = String.valueOf(filePath.getFileName());

    SyncFile syncFile =
        addSyncFile(
            null,
            null,
            null,
            filePath.toString(),
            Files.probeContentType(filePath),
            name,
            parentFolderId,
            repositoryId,
            SyncFile.STATE_SYNCED,
            syncAccountId,
            SyncFile.TYPE_FOLDER);

    // Remote sync file

    FileEventUtil.addFolder(parentFolderId, repositoryId, syncAccountId, name, syncFile);

    return syncFile;
  }
  @Test
  public void testDeleteInstanceDirAfterCreateFailure() throws Exception {
    assumeFalse(
        "Ignore test on windows because it does not delete data directory immediately after unload",
        Constants.WINDOWS);
    File solrHomeDirectory =
        new File(initCoreDataDir, getClass().getName() + "-corex-" + System.nanoTime());
    solrHomeDirectory.mkdirs();
    copySolrHomeToTemp(solrHomeDirectory, "corex");
    File corex = new File(solrHomeDirectory, "corex");
    FileUtils.write(new File(corex, "core.properties"), "", StandardCharsets.UTF_8);
    JettySolrRunner runner =
        new JettySolrRunner(solrHomeDirectory.getAbsolutePath(), buildJettyConfig("/solr"));
    runner.start();

    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl() + "/corex")) {
      client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      SolrInputDocument doc = new SolrInputDocument();
      doc.addField("id", "123");
      client.add(doc);
      client.commit();
    }

    Path dataDir = null;
    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
      CoreStatus status = CoreAdminRequest.getCoreStatus("corex", true, client);
      String dataDirectory = status.getDataDirectory();
      dataDir = Paths.get(dataDirectory);
      assertTrue(Files.exists(dataDir));
    }

    File subHome = new File(solrHomeDirectory, "corex" + File.separator + "conf");
    String top = SolrTestCaseJ4.TEST_HOME() + "/collection1/conf";
    FileUtils.copyFile(
        new File(top, "bad-error-solrconfig.xml"), new File(subHome, "solrconfig.xml"));

    try (HttpSolrClient client = getHttpSolrClient(runner.getBaseUrl().toString())) {
      client.setConnectionTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      client.setSoTimeout(SolrTestCaseJ4.DEFAULT_CONNECTION_TIMEOUT);
      try {
        CoreAdminRequest.reloadCore("corex", client);
      } catch (Exception e) {
        // this is expected because we put a bad solrconfig -- ignore
      }

      CoreAdminRequest.Unload req = new CoreAdminRequest.Unload(false);
      req.setDeleteDataDir(true);
      req.setDeleteInstanceDir(
          false); // important because the data directory is inside the instance directory
      req.setCoreName("corex");
      req.process(client);
    }

    runner.stop();

    assertTrue(
        "The data directory was not cleaned up on unload after a failed core reload",
        Files.notExists(dataDir));
  }
  /**
   * ファイルデータをストレージに保存します.
   *
   * @param metadata ファイルデータを含むurlTreeメタデータオブジェクト
   * @param ctx urlTreeコンテキストオブジェクト
   */
  @Override
  public void save(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx)
      throws BadContentException {

    String localFileName = metadata.getAbsolutePath();

    logger.debug("saving " + localFileName);
    Path f = this.generateFileObj(localFileName);

    InputStream b = metadata.getData();
    // nullの場合は書き換えない。
    if (b == null) {
      return;
    }
    try {
      Path parent = f.getParent();

      // 書き込む場所がなければ親ディレクトリを作成
      if (Files.notExists(parent)) {
        Files.createDirectories(parent);
      }
      Files.copy(b, f, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
      throw new GenericResourceException(e);
    }
  }
Exemplo n.º 9
0
  public static SyncFile addFileSyncFile(
      Path filePath, long folderId, long repositoryId, long syncAccountId) throws Exception {

    // Local sync file

    if (Files.notExists(filePath)) {
      return null;
    }

    String checksum = FileUtil.getChecksum(filePath);
    String name = String.valueOf(filePath.getFileName());
    String mimeType = Files.probeContentType(filePath);

    SyncFile syncFile =
        addSyncFile(
            null,
            checksum,
            null,
            filePath.toString(),
            mimeType,
            name,
            folderId,
            repositoryId,
            SyncFile.STATE_SYNCED,
            syncAccountId,
            SyncFile.TYPE_FILE);

    // Remote sync file

    FileEventUtil.addFile(
        filePath, folderId, repositoryId, syncAccountId, checksum, name, mimeType, syncFile);

    return syncFile;
  }
Exemplo n.º 10
0
  @AdviseWith(adviceClasses = NettyUtilAdvice.class)
  @Test
  public void testDispose() throws Exception {
    Path remoteFilePath = Paths.get("remoteFile");

    Path tempFilePath = FileServerTestUtil.createFileWithData(Paths.get("tempFile"));

    Map<Path, Path> pathMap = _nettyRepository.pathMap;

    FileServerTestUtil.createFileWithData(tempFilePath);

    try (CaptureHandler captureHandler =
        JDKLoggerTestUtil.configureJDKLogger(NettyRepository.class.getName(), Level.OFF)) {

      NoticeableFuture<Path> noticeableFuture =
          _nettyRepository.getFile(_embeddedChannel, remoteFilePath, null, false);

      FileResponse fileResponse =
          new FileResponse(remoteFilePath, System.currentTimeMillis(), 0, false);

      fileResponse.setLocalFile(tempFilePath);

      _asyncBroker.takeWithResult(remoteFilePath, fileResponse);

      Path localFilePath = noticeableFuture.get();

      Assert.assertNotNull(localFilePath);
      Assert.assertTrue(Files.notExists(tempFilePath));
      Assert.assertTrue(Files.exists(localFilePath));
      Assert.assertEquals(1, pathMap.size());
      Assert.assertSame(localFilePath, pathMap.get(remoteFilePath));

      _nettyRepository.dispose(false);

      Assert.assertTrue(Files.notExists(localFilePath));
      Assert.assertTrue(pathMap.isEmpty());
      Assert.assertTrue(Files.exists(_repositoryPath));

      _nettyRepository.dispose(true);

      Assert.assertTrue(Files.notExists(_repositoryPath));

      List<LogRecord> logRecords = captureHandler.getLogRecords();

      Assert.assertTrue(logRecords.isEmpty());
    }
  }
Exemplo n.º 11
0
  public void extract(boolean raw) throws IOException {
    List<ObjectPath> paths = asset.getPaths();
    Deserializer deser = new Deserializer(asset);

    for (AssetExtractHandler extractHandler : extractHandlerMap.values()) {
      extractHandler.setAssetFile(asset);
      extractHandler.setOutputDir(outputDir);
    }

    for (ObjectPath path : paths) {
      // skip filtered classes
      if (cf != null && !cf.accept(path)) {
        continue;
      }

      String className = ClassID.getNameForID(path.getClassID(), true);

      // write just the serialized object data or parsed and extracted content?
      if (raw) {
        String assetFileName = String.format("%06d.bin", path.getPathID());
        Path classDir = outputDir.resolve(className);
        if (Files.notExists(classDir)) {
          Files.createDirectories(classDir);
        }

        Path assetFile = classDir.resolve(assetFileName);

        L.log(Level.INFO, "Writing {0} {1}", new Object[] {className, assetFileName});

        ByteBuffer bbAsset = asset.getPathBuffer(path);

        try {
          ByteBufferUtils.save(assetFile, bbAsset);
        } catch (Exception ex) {
          L.log(Level.WARNING, "Can't write " + path + " to " + assetFile, ex);
        }
      } else {
        AssetExtractHandler handler = getHandler(className);

        if (handler != null) {
          UnityObject obj;

          try {
            obj = deser.deserialize(path);
          } catch (Exception ex) {
            L.log(Level.WARNING, "Can't deserialize " + path, ex);
            continue;
          }

          try {
            handler.setObjectPath(path);
            handler.extract(obj);
          } catch (Exception ex) {
            L.log(Level.WARNING, "Can't extract " + path, ex);
          }
        }
      }
    }
  }
Exemplo n.º 12
0
  @Test
  public void delete_file_java_apache() {

    Path path = Paths.get(DEST);

    FileUtils.deleteQuietly(path.toFile());

    assertTrue(Files.notExists(path));
  }
Exemplo n.º 13
0
  @Test
  public void delete_file_java_nio() throws IOException {

    Path path = Paths.get(DEST);

    java.nio.file.Files.delete(path);

    assertTrue(Files.notExists(path));
  }
Exemplo n.º 14
0
  public static boolean isValidChecksum(Path filePath) throws IOException {
    if (Files.notExists(filePath)
        || (Files.size(filePath) > PropsValues.SYNC_FILE_CHECKSUM_THRESHOLD_SIZE)) {

      return false;
    }

    return true;
  }
Exemplo n.º 15
0
  public static void delete(
      Path dir, FileVisitor<? super Path> monitor, Set<FileVisitOption> options)
      throws IOException {
    if (Files.notExists(dir)) {
      return;
    }

    Files.walkFileTree(
        dir, options, Integer.MAX_VALUE, createMonitoredFileVisitor(new Delete<>(), monitor));
  }
Exemplo n.º 16
0
  private static String resolveCurrentModuleVersion() throws IOException {
    Path restxModuleDescriptor = Paths.get(".").resolve("md.restx.json");
    if (Files.notExists(restxModuleDescriptor)) {
      throw new FileNotFoundException("md.restx.json not found !");
    }

    try (FileInputStream fis = new FileInputStream(restxModuleDescriptor.toFile()); ) {
      return new RestxJsonSupport().parse(fis).getGav().getVersion();
    }
  }
Exemplo n.º 17
0
  Writer getConfigurationWriter() throws IOException {
    final String configFilePath = getConfigurationFilePath();
    final Path configFile = Paths.get(configFilePath);

    if (Files.notExists(configFile)) {
      Files.createDirectories(configFile.getParent());
      Files.createFile(configFile);
    }

    return new FileWriter(getConfigurationFilePath());
  }
Exemplo n.º 18
0
 private void createFolders(String username) {
   Path userPath = Paths.get(Paths.get(dataFolder, "data").toString(), username);
   if (Files.notExists(userPath)) {
     try {
       Files.createDirectories(userPath);
     } catch (IOException e) {
       System.out.println("Error creating user data reporting folder.");
       System.out.println(e);
     }
   }
 }
 private static String getEdgeDefaultPath() {
   if (OsUtils.isWindows()) {
     if (OsUtils.is64Bit()
         && (Files.exists(Paths.get("./drivers/edgedriver-windows-64bit"))
             || Files.notExists(Paths.get("./drivers/edgedriver-windows-32bit")))) {
       return "drivers/edgedriver-windows-64bit";
     } else {
       return "drivers/edgedriver-windows-32bit";
     }
   }
   return null;
 }
    static void delete(Path directory) {

      checkNotNullArgument(directory, "directory");
      if (Files.notExists(directory))
        throw new IllegalArgumentException("引数directoryには実在するパスを渡してください。");
      if (!Files.isDirectory(directory))
        throw new IllegalArgumentException("引数directoryにはディレクトリを渡してください。");

      try {
        Files.walkFileTree(directory, new DeleteVisitor());
      } catch (final IOException ex) {
        throw new RuntimeException(ex);
      }
    }
 private static String getPhantomJsDefaultPath() {
   if (OsUtils.isWindows()) {
     return "drivers/phantomjs-windows-64bit.exe";
   } else if (OsUtils.isMac()) {
     return "drivers/phantomjs-mac-64bit";
   } else if (OsUtils.isLinux()) {
     if (OsUtils.is64Bit()
         && (Files.exists(Paths.get("./drivers/phantomjs-linux-64bit"))
             || Files.notExists(Paths.get("./drivers/phantomjs-linux-32bit")))) {
       return "drivers/phantomjs-linux-64bit";
     } else {
       return "drivers/phantomjs-linux-32bit";
     }
   }
   return null;
 }
 // Returns an unoccupied filename based on 'file'.
 private static Path getTempFile(Path file) {
   Path retVal = null;
   if (file != null && Files.isRegularFile(file)) {
     final String fmt = ".%03d";
     Path filePath = file.getParent();
     String fileName = file.getFileName().toString();
     for (int i = 0; i < 1000; i++) {
       Path tmp = filePath.resolve(fileName + String.format(fmt, i));
       if (!Files.exists(tmp) && Files.notExists(tmp)) {
         retVal = tmp;
         break;
       }
     }
   }
   return retVal;
 }
Exemplo n.º 23
0
  private GridProjected queryGrid(Dataset dataset, List<TimeSlice> tss) throws IOException {

    // Create a bounding box that encompasses all time slices.
    Box smbounds = timeSliceUtil.aggregateBounds(tss);
    if (smbounds == null) throw new IOException("Could not determine bounds: no time slices.");

    BoxReal bounds = new BoxReal(2);
    bounds.getMin().setX(smbounds.getXMin());
    bounds.getMin().setY(smbounds.getYMin());
    bounds.getMax().setX(smbounds.getXMax());
    bounds.getMax().setY(smbounds.getYMax());

    // Resolution.
    double cellSize = dataset.getResolution().toDouble();
    VectorReal resolution = VectorReal.createEmpty(2);
    resolution.setX(cellSize);
    resolution.setY(cellSize);

    // All files for a given dataset share a common coordinate system. So,
    // we can just open one of the blank files and take a peek at it.
    CoordinateSystem srs = null;
    List<Band> bands = datasetDao.getBands(dataset.getId());
    for (Band b : bands) {
      Path blankTilePath = bandUtil.getBlankTilePath(dataset, b);
      if (Files.notExists(blankTilePath)) continue;

      NetcdfDataset ncd = NetcdfDataset.openDataset(blankTilePath.toString());
      try {
        ncd.enhance();
        srs = ncd.getCoordinateSystems().get(0);
        break;
      } finally {
        ncd.close();
      }
    }
    if (srs == null) {
      throw new IOException(
          String.format(
              "Could not determine "
                  + "coordinate system for dataset %s. There may be no "
                  + "tiles, or the bounds in the database may not match the "
                  + "tiles stored on disk.",
              dataset));
    }

    return new GridProjected(bounds, resolution, srs);
  }
Exemplo n.º 24
0
  @Override
  public void processAsset(AssetFile asset) throws IOException {
    Path assetFile = asset.getSourceFile();
    Path assetDir = assetFile.getParent();
    String assetFileName = assetFile.getFileName().toString();
    String assetPath;

    if (assetDir == null) {
      assetPath = "";
    } else {
      assetPath = assetDir.toAbsolutePath().toString();
      assetPath = FilenameUtils.separatorsToUnix(assetPath) + "/";
    }

    // fix path for all assets with (shared)assets extension
    boolean changed = false;
    for (AssetRef ref : asset.getReferences()) {
      Path refFile = Paths.get(ref.getFilePath());
      String refExt = FilenameUtils.getExtension(refFile.getFileName().toString());
      if (refExt.endsWith("assets") && Files.notExists(refFile)) {
        String filePathOld = ref.getFilePath();
        String filePathNew = assetPath + FilenameUtils.getName(ref.getFilePath());
        Path refFileNew = Paths.get(filePathNew);

        if (Files.exists(refFileNew)) {
          L.log(Level.FINE, "Fixed reference: {0} -> {1}", new Object[] {filePathOld, filePathNew});
          ref.setFilePath(filePathNew);
          changed = true;
        } else {
          L.log(Level.FINE, "Fixed reference not found: {0}", refFileNew);
        }
      }
    }

    if (!changed) {
      L.fine("No references changed, skipping saving");
      return;
    }

    // create backup by renaming the original file
    Path assetFileBackup = assetFile.resolveSibling(assetFileName + ".bak");
    Files.move(assetFile, assetFileBackup, StandardCopyOption.REPLACE_EXISTING);

    // save asset
    asset.save(assetFile);
  }
  private void download() {
    if (validFile()) {
      Application app = ((AbstractComponent) subWindow).getApplication();
      String file2DL = AttachedDocumentsUtils.getBaseURL(app) + currentFile.getUrl();

      File file = new File(file2DL);
      if (Files.notExists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        getWindow()
            .showNotification(
                FactoryI18nManager.getI18nManager().getMessage(Messages.DIALOG_NONEXISTING_FILE),
                Notification.TYPE_ERROR_MESSAGE);
      } else {
        FileDownloadResource fileDL = new FileDownloadResource(file, app);
        fileDL.setOutputFile(currentFile.getName() + "." + currentFile.getExtension());
        getWindow().open(fileDL, "_top");
      }
    }
  }
Exemplo n.º 26
0
  private void insertFolder(
      Path apkPath, Map<String, String> zip_properties, File insert, String method, Path location)
      throws AndrolibException, IOException {
    try (FileSystem fs = FileSystems.newFileSystem(apkPath, null)) {
      Path root = fs.getPath("/");
      Path dest =
          fs.getPath(root.toString(), insert.getAbsolutePath().replace(location.toString(), ""));
      Path parent = dest.normalize();

      // check for folder existing in apkFileSystem
      if (parent != null && Files.notExists(parent)) {
        if (!Files.isDirectory(parent, LinkOption.NOFOLLOW_LINKS)) {
          Files.createDirectories(parent);
        }
      }
      fs.close();
    }
  }
Exemplo n.º 27
0
  public void rm(String fileName, boolean recursive) throws FileNotFoundException, IOException {
    Path file = getPath(fileName);

    if (Files.notExists(file)) {
      throw new FileNotFoundException(fileName);
    }

    if (Files.isDirectory(file) && !recursive) {
      String exMsg = "'%s' is Directory";
      throw new IOException(String.format(exMsg, fileName));
    }

    if (Files.isDirectory(file)) {
      rmDir(file);
    } else {
      Files.delete(file);
    }
  }
Exemplo n.º 28
0
  public static void createSymbolicLink(String src, String dest) {
    Path destPath = Paths.get(getPath(dest));
    Path srcPath = Paths.get(src);

    if (Files.notExists(srcPath) || !Files.isDirectory(srcPath)) {
      return;
    }

    if (Files.exists(destPath)) {
      return;
    }

    try {
      Files.createSymbolicLink(destPath, srcPath);
    } catch (IOException e) {
      log.warn(
          String.format("WebdavUtil.createSymbolicLink fail... src : %s, dest : %s", src, dest));
    }
  }
Exemplo n.º 29
0
 private void intialize() throws PAPException, IOException {
   //
   // Sanity check the repository path
   //
   if (this.repository == null) {
     throw new PAPException("No repository specified.");
   }
   if (Files.notExists(this.repository)) {
     Files.createDirectory(repository);
   }
   if (!Files.isDirectory(this.repository)) {
     throw new PAPException("Repository is NOT a directory: " + this.repository.toAbsolutePath());
   }
   if (!Files.isWritable(this.repository)) {
     throw new PAPException("Repository is NOT writable: " + this.repository.toAbsolutePath());
   }
   //
   // Load our groups
   //
   this.loadGroups();
 }
Exemplo n.º 30
0
  /**
   * Unmarshalls the given file. The root class of the XML must be given.
   *
   * @param <T> Type of root object.
   * @param path Path to file to unmarshall.
   * @param schemaPath Path to the XSD schema that will be used to validate the XML file. If no
   *     schema is provided no validation will be performed.
   * @param rootClass Root class of the XML document.
   * @return Unmarshalled object.
   * @throws JAXBException If {@link JAXBException} occurs during loading.
   * @throws IOException If {@link IOException} occurs during loading.
   * @throws SAXException If {@link SAXException} occurs during schema parsing.
   */
  @SuppressWarnings("unchecked")
  public <T> T unmarshall(Path path, Path schemaPath, Class<T> rootClass)
      throws JAXBException, IOException, SAXException {
    if (Files.notExists(path) || Files.isDirectory(path)) {
      return null;
    }

    JAXBContext context = JAXBContext.newInstance(rootClass);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    if (null != schemaPath && Files.exists(schemaPath)) {
      SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      try (InputStream inputStream = Files.newInputStream(schemaPath, StandardOpenOption.READ)) {
        Schema schema = sf.newSchema(new StreamSource(inputStream));
        unmarshaller.setSchema(schema);
      }
    }

    try (InputStream inputStream = Files.newInputStream(path, StandardOpenOption.READ)) {
      return (T) unmarshaller.unmarshal(inputStream);
    }
  }