下面列出了org.junit.jupiter.api.extension.ParameterResolutionException#java.io.UncheckedIOException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
/**
* 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();
}
}
}
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);
}
}
@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);
}
}
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();
}
}
@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);
}
}
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;
}
}
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");
}
}
/**
* 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;
}
@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()));
}
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);
}
}
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);
}
}
/**
* 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;
}
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);
}
}
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");
}
}
}
}
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);
}
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;
}
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);
}
}
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);
}
}
@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);
}
}
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);
}
}
/**
* 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);
}
}
@Override
public Optional<Long> contentLength() {
try {
return Optional.of(Files.size(path));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void finished()
{
try {
jsonGenerator.writeEndArray();
jsonGenerator.close();
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* 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);
}
}
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);
}
});
}
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);
}
}
}
@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;
}
@Override
public void close()
{
try (Closer closer = Closer.create()) {
closer.register(keyColumnReader::close);
closer.register(valueColumnReader::close);
}
catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@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);
}
}