From 0ec331573d0fe7c8c7aa5bb02ba8d600fe851bb2 Mon Sep 17 00:00:00 2001 From: Sven Diedrichsen Date: Wed, 27 Mar 2019 00:32:53 +0100 Subject: [PATCH 1/2] Fixing sonar blocker bugs with unclosed resources and potential NPE --- .../glassfish/appclient/client/acc/Util.java | 23 +-- .../appclient/client/jws/boot/JWSACCMain.java | 136 ++++++-------- .../org/glassfish/appclient/common/Util.java | 21 +-- .../naming/util/NamingUtilsImpl.java | 48 +++-- .../connectors/util/JarResourceExtractor.java | 54 ++---- .../payara/ejb/invoke/InvokeEJBServlet.java | 85 +++++---- .../store/adapter/file/FileBackingStore.java | 28 +-- .../metrics/writer/JsonWriter.java | 39 ++-- .../oauth2/OAuth2AuthenticationMechanism.java | 35 ++-- .../openid/OpenIdAuthenticationMechanism.java | 28 +-- .../rest/client/utils/MarshallingUtils.java | 3 +- .../admin/rest/client/utils/Util.java | 33 ++-- .../admin/rest/testing/Response.java | 13 +- .../internal/embedded/ScatteredArchive.java | 36 ++-- .../embeddable/archive/Assembler.java | 177 +++++++++--------- 15 files changed, 367 insertions(+), 392 deletions(-) diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/Util.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/Util.java index 34a22615e9a..c6acc1aa6dd 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/Util.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/acc/Util.java @@ -132,22 +132,15 @@ public static URI getURI(final File f) throws URISyntaxException { * @throws FileNotFoundException if the temp file cannot be opened for any reason */ public static File writeTextToTempFile(String content, String prefix, String suffix, boolean retainTempFiles) throws IOException, FileNotFoundException { - BufferedWriter wtr = null; - try { - File result = File.createTempFile(prefix, suffix); - if ( ! retainTempFiles) { - result.deleteOnExit(); - } - FileOutputStream fos = new FileOutputStream(result); - wtr = new BufferedWriter(new OutputStreamWriter(fos)); - wtr.write(content); - wtr.close(); - return result; - } finally { - if (wtr != null) { - wtr.close(); - } + File result = File.createTempFile(prefix, suffix); + if ( ! retainTempFiles) { + result.deleteOnExit(); + } + try (BufferedWriter writer = + new BufferedWriter(new OutputStreamWriter(new FileOutputStream(result)))) { + writer.write(content); } + return result; } /** diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java index 0d8c905e157..7d62f3d17c2 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java @@ -40,27 +40,22 @@ package org.glassfish.appclient.client.jws.boot; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; +import org.glassfish.appclient.client.acc.AppClientContainer; +import org.glassfish.appclient.client.acc.JWSACCClassLoader; +import org.glassfish.appclient.common.Util; + +import javax.swing.*; +import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; -import java.net.URLClassLoader; import java.security.Policy; import java.text.MessageFormat; import java.util.ResourceBundle; import java.util.Vector; -import javax.swing.SwingUtilities; -import org.glassfish.appclient.client.acc.AppClientContainer; -import org.glassfish.appclient.common.Util; -import org.glassfish.appclient.client.acc.JWSACCClassLoader; /** *Alternate main class for ACC, used when launched by Java Web Start. @@ -79,79 +74,79 @@ * @author tjquinn */ public class JWSACCMain implements Runnable { - + // /** path to a class in one of the app server lib jars downloaded by Java Web Start */ // private static final String APPSERVER_LIB_CLASS_NAME = "com.sun.enterprise.server.ApplicationServer"; - + /** name of the permissions template */ private static final String PERMISSIONS_TEMPLATE_NAME = "jwsclient.policy"; - + /** placeholder used in the policy template to substitute dynamically-generated grant clauses */ private static final String GRANT_CLAUSES_PROPERTY_EXPR = "${grant.clauses}"; - + /** line separator */ private static final String lineSep = System.getProperty("line.separator"); - + /** the user-specified security policy template to use */ private static String jwsPolicyTemplateURL = null; - + /** unpublished command-line argument conveying jwsacc information */ private static final String JWSACC_ARGUMENT_PREFIX = "-jwsacc"; - + private static final String JWSACC_EXIT_AFTER_RETURN = "ExitAfterReturn"; - + private static final String JWSACC_FORCE_ERROR = "ForceError"; - + private static final String JWSACC_KEEP_JWS_CLASS_LOADER = "KeepJWSClassLoader"; - + private static final String JWSACC_RUN_ON_SWING_THREAD = "RunOnSwingThread"; - + /** grant clause template for dynamically populating the policy */ private static final String GRANT_CLAUSE_TEMPLATE = "grant codeBase \"{0}\" '{'\n" + - " permission java.security.AllPermission;\n" + + " permission java.security.AllPermission;\n" + "'}';"; - + /** * request to exit the JVM upon return from the client - should be set (via - * the -jwsacc command-line argument value) only for + * the -jwsacc command-line argument value) only for * command-line clients; otherwise it can prematurely end the JVM when * the GUI and other user work is continuing */ private static boolean exitAfterReturn = false; - + /* *Normally the ACC is not run with the Java Web Start classloader as the *parent class loader because this causes problems loading dynamic stubs. - *To profile performance, though, sometimes we need to keep the JWS + *To profile performance, though, sometimes we need to keep the JWS *class loader as the parent rather than skipping it. */ private static boolean keepJWSClassLoader = false; - + private static boolean runOnSwingThread = false; - + /** helper for building the class loader and policy changes */ private static ClassPathManager classPathManager = null; - + /** URLs for downloaded JAR files to be used in the class path */ private static URL [] downloadedJarURLs; - + /** URLs for persistence-related JAR files for the class path and permissions */ private static URL [] persistenceJarURLs; - + /** localizable strings */ - private static final ResourceBundle rb = + private static final ResourceBundle rb = ResourceBundle.getBundle( dotToSlash(JWSACCMain.class.getPackage().getName() + ".LocalStrings")); /** make the arguments passed to the constructor available to the main method */ private String args[]; - + /** Creates a new instance of JWSMain */ public JWSACCMain(String[] args) { this.args = args; } - + /** * @param args the command line arguments */ @@ -162,7 +157,7 @@ public static void main(String[] args) { classPathManager = getClassPathManager(); downloadedJarURLs = classPathManager.locateDownloadedJars(); persistenceJarURLs = classPathManager.locatePersistenceJARs(); - + } catch (Throwable thr) { throw new IllegalArgumentException(rb.getString("jwsacc.errorLocJARs"), thr); } @@ -192,7 +187,7 @@ public static void main(String[] args) { System.exit(1); } } - + private static String dotToSlash(String orig) { return orig.replaceAll("\\.","/"); } @@ -234,7 +229,7 @@ public void run() { ErrorDisplayDialog.showErrors(thr, rb); } finally { /* - *If the user has requested, invoke System.exit as soon as the main + *If the user has requested, invoke System.exit as soon as the main *method returns. Do so on the Swing event thread so the ACC *main can complete whatever it may be doing. */ @@ -245,7 +240,7 @@ public void run() { System.out.printf("Exiting after return from client with status %1$d%n", statusValue); System.exit(statusValue); } - + public Runnable init(int exitStatus) { statusValue = exitStatus; return this; @@ -260,7 +255,7 @@ public Runnable init(int exitStatus) { } } } - + /** *Process any command line arguments that are targeted for the *Java Web Start ACC main program (this class) as opposed to the @@ -278,11 +273,11 @@ private static String[] prepareJWSArgs(String[] args) { nonJWSACCArgs.add(arg); } } - + processJWSArgs(JWSACCArgs); return nonJWSACCArgs.toArray(new String[nonJWSACCArgs.size()]); } - + /** *Interpret the JWSACC arguments (if any) supplied on the command line. *@param args the JWSACC arguments @@ -300,16 +295,16 @@ private static void processJWSArgs(Vector args) { } } } - + private static void setPermissions() { try { /* *Get the permissions template and write it to a temporary file. */ String permissionsTemplate = Util.loadResource(JWSACCMain.class, PERMISSIONS_TEMPLATE_NAME); - + /* - *Prepare the grant clauses for the downloaded jars and substitute + *Prepare the grant clauses for the downloaded jars and substitute *those clauses into the policy template. */ StringBuilder grantClauses = new StringBuilder(); @@ -317,17 +312,17 @@ private static void setPermissions() { for (URL url : downloadedJarURLs) { grantClauses.append(MessageFormat.format(GRANT_CLAUSE_TEMPLATE, url.toExternalForm())); } - + for (URL url : persistenceJarURLs) { grantClauses.append(MessageFormat.format(GRANT_CLAUSE_TEMPLATE, url.toExternalForm())); } - + String substitutedPermissionsTemplate = permissionsTemplate.replace(GRANT_CLAUSES_PROPERTY_EXPR, grantClauses.toString()); boolean retainTempFiles = Boolean.getBoolean(AppClientContainer.APPCLIENT_RETAIN_TEMP_FILES_PROPERTYNAME); File policyFile = writeTextToTempFile(substitutedPermissionsTemplate, "jwsacc", ".policy", retainTempFiles); refreshPolicy(policyFile); - + } catch (IOException ioe) { throw new RuntimeException("Error loading permissions template", ioe); } @@ -343,14 +338,14 @@ public static int firstFreePolicyIndex() { do { propValue = java.security.Security.getProperty("policy.url." + String.valueOf(++i)); } while ((propValue != null) && ( ! propValue.equals(""))); - + return i; } - + /** *Refreshes the current policy object using the contents of the specified file *as additional policy. - *@param policyFile the file containing additional policy + *@param policyFile the file containing additional policy */ public static void refreshPolicy(File policyFile) { int idx = firstFreePolicyIndex(); @@ -359,7 +354,7 @@ public static void refreshPolicy(File policyFile) { Policy p = Policy.getPolicy(); p.refresh(); } - + /** *The methods below are duplicates from the com.sun.enterprise.appclient.jws.Util class. *At the time this class is running, Java Web Start will not yet permit the Util class to @@ -378,48 +373,41 @@ public static void refreshPolicy(File policyFile) { *@throws FileNotFoundException if the temp file cannot be opened for any reason */ private static File writeTextToTempFile(String content, String prefix, String suffix, boolean retainTempFiles) throws IOException, FileNotFoundException { - BufferedWriter wtr = null; - try { - File result = File.createTempFile(prefix, suffix); - if ( ! retainTempFiles) { - result.deleteOnExit(); - } - FileOutputStream fos = new FileOutputStream(result); - wtr = new BufferedWriter(new OutputStreamWriter(fos)); + File result = File.createTempFile(prefix, suffix); + if ( ! retainTempFiles) { + result.deleteOnExit(); + } + try (BufferedWriter wtr = + new BufferedWriter(new OutputStreamWriter(new FileOutputStream(result)))){ wtr.write(content); - wtr.close(); - return result; - } finally { - if (wtr != null) { - wtr.close(); - } } + return result; } - + /** *Create the class loader for loading code from the unsigned downloaded *app server jars. *

*During a Java Web Start launch the ACC will be run under this class loader. - *Otherwise the JNLPClassLoader will load any stub classes that are + *Otherwise the JNLPClassLoader will load any stub classes that are *packaged at the top-level of the generated app client jar file. (It can *see them because it downloaded the gen'd app client jar, and therefore *includes the downloaded jar in its class path. This allows it to see the *classes at the top level of the jar but does not automatically let it see *classes in the jars nested within the gen'd app client jar. As a result, - *the JNLPClassLoader would be the one to try to define the class for a + *the JNLPClassLoader would be the one to try to define the class for a *web services stub, for instance. But the loader will not be able to find - *other classes and interfaces needed to completely define the class - + *other classes and interfaces needed to completely define the class - *because these are in the jars nested inside the gen'd app client jar. So *the attempt to define the class would fail. *@param downloadedAppclientJarFile the app client jar file *@return the class loader */ private static ClassLoader prepareClassLoader(File downloadedAppclientJarFile) throws IOException, URISyntaxException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { - ClassLoader ldr = new JWSACCClassLoader(downloadedJarURLs, classPathManager.getParentClassLoader()); + ClassLoader ldr = new JWSACCClassLoader(downloadedJarURLs, classPathManager.getParentClassLoader()); return ldr; } - + /* *Returns the jar that contains the specified resource. *@param target entry name to look for @@ -437,7 +425,7 @@ private static File findContainingJar(String target, ClassLoader loader) throws } return result; } - + /** *Locate the app client jar file during a Java Web Start launch. *@param loader the class loader to use in searching for the descriptor entries @@ -461,7 +449,7 @@ private File findAppClientFileForJWSLaunch(ClassLoader loader) throws URISyntaxE } return containingJar; } - + /** *Return the class path manager appropriate to the current version. *@return the correct type of ClassPathManager diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/Util.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/Util.java index 655dad8bee7..6a6deb8238d 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/Util.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/common/Util.java @@ -152,22 +152,15 @@ public static String getMainClassNameForAppClient(ModuleDescriptor moduleDescr) *@throws FileNotFoundException if the temp file cannot be opened for any reason */ public static File writeTextToTempFile(String content, String prefix, String suffix, boolean retainFile) throws IOException, FileNotFoundException { - BufferedWriter wtr = null; - try { - File result = File.createTempFile(prefix, suffix); - if ( ! retainFile) { - result.deleteOnExit(); - } - FileOutputStream fos = new FileOutputStream(result); - wtr = new BufferedWriter(new OutputStreamWriter(fos)); + File result = File.createTempFile(prefix, suffix); + if ( ! retainFile) { + result.deleteOnExit(); + } + try (BufferedWriter wtr = + new BufferedWriter(new OutputStreamWriter(new FileOutputStream(result)))) { wtr.write(content); - wtr.close(); - return result; - } finally { - if (wtr != null) { - wtr.close(); - } } + return result; } /** diff --git a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java index 8a0aa778fa9..0dcc7e2e98e 100644 --- a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java +++ b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java @@ -44,13 +44,10 @@ import com.sun.enterprise.naming.spi.NamingObjectFactory; import com.sun.enterprise.naming.spi.NamingUtils; - import org.glassfish.logging.annotation.LogMessageInfo; - import org.jvnet.hk2.annotations.Service; import javax.inject.Singleton; - import javax.naming.Context; import java.io.*; import java.security.AccessController; @@ -58,7 +55,9 @@ import java.util.logging.Level; import static com.sun.enterprise.naming.util.LogFacade.logger; -import static org.glassfish.common.util.ObjectInputOutputStreamFactoryFactory.getFactory;; +import static org.glassfish.common.util.ObjectInputOutputStreamFactoryFactory.getFactory; + +; /** * This is a utils class for refactoring the following method. @@ -107,42 +106,41 @@ public NamingObjectFactory createDelegatingNamingObjectFactory(String name, NamingObjectFactory delegate, boolean cacheResult) { return new DelegatingNamingObjectFactory(name, delegate, cacheResult); } - + @Override public Object makeCopyOfObject(Object obj) { if ( !(obj instanceof Context) && (obj instanceof Serializable) ) { if(logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "** makeCopyOfObject:: " + obj); } - try { // first serialize the object - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = getFactory().createObjectOutputStream(bos); - oos.writeObject(obj); - oos.flush(); - byte[] data = bos.toByteArray(); - oos.close(); - bos.close(); - + byte[] data = serialize(obj); // now deserialize it - ByteArrayInputStream bis = new ByteArrayInputStream(data); - final ObjectInputStream ois = getFactory().createObjectInputStream(bis); - obj = AccessController.doPrivileged(new PrivilegedExceptionAction() { - @Override - public Object run() throws IOException, ClassNotFoundException { - return ois.readObject(); - } - }); - return obj; + return deserialize(data); } catch (Exception ex) { logger.log(Level.SEVERE, EXCEPTION_COPY_MUTABLE, ex); - RuntimeException re = new RuntimeException("Cant copy Serializable object:", ex); - throw re; + throw new RuntimeException("Cant copy Serializable object:", ex); } } else { // XXX no copy ? return obj; } } + + private Object deserialize(byte[] data) throws IOException, java.security.PrivilegedActionException { + try(final ObjectInputStream ois = + getFactory().createObjectInputStream(new ByteArrayInputStream(data))){ + return AccessController.doPrivileged((PrivilegedExceptionAction) () -> ois.readObject()); + } + } + + private byte[] serialize(Object obj) throws IOException { + try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = getFactory().createObjectOutputStream(bos)) { + oos.writeObject(obj); + oos.flush(); + return bos.toByteArray(); + } + } } diff --git a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/JarResourceExtractor.java b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/JarResourceExtractor.java index ff3eccc9116..02f4f1b3854 100644 --- a/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/JarResourceExtractor.java +++ b/appserver/connectors/connectors-runtime/src/main/java/com/sun/enterprise/connectors/util/JarResourceExtractor.java @@ -52,7 +52,7 @@ /** * JarResourceExtractor: JarResourceExtractor maps all resources included in a Zip or Jar file. * Additionaly, it provides a method to extract one as a blob. - * + * * @author Sivakumar Thyagarajan */ @@ -61,21 +61,21 @@ public final class JarResourceExtractor { //resourceName as String Vs contents as byte[] private Hashtable htJarContents = new Hashtable(); - + /** * creates a JarResourceExtractor. It extracts all resources from a Jar into an * internal hashtable, keyed by resource names. - * + * * @param jarFileName * a jar or zip file */ public JarResourceExtractor(String jarFileName) { init(jarFileName); } - + /** * Extracts a jar resource as a blob. - * + * * @param name * a resource name. */ @@ -85,33 +85,21 @@ public byte[] getResource(String name) { } return (byte[]) htJarContents.get(name); } - + /** initializes internal hash tables with Jar file resources. */ private void init(String jarFileName) { - ZipInputStream zis = null; - try { - //extract resources and put them into the hashtable. - FileInputStream fis = new FileInputStream(jarFileName); - BufferedInputStream bis = new BufferedInputStream(fis); - zis = new ZipInputStream(bis); + //extract resources and put them into the hashtable. + try (ZipInputStream zis = + new ZipInputStream(new BufferedInputStream(new FileInputStream(jarFileName)))) { extractResources(zis); } catch (Exception ex){ - ex.printStackTrace(); - }finally{ - if(zis != null){ - try{ - zis.close(); - }catch(Exception e){} + if(_logger.isLoggable(Level.WARNING)) { + _logger.log(Level.WARNING, "ExtractResources failed.", ex); } } - } - - /** - * @throws FileNotFoundException - * @throws IOException - */ - private void extractResources(ZipInputStream zis) throws FileNotFoundException, IOException { + + private void extractResources(ZipInputStream zis) throws IOException { ZipEntry ze = null; while ((ze = zis.getNextEntry()) != null) { if(_logger.isLoggable(Level.FINER)) { @@ -120,11 +108,7 @@ private void extractResources(ZipInputStream zis) throws FileNotFoundException, extractZipEntryContents(ze, zis); } } - - /** - * @param zis - * @throws IOException - */ + private void extractZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOException { if (ze.isDirectory()) { return; @@ -157,19 +141,19 @@ private void extractZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOE } } } - + private byte[] getZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOException{ int size = (int) ze.getSize(); - + byte[] b = null; // -1 means unknown size. if (size != -1) { //got a proper size, read 'size' bytes b = new byte[(int) size]; - + int rb = 0; int chunk = 0; - + while (((int) size - rb) > 0) { chunk = zis.read(b, rb, (int) size - rb); if (chunk == -1) { @@ -193,7 +177,7 @@ private byte[] getZipEntryContents(ZipEntry ze, ZipInputStream zis) throws IOExc b[i] = btArr[i].byteValue(); } } - + return b; } } diff --git a/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java b/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java index f0c16d2906e..fd0ee0ccd0b 100644 --- a/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java +++ b/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java @@ -45,14 +45,13 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import java.io.IOException; +import java.io.Reader; import java.util.Base64; import java.util.List; import java.util.function.Supplier; -import javax.json.Json; -import javax.json.JsonObject; -import javax.json.JsonString; -import javax.json.JsonValue; +import javax.json.*; +import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import javax.naming.InitialContext; import javax.naming.NamingException; @@ -78,14 +77,12 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - JsonObject requestPayload = - Json.createReader(request.getReader()) - .readObject(); - + + final JsonObject requestPayload = readJsonObject(request.getReader()); + if (request.getRequestURI().endsWith("lookup")) { boolean success = excuteInAppContext(() -> { - + try { response.getWriter().print( new InitialContext().lookup(requestPayload.getString("lookup")) @@ -96,69 +93,75 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } catch (IOException | NamingException e) { // Ignore for now } - + return false; }); - + if (!success) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Name " + requestPayload.getString("lookup") + " not found when doing initial lookup"); } - + return; } - + // Convert JSON encoded method parameter type names to actually Class instances - Class[] argTypes = + Class[] argTypes = requestPayload.getJsonArray("argTypes").stream() .map(e -> toClass(e)) .toArray(Class[]::new); - + // Convert JSON encoded method parameter values to their object instances List jsonArgValues = requestPayload.getJsonArray("argValues"); Object[] argValues = new Object[argTypes.length]; for (int i = 0; i < jsonArgValues.size(); i++) { argValues[i] = toObject(jsonArgValues.get(i), argTypes[i]); } - + boolean success = excuteInAppContext(() -> { try { // Obtain the target EJB that we're going to invoke Object bean = new InitialContext().lookup(requestPayload.getString("lookup")); - + // Authenticates the caller and if successful sets the security context // *for the outgoing EJB call*. In other words, the security context for this // Servlet will not be changed. if (requestPayload.containsKey(SECURITY_PRINCIPAL)) { ProgrammaticLogin login = new ProgrammaticLogin(); login.login( - base64Decode(requestPayload.getString(SECURITY_PRINCIPAL)), + base64Decode(requestPayload.getString(SECURITY_PRINCIPAL)), base64Decode(requestPayload.getString(SECURITY_CREDENTIALS)), null, true); } - + // Actually invoke the target EJB - Object result = + Object result = bean.getClass() .getMethod(requestPayload.getString("method"), argTypes) .invoke(bean, argValues); - + response.setContentType(APPLICATION_JSON); response.getWriter().print(result instanceof String? result : JsonbBuilder.create().toJson(result)); - + return true; - + } catch (Exception e) { e.printStackTrace(); } - + return false; }); - + if (!success) { response.sendError(SC_INTERNAL_SERVER_ERROR, "Name " + requestPayload.getString("lookup") + " not found when invoking"); } } - + + private JsonObject readJsonObject(Reader reader) { + try (JsonReader jsonReader = Json.createReader(reader)) { + return jsonReader.readObject(); + } + } + private Class toClass(JsonValue classNameValue) { try { String className = null; @@ -167,28 +170,30 @@ private Class toClass(JsonValue classNameValue) { } else { className = classNameValue.toString().replace("\"", ""); } - return Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } - + private Object toObject(JsonValue objectValue, Class type) { - return JsonbBuilder - .create() - .fromJson(objectValue.toString(), type); + try(Jsonb jsonb = JsonbBuilder.create()) { + return jsonb.fromJson(objectValue.toString(), type); + } catch (Exception e) { + // cannot really happen. It is just from java.lang.AutoCloseable interface + throw new IllegalStateException("Problem closing Jsonb.", e); + } } - + private boolean excuteInAppContext(Supplier body) { ApplicationRegistry registry = Globals.get(ApplicationRegistry.class); - + for (String applicationName : registry.getAllApplicationNames()) { ClassLoader existingContextClassLoader = Thread.currentThread().getContextClassLoader(); try { - + Thread.currentThread().setContextClassLoader(registry.get(applicationName).getAppClassLoader()); - + try { if (body.get()) { return true; @@ -196,18 +201,18 @@ private boolean excuteInAppContext(Supplier body) { } catch (Exception e) { // ignore } - + } finally { if (existingContextClassLoader != null) { Thread.currentThread().setContextClassLoader(existingContextClassLoader); } } - + } - + return false; } - + private static String base64Decode(String input) { return new String(Base64.getDecoder().decode(input)); } diff --git a/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java b/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java index 6efc2714e72..ba2fd01e98e 100644 --- a/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java +++ b/appserver/ha/ha-file-store/src/main/java/org/glassfish/ha/store/adapter/file/FileBackingStore.java @@ -40,12 +40,15 @@ package org.glassfish.ha.store.adapter.file; -import org.glassfish.ha.store.api.*; +import org.glassfish.ha.store.api.BackingStore; +import org.glassfish.ha.store.api.BackingStoreConfiguration; +import org.glassfish.ha.store.api.BackingStoreException; +import org.glassfish.ha.store.api.BackingStoreFactory; import java.io.*; - import java.util.Map; -import java.util.logging.*; +import java.util.logging.Level; +import java.util.logging.Logger; /** * An implementation of BackingStore that uses file system to @@ -84,10 +87,10 @@ protected void initialize(BackingStoreConfiguration conf) if (conf.getLogger() != null) { logger = conf.getLogger(); } - + super.initialize(conf); debugStr = "[FileBackingStore - " + conf.getStoreName() + "] "; - + baseDir = conf.getBaseDirectory(); try { @@ -122,20 +125,17 @@ public BackingStoreFactory getBackingStoreFactory() { public V load(K key, String version) throws BackingStoreException { String fileName = key.toString(); - V value = null; - if (logger.isLoggable(TRACE_LEVEL)) { logger.log(TRACE_LEVEL, debugStr + "Entered load(" + key + ", " + version + ")"); } + V value = null; byte[] data = readFromfile(fileName); if (data != null) { - try { - ByteArrayInputStream bis2 = new ByteArrayInputStream(data); - ObjectInputStream ois = super.createObjectInputStream(bis2); + try (ObjectInputStream ois = + super.createObjectInputStream(new ByteArrayInputStream(data))) { value = (V) ois.readObject(); - if (logger.isLoggable(TRACE_LEVEL)) { logger.log(TRACE_LEVEL, debugStr + "Done load(" + key + ", " + version + ")"); } @@ -143,7 +143,7 @@ public V load(K key, String version) throws BackingStoreException { logger.log(Level.WARNING,debugStr + "Failed to load(" + key + ", " + version + ")", ex); } } - + return value; } @@ -198,7 +198,7 @@ public int removeExpired() { return removeExpired(defaultMaxIdleTimeoutInSeconds * 1000L); } - //TODO: deprecate after next shoal integration + //TODO: deprecate after next shoal integration public int removeExpired(long idleForMillis) { long threshold = System.currentTimeMillis() - idleForMillis; int expiredSessions = 0; @@ -271,7 +271,7 @@ public void updateTimeStamp(K k, String version, long timeStamp) throws BackingStoreException { updateTimestamp(k, timeStamp); } - + public void updateTimestamp(K sessionKey, long time) throws BackingStoreException { if (logger.isLoggable(TRACE_LEVEL)) { diff --git a/appserver/payara-appserver-modules/microprofile/metrics/src/main/java/fish/payara/microprofile/metrics/writer/JsonWriter.java b/appserver/payara-appserver-modules/microprofile/metrics/src/main/java/fish/payara/microprofile/metrics/writer/JsonWriter.java index dabbc0159f1..1ee30ad68c8 100644 --- a/appserver/payara-appserver-modules/microprofile/metrics/src/main/java/fish/payara/microprofile/metrics/writer/JsonWriter.java +++ b/appserver/payara-appserver-modules/microprofile/metrics/src/main/java/fish/payara/microprofile/metrics/writer/JsonWriter.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright (c) [2018] Payara Foundation and/or its affiliates. All rights reserved. - * + * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You @@ -11,20 +11,20 @@ * https://github.com/payara/Payara/blob/master/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. - * + * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. - * + * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. - * + * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" - * + * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] @@ -43,24 +43,23 @@ import fish.payara.microprofile.metrics.MetricsService; import fish.payara.microprofile.metrics.exception.NoSuchMetricException; import fish.payara.microprofile.metrics.exception.NoSuchRegistryException; +import org.glassfish.internal.api.Globals; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; import java.io.IOException; import java.io.Writer; import java.util.Map; import java.util.logging.Logger; + import static java.util.stream.Collectors.joining; -import javax.json.Json; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; -import javax.json.JsonWriterFactory; -import static org.eclipse.microprofile.metrics.MetricRegistry.Type.APPLICATION; -import static org.eclipse.microprofile.metrics.MetricRegistry.Type.BASE; -import static org.eclipse.microprofile.metrics.MetricRegistry.Type.VENDOR; -import org.glassfish.internal.api.Globals; +import static org.eclipse.microprofile.metrics.MetricRegistry.Type.*; public abstract class JsonWriter implements MetricsWriter { private final Writer writer; - + protected final MetricsService service; protected static final Logger LOGGER = Logger.getLogger(JsonWriter.class.getName()); @@ -133,18 +132,20 @@ public void write() throws IOException { } protected void serialize(JsonObject payload) throws IOException { - JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(null); - jsonWriterFactory.createWriter(writer).writeObject(payload); + try (javax.json.JsonWriter jsonWriter = + Json.createWriterFactory(null).createWriter(writer)) { + jsonWriter.writeObject(payload); + } } protected JsonObject getJsonFromMap(Map map) { JsonObjectBuilder payloadBuilder = Json.createObjectBuilder(); for (Map.Entry entry : map.entrySet()) { - addValueToJsonObject(payloadBuilder, entry.getKey(), entry.getValue()); + addValueToJsonObject(payloadBuilder, entry.getKey(), entry.getValue()); } return payloadBuilder.build(); } - + protected void addValueToJsonObject(JsonObjectBuilder payloadBuilder, String key, Number value){ if (value instanceof Integer) { payloadBuilder.add(key, value.intValue()); diff --git a/appserver/payara-appserver-modules/security-oauth2/src/main/java/fish/payara/security/oauth2/OAuth2AuthenticationMechanism.java b/appserver/payara-appserver-modules/security-oauth2/src/main/java/fish/payara/security/oauth2/OAuth2AuthenticationMechanism.java index 0748db199b3..b9c443b12fd 100644 --- a/appserver/payara-appserver-modules/security-oauth2/src/main/java/fish/payara/security/oauth2/OAuth2AuthenticationMechanism.java +++ b/appserver/payara-appserver-modules/security-oauth2/src/main/java/fish/payara/security/oauth2/OAuth2AuthenticationMechanism.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright (c) [2018] Payara Foundation and/or its affiliates. All rights reserved. - * + * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You @@ -11,20 +11,20 @@ * https://github.com/payara/Payara/blob/master/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. - * + * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. - * + * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. - * + * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" - * + * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] @@ -48,6 +48,7 @@ import javax.json.Json; import javax.json.JsonObject; +import javax.json.JsonReader; import javax.security.enterprise.AuthenticationException; import javax.security.enterprise.AuthenticationStatus; import javax.security.enterprise.authentication.mechanism.http.AutoApplySession; @@ -86,7 +87,7 @@ public class OAuth2AuthenticationMechanism implements HttpAuthenticationMechanism { private static final Logger logger = Logger.getLogger("OAuth2Mechanism"); - + private final ELProcessor elProcessor; private String authEndpoint; @@ -105,7 +106,7 @@ public class OAuth2AuthenticationMechanism implements HttpAuthenticationMechanis @Inject private IdentityStoreHandler identityStoreHandler; - + /** * Creates an OAuth2AuthenticationMechanism. *

@@ -143,7 +144,7 @@ public OAuth2AuthenticationMechanism setDefinition(OAuth2AuthenticationDefinitio clientSecret = getConfiguredValue(definition.clientSecret(), provider, OAuth2AuthenticationDefinition.OAUTH2_MP_CLIENT_SECRET).toCharArray(); redirectURI = getConfiguredValue(definition.redirectURI(), provider, OAuth2AuthenticationDefinition.OAUTH2_MP_REDIRECT_URI); scopes = getConfiguredValue(definition.scope(), provider, OAuth2AuthenticationDefinition.OAUTH2_MP_SCOPE); - + String[] params = definition.extraParameters(); extraParameters = new String[params.length]; for (int i = 0; i < params.length; i++) { @@ -215,7 +216,7 @@ private AuthenticationStatus validateCallback(HttpServletRequest request, HttpMe // Get back the result of the REST request String result = oauthResponse.readEntity(String.class); - JsonObject object = Json.createReader(new StringReader(result)).readObject(); + JsonObject object = readJsonObject(result); logger.log(Level.FINEST, "Response code from endpoint: {0}", oauthResponse.getStatus()); if (oauthResponse.getStatus() != 200) { @@ -239,6 +240,12 @@ private AuthenticationStatus validateCallback(HttpServletRequest request, HttpMe } } + private JsonObject readJsonObject(String result) { + try (JsonReader reader = Json.createReader(new StringReader(result))) { + return reader.readObject(); + } + } + /** * If the user is not logged in then redirect them to OAuth provider * @@ -264,7 +271,7 @@ private AuthenticationStatus redirectForAuth(HttpMessageContext context) { return context.redirect(authTokenRequest.toString()); } - + private String getConfiguredValue(String value, Config provider, String mpConfigKey){ String result = value; Optional configResult = provider.getOptionalValue(mpConfigKey, String.class); @@ -275,14 +282,14 @@ private String getConfiguredValue(String value, Config provider, String mpConfig if (isELExpression(value)){ result = (String) elProcessor.getValue(toRawExpression(result), String.class); } - + return result; } - + private static boolean isELExpression(String expression) { return !expression.isEmpty() && isDeferredExpression(expression); } - + private static boolean isDeferredExpression(String expression) { return expression.startsWith("#{") && expression.endsWith("}"); } diff --git a/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java b/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java index ca5879e459b..7b26296aad6 100644 --- a/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java +++ b/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java @@ -1,8 +1,8 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. - * + * * Copyright (c) [2018] Payara Foundation and/or its affiliates. All rights reserved. - * + * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You @@ -11,20 +11,20 @@ * https://github.com/payara/Payara/blob/master/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. - * + * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. - * + * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. - * + * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" - * + * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] @@ -63,6 +63,7 @@ import javax.inject.Inject; import javax.json.Json; import javax.json.JsonObject; +import javax.json.JsonReader; import javax.security.enterprise.AuthenticationException; import javax.security.enterprise.AuthenticationStatus; import javax.security.enterprise.authentication.mechanism.http.AutoApplySession; @@ -209,9 +210,8 @@ public AuthenticationStatus validateRequest( * Authorization Code Flow must be validated and exchanged for an ID Token, * an Access Token and optionally a Refresh Token directly. * - * @param request - * @param context - * @return + * @param httpContext the {@link HttpMessageContext} to validate authorization code from + * @return the authentication status. */ private AuthenticationStatus validateAuthorizationCode(HttpMessageContext httpContext) { HttpServletRequest request = httpContext.getRequest(); @@ -227,9 +227,7 @@ private AuthenticationStatus validateAuthorizationCode(HttpMessageContext httpCo LOGGER.finer("Authorization Code received, now fetching Access token & Id token"); Response response = tokenController.getTokens(configuration, request); - String tokensBody = response.readEntity(String.class); - JsonObject tokensObject = Json.createReader(new StringReader(tokensBody)).readObject(); - + JsonObject tokensObject = readJsonObject(response.readEntity(String.class)); if (response.getStatus() == Status.OK.getStatusCode()) { // Successful Token Response updateContext(tokensObject, httpContext); @@ -245,6 +243,12 @@ private AuthenticationStatus validateAuthorizationCode(HttpMessageContext httpCo } } + private JsonObject readJsonObject(String tokensBody) { + try(JsonReader reader = Json.createReader(new StringReader(tokensBody))) { + return reader.readObject(); + } + } + private void updateContext(JsonObject tokensObject, HttpMessageContext httpContext) { context.setProviderMetadata(configuration.getProviderMetadata().getDocument()); context.setTokenType(tokensObject.getString(TOKEN_TYPE, null)); diff --git a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java index e3fa53fd426..0736970a2ea 100644 --- a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java +++ b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/MarshallingUtils.java @@ -77,8 +77,7 @@ public static List> getPropertiesFromJson(String json) { properties = new ArrayList>(); properties.add(Util.processJsonMap(json)); } else if (json.startsWith("[")) { - try { - JsonParser parser = Json.createParser(new StringReader(json)); + try (JsonParser parser = Json.createParser(new StringReader(json))) { parser.next(); properties = Util.processJsonArray(parser.getArray()); } catch (JsonException e) { diff --git a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/Util.java b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/Util.java index f2474167a93..9db1506a552 100644 --- a/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/Util.java +++ b/nucleus/admin/rest/rest-client/src/main/java/org/glassfish/admin/rest/client/utils/Util.java @@ -3,10 +3,10 @@ * * Copyright (c) 2011-2013 Oracle and/or its affiliates. All rights reserved. * - * The contents of this file are subject to the terms of either the GNU + * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development - * and Distribution License("CDDL") (collectively, the "License"). You - * may not use this file except in compliance with the License. You can + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific @@ -28,7 +28,7 @@ * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] - * elects to include this software in this distribution under the [CDDL or GPL + * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to @@ -36,7 +36,7 @@ * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. - * + * */ // Portions Copyright [2017-2018] Payara Foundation and/or affiliates @@ -65,7 +65,7 @@ * @see org.glassfish.admin.rest.utils.JsonUtil */ public class Util { - + /** * Converts a String of JSON data into a map * If there is an error then an empty Map will be returned. @@ -74,16 +74,15 @@ public class Util { */ public static Map processJsonMap(String json) { Map map; - try { - JsonParser parser = Json.createParser(new StringReader(json)); + try (JsonParser parser = Json.createParser(new StringReader(json))) { if (parser.hasNext()){ parser.next(); - map = processJsonObject(parser.getObject()); + map = processJsonObject(parser.getObject()); } else { - map = new HashMap(); + map = new HashMap<>(); } } catch (JsonException e) { - map = new HashMap(); + map = new HashMap<>(); } return map; } @@ -95,10 +94,10 @@ public static Map processJsonMap(String json) { * {@link Map}, {@link Number}, {@code null} and/or {@link String}. *

* @param jsonObject - * @return + * @return */ - public static Map processJsonObject(JsonObject jsonObject) { - Map map = new HashMap(); + public static Map processJsonObject(JsonObject jsonObject) { + Map map = new HashMap<>(); try { for (String key : jsonObject.keySet()) { JsonValue value = jsonObject.get(key); @@ -120,7 +119,7 @@ public static Map processJsonObject(JsonObject jsonObject) { case TRUE: map.put(key, Boolean.TRUE); break; - case FALSE: + case FALSE: map.put(key, Boolean.FALSE); break; default: @@ -142,11 +141,11 @@ public static Map processJsonObject(JsonObject jsonObject) { * {@link Map}, {@link Number} and/or {@link String}. *

* @param jsonArray - * @return + * @return */ public static List processJsonArray(JsonArray jsonArray) { List results = new ArrayList(); - + try { for (JsonValue entry: jsonArray) { if (null == entry.getValueType()) { diff --git a/nucleus/admin/rest/rest-testing/src/main/java/org/glassfish/admin/rest/testing/Response.java b/nucleus/admin/rest/rest-testing/src/main/java/org/glassfish/admin/rest/testing/Response.java index d76be5e8947..08bbe2c61df 100644 --- a/nucleus/admin/rest/rest-testing/src/main/java/org/glassfish/admin/rest/testing/Response.java +++ b/nucleus/admin/rest/rest-testing/src/main/java/org/glassfish/admin/rest/testing/Response.java @@ -87,12 +87,13 @@ public String getStringBody() { } public JsonObject getJsonBody() throws Exception { - JsonParser parser = Json.createParser(new StringReader(getStringBody())); - if (parser.hasNext()){ - parser.next(); - return parser.getObject(); - } else { - return JsonValue.EMPTY_JSON_OBJECT; + try (JsonParser parser = Json.createParser(new StringReader(getStringBody()))){ + if (parser.hasNext()){ + parser.next(); + return parser.getObject(); + } else { + return JsonValue.EMPTY_JSON_OBJECT; + } } } diff --git a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/ScatteredArchive.java b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/ScatteredArchive.java index 52d8b7a29c1..f43a3f66086 100644 --- a/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/ScatteredArchive.java +++ b/nucleus/common/internal-api/src/main/java/org/glassfish/internal/embedded/ScatteredArchive.java @@ -334,14 +334,15 @@ public Enumeration entries() { f = new File(url.getPath()); } if (f.isFile()) { - JarFile jar = new JarFile(f); - Enumeration jarEntries = jar.entries(); - while (jarEntries.hasMoreElements()) { - JarEntry jarEntry = jarEntries.nextElement(); - if (jarEntry.isDirectory()) { - continue; + try (JarFile jar = new JarFile(f)) { + Enumeration jarEntries = jar.entries(); + while (jarEntries.hasMoreElements()) { + JarEntry jarEntry = jarEntries.nextElement(); + if (jarEntry.isDirectory()) { + continue; + } + entries.add(jarEntry.getName()); } - entries.add(jarEntry.getName()); } } else { getListOfFiles(f, prefix, entries); @@ -360,12 +361,17 @@ public Enumeration entries() { private void getListOfFiles(File directory, String prefix, List list) { if (!directory.isDirectory()) return; - for (File f : directory.listFiles()) { - String name = prefix==null?f.getName():prefix+"/"+f.getName(); - if (f.isDirectory()) { - getListOfFiles(f, name ,list); - } else { - list.add(name); + File[] files = directory.listFiles(); + if (files != null) { + for (File file : files) { + String name = prefix == null + ? file.getName() + : prefix + "/" + file.getName(); + if (file.isDirectory()) { + getListOfFiles(file, name ,list); + } else { + list.add(name); + } } } } @@ -511,7 +517,7 @@ public File getFile(String name) { private JarFile getJarWithEntry(String name) { for (URL url : urls) { - File f = null; + File f; try { f = new File(url.toURI()); } catch(URISyntaxException e) { @@ -522,6 +528,8 @@ private JarFile getJarWithEntry(String name) { JarFile jar = new JarFile(f); if (jar.getEntry(name) != null) { return jar; + } else { + jar.close(); } } } catch (Exception ex) { diff --git a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/Assembler.java b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/Assembler.java index 0fbfb35adb2..3499525eab4 100644 --- a/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/Assembler.java +++ b/nucleus/common/scattered-archive-api/src/main/java/org/glassfish/embeddable/archive/Assembler.java @@ -88,19 +88,19 @@ private URI assembleEAR(String name, Map archives, Map metadatas) throws IOException { File ear = new File(System.getProperty("java.io.tmpdir"), name + ".ear"); ear.deleteOnExit(); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(ear)); - for (Map.Entry me : metadatas.entrySet()) { - tranferFile(me.getValue(), jos, me.getKey(), false); - } - for (Map.Entry ame : archives.entrySet()) { - File archive = ame.getValue(); - if (archive.isDirectory()) { - archive = new File(assembleJAR(ame.getKey(), archive, - Collections.EMPTY_LIST, Collections.EMPTY_MAP)); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(ear))) { + for (Map.Entry me : metadatas.entrySet()) { + tranferFile(me.getValue(), jos, me.getKey(), false); + } + for (Map.Entry ame : archives.entrySet()) { + File archive = ame.getValue(); + if (archive.isDirectory()) { + archive = new File(assembleJAR(ame.getKey(), archive, + Collections.emptyList(), Collections.emptyMap())); + } + tranferFile(archive, jos, ame.getKey(), false); } - tranferFile(archive, jos, ame.getKey(), false); } - jos.close(); return ear.toURI(); } @@ -110,20 +110,20 @@ URI assembleWAR(String name, File rootDirectory, List classpaths, File archive = new File(System.getProperty("java.io.tmpdir"), name + ".war"); archive.deleteOnExit(); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(archive)); - - transferDir(rootDirectory, jos, ""); - for (Map.Entry me : metadatas.entrySet()) { - tranferFile(me.getValue(), jos, me.getKey(), false); - } - for (File classpath : classpaths) { - if (classpath.isDirectory()) { - transferDir(classpath, jos, "WEB-INF/classes/"); - } else { - tranferFile(classpath, jos, "WEB-INF/lib/" + classpath.getName(), false); + try(JarOutputStream jos = new JarOutputStream(new FileOutputStream(archive))) { + transferDir(rootDirectory, jos, ""); + for (Map.Entry me : metadatas.entrySet()) { + tranferFile(me.getValue(), jos, me.getKey(), false); + } + for (File classpath : classpaths) { + if (classpath.isDirectory()) { + transferDir(classpath, jos, "WEB-INF/classes/"); + } else { + tranferFile(classpath, jos, "WEB-INF/lib/" + classpath.getName(), false); + } } } - jos.close(); + return archive.toURI(); } @@ -131,19 +131,19 @@ URI assembleJAR(String name, File rootDirectory, List classpaths, Map metadatas) throws IOException { File archive = new File(System.getProperty("java.io.tmpdir"), name + ".jar"); archive.deleteOnExit(); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(archive)); - transferDir(rootDirectory, jos, ""); - for (Map.Entry me : metadatas.entrySet()) { - tranferFile(me.getValue(), jos, me.getKey(), false); - } - for (File classpath : classpaths) { - if (classpath.isDirectory()) { - transferDir(classpath, jos, ""); - } else { - tranferFile(classpath, jos, "", true); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(archive))) { + transferDir(rootDirectory, jos, ""); + for (Map.Entry me : metadatas.entrySet()) { + tranferFile(me.getValue(), jos, me.getKey(), false); + } + for (File classpath : classpaths) { + if (classpath.isDirectory()) { + transferDir(classpath, jos, ""); + } else { + tranferFile(classpath, jos, "", true); + } } } - jos.close(); return archive.toURI(); } @@ -151,42 +151,41 @@ URI assembleRAR(String name, File rootDirectory, List classpaths, Map metadatas) throws IOException { File rar = new File(System.getProperty("java.io.tmpdir"), name + ".rar"); rar.deleteOnExit(); - JarOutputStream jos = new JarOutputStream(new FileOutputStream(rar)); - transferDir(rootDirectory, jos, ""); - for (Map.Entry me : metadatas.entrySet()) { - tranferFile(me.getValue(), jos, me.getKey(), false); - } - - // Make a single connector jar out of all the classpath directories and add it to the RAR file. - List classpathDirs = new ArrayList(); - for (File classpath : classpaths) { - if (classpath.isDirectory()) { - classpathDirs.add(classpath); + try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(rar))) { + transferDir(rootDirectory, jos, ""); + for (Map.Entry me : metadatas.entrySet()) { + tranferFile(me.getValue(), jos, me.getKey(), false); } - } - if (!classpathDirs.isEmpty()) { - // Compute a unique connector jar name - String connectorJarName = name; - List topLevelFileNames = new ArrayList(); - topLevelFileNames.addAll(getFileNames(classpaths)); - topLevelFileNames.addAll(getFileNames(rootDirectory)); - int count = 0; - while (topLevelFileNames.contains(connectorJarName + ".jar")) { - connectorJarName = name + "_" + count; - ++count; + // Make a single connector jar out of all the classpath directories and add it to the RAR file. + List classpathDirs = new ArrayList<>(); + for (File classpath : classpaths) { + if (classpath.isDirectory()) { + classpathDirs.add(classpath); + } + } + if (!classpathDirs.isEmpty()) { + // Compute a unique connector jar name + String connectorJarName = name; + List topLevelFileNames = new ArrayList<>(); + topLevelFileNames.addAll(getFileNames(classpaths)); + topLevelFileNames.addAll(getFileNames(rootDirectory)); + int count = 0; + while (topLevelFileNames.contains(connectorJarName + ".jar")) { + connectorJarName = name + "_" + count; + ++count; + } + File connectorJar = new File(assembleJAR(connectorJarName, null, + classpathDirs, Collections.emptyMap())); + tranferFile(connectorJar, jos, connectorJar.getName(), false); } - File connectorJar = new File(assembleJAR(connectorJarName, null, - classpathDirs, Collections.EMPTY_MAP)); - tranferFile(connectorJar, jos, connectorJar.getName(), false); - } - // Add all the classpath files to the RAR files. - for (File classpath : classpaths) { - if (!classpath.isDirectory()) { - tranferFile(classpath, jos, classpath.getName(), false); + // Add all the classpath files to the RAR files. + for (File classpath : classpaths) { + if (!classpath.isDirectory()) { + tranferFile(classpath, jos, classpath.getName(), false); + } } } - jos.close(); return rar.toURI(); } @@ -200,13 +199,16 @@ void transferDir(File basedir, File dir, JarOutputStream jos, String entryNamePr if (dir == null || jos == null) { return; } - for (File f : dir.listFiles()) { - if (f.isFile()) { - String entryName = entryNamePrefix + - f.getPath().substring(basedir.getPath().length() + 1); - tranferFile(f, jos, entryName, false); - } else { - transferDir(basedir, f, jos, entryNamePrefix); + File[] files = dir.listFiles(); + if (files != null) { + for (File f : files) { + if (f.isFile()) { + String entryName = entryNamePrefix + + f.getPath().substring(basedir.getPath().length() + 1); + tranferFile(f, jos, entryName, false); + } else { + transferDir(basedir, f, jos, entryNamePrefix); + } } } } @@ -230,18 +232,17 @@ void transferFile(File file, JarOutputStream jos, String entryName) throws IOExc } catch (ZipException ex) { return; } - FileInputStream fin = new FileInputStream(file); - transferContents(fin, jos); - jos.closeEntry(); + try(FileInputStream fin = new FileInputStream(file)) { + transferContents(fin, jos); + jos.closeEntry(); + } } void tranferEntries(File file, JarOutputStream jos) throws IOException { if (file == null || jos == null) { return; } - JarFile jarFile = null; - try { - jarFile = new JarFile(file); + try (JarFile jarFile = new JarFile(file)) { Enumeration entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); @@ -257,15 +258,6 @@ void tranferEntries(File file, JarOutputStream jos) throws IOException { } } } - } finally { - if (jarFile != null) { - try { - jarFile.close(); - } catch (IOException ioe) { - //ignore - } - } - } } @@ -284,13 +276,16 @@ void transferContents(InputStream fin, JarOutputStream jos) private List getFileNames(File directory) { if (directory != null && directory.exists() && directory.isDirectory()) { - return getFileNames(Arrays.asList(directory.listFiles())); + File[] files = directory.listFiles(); + if (files != null) { + return getFileNames(Arrays.asList(files)); + } } - return Collections.EMPTY_LIST; + return Collections.emptyList(); } private List getFileNames(List files) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (File f : files) { if (!f.isDirectory()) { result.add(f.getName()); @@ -299,7 +294,7 @@ private List getFileNames(List files) { return result; } - private static final List EXCLUDE_JAR_ENTRIES = new ArrayList(); + private static final List EXCLUDE_JAR_ENTRIES = new ArrayList<>(); static { EXCLUDE_JAR_ENTRIES.add(Pattern.compile("META-INF/MANIFEST\\.MF")); From 0b881559b7c623a0218117fdad4a7088540aab64 Mon Sep 17 00:00:00 2001 From: Sven Diedrichsen Date: Wed, 3 Apr 2019 22:32:31 +0200 Subject: [PATCH 2/2] Requested changes from code review. --- .../appclient/client/jws/boot/JWSACCMain.java | 4 ++-- .../enterprise/naming/util/NamingUtilsImpl.java | 14 ++++++-------- .../fish/payara/ejb/invoke/InvokeEJBServlet.java | 2 +- .../openid/OpenIdAuthenticationMechanism.java | 2 +- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java index 7d62f3d17c2..a6e0195ce04 100644 --- a/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java +++ b/appserver/appclient/client/acc/src/main/java/org/glassfish/appclient/client/jws/boot/JWSACCMain.java @@ -44,7 +44,7 @@ import org.glassfish.appclient.client.acc.JWSACCClassLoader; import org.glassfish.appclient.common.Util; -import javax.swing.*; +import javax.swing.SwingUtilities; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -365,7 +365,7 @@ public static void refreshPolicy(File policyFile) { /** *Writes the provided text to a temporary file marked for deletion on exit. - *@param the content to be written + *@param content the content to be written *@param prefix for the temp file, conforming to the File.createTempFile requirements *@param suffix for the temp file *@return File object for the newly-created temp file diff --git a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java index 0dcc7e2e98e..ea81e40324e 100644 --- a/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java +++ b/appserver/common/glassfish-naming/src/main/java/com/sun/enterprise/naming/util/NamingUtilsImpl.java @@ -57,8 +57,6 @@ import static com.sun.enterprise.naming.util.LogFacade.logger; import static org.glassfish.common.util.ObjectInputOutputStreamFactoryFactory.getFactory; -; - /** * This is a utils class for refactoring the following method. */ @@ -129,18 +127,18 @@ public Object makeCopyOfObject(Object obj) { } private Object deserialize(byte[] data) throws IOException, java.security.PrivilegedActionException { - try(final ObjectInputStream ois = + try (final ObjectInputStream ois = getFactory().createObjectInputStream(new ByteArrayInputStream(data))){ return AccessController.doPrivileged((PrivilegedExceptionAction) () -> ois.readObject()); } } private byte[] serialize(Object obj) throws IOException { - try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream oos = getFactory().createObjectOutputStream(bos)) { - oos.writeObject(obj); - oos.flush(); - return bos.toByteArray(); + try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) { + try (final ObjectOutputStream oos = getFactory().createObjectOutputStream(bos)) { + oos.writeObject(obj); + } + return bos.toByteArray(); } } } diff --git a/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java b/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java index fd0ee0ccd0b..3611479f28f 100644 --- a/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java +++ b/appserver/ejb/ejb-http-remoting/endpoint/src/main/java/fish/payara/ejb/invoke/InvokeEJBServlet.java @@ -177,7 +177,7 @@ private Class toClass(JsonValue classNameValue) { } private Object toObject(JsonValue objectValue, Class type) { - try(Jsonb jsonb = JsonbBuilder.create()) { + try (Jsonb jsonb = JsonbBuilder.create()) { return jsonb.fromJson(objectValue.toString(), type); } catch (Exception e) { // cannot really happen. It is just from java.lang.AutoCloseable interface diff --git a/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java b/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java index 7b26296aad6..31ec9b570b4 100644 --- a/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java +++ b/appserver/payara-appserver-modules/security-openid/src/main/java/fish/payara/security/openid/OpenIdAuthenticationMechanism.java @@ -244,7 +244,7 @@ private AuthenticationStatus validateAuthorizationCode(HttpMessageContext httpCo } private JsonObject readJsonObject(String tokensBody) { - try(JsonReader reader = Json.createReader(new StringReader(tokensBody))) { + try (JsonReader reader = Json.createReader(new StringReader(tokensBody))) { return reader.readObject(); } }