modules/fxpackager/src/main/java/com/sun/javafx/tools/packager/PackagerLib.java
Print this page
@@ -68,11 +68,10 @@
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Set;
@@ -87,11 +86,10 @@
import java.util.zip.ZipOutputStream;
import sun.misc.BASE64Encoder;
import static com.oracle.bundlers.StandardBundlerParam.*;
-
public class PackagerLib {
public static final String JAVAFX_VERSION = "2.2";
private static final ResourceBundle bundle =
ResourceBundle.getBundle("com/sun/javafx/tools/packager/Bundle");
@@ -109,11 +107,11 @@
private CreateBSSParams createBssParams;
private File bssTmpDir;
private boolean isSignedJNLP;
- private enum Filter {ALL, CLASSES_ONLY, RESOURCES};
+ private enum Filter {ALL, CLASSES_ONLY, RESOURCES}
private ClassLoader classLoader;
private ClassLoader getClassLoader() throws PackagerException {
if (classLoader == null) {
@@ -140,25 +138,16 @@
PackagerResource p = params.resources.get(0);
File f = p.getFile();
if (!f.isFile() || !f.getAbsolutePath().toLowerCase().endsWith(".jar")) {
return null;
}
- JarFile jf = null;
- try {
- jf = new JarFile(f);
+ try (JarFile jf = new JarFile(f)) {
Manifest m = jf.getManifest(); //try to read manifest to validate it is jar
return f;
} catch (Exception e) {
- //treat any excepion as "not a special case" scenario
+ //treat any exception as "not a special case" scenario
Log.verbose(e);
- } finally {
- if (jf != null) {
- try {
- jf.close();
- } catch (IOException ex) {
- }
- }
}
}
return null;
}
@@ -176,15 +165,13 @@
//Special case: could be request for "update jar file"
File jarToUpdate = jarFileToUpdate(createJarParams);
Manifest m = null;
if (jarToUpdate != null) {
- JarFile jf = null;
- try {
- //extract data we want to preserve
Log.info(MessageFormat.format(bundle.getString("MSG_UpdatingJar"), jarToUpdate.getAbsolutePath()));
- jf = new JarFile(jarToUpdate);
+ try (JarFile jf = new JarFile(jarToUpdate)) {
+ //extract data we want to preserve
m = jf.getManifest();
if (m != null) {
Attributes attrs = m.getMainAttributes();
if (createJarParams.applicationClass == null) {
createJarParams.applicationClass =
@@ -196,17 +183,10 @@
}
}
} catch (IOException ex) {
throw new PackagerException(
ex, "ERR_FileReadFailed", jarToUpdate.getAbsolutePath());
- } finally {
- if (jf != null) {
- try {
- jf.close();
- } catch (IOException ex) {
- }
- }
}
}
if (createJarParams.applicationClass == null) {
throw new IllegalArgumentException(
@@ -316,28 +296,19 @@
this.createJarParams = null;
}
private String readTextFile(File in) throws PackagerException {
StringBuilder sb = new StringBuilder();
- InputStreamReader isr = null;
- try {
+ try (InputStreamReader isr = new InputStreamReader(new FileInputStream(in))) {
char[] buf = new char[16384];
int len;
- isr = new InputStreamReader(new FileInputStream(in));
while ((len = isr.read(buf)) > 0) {
sb.append(buf, sb.length(), len);
}
} catch (IOException ex) {
throw new PackagerException(ex, "ERR_FileReadFailed",
in.getAbsolutePath());
- } finally {
- if (isr != null) {
- try {
- isr.close();
- } catch (IOException ex) {
- }
- }
}
return sb.toString();
}
private String processTemplate(String inpText,
@@ -403,22 +374,22 @@
}
m.appendTail(result);
return result.toString();
}
- private static enum Mode {FX, APPLET, SwingAPP};
+ private static enum Mode {FX, APPLET, SwingAPP}
public void generateDeploymentPackages(DeployParams deployParams) throws PackagerException {
if (deployParams == null) {
throw new IllegalArgumentException("Parameters must not be null.");
}
this.deployParams = deployParams;
boolean templateOn = !deployParams.templates.isEmpty();
Map<TemplatePlaceholders, String> templateStrings = null;
if (templateOn) {
templateStrings =
- new EnumMap<TemplatePlaceholders, String>(TemplatePlaceholders.class);
+ new EnumMap<>(TemplatePlaceholders.class);
}
try {
//In case of FX app we will have one JNLP and one HTML
//In case of Swing with FX we will have 2 JNLP files and one HTML
String jnlp_filename_webstart = deployParams.outfile + ".jnlp";
@@ -495,18 +466,18 @@
//copy jar files
for (DeployResource resource: deployParams.resources) {
copyFiles(resource, deployParams.outdir);
}
- } catch (Exception ex) {
- throw new PackagerException(ex, "ERR_DeployFailed");
- }
BundleParams bp = deployParams.getBundleParams();
if (bp != null) {
generateNativeBundles(deployParams.outdir, bp.getBundleParamsAsMap(), deployParams.getBundleType(), deployParams.getTargetFormat(), deployParams.verbose);
}
+ } catch (Exception ex) {
+ throw new PackagerException(ex, "ERR_DeployFailed", ex.getMessage());
+ }
this.deployParams = null;
}
private void generateNativeBundles(File outdir, Map<String, ? super Object> params, BundleType bundleType, String bundleFormat, boolean verbose) {
@@ -536,11 +507,15 @@
}
} catch (UnsupportedPlatformException e) {
Log.debug(MessageFormat.format(bundle.getString("MSG_BundlerPlatformException"), bundler.getName()));
} catch (ConfigException e) {
+ if (e.getAdvice() != null) {
Log.info(MessageFormat.format(bundle.getString("MSG_BundlerConfigException"), bundler.getName(), e.getMessage(), e.getAdvice()));
+ } else {
+ Log.info(MessageFormat.format(bundle.getString("MSG_BundlerConfigExceptionNoAdvice"), bundler.getName(), e.getMessage()));
+ }
} catch (RuntimeException re) {
Log.info(MessageFormat.format(bundle.getString("MSG_BundlerRuntimeException"), bundler.getName(), re.toString()));
Log.debug(re);
}
}
@@ -676,16 +651,11 @@
{
if (signature == null) {
throw new IllegalStateException("Should retrieve signature first");
}
- InputStreamSource in = new InputStreamSource() {
- @Override
- public InputStream getInputStream() throws IOException {
- return new FileInputStream(jar);
- }
- };
+ InputStreamSource in = () -> new FileInputStream(jar);
if (!signedJar.isFile()) {
signedJar.createNewFile();
}
FileOutputStream fos = new FileOutputStream(signedJar);
signature.signJarAsBLOB(in, new ZipOutputStream(fos));
@@ -726,15 +696,12 @@
compiledDir.mkdir();
try {
final File tmpFile = File.createTempFile("javac", "sources", new File("."));
tmpFile.deleteOnExit();
- final FileWriter sources = new FileWriter(tmpFile);
- try {
+ try (FileWriter sources = new FileWriter(tmpFile)) {
scanAndCopy(new PackagerResource(new File(srcDirName), "."), sources, compiledDir);
- } finally {
- sources.close();
}
String classpath = jfxHome + "/../rt/lib/ext/jfxrt.jar";
if (makeAllParams.classpath != null) {
classpath += File.pathSeparator + makeAllParams.classpath;
}
@@ -786,12 +753,13 @@
generateDeploymentPackages(dp);
deleteDirectory(compiledDir);
}
+ @SuppressWarnings("unchecked")
private static int execute(Object ... args) throws IOException, InterruptedException {
- final ArrayList<String> argsList = new ArrayList();
+ final ArrayList<String> argsList = new ArrayList<>();
for (Object a : args) {
if (a instanceof List) {
argsList.addAll((List)a);
} else if (a instanceof String) {
argsList.add((String)a);
@@ -835,15 +803,16 @@
private static void scanAndCopy(PackagerResource dir, Writer out, File outdir) throws PackagerException {
if (!dir.getFile().exists()) {
throw new PackagerException("ERR_MissingDirectory", dir.getFile().getName());
}
- if ((dir.getFile().listFiles() == null) || (dir.getFile().listFiles().length == 0)) {
+ File[] dirFilesList = dir.getFile().listFiles();
+ if ((dirFilesList == null) || (dirFilesList.length == 0)) {
throw new PackagerException("ERR_EmptySourceDirectory", dir.getFile().getName());
}
try {
- for (File f : dir.getFile().listFiles()) {
+ for (File f : dirFilesList) {
if (f.isDirectory()) {
scanAndCopy(new PackagerResource(dir.getBaseDir(), f), out, outdir);
} else if (f.getName().endsWith(".java")) {
out.write('\'' + f.getAbsolutePath().replace('\\', '/') + "\'\n");
} else {
@@ -901,21 +870,20 @@
"</vendor>");
out.println(" <description>" +
((deployParams.description != null)
? deployParams.description : "Sample JavaFX 2.0 application.") +
"</description>");
- for (Iterator<Icon> it = deployParams.icons.iterator(); it.hasNext();) {
- DeployParams.Icon i = it.next();
+ for (Icon i : deployParams.icons) {
if (i.mode == DeployParams.RunMode.WEBSTART ||
i.mode == DeployParams.RunMode.ALL) {
- out.println(" <icon href=\"" + i.href+"\" " +
+ out.println(" <icon href=\"" + i.href + "\" " +
((i.kind != null) ? " kind=\"" + i.kind + "\"" : "") +
- ((i.width != DeployParams.Icon.UNDEFINED) ?
+ ((i.width != Icon.UNDEFINED) ?
" width=\"" + i.width + "\"" : "") +
- ((i.height != DeployParams.Icon.UNDEFINED) ?
+ ((i.height != Icon.UNDEFINED) ?
" height=\"" + i.height + "\"" : "") +
- ((i.depth != DeployParams.Icon.UNDEFINED) ?
+ ((i.depth != Icon.UNDEFINED) ?
" depth=\"" + i.depth + "\"" : "") +
"/>");
}
}
@@ -1174,13 +1142,13 @@
String webstartError = "System is not setup to launch JavaFX applications. " +
"Make sure that you have a recent Java runtime, then install JavaFX Runtime 2.0 "+
"and check that JavaFX is enabled in the Java Control Panel.";
- List w_app = new ArrayList();
- List w_platform = new ArrayList();
- List w_callback = new ArrayList();
+ List<String> w_app = new ArrayList<>();
+ List<String> w_platform = new ArrayList<>();
+ List<String> w_callback = new ArrayList<>();
addToList(w_app, "url", jnlpfile_webstart, true);
if (jnlp_content_webstart != null) {
addToList(w_app, "jnlp_content", jnlp_content_webstart, true);
}
@@ -1226,13 +1194,13 @@
if (placeholder == null) { //placeholder can not be null
placeholder = "'javafx-app-placeholder'";
}
//prepare content of embedApp()
- List p_app = new ArrayList();
- List p_platform = new ArrayList();
- List p_callback = new ArrayList();
+ List<String> p_app = new ArrayList<>();
+ List<String> p_platform = new ArrayList<>();
+ List<String> p_callback = new ArrayList<>();
if (appId != null) {
addToList(p_app, "id", appId, true);
}
if (deployParams.isSwingApp) {
@@ -1344,39 +1312,24 @@
fos.write(content);
fos.close();
}
private static void copyFileToOutDir(
- InputStream is, File fout) throws PackagerException {
+ InputStream isa, File fout) throws PackagerException {
- OutputStream out = null;
final File outDir = fout.getParentFile();
- try {
if (!outDir.exists() && !outDir.mkdirs()) {
throw new PackagerException("ERR_CreatingDirFailed", outDir.getPath());
}
-
- out = new FileOutputStream(fout);
+ try (InputStream is = isa; OutputStream out = new FileOutputStream(fout)) {
byte[] buf = new byte[16384];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
} catch (IOException ex) {
throw new PackagerException(ex, "ERR_FileCopyFailed", outDir.getPath());
- } finally {
- try {
- is.close();
- } catch (IOException ex) {
- }
-
- if (out != null) {
- try {
- out.close();
- } catch (IOException ex) {
- }
- }
}
}
private String getAppletParameters() {
@@ -1417,11 +1370,11 @@
jar.close();
alreadyAddedEntries.clear();
}
}
- private Set<String> alreadyAddedEntries = new HashSet<String>();
+ private Set<String> alreadyAddedEntries = new HashSet<>();
private void createParentEntries(String relativePath, JarOutputStream jar) throws IOException {
String[] pathComponents = relativePath.split("/");
StringBuilder pathSB = new StringBuilder();
// iterating over directories only, the last component is the file
// or will be created next time.
@@ -1447,21 +1400,18 @@
if ("META-INF/MANIFEST.MF".equals(je.getName().toUpperCase())
|| "META-INF/".equals(je.getName().toUpperCase())) {
continue;
}
- InputStream in = inJar.getInputStream(je);
jar.putNextEntry(new JarEntry(je.getName()));
byte b[] = new byte[65000];
int i;
- try {
+ try (InputStream in = inJar.getInputStream(je)) {
while ((i = in.read(b)) > 0) {
jar.write(b, 0, i);
}
- } finally {
- in.close();
}
jar.closeEntry();
}
}
@@ -1506,17 +1456,15 @@
jar.putNextEntry(new ZipEntry(absPath.substring(cut).replace('\\', '/')));
}
byte b[] = new byte[65000];
int i;
- FileInputStream in = new FileInputStream(f);
- try {
+
+ try (FileInputStream in = new FileInputStream(f)) {
while ((i = in.read(b)) > 0) {
jar.write(b, 0, i);
}
- } finally {
- in.close();
}
jar.closeEntry();
}
}
@@ -1551,22 +1499,21 @@
private String getJfxrtPath() throws PackagerException {
String theClassFile = "PackagerLib.class";
Class theClass = PackagerLib.class;
String classUrl = theClass.getResource(theClassFile).toString();
- if (!classUrl.startsWith("jar:file:") || classUrl.indexOf("!") == -1){
+ if (!classUrl.startsWith("jar:file:") || !classUrl.contains("!")){
throw new PackagerException("ERR_CantFindRuntime");
}
// Strip everything after and including the "!"
classUrl = classUrl.substring(0, classUrl.lastIndexOf("!"));
// Strip everything after the last "/" or "\" to get rid of the jar filename
int lastIndexOfSlash = Math.max(classUrl.lastIndexOf("/"), classUrl.lastIndexOf("\\"));
- String jfxrtPath = classUrl.substring(0, lastIndexOfSlash)
- + "/../rt/lib/ext/jfxrt.jar!/";
- return jfxrtPath;
+ return classUrl.substring(0, lastIndexOfSlash)
+ + "/../rt/lib/ext/jfxrt.jar!/";
}
private Class loadClassFromRuntime(String className) throws PackagerException {
try {
ClassLoader cl = getClassLoader();
@@ -1575,36 +1522,35 @@
throw new PackagerException(ex, "ERR_CantFindRuntime");
}
}
private void createBinaryCss(String cssFile, String binCssFile) throws PackagerException {
- String ifname = cssFile;
String ofname = (binCssFile != null)
? binCssFile
- : replaceExtensionByBSS(ifname);
+ : replaceExtensionByBSS(cssFile);
// create parent directories
File of = new File(ofname);
File parentFile = of.getParentFile();
if (parentFile != null) {
parentFile.mkdirs();
}
// Using reflection because CSS parser is part of runtime
// and we want to avoid dependency on jfxrt during build
- Class clazz;
+ Class<?> clazz;
try {
clazz = Class.forName("com.sun.javafx.css.parser.Css2Bin");
} catch (ClassNotFoundException e) {
// class was not found with default class loader, trying to
// locate it by loading from jfxrt.jar
clazz = loadClassFromRuntime("com.sun.javafx.css.parser.Css2Bin");
}
try {
Method m = clazz.getMethod("convertToBinary", new Class[]{String.class, String.class});
- m.invoke(null, ifname, ofname);
+ m.invoke(null, cssFile, ofname);
} catch (Exception ex) {
Throwable causeEx = ex.getCause();
String cause = (causeEx != null) ? causeEx.getMessage()
: bundle.getString("ERR_UnknownReason");
@@ -1641,29 +1587,29 @@
}
if (name.endsWith("~")) {
return false;
}
name = name.replace('\\', '/');
- if (name.indexOf("/CVS/") >= 0) {
+ if (name.contains("/CVS/")) {
return false;
}
- if (name.indexOf("/.svn/") >= 0) {
+ if (name.contains("/.svn/")) {
return false;
}
- if (name.indexOf("/.hg/") >= 0) {
+ if (name.contains("/.hg/")) {
return false;
}
- if (name.indexOf("/.#") >= 0) {
+ if (name.contains("/.#")) {
return false;
}
- if (name.indexOf("/._") >= 0) {
+ if (name.contains("/._")) {
return false;
}
- if (name.endsWith("#") && name.indexOf("/#") >= 0) {
+ if (name.endsWith("#") && name.contains("/#")) {
return false;
}
- if (name.endsWith("%") && name.indexOf("/%") >= 0) {
+ if (name.endsWith("%") && name.contains("/%")) {
return false;
}
if (name.endsWith("MANIFEST.MF")) {
return false;
}
@@ -1735,11 +1681,11 @@
}
}
}
private Set<CertPath> collectCertPaths() throws IOException {
- Set<CertPath> result = new HashSet<CertPath>();
+ Set<CertPath> result = new HashSet<>();
for (DeployResource resource: deployParams.resources) {
final File srcFile = resource.getFile();
if (srcFile.exists() && srcFile.isFile() &&
srcFile.getName().toLowerCase().endsWith("jar")) {
result.addAll(extractCertPaths(srcFile));
@@ -1747,11 +1693,11 @@
}
return result;
}
private Set<CertPath> extractCertPaths(File jar) throws IOException {
- Set<CertPath> result = new HashSet<CertPath>();
+ Set<CertPath> result = new HashSet<>();
JarFile jf = new JarFile(jar);
// need to fully read jar file to build up internal signer info map
Utils.readAllFully(jf);
@@ -1759,11 +1705,11 @@
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
String entryName = je.getName();
- CodeSigner[] signers = null;
+ CodeSigner[] signers;
if (entryName.equalsIgnoreCase(JarSignature.BLOB_SIGNATURE)) {
byte[] raw = Utils.getBytes(jf.getInputStream(je));
try {
JarSignature js = JarSignature.load(raw);
blobSigned = true;
@@ -1788,11 +1734,11 @@
}
return result;
}
private static Collection<CertPath> extractCertPaths(CodeSigner[] signers) {
- Collection<CertPath> result = new ArrayList<CertPath>();
+ Collection<CertPath> result = new ArrayList<>();
if (signers != null) {
for (CodeSigner cs : signers) {
CertPath cp = cs.getSignerCertPath();
if (cp != null) {
result.add(cp);