Skip to content

Commit

Permalink
Merge pull request #3868 from svendiedrichsen/sonar-blocker-npe
Browse files Browse the repository at this point in the history
PAYARA-3723 Fixing sonar blocker bugs with unclosed resources and potential NPE
  • Loading branch information
Pandrex247 authored Apr 10, 2019
2 parents 79bb40d + 62163c6 commit e797815
Show file tree
Hide file tree
Showing 15 changed files with 366 additions and 393 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.SwingUtilities;
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.
Expand All @@ -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
*/
Expand All @@ -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);
}
Expand Down Expand Up @@ -192,7 +187,7 @@ public static void main(String[] args) {
System.exit(1);
}
}

private static String dotToSlash(String orig) {
return orig.replaceAll("\\.","/");
}
Expand Down Expand Up @@ -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.
*/
Expand All @@ -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;
Expand All @@ -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
Expand All @@ -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
Expand All @@ -300,34 +295,34 @@ private static void processJWSArgs(Vector<String> 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();

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);
}
Expand All @@ -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();
Expand All @@ -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
Expand All @@ -370,56 +365,49 @@ 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
*@throws IOException for any errors writing the temporary file
*@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.
*<p>
*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
Expand All @@ -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
Expand All @@ -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
Expand Down
Loading

0 comments on commit e797815

Please sign in to comment.