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 Project: redis-rdb-cli   Author: leonchen83   File: Configure.java    License: 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 #2
Source Project: Bytecoder   Author: mirkosertic   File: ZipFile.java    License: 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 #3
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: StreamTest.java    License: 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 #4
Source Project: shrinker   Author: yrom   File: WriteStyleablesProcessor.java    License: 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 #5
Source Project: powsybl-core   Author: powsybl   File: LocalComputationManager.java    License: 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 #6
Source Project: smallrye-reactive-messaging   Author: smallrye   File: MapBasedConfig.java    License: 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 #7
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JmodTask.java    License: 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 #8
Source Project: bazel-tools   Author: spotify   File: Main.java    License: 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 #9
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JmodTask.java    License: 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 #10
Source Project: presto   Author: prestosql   File: EvaluateClassifierPredictionsStateSerializer.java    License: 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 Project: TencentKona-8   Author: Tencent   File: StreamTest.java    License: 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 #12
Source Project: presto   Author: prestosql   File: PartitionData.java    License: 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 #13
Source Project: Bytecoder   Author: mirkosertic   File: AbstractResourceBundleProvider.java    License: 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 #14
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: HashesTest.java    License: 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 #15
Source Project: powsybl-core   Author: powsybl   File: ItoolsPackagerMojo.java    License: 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 #16
Source Project: kogito-runtimes   Author: kiegroup   File: IncrementalRuleCodegen.java    License: 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 #17
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: JdepsConfiguration.java    License: 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 #18
Source Project: helidon-build-tools   Author: oracle   File: Jar.java    License: 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 Project: openjdk-jdk9   Author: AdoptOpenJDK   File: Archive.java    License: 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 #20
Source Project: skara   Author: openjdk   File: SlackNotifier.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onNewCommits(HostedRepository repository,
                         Repository localRepository,
                         List<Commit> commits,
                         Branch branch) throws NonRetriableException {
    if (commitWebhook == null) {
        return;
    }

    try {
        for (var commit : commits) {
            var query = JSON.object();
            if (username != null && !username.isEmpty()) {
                query.put("username", username);
            }
            var title = commit.message().get(0);
            query.put("text", branch.name() + ": " + commit.hash().abbreviate() + ": " + title + "\n" +
                              "Author: " + commit.author().name() + "\n" +
                              "Committer: " + commit.author().name() + "\n" +
                              "Date: " + commit.authored().format(DateTimeFormatter.RFC_1123_DATE_TIME) + "\n");

            var attachment = JSON.object();
            attachment.put("fallback", "Link to commit");
            attachment.put("color", "#cc0e31");
            attachment.put("title", "View on " + repository.forge().name());
            attachment.put("title_link", repository.webUrl(commit.hash()).toString());
            var attachments = JSON.array();
            attachments.add(attachment);
            query.put("attachments", attachments);
            commitWebhook.post("").body(query).executeUnparsed();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #21
Source Project: powsybl-core   Author: powsybl   File: AbstractUncompressedDataChunk.java    License: 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 #22
Source Project: helidon-build-tools   Author: oracle   File: Jar.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a stream to access the data for this entry.
 *
 * @return The stream.
 */
public InputStream data() {
    try {
        return jar.getInputStream(this);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #23
Source Project: aws-sdk-java-v2   Author: aws   File: FileAsyncRequestBody.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Long> contentLength() {
    try {
        return Optional.of(Files.size(path));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #24
Source Project: presto   Author: prestosql   File: OdsBenchmarkResultWriter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void finished()
{
    try {
        jsonGenerator.writeEndArray();
        jsonGenerator.close();
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #25
Source Project: powsybl-core   Author: powsybl   File: JsonSensitivityComputationParameters.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Updates parameters by reading the content of a JSON stream.
 */
public static SensitivityComputationParameters update(SensitivityComputationParameters parameters, InputStream jsonStream) {
    Objects.requireNonNull(parameters);
    Objects.requireNonNull(jsonStream);

    try {
        ObjectMapper objectMapper = createObjectMapper();
        return objectMapper.readerForUpdating(parameters).readValue(jsonStream);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #26
Source Project: powsybl-core   Author: powsybl   File: ValidationWriters.java    License: Mozilla Public License 2.0 5 votes vote down vote up
public ValidationWriters(String networkId, Set<ValidationType> validationTypes, Path folder, ValidationConfig config) {
    validationTypes.forEach(validationType -> {
        try {
            Writer writer = Files.newBufferedWriter(validationType.getOutputFile(folder), StandardCharsets.UTF_8);
            writersMap.put(validationType, writer);
            validationWritersMap.put(validationType, ValidationUtils.createValidationWriter(networkId, config, writer, validationType));
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}
 
Example #27
Source Project: smart-testing   Author: arquillian   File: GitCloner.java    License: 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 #28
Source Project: incubator-tuweni   Author: apache   File: TempDirectoryExtension.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (tempDirectory == null) {
    try {
      tempDirectory = createTempDirectory(extensionContext.getRequiredTestClass().getSimpleName());
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  }
  return tempDirectory;
}
 
Example #29
Source Project: presto   Author: prestosql   File: MapColumnReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void close()
{
    try (Closer closer = Closer.create()) {
        closer.register(keyColumnReader::close);
        closer.register(valueColumnReader::close);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example #30
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: ExternalEditorTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getSource() {
    try {
        outputStream.writeInt(CustomEditor.GET_SOURCE_CODE);
        int length = inputStream.readInt();
        byte[] bytes = new byte[length];
        inputStream.readFully(bytes);
        return new String(bytes, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}