Java Code Examples for java.nio.file.NoSuchFileException

The following are top voted examples for showing how to use java.nio.file.NoSuchFileException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rdf-delta   File: S_Data.java   View source code 8 votes vote down vote up
@Override
protected void executeAction(DeltaAction action) throws IOException {
    LOG.info("GET "+action.getURL());
    Id dsRef = Id.fromString(action.httpArgs.datasourceName);
    String filenameIRI = determineData(action, dsRef);
    ContentType ct = RDFLanguages.guessContentType(filenameIRI) ;
    String fn = IRILib.IRIToFilename(filenameIRI);
    Path path = Paths.get(fn);
    try ( InputStream in = Files.newInputStream(path) ) {
        action.response.setStatus(HttpSC.OK_200);
        action.response.setContentType(ct.getContentType());
        IOUtils.copy(in, action.response.getOutputStream());
    } catch (NoSuchFileException | FileNotFoundException ex) {
        throw new DeltaNotFoundException(action.getURL());
    }
}
 
Example 2
Project: uavstack   File: ReliableTaildirEventReader.java   View source code 7 votes vote down vote up
private long getInode(File file) throws IOException {

        UserDefinedFileAttributeView view = null;
        // windows system and file customer Attribute
        if (OS_WINDOWS.equals(os)) {
            view = Files.getFileAttributeView(file.toPath(), UserDefinedFileAttributeView.class);// 把文件的内容属性值放置在view里面?
            try {
                ByteBuffer buffer = ByteBuffer.allocate(view.size(INODE));// view.size得到inode属性值大小
                view.read(INODE, buffer);// 把属性值放置在buffer中
                buffer.flip();
                return Long.parseLong(Charset.defaultCharset().decode(buffer).toString());// 返回编码后的inode的属性值

            }
            catch (NoSuchFileException e) {
                long winode = random.nextLong();
                view.write(INODE, Charset.defaultCharset().encode(String.valueOf(winode)));
                return winode;
            }
        }
        long inode = (long) Files.getAttribute(file.toPath(), "unix:ino");// 返回unix的inode的属性值
        return inode;
    }
 
Example 3
Project: Reer   File: WatchServiceRegistrar.java   View source code 6 votes vote down vote up
protected void watchDir(Path dir) throws IOException {
    LOG.debug("Registering watch for {}", dir);
    if (Thread.currentThread().isInterrupted()) {
        LOG.debug("Skipping adding watch since current thread is interrupted.");
    }

    // check if directory is already watched
    // on Windows, check if any parent is already watched
    for (Path path = dir; path != null; path = FILE_TREE_WATCHING_SUPPORTED ? path.getParent() : null) {
        WatchKey previousWatchKey = watchKeys.get(path);
        if (previousWatchKey != null && previousWatchKey.isValid()) {
            LOG.debug("Directory {} is already watched and the watch is valid, not adding another one.", path);
            return;
        }
    }

    int retryCount = 0;
    IOException lastException = null;
    while (retryCount++ < 2) {
        try {
            WatchKey watchKey = dir.register(watchService, WATCH_KINDS, WATCH_MODIFIERS);
            watchKeys.put(dir, watchKey);
            return;
        } catch (IOException e) {
            LOG.debug("Exception in registering for watching of " + dir, e);
            lastException = e;

            if (e instanceof NoSuchFileException) {
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            }

            if (e instanceof FileSystemException && e.getMessage() != null && e.getMessage().contains("Bad file descriptor")) {
                // retry after getting "Bad file descriptor" exception
                LOG.debug("Retrying after 'Bad file descriptor'");
                continue;
            }

            // Windows at least will sometimes throw odd exceptions like java.nio.file.AccessDeniedException
            // if the file gets deleted while the watch is being set up.
            // So, we just ignore the exception if the dir doesn't exist anymore
            if (!Files.exists(dir)) {
                // return silently when directory doesn't exist
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            } else {
                // no retry
                throw e;
            }
        }
    }
    LOG.debug("Retry count exceeded, throwing last exception");
    throw lastException;
}
 
Example 4
Project: joanne   File: ErrorLogger.java   View source code 6 votes vote down vote up
public void prepareErrorList(){
    
    errors.put(new Exception(), Integer.MIN_VALUE);
    errors.put(new NullPointerException(), 10);
    errors.put(new NoSuchFileException("The file could not be found. Sorry for the inconvience"), 20);
    errors.put(new IllegalStateException(), 30);
    errors.put(new FileNotFoundException(), 200);
    errors.put(new AccessDeniedException("The account "+System.getProperty("user.name")+"\nhas not the privileges to do this action."), 40);
    errors.put(new ArrayIndexOutOfBoundsException(),  50);
    errors.put(new UnsupportedOperationException(), 60);
    errors.put(new IOException(), 70);
    errors.put(new MalformedURLException(), 80);
    errors.put(new IllegalArgumentException(), 90);
    
    desc.put(10,"NullPointerException - w którymś momencie w kodzie została napotkana wartość null.");
    desc.put(30,"The value or component has tried to gain illegal state.");
    desc.put(200, "The given file hasn't been found, asure that you gave\nan absolute path and the file exists!");
    desc.put(50, "The index is out of range; it means that the method tried to access the index which is\n"
            + "not in that array.");
    desc.put(60, "Requested operation is not supported at the moment.");
    desc.put(70, "The problem was occured while operating on Input/Output streams.");
    desc.put(90, "The argument given was illegal.");
    desc.put(80, "Given URL is malformed, check\nthat you have write a proper URL address");
}
 
Example 5
Project: elasticsearch_my   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * Returns the json files found within the directory provided as argument.
 * Files are looked up in the classpath, or optionally from {@code fileSystem} if its not null.
 */
public static Set<Path> findJsonSpec(FileSystem fileSystem, String optionalPathPrefix, String path) throws IOException {
    Path dir = resolveFile(fileSystem, optionalPathPrefix, path, null);

    if (!Files.isDirectory(dir)) {
        throw new NotDirectoryException(path);
    }

    Set<Path> jsonFiles = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path item : stream) {
            if (item.toString().endsWith(JSON_SUFFIX)) {
                jsonFiles.add(item);
            }
        }
    }

    if (jsonFiles.isEmpty()) {
        throw new NoSuchFileException(path, null, "no json files found");
    }

    return jsonFiles;
}
 
Example 6
Project: elasticsearch_my   File: BlobStoreRepository.java   View source code 6 votes vote down vote up
/**
 * Get the latest snapshot index blob id.  Snapshot index blobs are named index-N, where N is
 * the next version number from when the index blob was written.  Each individual index-N blob is
 * only written once and never overwritten.  The highest numbered index-N blob is the latest one
 * that contains the current snapshots in the repository.
 *
 * Package private for testing
 */
long latestIndexBlobId() throws IOException {
    try {
        // First, try listing all index-N blobs (there should only be two index-N blobs at any given
        // time in a repository if cleanup is happening properly) and pick the index-N blob with the
        // highest N value - this will be the latest index blob for the repository.  Note, we do this
        // instead of directly reading the index.latest blob to get the current index-N blob because
        // index.latest is not written atomically and is not immutable - on every index-N change,
        // we first delete the old index.latest and then write the new one.  If the repository is not
        // read-only, it is possible that we try deleting the index.latest blob while it is being read
        // by some other operation (such as the get snapshots operation).  In some file systems, it is
        // illegal to delete a file while it is being read elsewhere (e.g. Windows).  For read-only
        // repositories, we read for index.latest, both because listing blob prefixes is often unsupported
        // and because the index.latest blob will never be deleted and re-written.
        return listBlobsToGetLatestIndexId();
    } catch (UnsupportedOperationException e) {
        // If its a read-only repository, listing blobs by prefix may not be supported (e.g. a URL repository),
        // in this case, try reading the latest index generation from the index.latest blob
        try {
            return readSnapshotIndexLatestBlob();
        } catch (NoSuchFileException nsfe) {
            return RepositoryData.EMPTY_REPO_GEN;
        }
    }
}
 
Example 7
Project: elasticsearch_my   File: IndexFolderUpgrader.java   View source code 6 votes vote down vote up
/**
 * Moves the index folder found in <code>source</code> to <code>target</code>
 */
void upgrade(final Index index, final Path source, final Path target) throws IOException {
    boolean success = false;
    try {
        Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
        success = true;
    } catch (NoSuchFileException | FileNotFoundException exception) {
        // thrown when the source is non-existent because the folder was renamed
        // by another node (shared FS) after we checked if the target exists
        logger.error((Supplier<?>) () -> new ParameterizedMessage("multiple nodes trying to upgrade [{}] in parallel, retry " +
            "upgrading with single node", target), exception);
        throw exception;
    } finally {
        if (success) {
            logger.info("{} moved from [{}] to [{}]", index, source, target);
            logger.trace("{} syncing directory [{}]", index, target);
            IOUtils.fsync(target, true);
        }
    }
}
 
Example 8
Project: elasticsearch_my   File: ExceptionSerializationTests.java   View source code 6 votes vote down vote up
public void testFileSystemExceptions() throws IOException {
    for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"),
        new NoSuchFileException("a", "b", "c"),
        new NotDirectoryException("a"),
        new DirectoryNotEmptyException("a"),
        new AtomicMoveNotSupportedException("a", "b", "c"),
        new FileAlreadyExistsException("a", "b", "c"),
        new AccessDeniedException("a", "b", "c"),
        new FileSystemLoopException("a"))) {

        FileSystemException serialize = serialize(ex);
        assertEquals(serialize.getClass(), ex.getClass());
        assertEquals("a", serialize.getFile());
        if (serialize.getClass() == NotDirectoryException.class ||
            serialize.getClass() == FileSystemLoopException.class ||
            serialize.getClass() == DirectoryNotEmptyException.class) {
            assertNull(serialize.getOtherFile());
            assertNull(serialize.getReason());
        } else {
            assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile());
            assertEquals(serialize.getClass().toString(), "c", serialize.getReason());
        }
    }
}
 
Example 9
Project: elasticsearch_my   File: S3BlobContainer.java   View source code 6 votes vote down vote up
@Override
public InputStream readBlob(String blobName) throws IOException {
    int retry = 0;
    while (retry <= blobStore.numberOfRetries()) {
        try {
            S3Object s3Object = SocketAccess.doPrivileged(() -> blobStore.client().getObject(blobStore.bucket(), buildKey(blobName)));
            return s3Object.getObjectContent();
        } catch (AmazonClientException e) {
            if (blobStore.shouldRetry(e) && (retry < blobStore.numberOfRetries())) {
                retry++;
            } else {
                if (e instanceof AmazonS3Exception) {
                    if (404 == ((AmazonS3Exception) e).getStatusCode()) {
                        throw new NoSuchFileException("Blob object [" + blobName + "] not found: " + e.getMessage());
                    }
                }
                throw e;
            }
        }
    }
    throw new BlobStoreException("retries exhausted while attempting to access blob object [name:" + blobName + ", bucket:" + blobStore.bucket() + "]");
}
 
Example 10
Project: centraldogma   File: FileBasedSessionDAO.java   View source code 6 votes vote down vote up
@Override
public SimpleSession readSession(Serializable sessionIdObj) {
    final String sessionId = ensureStringSessionId(sessionIdObj);
    final SimpleSession cachedSession = getFromCache(sessionId);
    if (cachedSession != null) {
        return cachedSession;
    }

    try {
        final SimpleSession session = uncachedRead(sessionId);
        updateCache(sessionId, session);
        return session;
    } catch (FileNotFoundException | NoSuchFileException unused) {
        // Unknown session
        throw new UnknownSessionException(sessionId);
    } catch (ClassNotFoundException | IOException e) {
        throw new SerializationException(e);
    }
}
 
Example 11
Project: guava-mock   File: MoreFiles.java   View source code 6 votes vote down vote up
/**
 * Like the unix command of the same name, creates an empty file or updates the last modified
 * timestamp of the existing file at the given path to the current system time.
 */
public static void touch(Path path) throws IOException {
  checkNotNull(path);

  try {
    Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
  } catch (NoSuchFileException e) {
    try {
      Files.createFile(path);
    } catch (FileAlreadyExistsException ignore) {
      // The file didn't exist when we called setLastModifiedTime, but it did when we called
      // createFile, so something else created the file in between. The end result is
      // what we wanted: a new file that probably has its last modified time set to approximately
      // now. Or it could have an arbitrary last modified time set by the creator, but that's no
      // different than if another process set its last modified time to something else after we
      // created it here.
    }
  }
}
 
Example 12
Project: state-channels   File: BlockStateManager.java   View source code 6 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    contractsManager = contractsManagerFactory.getMainContractManager();
    try {
        loadState();
    } catch (FileNotFoundException|NoSuchFileException ignored) {
        state = new BlockState();
        state.blockId = blockId;
        state.created = System.currentTimeMillis();
        storeState();
    }
    //TODO sync state with ethereum
    if (state.partCompleted.timestamp == 0) {
        writer = new FileBlockWriter(blockId, dataFile);
    }
    if (!isProcessingFinished()) {
        cycleTask = executorService.scheduleAtFixedRate(() -> {
            try {
                cycle();
            } catch (Exception e) {
                log.warn("Cycle failed", e);
            }
        }, 1, 1, TimeUnit.SECONDS);
    }
}
 
Example 13
Project: jdk8u-jdk   File: BlockDeviceSize.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example 14
Project: openjdk-jdk10   File: Scan.java   View source code 6 votes vote down vote up
/**
 * Scans a jar file for uses of deprecated APIs.
 *
 * @param jarname the jar file to process
 * @return true on success, false on failure
 */
public boolean scanJar(String jarname) {
    try (JarFile jf = new JarFile(jarname)) {
        out.println(Messages.get("scan.head.jar", jarname));
        finder.addJar(jarname);
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class")
                    && !name.endsWith("package-info.class")
                    && !name.endsWith("module-info.class")) {
                processClass(ClassFile.read(jf.getInputStream(entry)));
            }
        }
        return true;
    } catch (NoSuchFileException nsfe) {
        errorNoFile(jarname);
    } catch (IOException | ConstantPoolException ex) {
        errorException(ex);
    }
    return false;
}
 
Example 15
Project: openjdk-jdk10   File: Resources.java   View source code 6 votes vote down vote up
/**
 * Returns a file path to a resource in a file tree. If the resource
 * name has a trailing "/" then the file path will locate a directory.
 * Returns {@code null} if the resource does not map to a file in the
 * tree file.
 */
public static Path toFilePath(Path dir, String name) throws IOException {
    boolean expectDirectory = name.endsWith("/");
    if (expectDirectory) {
        name = name.substring(0, name.length() - 1);  // drop trailing "/"
    }
    Path path = toSafeFilePath(dir.getFileSystem(), name);
    if (path != null) {
        Path file = dir.resolve(path);
        try {
            BasicFileAttributes attrs;
            attrs = Files.readAttributes(file, BasicFileAttributes.class);
            if (attrs.isDirectory()
                || (!attrs.isDirectory() && !expectDirectory))
                return file;
        } catch (NoSuchFileException ignore) { }
    }
    return null;
}
 
Example 16
Project: openjdk-jdk10   File: BlockDeviceSize.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example 17
Project: googles-monorepo-demo   File: MoreFiles.java   View source code 6 votes vote down vote up
/**
 * Like the unix command of the same name, creates an empty file or updates the last modified
 * timestamp of the existing file at the given path to the current system time.
 */
public static void touch(Path path) throws IOException {
  checkNotNull(path);

  try {
    Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
  } catch (NoSuchFileException e) {
    try {
      Files.createFile(path);
    } catch (FileAlreadyExistsException ignore) {
      // The file didn't exist when we called setLastModifiedTime, but it did when we called
      // createFile, so something else created the file in between. The end result is
      // what we wanted: a new file that probably has its last modified time set to approximately
      // now. Or it could have an arbitrary last modified time set by the creator, but that's no
      // different than if another process set its last modified time to something else after we
      // created it here.
    }
  }
}
 
Example 18
Project: openjdk9   File: BlockDeviceSize.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example 19
Project: Mastering-Mesos   File: JsonObjectFileHelper.java   View source code 6 votes vote down vote up
public <T> Optional<T> read(Path file, Logger log, Class<T> clazz) throws IOException {
  final long start = System.currentTimeMillis();

  log.info("Reading {}", file);

  byte[] bytes = new byte[0];

  try {
    bytes = Files.readAllBytes(file);

    log.trace("Read {} bytes from {} in {}", bytes.length, file, JavaUtils.duration(start));

    if (bytes.length == 0) {
      return Optional.absent();
    }

    T object = objectMapper.readValue(bytes, clazz);
    return Optional.of(object);
  } catch (NoSuchFileException nsfe) {
    log.warn("File {} does not exist", file);
  } catch (IOException e) {
    log.warn("File {} is not a valid {} ({})", file, clazz.getSimpleName(), new String(bytes, UTF_8), e);
  }

  return Optional.absent();
}
 
Example 20
Project: apache-archiva   File: DuplicateArtifactsConsumerTest.java   View source code 6 votes vote down vote up
@Test
public void testConsumerArtifactFileNotExist()
    throws Exception
{
    consumer.beginScan( config, new Date() );
    try
    {
        consumer.processFile( "com/example/test/test-artifact/2.0/test-artifact-2.0.jar" );
        fail( "Should have failed to find file" );
    }
    catch ( ConsumerException e )
    {
        assertTrue( e.getCause() instanceof NoSuchFileException );
    }
    finally
    {
        consumer.completeScan();
    }

    verify( metadataRepository, never() ).addMetadataFacet( eq( TEST_REPO ), Matchers.<MetadataFacet>anyObject() );
}
 
Example 21
Project: mycore   File: MCRIView2Tools.java   View source code 6 votes vote down vote up
public static BufferedImage readTile(Path iviewFileRoot, ImageReader imageReader, int zoomLevel, int x, int y)
    throws IOException {
    String tileName = MessageFormat.format("{0}/{1}/{2}.jpg", zoomLevel, y, x);
    Path tile = iviewFileRoot.resolve(tileName);
    if (Files.exists(tile)) {
        try (SeekableByteChannel fileChannel = Files.newByteChannel(tile)) {
            ImageInputStream iis = ImageIO.createImageInputStream(fileChannel);
            if (iis == null) {
                throw new IOException("Could not acquire ImageInputStream from SeekableByteChannel: " + tile);
            }
            imageReader.setInput(iis, true);
            BufferedImage image = imageReader.read(0);
            imageReader.reset();
            iis.close();
            return image;
        }
    } else {
        throw new NoSuchFileException(iviewFileRoot.toString(), tileName, null);
    }
}
 
Example 22
Project: mycore   File: MCRIView2Tools.java   View source code 6 votes vote down vote up
public static int getImageType(Path iviewFileRoot, ImageReader imageReader, int zoomLevel, int x, int y)
    throws IOException {
    String tileName = MessageFormat.format("{0}/{1}/{2}.jpg", zoomLevel, y, x);
    Path tile = iviewFileRoot.resolve(tileName);
    if (Files.exists(tile)) {
        try (SeekableByteChannel fileChannel = Files.newByteChannel(tile)) {
            ImageInputStream iis = ImageIO.createImageInputStream(fileChannel);
            if (iis == null) {
                throw new IOException("Could not acquire ImageInputStream from SeekableByteChannel: " + tile);
            }
            imageReader.setInput(iis, true);
            int imageType = MCRImage.getImageType(imageReader);
            imageReader.reset();
            iis.close();
            return imageType;
        }
    } else {
        throw new NoSuchFileException(iviewFileRoot.toString(), tileName, null);
    }
}
 
Example 23
Project: mycore   File: MCRContentServlet.java   View source code 6 votes vote down vote up
@Override
protected void render(final MCRServletJob job, final Exception ex) throws Exception {
    if (ex != null) {
        throw ex;
    }
    final HttpServletRequest request = job.getRequest();
    final HttpServletResponse response = job.getResponse();
    final MCRContent content = getContent(request, response);
    boolean serveContent = MCRServletContentHelper.isServeContent(request);
    try {
        MCRServletContentHelper.serveContent(content, request, response, getServletContext(), getConfig(),
            serveContent);
    } catch (NoSuchFileException | FileNotFoundException e) {
        LOGGER.info("Catched {}:", e.getClass().getSimpleName(), e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }
    LOGGER.info("Finished serving resource.");
}
 
Example 24
Project: mycore   File: MCRCompressServlet.java   View source code 6 votes vote down vote up
private void sendDerivate(MCRObjectID id, String path, T container) throws IOException {

        MCRPath resolvedPath = MCRPath.getPath(id.toString(), path == null ? "/" : path);

        if (!Files.exists(resolvedPath)) {
            throw new NoSuchFileException(id.toString(), path, "Could not find path " + resolvedPath);
        }

        if (Files.isRegularFile(resolvedPath)) {
            BasicFileAttributes attrs = Files.readAttributes(resolvedPath, BasicFileAttributes.class);
            sendCompressedFile(resolvedPath, attrs, container);
            LOGGER.debug("file {} zipped", resolvedPath);
            return;
        }
        // root is a directory
        Files.walkFileTree(resolvedPath, new CompressVisitor<>(this, container));
    }
 
Example 25
Project: mycore   File: MCRAbstractFileSystem.java   View source code 6 votes vote down vote up
/**
 * Checks if the file for given Path is still valid.
 * 
 * This should check if the file is still completely readable and the MD5 sum still matches the recorded value.
 * This method does the same as {@link #verifies(MCRPath)} but uses the given attributes to save a file access.
 * @param path Path to the file to check
 * @param attrs matching attributes to file
 */
public boolean verifies(MCRPath path, MCRFileAttributes<?> attrs) throws NoSuchFileException {
    if (Files.notExists(Objects.requireNonNull(path, "Path may not be null."))) {
        throw new NoSuchFileException(path.toString());
    }
    Objects.requireNonNull(attrs, "attrs may not be null");
    String md5Sum;
    try {
        md5Sum = MCRUtils.getMD5Sum(Files.newInputStream(path));
    } catch (IOException e) {
        LogManager.getLogger(getClass()).error("Could not verify path: {}", path, e);
        return false;
    }
    boolean returns = md5Sum.matches(attrs.md5sum());
    if (!returns) {
        LogManager.getLogger(getClass()).warn("MD5sum does not match: {}", path);
    }
    return returns;
}
 
Example 26
Project: mycore   File: MCRFile.java   View source code 6 votes vote down vote up
/**
 * Opens a file, returning a seekable byte channel to access the file.
 * See
 * @throws  IllegalArgumentException
 *          if the set contains an invalid combination of options
 * @throws  UnsupportedOperationException
 *          if an unsupported open option is specified
 * @throws  IOException
 *          if an I/O error occurs
 *
 * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[])
 */
public FileChannel getFileChannel(Set<? extends OpenOption> options) throws IOException {
    for (OpenOption option : options) {
        checkOpenOption(option);
    }
    File localFile;
    try {
        localFile = getLocalFile();
    } catch (IOException e) {
        throw new NoSuchFileException(toPath().toString(), null, e.getMessage());
    }
    FileChannel fileChannel = FileChannel.open(localFile.toPath(), options);
    boolean write = options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND);
    boolean read = options.contains(StandardOpenOption.READ) || !write;
    return new MCRFileChannel(this, fileChannel, write);
}
 
Example 27
Project: mycore   File: MCRIFSFileSystem.java   View source code 6 votes vote down vote up
@Override
public void removeRoot(String owner) throws FileSystemException {
    MCRPath rootPath = getPath(owner, "", this);
    MCRDirectory rootDirectory = MCRDirectory.getRootDirectory(owner);
    if (rootDirectory == null) {
        throw new NoSuchFileException(rootPath.toString());
    }
    if (rootDirectory.isDeleted()) {
        return;
    }
    if (rootDirectory.hasChildren()) {
        throw new DirectoryNotEmptyException(rootPath.toString());
    }
    try {
        rootDirectory.delete();
    } catch (RuntimeException e) {
        LogManager.getLogger(getClass()).warn("Catched run time exception while removing root directory.", e);
        throw new FileSystemException(rootPath.toString(), null, e.getMessage());
    }
    LogManager.getLogger(getClass()).info("Removed root directory: {}", rootPath);
}
 
Example 28
Project: mycore   File: MCRFileSystemProvider.java   View source code 6 votes vote down vote up
@Override
public String load(MCRPath path) throws Exception {
    if (path.getNameCount() == 0) {
        return Optional.ofNullable(doResolvePath(path))
            .map(MCRFilesystemNode::getID)
            .orElseThrow(() -> new NoSuchFileException(path.toString(), null, "derivate does not exist"));
    }
    //recursive call
    String fileOrDir = path.getFileName().toString();
    MCRDirectory parentDir = Optional.ofNullable(resolvePath(path.getParent()))
        .map(MCRDirectory.class::cast)
        .orElseThrow(() -> new NoSuchFileException(path.getParent().toString(), fileOrDir,
            "parent directory does not exist"));

    return Optional.ofNullable(parentDir.getChild(fileOrDir))
        .map(MCRFilesystemNode::getID)
        .orElseThrow(
            () -> new NoSuchFileException(path.getParent().toString(), fileOrDir, "file does not exist"));
}
 
Example 29
Project: mycore   File: MCRFileSystemProvider.java   View source code 6 votes vote down vote up
private static MCRDirectory getParentDirectory(MCRPath mcrPath) throws NoSuchFileException, NotDirectoryException {
    if (mcrPath.getNameCount() == 0) {
        throw new IllegalArgumentException("Root component has no parent: " + mcrPath);
    }
    MCRDirectory rootDirectory = getRootDirectory(mcrPath);
    if (mcrPath.getNameCount() == 1) {
        return rootDirectory;
    }
    MCRPath parentPath = mcrPath.getParent();
    MCRFilesystemNode parentNode = rootDirectory.getChildByPath(getAbsolutePathFromRootComponent(parentPath)
        .toString());
    if (parentNode == null) {
        throw new NoSuchFileException(rootDirectory.toPath().toString(), getAbsolutePathFromRootComponent(mcrPath)
            .toString(), "Parent directory does not exists.");
    }
    if (parentNode instanceof MCRFile) {
        throw new NotDirectoryException(parentNode.toPath().toString());
    }
    MCRDirectory parentDir = (MCRDirectory) parentNode;
    parentDir.getChildren();//warm-up cache
    return parentDir;
}
 
Example 30
Project: mycore   File: MCRFileSystemProvider.java   View source code 6 votes vote down vote up
static MCRFilesystemNode resolvePath(MCRPath path) throws IOException {
    try {
        String ifsid = nodeCache.getUnchecked(path);
        MCRFilesystemNode node = MCRFilesystemNode.getNode(ifsid);
        if (node != null) {
            return node;
        }
        nodeCache.invalidate(path);
        return resolvePath(path);
    } catch (UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NoSuchFileException) {
            throw (NoSuchFileException) cause;
        }
        if (cause instanceof NotDirectoryException) {
            throw (NotDirectoryException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw e;
    }
}
 
Example 31
Project: mycore   File: MCRFileSystemProvider.java   View source code 6 votes vote down vote up
private static MCRFilesystemNode doResolvePath(MCRPath path) throws IOException {
    if (path.getNameCount() == 0) {
        //root components
        MCRDirectory rootDirectory = MCRDirectory.getRootDirectory(path.getOwner());
        if (rootDirectory == null) {
            throw new NoSuchFileException(path.toString());
        }
        rootDirectory.getChildren(); //prepare cache
        return rootDirectory;
    }
    MCRDirectory parent = getParentDirectory(path);
    MCRFilesystemNode child;
    try {
        child = parent.getChild(path.getFileName().toString());
    } catch (RuntimeException e) {
        throw new IOException(e);
    }
    if (child == null) {
        throw new NoSuchFileException(parent.toPath().toString(), path.toString(), null);
    }
    return child;
}
 
Example 32
Project: mycore   File: MCRDirectoryStream.java   View source code 6 votes vote down vote up
/**
 * Deletes {@link MCRFilesystemNode} if it exists.
 *
 * @param path
 *            relative or absolute
 * @throws IOException
 */
private void deleteFileSystemNode(MCRPath path) throws IOException {
    checkClosed();
    if (path.isAbsolute()) {
        Files.delete(path);
    }
    MCRFilesystemNode childByPath = dir.getChildByPath(path.toString());
    if (childByPath == null) {
        throw new NoSuchFileException(dir.toPath().toString(), path.toString(), null);
    }
    try {
        childByPath.delete();
    } catch (MCRPersistenceException e) {
        throw new IOException("Error whil deleting file system node.", e);
    }
}
 
Example 33
Project: mycore   File: MCRJWPlayerResource.java   View source code 6 votes vote down vote up
@GET
@Path("{derivateId}/{path: .+}/sources.json")
@Produces({ "application/javascript" })
public String getSources(@PathParam("derivateId") String derivateId, @PathParam("path") String path)
    throws URISyntaxException, IOException {
    MCRObjectID derivate = MCRJerseyUtil.getID(derivateId);
    MCRJerseyUtil.checkDerivateReadPermission(derivate);
    try {
        MCRMediaSourceProvider formatter = new MCRMediaSourceProvider(derivateId, path,
            Optional.ofNullable(request.getHeader("User-Agent")),
            () -> Arrays.stream(Optional.ofNullable(request.getQueryString()).orElse("").split("&"))
                .filter(p -> !p.startsWith("callback="))
                .toArray(String[]::new));
        return toJson(formatter.getSources());
    } catch (NoSuchFileException e) {
        LogManager.getLogger().warn("Could not find video file.", e);
        throw new WebApplicationException(Status.NOT_FOUND);
    }
}
 
Example 34
Project: baratine   File: JFileSystemProvider.java   View source code 6 votes vote down vote up
@Override
public void checkAccess(Path path, AccessMode... modes) throws IOException
{
  JPath jPath = (JPath) path;
  Status status;

  try {
    status = jPath.getBfsFile().getStatus();
  }
  catch (Exception e) {
    throw createIOException(e);
  }

  if (status.getType() == Status.FileType.FILE) {
    // do nothing
  }
  else if (status.getType() == Status.FileType.DIRECTORY) {
    // do nothing
  }
  else {
    throw new NoSuchFileException(path.toUri().toString());
  }
}
 
Example 35
Project: TorchEngine   File: Assets2.java   View source code 6 votes vote down vote up
private static String getPath(String path) throws NoSuchFileException
{
	String target = path;
	
	try
	{
		FileUtils.toURI(target + ".dat");
	}
	catch(NoSuchFileException e)
	{
		target = "torch_default/" + target;
		
		try
		{
			FileUtils.toURI(target + ".dat");
		}
		catch(NoSuchFileException ex)
		{
			throw new NoSuchFileException("No file found at " + path + " or " + target);
		}
	}
	
	return target;
}
 
Example 36
Project: TorchEngine   File: Texture2D.java   View source code 6 votes vote down vote up
Texture2D(String name)
{
	super(name);
	
	if(isCreator())
	{
		try
		{
			BufferedImage bufferedImage = TextureInternal.loadBufferedImage(name);
			create(bufferedImage);
		}
		catch(NoSuchFileException e)
		{
			destroy();
		}
	}
}
 
Example 37
Project: TorchEngine   File: Scene.java   View source code 6 votes vote down vote up
/**
 * <p>
 * Load the scene with the given {@code name}.
 * </p>
 *
 * @param name The name of the scene.
 */
public static void load(String name)
{
	LoggerInternal.log("Begin loading of scene: " + name);
	
	try
	{
		SceneParser.SceneData sceneData = (SceneParser.SceneData)XMLParser.decode(name + ".scene");
		
		create();
		
		for(GameObjectParser.GameObjectData gameObjectData : sceneData.gameObjectData)
		{
			GameObjectLoader.load(gameObjectData);
		}
	}
	catch(NoSuchFileException e)
	{
		Logger.logError(e.getMessage(), e);
	}
}
 
Example 38
Project: TorchEngine   File: FileUtils.java   View source code 6 votes vote down vote up
/**
 * <p>
 * Convert the path to a file to an {@link URI}.
 * </p>
 *
 * @param path The path to the file.
 * @return An {@code URI} representing the path.
 * @throws NoSuchFileException Thrown if the specified {@code path} does not exist.
 */
public static URI toURI(String path) throws NoSuchFileException
{
	try
	{
		URL resource = FileUtils.class.getResource("/" + path);
		if(resource != null)
		{
			return resource.toURI();
		}
	}
	catch(URISyntaxException e)
	{
		Logger.logError(e.toString(), e);
	}
	
	throw new NoSuchFileException("No file found at: " + path);
}
 
Example 39
Project: TorchEngine   File: Assets.java   View source code 6 votes vote down vote up
private static String getPath(String path) throws NoSuchFileException
{
	String target = path;
	
	try
	{
		FileUtils.toURI(target);
	}
	catch(NoSuchFileException e)
	{
		target = "torch_default/" + target;
		
		try
		{
			FileUtils.toURI(target);
		}
		catch(NoSuchFileException ex)
		{
			throw new NoSuchFileException("No file found at " + path + " or " + target);
		}
	}
	
	return target;
}
 
Example 40
Project: RedisHttpSession   File: RedisConfig.java   View source code 6 votes vote down vote up
private static String readConfig(){
    try {
        //read config file from src folder
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream is =  classLoader.getResourceAsStream(REDIS_CONFIG);
        if (is == null){
            throw new NoSuchFileException("Resource file not found. Note that the current directory is the source folder!");
        }
        StringBuilder sb = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
        String line = bufferedReader.readLine();
        while (line != null){
            sb.append(line);
            line = bufferedReader.readLine();
        }
        bufferedReader.close();
        is.close();

        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}