diff --git a/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConfiguration.java b/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConfiguration.java index 62129407..c0b0fc5f 100644 --- a/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConfiguration.java +++ b/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConfiguration.java @@ -22,7 +22,8 @@ */ package net.tirasa.connid.commons.scripted; -import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; import org.identityconnectors.common.logging.Log; import org.identityconnectors.framework.spi.AbstractConfiguration; import org.identityconnectors.framework.spi.ConfigurationProperty; @@ -380,9 +381,9 @@ private void checkFileIsReadable(final String type, final String fileName) { if (fileName == null) { LOG.ok("{0} Script Filename is null", type); } else { - File file = new File(AbstractScriptedConnector.resolveVariables(fileName)); + Path file = Path.of(AbstractScriptedConnector.resolveVariables(fileName)); try { - if (file.canRead()) { + if (Files.isReadable(file)) { LOG.ok("{0} is readable", fileName); } else { throw new IllegalArgumentException("Can't read " + fileName); @@ -392,5 +393,4 @@ private void checkFileIsReadable(final String type, final String fileName) { } } } - } diff --git a/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConnector.java b/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConnector.java index 14a5cd81..8134551b 100644 --- a/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConnector.java +++ b/java/commons/scripted/src/main/java/net/tirasa/connid/commons/scripted/AbstractScriptedConnector.java @@ -28,8 +28,8 @@ import static net.tirasa.connid.commons.scripted.Constants.MSG_BLANK_RESULT_HANDLER; import static net.tirasa.connid.commons.scripted.Constants.MSG_INVALID_SCRIPT; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -158,7 +158,7 @@ private ScriptExecutor getScriptExecutor(String script, String scriptFileName) { try { if (scriptFileName != null) { - scriptCode = IOUtil.readFileUTF8(new File(resolveVariables(scriptFileName))); + scriptCode = IOUtil.readFileUTF8(Path.of(resolveVariables(scriptFileName))); } if (scriptCode.length() > 0) { scriptExec = factory.newScriptExecutor(getClass().getClassLoader(), scriptCode, true); diff --git a/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/data/GroovyDataProvider.java b/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/data/GroovyDataProvider.java index 006df40e..7f7e940b 100644 --- a/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/data/GroovyDataProvider.java +++ b/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/data/GroovyDataProvider.java @@ -31,11 +31,14 @@ import groovy.util.ConfigObject; import groovy.util.ConfigSlurper; import java.io.File; -import java.io.FileWriter; import java.io.IOException; +import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -56,7 +59,6 @@ import org.identityconnectors.test.common.TestHelpers; /** - *

* Default implementation of {@link DataProvider}. It uses ConfigSlurper from * Groovy to parse the property file. * The groovy files are read as classpath resources using following paths : @@ -248,7 +250,7 @@ private void initQueriedPropsDump() { String pOut = System.getProperty(PARAM_QUERIED_PROPERTY_OUT_FILE); if (StringUtil.isNotBlank(pOut)) { try { - _queriedPropsOutFile = new File(pOut); + _queriedPropsOutFile = Path.of(pOut).toFile(); if (!_queriedPropsOutFile.exists()) { _queriedPropsOutFile.createNewFile(); } @@ -274,7 +276,7 @@ private void initSnapshot() { String pOut = System.getProperty(PARAM_PROPERTY_OUT_FILE); if (StringUtil.isNotBlank(pOut)) { try { - _propertyOutFile = new File(pOut); + _propertyOutFile = Path.of(pOut).toFile(); if (!_propertyOutFile.exists()) { _propertyOutFile.createNewFile(); } @@ -884,7 +886,11 @@ Object writeDataToFile() { // parse configuration information to flatten String result = flatten(configObject); - try (FileWriter fw = new FileWriter(_propertyOutFile, StandardCharsets.UTF_8, true)) { + try (Writer fw = Files.newBufferedWriter( + _propertyOutFile.toPath(), + StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { + fw.append("\n\n\n ============================ NEW TEST ==================== \n\n\n"); fw.append(result); } catch (IOException e) { @@ -903,7 +909,11 @@ private String writeQueriedDumpToFile() { return null; } - try (FileWriter fw = new FileWriter(_queriedPropsOutFile, StandardCharsets.UTF_8, true)) { + try (Writer fw = Files.newBufferedWriter( + _queriedPropsOutFile.toPath(), + StandardCharsets.UTF_8, + StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { + fw.append("\n"); // MISSING PROPS fw.append(" \n"); diff --git a/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/test/ConnectorHelper.java b/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/test/ConnectorHelper.java index 263adc67..546ed58c 100644 --- a/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/test/ConnectorHelper.java +++ b/java/connector-framework-contract/src/main/java/org/identityconnectors/contract/test/ConnectorHelper.java @@ -31,8 +31,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -import java.io.File; import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -1093,10 +1094,10 @@ private static ConnectorInfoManager getLocalManager(final DataProvider dataProvi ConnectorInfoManager manager = null; // try to load bundleJar property (which should be set by ant) - File bundleJar = new File(((String) dataProvider.getTestSuiteAttribute("bundleJar")).trim()); - assertTrue(bundleJar.isFile(), "BundleJar does not exist: " + bundleJar.getAbsolutePath()); + Path bundleJar = Path.of(((String) dataProvider.getTestSuiteAttribute("bundleJar")).trim()); + assertTrue(Files.isRegularFile(bundleJar), "BundleJar does not exist: " + bundleJar.toString()); try { - manager = fact.getLocalManager(bundleJar.toURI().toURL()); + manager = fact.getLocalManager(bundleJar.toUri().toURL()); } catch (MalformedURLException ex) { throw ContractException.wrap(ex); } diff --git a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/api/local/LocalConnectorInfoManagerImpl.java b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/api/local/LocalConnectorInfoManagerImpl.java index 71c1f7a6..1ee25189 100644 --- a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/api/local/LocalConnectorInfoManagerImpl.java +++ b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/api/local/LocalConnectorInfoManagerImpl.java @@ -20,18 +20,19 @@ * "Portions Copyrighted [year] [name of copyright owner]" * ==================== * Portions Copyrighted 2010-2014 ForgeRock AS. - * Portions Copyrighted 2010-2018 ConnId + * Portions Copyrighted 2010 ConnId */ package org.identityconnectors.framework.impl.api.local; import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.lang.annotation.Annotation; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -90,8 +91,8 @@ private static List expandBundles(final List bundleURLs) WorkingBundleInfo info = null; try { if ("file".equals(url.getProtocol())) { - final File file = new File(url.toURI()); - if (file.isDirectory()) { + Path file = Path.of(url.toURI()); + if (Files.isDirectory(file)) { info = processDirectory(file); } } @@ -106,32 +107,27 @@ private static List expandBundles(final List bundleURLs) return rv; } - private static WorkingBundleInfo processDirectory(final File dir) throws ConfigurationException { - final WorkingBundleInfo info = new WorkingBundleInfo(dir.getAbsolutePath()); + private static WorkingBundleInfo processDirectory(final Path dir) throws ConfigurationException { + final WorkingBundleInfo info = new WorkingBundleInfo(dir.toAbsolutePath().toString()); try { // easy case - nothing needs to be copied - final File manifest = new File(dir, "META-INF/MANIFEST.MF"); - InputStream in = null; - try { - in = new FileInputStream(manifest); + Path manifest = dir.resolve("META-INF/MANIFEST.MF"); + try (InputStream in = Files.newInputStream(manifest)) { Manifest rawManifest = new Manifest(in); ConnectorBundleManifestParser parser = new ConnectorBundleManifestParser(info.getOriginalLocation(), rawManifest); info.setManifest(parser.parse()); - } finally { - IOUtil.quietClose(in); } - info.getImmediateClassPath().add(dir.toURI().toURL()); - final List bundleContents = listBundleContents(dir); - info.getImmediateBundleContents().addAll(bundleContents); - final File libDir = new File(dir, "lib"); + info.getImmediateClassPath().add(dir.toUri().toURL()); + info.getImmediateBundleContents().addAll(listBundleContents(dir.toFile())); + final File libDir = dir.resolve("lib").toFile(); if (libDir.exists()) { final List libURLs = BundleLibSorter.getSortedURLs(libDir); libURLs.forEach((lib) -> { info.getEmbeddedBundles().add(processURL(lib, false)); }); } - final File nativeDir = new File(dir, "native"); + final File nativeDir = dir.resolve("native").toFile(); if (nativeDir.exists()) { for (File file : BundleLibSorter.getSortedFiles(nativeDir)) { if (file.isFile()) { @@ -328,7 +324,7 @@ public static APIConfigurationImpl createDefaultAPIConfiguration(final LocalConn try { final Class connectorClass = localInfo.getConnectorClass(); final APIConfigurationImpl rv = new APIConfigurationImpl(); - final Configuration config = + final Configuration config = localInfo.getConnectorConfigurationClass().getDeclaredConstructor().newInstance(); final boolean pooling = PoolableConnector.class.isAssignableFrom(connectorClass); rv.setConnectorPoolingSupported(pooling); @@ -450,16 +446,16 @@ public File copyStreamToFile(final InputStream stream) throws IOException { final File bundleDir = getBundleTempDir(); File candidate; do { - candidate = new File(bundleDir, "file-" + nextRandom()); + candidate = bundleDir.toPath().resolve("file-" + nextRandom()).toFile(); } while (!candidate.createNewFile()); candidate.deleteOnExit(); - copyStream(stream, candidate); + copyStream(stream, candidate.toPath()); return candidate; } public File copyStreamToFile(final InputStream stream, final String name) throws IOException { final File bundleDir = getBundleTempDir(); - final File newFile = new File(bundleDir, name); + final File newFile = bundleDir.toPath().resolve(name).toFile(); if (newFile.exists()) { throw new IOException("File " + newFile + " already exists"); } @@ -472,12 +468,12 @@ public File copyStreamToFile(final InputStream stream, final String name) throws parent = parent.getParentFile(); } newFile.deleteOnExit(); - copyStream(stream, newFile); + copyStream(stream, newFile.toPath()); return newFile; } - private void copyStream(final InputStream stream, final File toFile) throws IOException { - try (FileOutputStream out = new FileOutputStream(toFile)) { + private static void copyStream(final InputStream stream, final Path toFile) throws IOException { + try (OutputStream out = Files.newOutputStream(toFile)) { IOUtil.copyFile(stream, out); } } @@ -486,13 +482,13 @@ private File getBundleTempDir() throws IOException { if (_bundleTempDir != null) { return _bundleTempDir; } - final File tempDir = new File(System.getProperty("java.io.tmpdir")); + final File tempDir = Path.of(System.getProperty("java.io.tmpdir")).toFile(); if (!tempDir.exists()) { throw new IOException("Temporary directory " + tempDir + " does not exist"); } File candidate; do { - candidate = new File(tempDir, "bundle-" + nextRandom()); + candidate = tempDir.toPath().resolve("bundle-" + nextRandom()).toFile(); } while (!candidate.mkdir()); candidate.deleteOnExit(); _bundleTempDir = candidate; diff --git a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/serializer/Primitives.java b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/serializer/Primitives.java index 69f5b543..ea7e836a 100644 --- a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/serializer/Primitives.java +++ b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/impl/serializer/Primitives.java @@ -30,6 +30,7 @@ import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; @@ -260,7 +261,7 @@ public void serialize(final Object object, final ObjectEncoder encoder) { @Override public Object deserialize(final ObjectDecoder decoder) { final String val = decoder.readStringContents(); - return new File(val); + return Path.of(val).toFile(); } @Override diff --git a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/server/Main.java b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/server/Main.java index 6be06deb..9fd245b7 100644 --- a/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/server/Main.java +++ b/java/connector-framework-internal/src/main/java/org/identityconnectors/framework/server/Main.java @@ -24,19 +24,16 @@ package org.identityconnectors.framework.server; import java.io.File; -import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; +import java.nio.file.Path; import java.util.ArrayList; -import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.logging.LogManager; - import org.identityconnectors.common.IOUtil; import org.identityconnectors.common.logging.Log; import org.identityconnectors.common.security.SecurityUtil; @@ -112,13 +109,13 @@ public static void main(String[] args) throws Exception { } Properties properties = IOUtil.loadPropertiesFile(propertiesFileName); properties.put(PROP_KEY, SecurityUtil.computeBase64SHA1Hash(key.toCharArray())); - IOUtil.storePropertiesFile(new File(propertiesFileName), properties); + IOUtil.storePropertiesFile(Path.of(propertiesFileName), properties); } else if (cmd.equalsIgnoreCase("-setDefaults")) { if (propertiesFileName == null || key != null) { usage(); return; } - IOUtil.extractResourceToFile(Main.class, "connectorserver.properties", new File(propertiesFileName)); + IOUtil.extractResourceToFile(Main.class, "connectorserver.properties", Path.of(propertiesFileName)); } else { usage(); } @@ -151,7 +148,6 @@ private static void run(Properties properties) throws Exception { if (loggerClass == null) { - System.out.println("Logger Class is null"); loggerClass = DEFAULT_LOG_SPI; } @@ -173,9 +169,9 @@ private static void run(Properties properties) throws Exception { connectorServer = ConnectorServer.newInstance(); connectorServer.setPort(port); - connectorServer.setBundleURLs(buildBundleURLs(new File(bundleDirStr))); + connectorServer.setBundleURLs(buildBundleURLs(Path.of(bundleDirStr))); if (libDirStr != null) { - ClassLoader cl = buildLibClassLoader(new File(libDirStr)); + ClassLoader cl = buildLibClassLoader(Path.of(libDirStr)); connectorServer.setBundleParentClassLoader(cl); } @@ -226,29 +222,28 @@ private static void ensureLoggingNotInitialized() throws Exception { } } - private static List buildBundleURLs(File dir) throws MalformedURLException { - List rv = getJarFiles(dir); + private static List buildBundleURLs(final Path dir) throws MalformedURLException { + List rv = getJarFiles(dir.toFile()); if (rv.isEmpty()) { getLog().warn("No bundles found in the bundles directory."); } return rv; } - private static ClassLoader buildLibClassLoader(File dir) throws MalformedURLException { - List jars = getJarFiles(dir); + private static ClassLoader buildLibClassLoader(final Path dir) throws MalformedURLException { + List jars = getJarFiles(dir.toFile()); if (!jars.isEmpty()) { - return new URLClassLoader(jars.toArray(new URL[jars.size()]), - ConnectorInfoManagerFactory.class.getClassLoader()); + return new URLClassLoader(jars.toArray(URL[]::new), ConnectorInfoManagerFactory.class.getClassLoader()); } return null; } - private static List getJarFiles(File dir) throws MalformedURLException { + private static List getJarFiles(final File dir) throws MalformedURLException { if (!dir.isDirectory()) { throw new ConnectorException(dir.getPath() + " does not exist"); } - List rv = new ArrayList(); + List rv = new ArrayList<>(); for (File bundle : dir.listFiles()) { if (bundle.getName().endsWith(".jar")) { rv.add(bundle.toURI().toURL()); diff --git a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/ConnectorInfoManagerTestBase.java b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/ConnectorInfoManagerTestBase.java index ba947345..adb28d89 100644 --- a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/ConnectorInfoManagerTestBase.java +++ b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/ConnectorInfoManagerTestBase.java @@ -33,6 +33,7 @@ import java.io.File; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; import java.util.List; @@ -667,9 +668,9 @@ public void testTimeout() throws Exception { } } - final File getTestBundlesDir() throws URISyntaxException { + static File getTestBundlesDir() throws URISyntaxException { URL testOutputDirectory = ConnectorInfoManagerTestBase.class.getResource("/"); - File testBundlesDir = new File(testOutputDirectory.toURI()); + File testBundlesDir = Path.of(testOutputDirectory.toURI()).toFile(); if (!testBundlesDir.isDirectory()) { throw new ConnectorException(testBundlesDir.getPath() + " does not exist"); } diff --git a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/RemoteConnectorInfoManagerSSLTests.java b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/RemoteConnectorInfoManagerSSLTests.java index 389aa9df..73e0cd93 100644 --- a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/RemoteConnectorInfoManagerSSLTests.java +++ b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/api/RemoteConnectorInfoManagerSSLTests.java @@ -19,11 +19,11 @@ * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * ==================== + * Portions Copyrighted 2024 ConnId */ package org.identityconnectors.framework.impl.api; import java.io.ByteArrayInputStream; -import java.io.File; import java.net.InetAddress; import java.net.Socket; import java.net.URL; @@ -33,13 +33,11 @@ import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.List; - import javax.net.ssl.KeyManager; import javax.net.ssl.SSLEngine; import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509ExtendedTrustManager; - import org.identityconnectors.common.CollectionUtil; import org.identityconnectors.common.IOUtil; import org.identityconnectors.common.security.GuardedString; @@ -55,9 +53,7 @@ public class RemoteConnectorInfoManagerSSLTests extends ConnectorInfoManagerTest private KeyStore loadKeyStoreResource(String name) { try { - File bundlesDir = getTestBundlesDir(); - File file = new File(bundlesDir, name); - byte[] bytes = IOUtil.readFileBytes(file); + byte[] bytes = IOUtil.readFileBytes(getTestBundlesDir().toPath().resolve(name)); KeyStore store = KeyStore.getInstance("PKCS12"); store.load(new ByteArrayInputStream(bytes), "changeit".toCharArray()); return store; diff --git a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/serializer/ObjectSerializationTests.java b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/serializer/ObjectSerializationTests.java index a81e0ddf..34d75d89 100644 --- a/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/serializer/ObjectSerializationTests.java +++ b/java/connector-framework-internal/src/test/java/org/identityconnectors/framework/impl/serializer/ObjectSerializationTests.java @@ -36,6 +36,7 @@ import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; @@ -241,7 +242,7 @@ public void testURI() throws Exception { @Test public void testFile() throws Exception { - File v1 = new File("c:/foo.txt"); + File v1 = Path.of("c:/foo.txt").toFile(); File v2 = (File) cloneObject(v1); assertTrue(v1 != v2); assertEquals(v1, v2); diff --git a/java/connector-framework/src/main/java/org/identityconnectors/common/IOUtil.java b/java/connector-framework/src/main/java/org/identityconnectors/common/IOUtil.java index f4bd15f0..4c7032c2 100644 --- a/java/connector-framework/src/main/java/org/identityconnectors/common/IOUtil.java +++ b/java/connector-framework/src/main/java/org/identityconnectors/common/IOUtil.java @@ -25,7 +25,6 @@ import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; @@ -40,11 +39,14 @@ import java.net.URL; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Enumeration; +import java.util.Optional; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -358,30 +360,24 @@ public static String readerToString(final Reader rdr) { * @param dest This can be a directory or a file. * @return True if succeeded otherwise false. */ - public static boolean copyFile(final File src, File dest) throws IOException { - boolean ret = true; + public static boolean copyFile(final File src, final File dest) throws IOException { // quick exit if this is bogus if (src == null || dest == null || !src.isFile()) { throw new FileNotFoundException(); } + // check for directory + Path dst = dest.toPath(); if (dest.isDirectory()) { - final String name = src.getName(); - dest = new File(dest, name); + dst = dst.resolve(src.getName()); } - FileInputStream fis = null; - FileOutputStream fout = null; - try { - // get source stream - fis = new FileInputStream(src); - // get destination stream - fout = new FileOutputStream(dest); + + boolean ret; + try (InputStream fis = Files.newInputStream(src.toPath()); + OutputStream fout = Files.newOutputStream(dst)) { + // copy source to destination.. ret = copyFile(fis, fout) > 0; - } finally { - // close open streams.. - quietClose(fis); - quietClose(fout); } return ret; } @@ -412,7 +408,7 @@ public static long copyFile(final InputStream fis, final OutputStream fos) throw * @return */ public static long checksum(final String fileName) throws IOException, FileNotFoundException { - return (checksum(new File(fileName))); + return checksum(Path.of(fileName)); } /** @@ -421,12 +417,10 @@ public static long checksum(final String fileName) throws IOException, FileNotFo * @param file the file on which to calculate the checksum * @return */ - public static long checksum(final File file) throws IOException, FileNotFoundException { - FileInputStream fis = null; + public static long checksum(final Path file) throws IOException, FileNotFoundException { final byte[] bytes = new byte[16384]; int len; - try { - fis = new FileInputStream(file); + try (InputStream fis = Files.newInputStream(file)) { CRC32 chkSum = new CRC32(); len = fis.read(bytes); while (len != -1) { @@ -434,8 +428,6 @@ public static long checksum(final File file) throws IOException, FileNotFoundExc len = fis.read(bytes); } return chkSum.getValue(); - } finally { - quietClose(fis); } } @@ -503,27 +495,20 @@ public static void delete(final File file) throws IOException { * the file to load the propertied from * @return properties loaded */ - public static Properties loadPropertiesFile(final File file) throws IOException { - FileInputStream in = new FileInputStream(file); - try { - final Properties rv = new Properties(); + public static Properties loadPropertiesFile(final Path file) throws IOException { + try (InputStream in = Files.newInputStream(file)) { + Properties rv = new Properties(); rv.load(in); return rv; - } finally { - in.close(); } } /** * Stores the given file as a Properties file. */ - public static void storePropertiesFile(final File f, final Properties properties) - throws IOException { - final FileOutputStream out = new FileOutputStream(f); - try { + public static void storePropertiesFile(final Path file, final Properties properties) throws IOException { + try (OutputStream out = Files.newOutputStream(file)) { properties.store(out, null); - } finally { - out.close(); } } @@ -565,23 +550,16 @@ public static Properties getResourceAsProperties(final ClassLoader loader, final * @throws IOException * If an error occurs reading it */ - public static void extractResourceToFile(final Class clazz, final String path, - final File file) throws IOException { + public static void extractResourceToFile( + final Class clazz, + final String path, + final Path file) throws IOException { - final InputStream in = getResourceAsStream(clazz, path); - if (in == null) { - throw new IOException("Missing resource: " + path); - } - OutputStream out = null; - try { - out = new FileOutputStream(file); - IOUtil.copyFile(in, out); - } finally { - if (out != null) { - out.close(); - } + try (InputStream in = Optional.ofNullable(getResourceAsStream(clazz, path)). + orElseThrow(() -> new IOException("Missing resource: " + path)); + OutputStream out = Files.newOutputStream(file)) { - in.close(); + copyFile(in, out); } } @@ -594,24 +572,15 @@ public static void extractResourceToFile(final Class clazz, final String path * @param toDir * The directory to unjar to. */ - public static void unjar(final JarFile jarFile, final File toDir) throws IOException { - final Enumeration entries = jarFile.entries(); + public static void unjar(final JarFile jarFile, final Path toDir) throws IOException { + Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { - final JarEntry entry = entries.nextElement(); - final File outFile = new File(toDir, entry.getName()); - FileOutputStream fos = null; - InputStream in = null; - try { - fos = new FileOutputStream(outFile); - in = jarFile.getInputStream(entry); - IOUtil.copyFile(in, fos); - } finally { - if (in != null) { - in.close(); - } - if (fos != null) { - fos.close(); - } + JarEntry entry = entries.nextElement(); + Path outFile = toDir.resolve(entry.getName()); + try (InputStream in = jarFile.getInputStream(entry); + OutputStream fos = Files.newOutputStream(outFile)) { + + copyFile(in, fos); } } } @@ -625,8 +594,8 @@ public static void unjar(final JarFile jarFile, final File toDir) throws IOExcep * @throws IOException * if there is an issue reading the file. */ - public static String readFileUTF8(final File file) throws IOException { - final byte[] bytes = IOUtil.readFileBytes(file); + public static String readFileUTF8(final Path file) throws IOException { + final byte[] bytes = readFileBytes(file); return new String(bytes, StandardCharsets.UTF_8); } @@ -639,9 +608,8 @@ public static String readFileUTF8(final File file) throws IOException { * @throws IOException * if there is an issue reading the file. */ - public static byte[] readFileBytes(final File file) throws IOException { - final InputStream ins = new FileInputStream(file); - return IOUtil.readInputStreamBytes(ins, true); + public static byte[] readFileBytes(final Path file) throws IOException { + return readInputStreamBytes(Files.newInputStream(file), true); } /** @@ -656,8 +624,8 @@ public static byte[] readFileBytes(final File file) throws IOException { * @throws NullPointerException * if the file parameter is null. */ - public static void writeFileUTF8(final File file, final String contents) throws IOException { - try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) { + public static void writeFileUTF8(final Path file, final String contents) throws IOException { + try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { writer.write(contents); } } @@ -674,8 +642,8 @@ public static void writeFileUTF8(final File file, final String contents) throws * if the URL create from the parameters does not specify a * file. */ - public static URL makeURL(final File dir, final String path) throws IOException { - final File file = new File(dir, path); + public static URL makeURL(final Path dir, final String path) throws IOException { + final File file = dir.resolve(path).toFile(); if (!file.isFile()) { throw new IOException(file.getPath() + " does not exist"); } @@ -692,6 +660,6 @@ public static URL makeURL(final File dir, final String path) throws IOException * if there is an issue. */ public static Properties loadPropertiesFile(final String string) throws IOException { - return loadPropertiesFile(new File(string)); + return loadPropertiesFile(Path.of(string)); } } diff --git a/java/connector-framework/src/main/java/org/identityconnectors/common/logging/Log.java b/java/connector-framework/src/main/java/org/identityconnectors/common/logging/Log.java index b75e01d9..ce26e82e 100644 --- a/java/connector-framework/src/main/java/org/identityconnectors/common/logging/Log.java +++ b/java/connector-framework/src/main/java/org/identityconnectors/common/logging/Log.java @@ -25,13 +25,15 @@ package org.identityconnectors.common.logging; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.Collection; +import java.util.Optional; import java.util.Properties; import java.util.Set; - import org.identityconnectors.common.CollectionUtil; import org.identityconnectors.common.IOUtil; import org.identityconnectors.common.ReflectionUtil; @@ -43,10 +45,9 @@ public final class Log { /** - * Default SPI implementation should all attempts to load the custom logger - * fail. + * Default SPI implementation should all attempts to load the custom logger fail. */ - private static Class defaultSPI = StdOutLogger.class; + private static final Class DEFAULT_SPI = StdOutLogger.class; // Hack for OIM: this ought to be Log.class.getPackage().getName(). However, // OIM's @@ -102,6 +103,7 @@ public static enum Level { * Maps to java.util.logging.Level.SEVERE. */ ERROR; + } /** @@ -134,8 +136,7 @@ static Log getLog(final Class clazz, final LogSpi logImpl) { * private static final Log LOG = Log.getLog(MyClass.class); * * - * @param clazz - * class to log information about. + * @param clazz class to log information about. * @return logger to use for logging. */ public static Log getLog(final Class clazz) { @@ -167,19 +168,18 @@ public boolean isLoggable(final Level level) { /** * Lowest level logging method. * - * @param clazz - * Class that is being logged. - * @param method - * Method name that is being logged. - * @param level - * Logging level. - * @param message - * Message about the log. - * @param ex - * Exception to use process. + * @param clazz Class that is being logged. + * @param method Method name that is being logged. + * @param level Logging level. + * @param message Message about the log. + * @param ex Exception to use process. */ - public void log(final Class clazz, final String method, final Log.Level level, - final String message, final Throwable ex) { + public void log( + final Class clazz, + final String method, + final Log.Level level, + final String message, + final Throwable ex) { if (isLoggable(level)) { logImpl.log(clazz, method, level, message, ex); @@ -190,17 +190,17 @@ public void log(final Class clazz, final String method, final Log.Level level * Logs based on the parameters given. Uses the format parameter inside * {@link MessageFormat}. * - * @param level - * the logging level at which to write the message. - * @param ex - * [optional] exception stack trace to log. - * @param format - * [optional] create a message of a particular format. - * @param args - * [optional] parameters to the format string. + * @param level the logging level at which to write the message. + * @param ex [optional] exception stack trace to log. + * @param format [optional] create a message of a particular format. + * @param args [optional] parameters to the format string. */ - public void log(final Level level, final Throwable ex, final String format, + public void log( + final Level level, + final Throwable ex, + final String format, final Object... args) { + if (isLoggable(level)) { String message = format; if (format != null && args != null) { @@ -210,24 +210,32 @@ public void log(final Level level, final Throwable ex, final String format, } else if (format == null && ex != null) { message = ex.getLocalizedMessage(); } - //To get the StackTrace is expensive. Extract the method name only if it's necessary!!! - log(level, ex, message, logImpl.needToInferCaller(clazz, level) ? Thread.currentThread().getStackTrace() : null); + + // To get the StackTrace is expensive. Extract the method name only if it's necessary!!! + log(level, + ex, + message, + logImpl.needToInferCaller(clazz, level) + ? Thread.currentThread().getStackTrace() + : null); } } - protected void log(final Level level, final Throwable ex, final String message, - final StackTraceElement[] locations) { - final StackTraceElement caller = extract(locations, EXCLUDE_LIST); - if (null != caller) { - logImpl.log(clazz, caller, level, message, ex); - } else { - logImpl.log(clazz, (String)null, level, message, ex); - } + protected void log( + final Level level, + final Throwable ex, + final String message, + final StackTraceElement[] locations) { + + Optional.ofNullable(extract(locations, EXCLUDE_LIST)).ifPresentOrElse( + caller -> logImpl.log(clazz, caller, level, message, ex), + () -> logImpl.log(clazz, (String) null, level, message, ex)); } + protected static StackTraceElement extract( + final StackTraceElement[] steArray, + final Collection frameworkPackageList) { - protected StackTraceElement extract(StackTraceElement[] steArray, - Collection frameworkPackageList) { if (steArray == null) { return null; } @@ -237,10 +245,14 @@ protected StackTraceElement extract(StackTraceElement[] steArray, return current; } } + return null; } - protected boolean isInFrameworkPackageList(String currentClass, Collection frameworkPackageList) { + protected static boolean isInFrameworkPackageList( + final String currentClass, + final Collection frameworkPackageList) { + if (frameworkPackageList == null) { return false; } @@ -322,25 +334,19 @@ private static Class findSpiClass() { return forName(impl); } // attempt to find the properties file.. - final File javaHome = new File(System.getProperty("java.home")); - final File javaHomeLib = new File(javaHome, "lib"); - final File propsFile = new File(javaHomeLib, LOGSPI_PROPS_FILE); + File propsFile = Path.of(System.getProperty("java.home")).resolve("lib").resolve(LOGSPI_PROPS_FILE).toFile(); if (propsFile.isFile() && propsFile.canRead()) { - FileInputStream fis = null; - try { - final Properties props = new Properties(); - fis = new FileInputStream(propsFile); + try (InputStream fis = Files.newInputStream(propsFile.toPath())) { + Properties props = new Properties(); props.load(fis); // get the same system property from the properties file.. - final String prop = props.getProperty(LOGSPI_PROP); + String prop = props.getProperty(LOGSPI_PROP); if (StringUtil.isNotBlank(prop)) { return forName(prop); } } catch (IOException e) { // throw to alert the caller the file is corrupt throw new RuntimeException(e); - } finally { - IOUtil.quietClose(fis); } } // attempt to find through the jar META-INF/services.. @@ -350,7 +356,7 @@ private static Class findSpiClass() { return forName(clazz.trim()); } // return the default.. - return defaultSPI; + return DEFAULT_SPI; } /** diff --git a/java/connector-test-common/src/main/java/org/identityconnectors/test/common/TestHelpers.java b/java/connector-test-common/src/main/java/org/identityconnectors/test/common/TestHelpers.java index 88fcc225..fa8c115d 100644 --- a/java/connector-test-common/src/main/java/org/identityconnectors/test/common/TestHelpers.java +++ b/java/connector-test-common/src/main/java/org/identityconnectors/test/common/TestHelpers.java @@ -28,6 +28,7 @@ import java.lang.reflect.Method; import java.net.URI; import java.net.URL; +import java.nio.file.Path; import java.text.MessageFormat; import java.util.HashMap; import java.util.HashSet; @@ -79,7 +80,7 @@ public static APIConfiguration createTestConfiguration( try { URI relative = url.toURI(); - for (File file : new File(url.toURI()).listFiles()) { + for (File file : Path.of(url.toURI()).toFile().listFiles()) { bundleContents.add(relative.relativize(file.toURI()).getPath()); } return getSpi().createTestConfiguration(clazz, bundleContents, configData, prefix); diff --git a/java/pom.xml b/java/pom.xml index e922394e..9da36a5c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -318,7 +318,7 @@ org.gaul modernizer-maven-plugin - 2.9.0 + 3.0.0 ${targetJdk}