java.io.UncheckedIOException Java Examples

The following examples show how to use java.io.UncheckedIOException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Archive.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isSameLocation(Archive archive, Archive other) {
    if (archive.path == null || other.path == null)
        return false;

    if (archive.location != null && other.location != null &&
            archive.location.equals(other.location)) {
        return true;
    }

    if (archive.isJrt() || other.isJrt()) {
        return false;
    }

    try {
        return Files.isSameFile(archive.path, other.path);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #2
Source File: Configure.java    From redis-rdb-cli with Apache License 2.0 6 votes vote down vote up
private Configure() {
    this.properties = new Properties();
    try {
        String path = System.getProperty("conf");
        if (path != null && path.trim().length() != 0) {
            try (InputStream in = new FileInputStream(path)) {
                properties.load(in);
            }
        } else {
            ClassLoader loader = Configure.class.getClassLoader();
            try (InputStream in = loader.getResourceAsStream("redis-rdb-cli.conf")) {
                properties.load(in);
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #3
Source File: LocalComputationManager.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
public static ComputationManager getDefault() {
    LOCK.lock();
    try {
        if (defaultInstance == null) {
            try {
                defaultInstance = new LocalComputationManager();
                Runtime.getRuntime().addShutdownHook(new Thread(() -> defaultInstance.close()));
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        return defaultInstance;
    } finally {
        LOCK.unlock();
    }
}
 
Example #4
Source File: StreamTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #5
Source File: ZipFile.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the ZIP file.
 *
 * <p> Closing this ZIP file will close all of the input streams
 * previously returned by invocations of the {@link #getInputStream
 * getInputStream} method.
 *
 * @throws IOException if an I/O error has occurred
 */
public void close() throws IOException {
    if (closeRequested) {
        return;
    }
    closeRequested = true;

    synchronized (this) {
        // Close streams, release their inflaters, release cached inflaters
        // and release zip source
        try {
            res.clean();
        } catch (UncheckedIOException ioe) {
            throw ioe.getCause();
        }
    }
}
 
Example #6
Source File: WriteStyleablesProcessor.java    From shrinker with Apache License 2.0 6 votes vote down vote up
@Override
public void proceed() {
    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    writer.visit(Opcodes.V1_6,
            Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC | Opcodes.ACC_SUPER,
            RSymbols.R_STYLEABLES_CLASS_NAME,
            null,
            "java/lang/Object",
            null);
    for (String name : symbols.getStyleables().keySet()) {
        writer.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, name, "[I", null, null);
    }

    writeClinit(writer);
    writer.visitEnd();
    byte[] bytes = writer.toByteArray();
    try {
        if (!dir.isDirectory() && !dir.mkdirs()) {
            throw new RuntimeException("Cannot mkdir " + dir);
        }
        Files.write(dir.toPath().resolve(RSymbols.R_STYLEABLES_CLASS_NAME + ".class"), bytes);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #7
Source File: MapBasedConfig.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("ResultOfMethodCallIgnored")
void write() {
    File out = new File("target/test-classes/META-INF/microprofile-config.properties");
    if (out.isFile()) {
        out.delete();
    }
    out.getParentFile().mkdirs();

    Properties properties = new Properties();
    map.forEach((key, value) -> properties.setProperty(key, value.toString()));
    try (FileOutputStream fos = new FileOutputStream(out)) {
        properties.store(fos, "file generated for testing purpose");
        fos.flush();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #8
Source File: JmodTask.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private boolean extract() throws IOException {
    Path dir = options.extractDir != null ? options.extractDir : CWD;
    try (JmodFile jf = new JmodFile(options.jmodFile)) {
        jf.stream().forEach(e -> {
            try {
                ZipEntry entry = e.zipEntry();
                String name = entry.getName();
                int index = name.lastIndexOf("/");
                if (index != -1) {
                    Path p = dir.resolve(name.substring(0, index));
                    if (Files.notExists(p))
                        Files.createDirectories(p);
                }

                try (OutputStream os = Files.newOutputStream(dir.resolve(name))) {
                    jf.getInputStream(e).transferTo(os);
                }
            } catch (IOException x) {
                throw new UncheckedIOException(x);
            }
        });

        return true;
    }
}
 
Example #9
Source File: Main.java    From bazel-tools with Apache License 2.0 6 votes vote down vote up
private static void describeFile(
    final Path workspaceDirectory, final Path path, final PrintWriter out) {
  final Path relativeFileName = workspaceDirectory.relativize(path);
  if (Files.isDirectory(path)) {
    // Do nothing
  } else if (Files.isSymbolicLink(path)) {
    out.printf("link\t%s\t%s\t%s\n", Strings.repeat("-", 32), relativeFileName, readLink(path));
  } else if (Files.isRegularFile(path)) {
    final HashCode sha256;

    try {
      sha256 = PathUtils.sha256(path);
    } catch (IOException e) {
      throw new UncheckedIOException("Could not compute sha256 of " + path, e);
    }

    out.printf("file\t%s\t%s\n", sha256, relativeFileName);
  } else {
    throw new IllegalStateException("Path " + path + " is an unsupported type");
  }
}
 
Example #10
Source File: EvaluateClassifierPredictionsStateSerializer.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public void deserialize(Block block, int index, EvaluateClassifierPredictionsState state)
{
    Slice slice = VARCHAR.getSlice(block, index);
    Map<String, Map<String, Integer>> jsonState;
    try {
        jsonState = OBJECT_MAPPER.readValue(slice.getBytes(), new TypeReference<Map<String, Map<String, Integer>>>() {});
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    state.addMemoryUsage(slice.length());
    state.getTruePositives().putAll(jsonState.getOrDefault(TRUE_POSITIVES, ImmutableMap.of()));
    state.getFalsePositives().putAll(jsonState.getOrDefault(FALSE_POSITIVES, ImmutableMap.of()));
    state.getFalseNegatives().putAll(jsonState.getOrDefault(FALSE_NEGATIVES, ImmutableMap.of()));
}
 
Example #11
Source File: PartitionData.java    From presto with Apache License 2.0 6 votes vote down vote up
public String toJson()
{
    try {
        StringWriter writer = new StringWriter();
        JsonGenerator generator = FACTORY.createGenerator(writer);
        generator.writeStartObject();
        generator.writeArrayFieldStart(PARTITION_VALUES_FIELD);
        for (Object value : partitionValues) {
            generator.writeObject(value);
        }
        generator.writeEndArray();
        generator.writeEndObject();
        generator.flush();
        return writer.toString();
    }
    catch (IOException e) {
        throw new UncheckedIOException("JSON conversion failed for PartitionData: " + Arrays.toString(partitionValues), e);
    }
}
 
Example #12
Source File: AbstractResourceBundleProvider.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@code ResourceBundle} for the given {@code baseName} and
 * {@code locale}.
 *
 * @implNote
 * The default implementation of this method calls the
 * {@link #toBundleName(String, Locale) toBundleName} method to get the
 * bundle name for the {@code baseName} and {@code locale} and finds the
 * resource bundle of the bundle name local in the module of this provider.
 * It will only search the formats specified when this provider was
 * constructed.
 *
 * @param baseName the base bundle name of the resource bundle, a fully
 *                 qualified class name.
 * @param locale the locale for which the resource bundle should be instantiated
 * @return {@code ResourceBundle} of the given {@code baseName} and
 *         {@code locale}, or {@code null} if no resource bundle is found
 * @throws NullPointerException if {@code baseName} or {@code locale} is
 *         {@code null}
 * @throws UncheckedIOException if any IO exception occurred during resource
 *         bundle loading
 */
@Override
public ResourceBundle getBundle(String baseName, Locale locale) {
    Module module = this.getClass().getModule();
    String bundleName = toBundleName(baseName, locale);
    ResourceBundle bundle = null;

    for (String format : formats) {
        try {
            if (FORMAT_CLASS.equals(format)) {
                bundle = loadResourceBundle(module, bundleName);
            } else if (FORMAT_PROPERTIES.equals(format)) {
                bundle = loadPropertyResourceBundle(module, bundleName);
            }
            if (bundle != null) {
                break;
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
    return bundle;
}
 
Example #13
Source File: HashesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void makeJar(String moduleName, String... options) {
    Path mclasses = mods.resolve(moduleName);
    Path outfile = lib.resolve(moduleName + ".jar");
    List<String> args = new ArrayList<>();
    Stream.concat(Stream.of("--create",
                            "--file=" + outfile.toString()),
                  Arrays.stream(options))
          .forEach(args::add);
    args.add("-C");
    args.add(mclasses.toString());
    args.add(".");

    if (Files.exists(outfile)) {
        try {
            Files.delete(outfile);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    int rc = JAR_TOOL.run(System.out, System.out, args.toArray(new String[args.size()]));
    System.out.println("jar " + args.stream().collect(Collectors.joining(" ")));
    if (rc != 0) {
        throw new AssertionError("jar failed: rc = " + rc);
    }
}
 
Example #14
Source File: ItoolsPackagerMojo.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private void copyFiles(CopyTo copyTo, Path destDir) {
    if (copyTo != null) {
        for (File file : copyTo.getFiles()) {
            Path path = file.toPath();
            if (Files.exists(path)) {
                getLog().info("Copy file " + path + " to " + destDir);
                try {
                    Files.copy(path, destDir.resolve(path.getFileName().toString()), StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            } else {
                getLog().warn("File " + path + " not found");
            }
        }
    }
}
 
Example #15
Source File: IncrementalRuleCodegen.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static IncrementalRuleCodegen ofJar(Path... jarPaths) {
    Collection<Resource> resources = new ArrayList<>();

    for (Path jarPath : jarPaths) {
        try (ZipFile zipFile = new ZipFile( jarPath.toFile() )) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                ResourceType resourceType = determineResourceType( entry.getName() );
                if ( resourceType != null ) {
                    InternalResource resource = new ByteArrayResource( readBytesFromInputStream( zipFile.getInputStream( entry ) ) );
                    resource.setResourceType( resourceType );
                    resource.setSourcePath( entry.getName() );
                    resources.add( resource );
                }
            }
        } catch (IOException e) {
            throw new UncheckedIOException( e );
        }
    }

    return new IncrementalRuleCodegen(resources);
}
 
Example #16
Source File: JdepsConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private List<Path> getClassPaths(String cpaths) {
    if (cpaths.isEmpty()) {
        return Collections.emptyList();
    }
    List<Path> paths = new ArrayList<>();
    for (String p : cpaths.split(File.pathSeparator)) {
        if (p.length() > 0) {
            // wildcard to parse all JAR files e.g. -classpath dir/*
            int i = p.lastIndexOf(".*");
            if (i > 0) {
                Path dir = Paths.get(p.substring(0, i));
                try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.jar")) {
                    for (Path entry : stream) {
                        paths.add(entry);
                    }
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            } else {
                paths.add(Paths.get(p));
            }
        }
    }
    return paths;
}
 
Example #17
Source File: StreamTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void validateFileSystemLoopException(Path start, Path... causes) {
    try (Stream<Path> s = Files.walk(start, FileVisitOption.FOLLOW_LINKS)) {
        try {
            int count = s.mapToInt(p -> 1).reduce(0, Integer::sum);
            fail("Should got FileSystemLoopException, but got " + count + "elements.");
        } catch (UncheckedIOException uioe) {
            IOException ioe = uioe.getCause();
            if (ioe instanceof FileSystemLoopException) {
                FileSystemLoopException fsle = (FileSystemLoopException) ioe;
                boolean match = false;
                for (Path cause: causes) {
                    if (fsle.getFile().equals(cause.toString())) {
                        match = true;
                        break;
                    }
                }
                assertTrue(match);
            } else {
                fail("Unexpected UncheckedIOException cause " + ioe.toString());
            }
        }
    } catch(IOException ex) {
        fail("Unexpected IOException " + ex);
    }
}
 
Example #18
Source File: Jar.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
private Jar(Path path) {
    this.path = assertFile(path); // Absolute and normalized
    this.isJmod = fileName(path).endsWith(JMOD_SUFFIX);
    try {
        this.jar = new JarFile(path.toFile());
        this.manifest = jar.getManifest();
        this.isMultiRelease = !isJmod && isMultiRelease(manifest);
        this.isSigned = !isJmod && hasSignatureFile();
        this.isBeansArchive = !isJmod && hasEntry(BEANS_RESOURCE_PATH);
        final Entry moduleInfo = findEntry(isJmod ? JMOD_CLASSES_PREFIX + MODULE_INFO_CLASS : MODULE_INFO_CLASS);
        if (moduleInfo != null) {
            this.descriptor = ModuleDescriptor.read(moduleInfo.data());
        } else {
            this.descriptor = null;
        }
        this.resources = new AtomicReference<>();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #19
Source File: JmodTask.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the set of all packages on the given class path.
 */
Set<String> findPackages(List<Path> classpath) {
    Set<String> packages = new HashSet<>();
    for (Path path : classpath) {
        if (Files.isDirectory(path)) {
            packages.addAll(findPackages(path));
        } else if (Files.isRegularFile(path) && path.toString().endsWith(".jar")) {
            try (JarFile jf = new JarFile(path.toString())) {
                packages.addAll(findPackages(jf));
            } catch (ZipException x) {
                // Skip. Do nothing. No packages will be added.
            } catch (IOException ioe) {
                throw new UncheckedIOException(ioe);
            }
        }
    }
    return packages;
}
 
Example #20
Source File: AbstractUncompressedDataChunk.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public void writeJson(JsonGenerator generator) {
    Objects.requireNonNull(generator);
    try {
        generator.writeStartObject();
        generator.writeNumberField("offset", offset);
        generator.writeFieldName("values");
        writeValuesJson(generator);
        generator.writeEndObject();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #21
Source File: WebpSuggester.java    From size-analyzer with Apache License 2.0 5 votes vote down vote up
static BufferedImage safelyParseImage(InputStream inputStream) throws ImageReadException {
  try {
    return Imaging.getBufferedImage(inputStream);
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #22
Source File: GitCloner.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
public void removeClone() {
    if (targetFolder != null) {
        try {
            Files.walk(targetFolder.toPath(), FileVisitOption.FOLLOW_LINKS)
                .sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
            targetFolder.delete();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
 
Example #23
Source File: BufferDirectCellManager.java    From yosegi with Apache License 2.0 5 votes vote down vote up
@Override
public void setPrimitiveObjectArray(
    final IExpressionIndex indexList ,
    final int start ,
    final int length ,
    final IMemoryAllocator allocator ) {
  int loopEnd = ( start + length );
  if ( indexList.size() < loopEnd ) {
    loopEnd = indexList.size();
  }
  try {
    int index = 0;
    for ( int i = start ; i < loopEnd ; i++,index++ ) {
      int targetIndex = indexList.get( i );
      if ( indexSize <= targetIndex ) {
        break;
      }
      PrimitiveObject obj = dicManager.get( targetIndex );
      if ( obj == null ) {
        allocator.setNull( index );
      } else {
        allocator.setPrimitiveObject( index , obj );
      }
    }
    for ( int i = index ; i < length ; i++ ) {
      allocator.setNull( i );
    }
  } catch ( IOException ex ) {
    throw new UncheckedIOException( ex );
  }
}
 
Example #24
Source File: GrpcReplicationClient.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public StreamDownloader(long containerId, CompletableFuture<Path> response,
    Path outputPath) {
  this.response = response;
  this.containerId = containerId;
  this.outputPath = outputPath;
  try {
    Preconditions.checkNotNull(outputPath, "Output path cannot be null");
    Path parentPath = Preconditions.checkNotNull(outputPath.getParent());
    Files.createDirectories(parentPath);
    stream = new FileOutputStream(outputPath.toFile());
  } catch (IOException e) {
    throw new UncheckedIOException(
        "Output path can't be used: " + outputPath, e);
  }
}
 
Example #25
Source File: JavaRuntime.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private Runtime.Version findVersion() {
    final Path javaBase = assertFile(jmodsDir.resolve(JAVA_BASE_JMOD));
    try (ZipFile zip = new ZipFile(javaBase.toFile())) {
        final ZipEntry entry = zip.getEntry(JMOD_MODULE_INFO_PATH);
        if (entry == null) {
            throw new IllegalStateException("Cannot find " + JMOD_MODULE_INFO_PATH + " in " + javaBase);
        }
        final ModuleDescriptor descriptor = ModuleDescriptor.read(zip.getInputStream(entry));
        return Runtime.Version.parse(descriptor.version()
                                               .orElseThrow(() -> new IllegalStateException("No version in " + javaBase))
                                               .toString());
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #26
Source File: TagsCheck.java    From skara with GNU General Public License v2.0 5 votes vote down vote up
@Override
Iterator<Issue> check(ReadOnlyRepository repo) {
    log.finer("Allowed tags: " + allowed.toString());
    try {
        return repo.tags()
                   .stream()
                   .filter(t -> !isAllowed(t, repo))
                   .map(t -> (Issue) new TagIssue(t, this))
                   .iterator();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #27
Source File: Json.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Serialize {@link JsonNode} as a {@link String}.
 */
public static String asString(JsonNode data) {
  try {
    return MAPPER.writeValueAsString(data);
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example #28
Source File: MaxLengthBasedArrayColumnBinaryMaker.java    From yosegi with Apache License 2.0 5 votes vote down vote up
@Override
public IColumn get() {
  if ( ! isCreate ) {
    try {
      create();
    } catch ( IOException ex ) {
      throw new UncheckedIOException( ex );
    }
  }
  return arrayColumn;
}
 
Example #29
Source File: StreamTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void checkMalformedInputException(Stream<String> s) {
    try {
        List<String> lines = s.collect(Collectors.toList());
        fail("UncheckedIOException expected");
    } catch (UncheckedIOException ex) {
        IOException cause = ex.getCause();
        assertTrue(cause instanceof MalformedInputException,
            "MalformedInputException expected");
    }
}
 
Example #30
Source File: AstUtil.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
public static String toString(BlockStatement blockStatement) {
    try (StringWriter writer = new StringWriter()) {
        blockStatement.visit(new AstNodeToScriptVisitor(writer));
        writer.flush();
        return writer.toString();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}