1 // Copyright 2008 Google Inc. All Rights Reserved.
3 package com
.google
.appengine
.tools
.admin
;
5 import com
.google
.appengine
.tools
.admin
.AppAdminFactory
.ApplicationProcessingOptions
;
6 import com
.google
.appengine
.tools
.info
.SdkImplInfo
;
7 import com
.google
.appengine
.tools
.info
.SdkInfo
;
8 import com
.google
.appengine
.tools
.info
.Version
;
9 import com
.google
.appengine
.tools
.plugins
.AppYamlProcessor
;
10 import com
.google
.appengine
.tools
.plugins
.SDKPluginManager
;
11 import com
.google
.appengine
.tools
.plugins
.SDKRuntimePlugin
;
12 import com
.google
.appengine
.tools
.util
.ApiVersionFinder
;
13 import com
.google
.appengine
.tools
.util
.FileIterator
;
14 import com
.google
.appengine
.tools
.util
.JarSplitter
;
15 import com
.google
.appengine
.tools
.util
.JarTool
;
16 import com
.google
.apphosting
.utils
.config
.AppEngineConfigException
;
17 import com
.google
.apphosting
.utils
.config
.AppEngineWebXml
;
18 import com
.google
.apphosting
.utils
.config
.AppEngineWebXmlReader
;
19 import com
.google
.apphosting
.utils
.config
.BackendsXml
;
20 import com
.google
.apphosting
.utils
.config
.BackendsXmlReader
;
21 import com
.google
.apphosting
.utils
.config
.BackendsYamlReader
;
22 import com
.google
.apphosting
.utils
.config
.CronXml
;
23 import com
.google
.apphosting
.utils
.config
.CronXmlReader
;
24 import com
.google
.apphosting
.utils
.config
.CronYamlReader
;
25 import com
.google
.apphosting
.utils
.config
.DispatchXml
;
26 import com
.google
.apphosting
.utils
.config
.DispatchXmlReader
;
27 import com
.google
.apphosting
.utils
.config
.DispatchYamlReader
;
28 import com
.google
.apphosting
.utils
.config
.DosXml
;
29 import com
.google
.apphosting
.utils
.config
.DosXmlReader
;
30 import com
.google
.apphosting
.utils
.config
.DosYamlReader
;
31 import com
.google
.apphosting
.utils
.config
.GenerationDirectory
;
32 import com
.google
.apphosting
.utils
.config
.IndexesXml
;
33 import com
.google
.apphosting
.utils
.config
.IndexesXmlReader
;
34 import com
.google
.apphosting
.utils
.config
.QueueXml
;
35 import com
.google
.apphosting
.utils
.config
.QueueXmlReader
;
36 import com
.google
.apphosting
.utils
.config
.QueueYamlReader
;
37 import com
.google
.apphosting
.utils
.config
.WebXml
;
38 import com
.google
.apphosting
.utils
.config
.WebXmlReader
;
39 import com
.google
.common
.collect
.ImmutableSet
;
40 import com
.google
.common
.io
.Files
;
42 import org
.mortbay
.io
.Buffer
;
43 import org
.mortbay
.jetty
.MimeTypes
;
44 import org
.xml
.sax
.SAXException
;
47 import java
.io
.FileInputStream
;
48 import java
.io
.FileNotFoundException
;
49 import java
.io
.FileOutputStream
;
50 import java
.io
.FileWriter
;
51 import java
.io
.IOException
;
52 import java
.io
.PrintWriter
;
54 import java
.net
.URLConnection
;
55 import java
.util
.ArrayList
;
56 import java
.util
.Arrays
;
57 import java
.util
.HashSet
;
58 import java
.util
.List
;
60 import java
.util
.logging
.Level
;
61 import java
.util
.logging
.Logger
;
62 import java
.util
.regex
.Pattern
;
64 import javax
.activation
.FileTypeMap
;
65 import javax
.tools
.JavaCompiler
;
66 import javax
.tools
.JavaFileObject
;
67 import javax
.tools
.StandardJavaFileManager
;
68 import javax
.tools
.ToolProvider
;
69 import javax
.xml
.XMLConstants
;
70 import javax
.xml
.transform
.stream
.StreamSource
;
71 import javax
.xml
.validation
.SchemaFactory
;
74 * An App Engine application. You can {@link #readApplication read} an
75 * {@code Application} from a path, and
76 * {@link com.google.appengine.tools.admin.AppAdminFactory#createAppAdmin create}
77 * an {@link com.google.appengine.tools.admin.AppAdmin} to upload, create
78 * indexes, or otherwise manage it.
81 public class Application
implements GenericApplication
{
83 private static final int MAX_COMPILED_JSP_JAR_SIZE
= 1024 * 1024 * 5;
84 private static final String COMPILED_JSP_JAR_NAME_PREFIX
= "_ah_compiled_jsps";
86 private static final int MAX_CLASSES_JAR_SIZE
= 1024 * 1024 * 5;
87 private static final String CLASSES_JAR_NAME_PREFIX
= "_ah_webinf_classes";
89 private static final String JAVA_7_RUNTIME_ID
= "java7";
90 private static final ImmutableSet
<String
> ALLOWED_RUNTIME_IDS
= ImmutableSet
.of(
93 private static Pattern JSP_REGEX
= Pattern
.compile(".*\\.jspx?");
95 /** If available, this is set to a program to make symlinks, e.g. /bin/ln */
96 private static File ln
= Utility
.findLink();
97 private static File sdkDocsDir
;
98 public static synchronized File
getSdkDocsDir(){
99 if (null == sdkDocsDir
){
100 sdkDocsDir
= new File(SdkInfo
.getSdkRoot(), "docs");
105 private static Version sdkVersion
;
106 public static synchronized Version
getSdkVersion() {
107 if (null == sdkVersion
) {
108 sdkVersion
= SdkInfo
.getLocalVersion();
113 private static final String STAGEDIR_PREFIX
= "appcfg";
115 private static final Logger logger
= Logger
.getLogger(Application
.class.getName());
117 private static final MimeTypes mimeTypes
= new MimeTypes();
119 private AppEngineWebXml appEngineWebXml
;
120 private WebXml webXml
;
121 private CronXml cronXml
;
122 private DispatchXml dispatchXml
;
123 private DosXml dosXml
;
124 private String pagespeedYaml
;
125 private QueueXml queueXml
;
126 private IndexesXml indexesXml
;
127 private BackendsXml backendsXml
;
128 private File baseDir
;
129 private File stageDir
;
130 private File externalResourceDir
;
131 private String apiVersion
;
132 private String appYaml
;
134 private UpdateListener listener
;
135 private PrintWriter detailsWriter
;
136 private int updateProgress
= 0;
137 private int progressAmount
= 0;
139 protected Application(){
143 * Builds a normalized path for the given directory in which
144 * forward slashes are used as the file separator on all platforms.
145 * @param dir A directory
146 * @return The normalized path
148 private static String
buildNormalizedPath(File dir
) {
149 String normalizedPath
= dir
.getPath();
150 if (File
.separatorChar
== '\\') {
151 normalizedPath
= normalizedPath
.replace('\\', '/');
153 return normalizedPath
;
156 private Application(String explodedPath
, String appId
, String module
, String appVersion
) {
157 this.baseDir
= new File(explodedPath
);
158 explodedPath
= buildNormalizedPath(baseDir
);
159 File webinf
= new File(baseDir
, "WEB-INF");
160 if (!webinf
.getName().equals("WEB-INF")) {
161 throw new AppEngineConfigException("WEB-INF directory must be capitalized.");
164 String webinfPath
= webinf
.getPath();
165 AppEngineWebXmlReader aewebReader
= new AppEngineWebXmlReader(explodedPath
);
166 WebXmlReader webXmlReader
= new WebXmlReader(explodedPath
);
167 AppYamlProcessor
.convert(webinf
, aewebReader
.getFilename(), webXmlReader
.getFilename());
169 validateXml(aewebReader
.getFilename(), new File(getSdkDocsDir(), "appengine-web.xsd"));
170 appEngineWebXml
= aewebReader
.readAppEngineWebXml();
171 appEngineWebXml
.setSourcePrefix(explodedPath
);
173 if (appEngineWebXml
.getAppId() == null) {
174 throw new AppEngineConfigException(
175 "No app id supplied and XML files have no <application> element");
178 appEngineWebXml
.setAppId(appId
);
180 if (module
!= null) {
181 appEngineWebXml
.setModule(module
);
183 if (appVersion
!= null) {
184 appEngineWebXml
.setMajorVersionId(appVersion
);
187 webXml
= webXmlReader
.readWebXml();
190 CronXmlReader cronReader
= new CronXmlReader(explodedPath
);
191 validateXml(cronReader
.getFilename(), new File(getSdkDocsDir(), "cron.xsd"));
192 cronXml
= cronReader
.readCronXml();
193 if (cronXml
== null) {
194 CronYamlReader cronYaml
= new CronYamlReader(webinfPath
);
195 cronXml
= cronYaml
.parse();
198 QueueXmlReader queueReader
= new QueueXmlReader(explodedPath
);
199 validateXml(queueReader
.getFilename(), new File(getSdkDocsDir(), "queue.xsd"));
200 queueXml
= queueReader
.readQueueXml();
201 if (queueXml
== null) {
202 QueueYamlReader queueYaml
= new QueueYamlReader(webinfPath
);
203 queueXml
= queueYaml
.parse();
206 DispatchXmlReader dispatchXmlReader
= new DispatchXmlReader(explodedPath
,
207 DispatchXmlReader
.DEFAULT_RELATIVE_FILENAME
);
208 validateXml(dispatchXmlReader
.getFilename(), new File(getSdkDocsDir(), "dispatch.xsd"));
209 dispatchXml
= dispatchXmlReader
.readDispatchXml();
210 if (dispatchXml
== null) {
211 DispatchYamlReader dispatchYamlReader
= new DispatchYamlReader(webinfPath
);
212 dispatchXml
= dispatchYamlReader
.parse();
215 DosXmlReader dosReader
= new DosXmlReader(explodedPath
);
216 validateXml(dosReader
.getFilename(), new File(getSdkDocsDir(), "dos.xsd"));
217 dosXml
= dosReader
.readDosXml();
218 if (dosXml
== null) {
219 DosYamlReader dosYaml
= new DosYamlReader(webinfPath
);
220 dosXml
= dosYaml
.parse();
223 if (getAppEngineWebXml().getPagespeed() != null) {
224 StringBuilder pagespeedYamlBuilder
= new StringBuilder();
225 AppYamlTranslator
.appendPagespeed(
226 getAppEngineWebXml().getPagespeed(), pagespeedYamlBuilder
, 0);
227 pagespeedYaml
= pagespeedYamlBuilder
.toString();
230 IndexesXmlReader indexReader
= new IndexesXmlReader(explodedPath
);
231 validateXml(indexReader
.getFilename(), new File(getSdkDocsDir(), "datastore-indexes.xsd"));
232 indexesXml
= indexReader
.readIndexesXml();
234 BackendsXmlReader backendsReader
= new BackendsXmlReader(explodedPath
);
235 validateXml(backendsReader
.getFilename(), new File(getSdkDocsDir(), "backends.xsd"));
236 backendsXml
= backendsReader
.readBackendsXml();
237 if (backendsXml
== null) {
238 BackendsYamlReader backendsYaml
= new BackendsYamlReader(webinfPath
);
239 backendsXml
= backendsYaml
.parse();
244 * Reads the App Engine application from {@code path}. The path may either
245 * be a WAR file or the root of an exploded WAR directory.
247 * @param path a not {@code null} path.
249 * @throws IOException if an error occurs while trying to read the
250 * {@code Application}.
251 * @throws com.google.apphosting.utils.config.AppEngineConfigException if the
252 * {@code Application's} appengine-web.xml file is malformed.
254 public static Application
readApplication(String path
)
256 return new Application(path
, null, null, null);
260 * Sets the external resource directory. Call this method before invoking
261 * {@link #createStagingDirectory(ApplicationProcessingOptions, ResourceLimits)}.
263 * The external resource directory is a directory outside of the war directory where additional
264 * files live. These files will be copied into the staging directory during an upload, after the
265 * war directory is copied there. Consequently if there are any name collisions the files in the
266 * external resource directory will win.
268 * @param path a not {@code null} path to an existing directory.
270 * @throws IllegalArgumentException If {@code path} does not refer to an existing
273 public void setExternalResourceDir(String path
) {
275 throw new NullPointerException("path is null");
277 if (stageDir
!= null) {
278 throw new IllegalStateException(
279 "This method must be invoked prior to createStagingDirectory()");
281 File dir
= new File(path
);
283 throw new IllegalArgumentException("path does not exist: " + path
);
285 if (!dir
.isDirectory()) {
286 throw new IllegalArgumentException(path
+ " is not a directory.");
288 this.externalResourceDir
= dir
;
292 * Reads the App Engine application from {@code path}. The path may either
293 * be a WAR file or the root of an exploded WAR directory.
295 * @param path a not {@code null} path.
296 * @param appId if non-null, use this as an application id override.
297 * @param module if non-null, use this as a module id override.
298 * @param appVersion if non-null, use this as an application version override.
300 * @throws IOException if an error occurs while trying to read the
301 * {@code Application}.
302 * @throws com.google.apphosting.utils.config.AppEngineConfigException if the
303 * {@code Application's} appengine-web.xml file is malformed.
305 public static Application
readApplication(String path
,
308 String appVersion
) throws IOException
{
309 return new Application(path
, appId
, module
, appVersion
);
313 * Returns the application identifier, from the AppEngineWebXml config
314 * @return application identifier
317 public String
getAppId() {
318 return appEngineWebXml
.getAppId();
322 * Returns the application version, from the AppEngineWebXml config
323 * @return application version
326 public String
getVersion() {
327 return appEngineWebXml
.getMajorVersionId();
331 public String
getSourceLanguage() {
332 return appEngineWebXml
.getSourceLanguage();
336 public String
getModule() {
337 return appEngineWebXml
.getModule();
341 public String
getInstanceClass() {
342 return appEngineWebXml
.getInstanceClass();
346 public boolean isPrecompilationEnabled() {
347 return appEngineWebXml
.getPrecompilationEnabled();
351 public List
<ErrorHandler
> getErrorHandlers() {
352 class ErrorHandlerImpl
implements ErrorHandler
{
353 private final AppEngineWebXml
.ErrorHandler errorHandler
;
354 public ErrorHandlerImpl(AppEngineWebXml
.ErrorHandler errorHandler
) {
355 this.errorHandler
= errorHandler
;
358 public String
getFile() {
359 return "__static__/" + errorHandler
.getFile();
362 public String
getErrorCode() {
363 return errorHandler
.getErrorCode();
366 public String
getMimeType() {
367 return getMimeTypeIfStatic(getFile());
370 List
<ErrorHandler
> errorHandlers
= new ArrayList
<ErrorHandler
>();
371 for (AppEngineWebXml
.ErrorHandler errorHandler
: appEngineWebXml
.getErrorHandlers()) {
372 errorHandlers
.add(new ErrorHandlerImpl(errorHandler
));
374 return errorHandlers
;
378 public String
getMimeTypeIfStatic(String path
) {
379 if (!path
.contains("__static__/")) {
382 String mimeType
= webXml
.getMimeTypeForPath(path
);
383 if (mimeType
!= null) {
386 return guessContentTypeFromName(path
);
390 * @param fileName path of a file with extension
391 * @return the mimetype of the file (or application/octect-stream if not recognized)
393 public static String
guessContentTypeFromName(String fileName
) {
394 String defaultValue
= "application/octet-stream";
396 Buffer buffer
= mimeTypes
.getMimeByExtension(fileName
);
397 if (buffer
!= null) {
398 return new String(buffer
.asArray());
400 String lowerName
= fileName
.toLowerCase();
401 if (lowerName
.endsWith(".json")) {
402 return "application/json";
404 FileTypeMap typeMap
= FileTypeMap
.getDefaultFileTypeMap();
405 String ret
= typeMap
.getContentType(fileName
);
409 ret
= URLConnection
.guessContentTypeFromName(fileName
);
414 } catch (Throwable t
) {
415 logger
.log(Level
.WARNING
, "Error identify mimetype for " + fileName
, t
);
420 * Returns the AppEngineWebXml describing the application.
422 * @return a not {@code null} deployment descriptor
424 public AppEngineWebXml
getAppEngineWebXml() {
425 return appEngineWebXml
;
429 * Returns the CronXml describing the applications' cron jobs.
430 * @return a cron descriptor, possibly empty or {@code null}
433 public CronXml
getCronXml() {
438 * Returns the QueueXml describing the applications' task queues.
439 * @return a queue descriptor, possibly empty or {@code null}
442 public QueueXml
getQueueXml() {
447 public DispatchXml
getDispatchXml() {
452 * Returns the DosXml describing the applications' DoS entries.
453 * @return a dos descriptor, possibly empty or {@code null}
456 public DosXml
getDosXml() {
461 * Returns the pagespeed.yaml describing the applications' PageSpeed configuration.
462 * @return a pagespeed.yaml string, possibly empty or {@code null}
465 public String
getPagespeedYaml() {
466 return pagespeedYaml
;
470 * Returns the IndexesXml describing the applications' indexes.
471 * @return a index descriptor, possibly empty or {@code null}
474 public IndexesXml
getIndexesXml() {
479 * Returns the WebXml describing the applications' servlets and generic web
480 * application information.
482 * @return a WebXml descriptor, possibly empty but not {@code null}
484 public WebXml
getWebXml() {
489 public BackendsXml
getBackendsXml() {
494 * Returns the desired API version for the current application, or
495 * {@code "none"} if no API version was used.
497 * @throws IllegalStateException if createStagingDirectory has not been called.
500 public String
getApiVersion() {
501 if (apiVersion
== null) {
502 throw new IllegalStateException("Must call createStagingDirectory first.");
508 * Returns a path to an exploded WAR directory for the application.
509 * This may be a temporary directory.
511 * @return a not {@code null} path pointing to a directory
514 public String
getPath() {
515 return baseDir
.getAbsolutePath();
519 * Returns the staging directory, or {@code null} if none has been created.
522 public File
getStagingDir() {
527 public void resetProgress() {
533 * Creates a new staging directory, if needed, or returns the existing one
534 * if already created.
536 * @param opts User-specified options for processing the application.
537 * @return staging directory
538 * @throws IOException
541 public File
createStagingDirectory(ApplicationProcessingOptions opts
,
542 ResourceLimits resourceLimits
) throws IOException
{
543 if (stageDir
!= null) {
548 while (stageDir
== null && i
++ < 3) {
550 stageDir
= File
.createTempFile(STAGEDIR_PREFIX
, null);
551 } catch (IOException ex
) {
555 if (!stageDir
.mkdir()) {
560 throw new IOException("Couldn't create a temporary directory in 3 tries.");
562 statusUpdate("Created staging directory at: '" + stageDir
.getPath() + "'", 20);
564 File staticDir
= new File(stageDir
, "__static__");
566 copyOrLink(baseDir
, stageDir
, staticDir
, false, opts
);
567 if (externalResourceDir
!= null) {
568 String previousPrefix
= appEngineWebXml
.getSourcePrefix();
569 String newPrefix
= buildNormalizedPath(externalResourceDir
);
571 appEngineWebXml
.setSourcePrefix(newPrefix
);
572 copyOrLink(externalResourceDir
, stageDir
, staticDir
, false, opts
);
574 appEngineWebXml
.setSourcePrefix(previousPrefix
);
578 apiVersion
= findApiVersion(stageDir
, true);
580 String runtime
= getRuntime(opts
);
582 if (opts
.isCompileJspsSet()) {
583 compileJsps(stageDir
, opts
);
586 appYaml
= generateAppYaml(stageDir
, runtime
);
588 if (GenerationDirectory
.getGenerationDirectory(stageDir
).mkdirs()) {
589 writePreparedYamlFile("app", appYaml
);
590 writePreparedYamlFile("backends", backendsXml
== null ?
null : backendsXml
.toYaml());
591 writePreparedYamlFile("index", indexesXml
.size() == 0 ?
null : indexesXml
.toYaml());
592 writePreparedYamlFile("cron", cronXml
== null ?
null : cronXml
.toYaml());
593 writePreparedYamlFile("queue", queueXml
== null ?
null : queueXml
.toYaml());
594 writePreparedYamlFile("dos", dosXml
== null ?
null : dosXml
.toYaml());
597 int maxJarSize
= (int) resourceLimits
.maxFileSize();
599 if (opts
.isSplitJarsSet()) {
600 splitJars(new File(new File(stageDir
, "WEB-INF"), "lib"),
601 maxJarSize
, opts
.getJarSplittingExcludes());
604 if (getSourceLanguage() != null) {
605 SDKRuntimePlugin runtimePlugin
= SDKPluginManager
.findRuntimePlugin(getSourceLanguage());
606 if (runtimePlugin
!= null) {
607 runtimePlugin
.processStagingDirectory(stageDir
);
615 * Write yaml file to generation subdirectory within stage directory.
617 private void writePreparedYamlFile(String yamlName
, String yamlString
) throws IOException
{
618 File f
= new File(GenerationDirectory
.getGenerationDirectory(stageDir
), yamlName
+ ".yaml");
619 if (yamlString
!= null && f
.createNewFile()) {
620 FileWriter fw
= new FileWriter(f
);
621 fw
.write(yamlString
);
626 private static String
findApiVersion(File baseDir
, boolean deleteApiJars
) {
627 ApiVersionFinder finder
= new ApiVersionFinder();
629 String foundApiVersion
= null;
630 File webInf
= new File(baseDir
, "WEB-INF");
631 File libDir
= new File(webInf
, "lib");
632 for (File file
: new FileIterator(libDir
)) {
633 if (file
.getPath().endsWith(".jar")) {
635 String apiVersion
= finder
.findApiVersion(file
);
636 if (apiVersion
!= null) {
637 if (foundApiVersion
== null) {
638 foundApiVersion
= apiVersion
;
639 } else if (!foundApiVersion
.equals(apiVersion
)) {
640 logger
.warning("Warning: found duplicate API version: " + foundApiVersion
+
641 ", using " + apiVersion
);
644 if (!file
.delete()) {
645 logger
.log(Level
.SEVERE
, "Could not delete API jar: " + file
);
649 } catch (IOException ex
) {
650 logger
.log(Level
.WARNING
, "Could not identify API version in " + file
, ex
);
655 if (foundApiVersion
== null) {
656 foundApiVersion
= "none";
658 return foundApiVersion
;
662 * Returns the runtime id to use in the generated app.yaml.
664 * This method returns {@code "java7"}, unless an explicit runtime id was specified
665 * using the {@code -r} option.
667 * Before accepting an explicit runtime id, this method validates it against the list of
668 * supported Java runtimes (currently only {@code "java7"}), unless validation was turned
669 * off using the {@code --allowAnyRuntimes} option.
671 private String
getRuntime(ApplicationProcessingOptions opts
) {
672 String runtime
= opts
.getRuntime();
673 if (runtime
!= null) {
674 if (!opts
.isAllowAnyRuntime() && !ALLOWED_RUNTIME_IDS
.contains(runtime
)) {
675 throw new AppEngineConfigException("Invalid runtime id: " + runtime
+ ". Valid " +
676 "runtime id: java7.");
680 return JAVA_7_RUNTIME_ID
;
684 * Validates a given XML document against a given schema.
686 * @param xmlFilename filename with XML document
687 * @param schema XSD schema to validate with
689 * @throws AppEngineConfigException for malformed XML, or IO errors
691 private static void validateXml(String xmlFilename
, File schema
) {
692 File xml
= new File(xmlFilename
);
697 SchemaFactory factory
= SchemaFactory
.newInstance(XMLConstants
.W3C_XML_SCHEMA_NS_URI
);
699 factory
.newSchema(schema
).newValidator().validate(
700 new StreamSource(new FileInputStream(xml
)));
701 } catch (SAXException ex
) {
702 throw new AppEngineConfigException("XML error validating " +
703 xml
.getPath() + " against " + schema
.getPath(), ex
);
705 } catch (IOException ex
) {
706 throw new AppEngineConfigException("IO error validating " +
707 xml
.getPath() + " against " + schema
.getPath(), ex
);
711 private static final String JSPC_MAIN
= "com.google.appengine.tools.development.LocalJspC";
713 private void compileJsps(File stage
, ApplicationProcessingOptions opts
)
715 statusUpdate("Scanning for jsp files.");
717 if (matchingFileExists(new File(stage
.getPath()), JSP_REGEX
)) {
718 statusUpdate("Compiling jsp files.");
720 File webInf
= new File(stage
, "WEB-INF");
722 for (File file
: SdkImplInfo
.getUserJspLibFiles()) {
723 copyOrLinkFile(file
, new File(new File(webInf
, "lib"), file
.getName()));
725 for (File file
: SdkImplInfo
.getSharedJspLibFiles()) {
726 copyOrLinkFile(file
, new File(new File(webInf
, "lib"), file
.getName()));
729 File classes
= new File(webInf
, "classes");
730 File generatedWebXml
= new File(webInf
, "generated_web.xml");
731 File tempDir
= Files
.createTempDir();
732 String classpath
= getJspClasspath(classes
, tempDir
);
734 String javaCmd
= opts
.getJavaExecutable().getPath();
735 String
[] args
= new String
[] {
737 "-classpath", classpath
,
739 "-uriroot", stage
.getPath(),
740 "-p", "org.apache.jsp",
742 "-webinc", generatedWebXml
.getPath(),
743 "-d", tempDir
.getPath(),
744 "-javaEncoding", opts
.getCompileEncoding(),
746 Process jspc
= startProcess(args
);
750 status
= jspc
.waitFor();
751 } catch (InterruptedException ex
) { }
754 detailsWriter
.println("Error while executing: " + formatCommand(Arrays
.asList(args
)));
755 throw new JspCompilationException("Failed to compile jsp files.",
756 JspCompilationException
.Source
.JASPER
);
759 compileJavaFiles(classpath
, webInf
, tempDir
, opts
);
761 webXml
= new WebXmlReader(stage
.getPath()).readWebXml();
766 private void compileJavaFiles(String classpath
, File webInf
, File jspClassDir
,
767 ApplicationProcessingOptions opts
) throws IOException
{
769 JavaCompiler compiler
= ToolProvider
.getSystemJavaCompiler();
770 if (compiler
== null) {
771 throw new RuntimeException(
772 "Cannot get the System Java Compiler. Please use a JDK, not a JRE.");
774 StandardJavaFileManager fileManager
= compiler
.getStandardFileManager(null, null, null);
776 ArrayList
<File
> files
= new ArrayList
<File
>();
777 for (File f
: new FileIterator(jspClassDir
)) {
778 if (f
.getPath().toLowerCase().endsWith(".java")) {
782 if (files
.isEmpty()) {
785 List
<String
> optionList
= new ArrayList
<String
>();
786 optionList
.addAll(Arrays
.asList("-classpath", classpath
.toString()));
787 optionList
.addAll(Arrays
.asList("-d", jspClassDir
.getPath()));
788 optionList
.addAll(Arrays
.asList("-encoding", opts
.getCompileEncoding()));
790 Iterable
<?
extends JavaFileObject
> compilationUnits
=
791 fileManager
.getJavaFileObjectsFromFiles(files
);
792 boolean success
= compiler
.getTask(
793 null, fileManager
, null, optionList
, null, compilationUnits
).call();
797 throw new JspCompilationException("Failed to compile the generated JSP java files.",
798 JspCompilationException
.Source
.JSPC
);
800 if (opts
.isJarJSPsSet()) {
801 zipJasperGeneratedFiles(webInf
, jspClassDir
);
803 copyOrLinkDirectories(jspClassDir
, new File(webInf
, "classes"));
805 if (opts
.isDeleteJSPs()) {
806 for (File f
: new FileIterator(webInf
.getParentFile())) {
807 if (f
.getPath().toLowerCase().endsWith(".jsp")) {
812 if (opts
.isJarClassesSet()) {
813 zipWebInfClassesFiles(webInf
);
818 private void zipJasperGeneratedFiles(File webInfDir
, File jspClassDir
) throws IOException
{
819 Set
<String
> fileTypesToExclude
= ImmutableSet
.of(".java");
820 File libDir
= new File(webInfDir
, "lib");
821 JarTool jarTool
= new JarTool(
822 COMPILED_JSP_JAR_NAME_PREFIX
, jspClassDir
, libDir
, MAX_COMPILED_JSP_JAR_SIZE
,
825 recursiveDelete(jspClassDir
);
828 private void zipWebInfClassesFiles(File webInfDir
) throws IOException
{
829 File libDir
= new File(webInfDir
, "lib");
830 File classesDir
= new File(webInfDir
, "classes");
831 JarTool jarTool
= new JarTool(
832 CLASSES_JAR_NAME_PREFIX
, classesDir
, libDir
, MAX_CLASSES_JAR_SIZE
,
835 recursiveDelete(classesDir
);
839 private String
getJspClasspath(File classDir
, File genDir
) {
840 StringBuilder classpath
= new StringBuilder();
841 for (URL lib
: SdkImplInfo
.getImplLibs()) {
842 classpath
.append(lib
.getPath());
843 classpath
.append(File
.pathSeparatorChar
);
845 for (File lib
: SdkInfo
.getSharedLibFiles()) {
846 classpath
.append(lib
.getPath());
847 classpath
.append(File
.pathSeparatorChar
);
850 classpath
.append(classDir
.getPath());
851 classpath
.append(File
.pathSeparatorChar
);
852 classpath
.append(genDir
.getPath());
853 classpath
.append(File
.pathSeparatorChar
);
855 for (File f
: new FileIterator(new File(classDir
.getParentFile(), "lib"))) {
856 String filename
= f
.getPath().toLowerCase();
857 if (filename
.endsWith(".jar") || filename
.endsWith(".zip")) {
858 classpath
.append(f
.getPath());
859 classpath
.append(File
.pathSeparatorChar
);
863 return classpath
.toString();
866 private Process
startProcess(String
... args
) throws IOException
{
867 ProcessBuilder builder
= new ProcessBuilder(args
);
868 Process proc
= builder
.redirectErrorStream(true).start();
869 logger
.fine(formatCommand(builder
.command()));
870 new Thread(new OutputPump(proc
.getInputStream(), detailsWriter
)).start();
874 private String
formatCommand(Iterable
<String
> args
) {
875 StringBuilder command
= new StringBuilder();
876 for (String chunk
: args
) {
877 command
.append(chunk
);
880 return command
.toString();
884 * Scans a given directory tree, testing whether any file matches a given
887 * @param dir the directory under which to scan
888 * @param regex the pattern to look for
889 * @returns Returns {@code true} on the first instance of such a file,
890 * {@code false} otherwise.
892 private static boolean matchingFileExists(File dir
, Pattern regex
) {
893 for (File file
: dir
.listFiles()) {
894 if (file
.isDirectory()) {
895 if (matchingFileExists(file
, regex
)) {
899 if (regex
.matcher(file
.getName()).matches()) {
908 * Invokes the JarSplitter code on any jar files found in {@code dir}. Any
909 * jars larger than {@code max} will be split into fragments of at most that
911 * @param dir the directory to search, recursively
912 * @param max the maximum allowed size
913 * @param excludes a set of suffixes to exclude.
914 * @throws IOException on filesystem errors.
916 private static void splitJars(File dir
, int max
, Set
<String
> excludes
) throws IOException
{
917 String children
[] = dir
.list();
918 if (children
== null) {
921 for (String name
: children
) {
922 File subfile
= new File(dir
, name
);
923 if (subfile
.isDirectory()) {
924 splitJars(subfile
, max
, excludes
);
925 } else if (name
.endsWith(".jar")) {
926 if (subfile
.length() > max
) {
927 new JarSplitter(subfile
, dir
, max
, false, 4, excludes
).run();
934 private static final Pattern SKIP_FILES
= Pattern
.compile(
935 "^(.*/)?((#.*#)|(.*~)|(.*/RCS/.*)|)$");
938 * Copies files from the app to the upload staging directory, or makes
939 * symlinks instead if supported. Puts the files into the correct places for
940 * static vs. resource files, recursively.
942 * @param sourceDir application war dir, or on recursion a subdirectory of it
943 * @param resDir staging resource dir, or on recursion a subdirectory matching
944 * the subdirectory in {@code sourceDir}
945 * @param staticDir staging {@code __static__} dir, or an appropriate recursive
947 * @param forceResource if all files should be considered resource files
948 * @param opts processing options, used primarily for handling of *.jsp files
949 * @throws FileNotFoundException
950 * @throws IOException
952 private void copyOrLink(File sourceDir
, File resDir
, File staticDir
, boolean forceResource
,
953 ApplicationProcessingOptions opts
)
954 throws FileNotFoundException
, IOException
{
956 for (String name
: sourceDir
.list()) {
957 File file
= new File(sourceDir
, name
);
959 String path
= file
.getPath();
960 if (File
.separatorChar
== '\\') {
961 path
= path
.replace('\\', '/');
964 if (file
.getName().startsWith(".") ||
965 file
.equals(GenerationDirectory
.getGenerationDirectory(baseDir
))) {
969 if (file
.isDirectory()) {
970 if (file
.getName().equals("WEB-INF")) {
971 copyOrLink(file
, new File(resDir
, name
), new File(staticDir
, name
), true, opts
);
973 copyOrLink(file
, new File(resDir
, name
), new File(staticDir
, name
), forceResource
,
977 if (SKIP_FILES
.matcher(path
).matches()) {
981 if (forceResource
|| appEngineWebXml
.includesResource(path
) ||
982 (opts
.isCompileJspsSet() && name
.toLowerCase().endsWith(".jsp"))) {
983 copyOrLinkFile(file
, new File(resDir
, name
));
985 if (!forceResource
&& appEngineWebXml
.includesStatic(path
)) {
986 copyOrLinkFile(file
, new File(staticDir
, name
));
993 * Attempts to symlink a single file, or copies it if symlinking is either
994 * unsupported or fails.
996 * @param source source file
997 * @param dest destination file
998 * @throws FileNotFoundException
999 * @throws IOException
1001 private void copyOrLinkFile(File source
, File dest
)
1002 throws FileNotFoundException
, IOException
{
1003 dest
.getParentFile().mkdirs();
1004 if (ln
!= null && !source
.getName().endsWith("web.xml")) {
1008 } catch (Exception e
) {
1009 System
.err
.println("Warning: We tried to delete " + dest
.getPath());
1010 System
.err
.println("in order to create a symlink from " + source
.getPath());
1011 System
.err
.println("but the delete failed with message: " + e
.getMessage());
1014 Process link
= startProcess(ln
.getAbsolutePath(), "-s",
1015 source
.getAbsolutePath(),
1016 dest
.getAbsolutePath());
1018 int stat
= link
.waitFor();
1022 System
.err
.println(ln
.getAbsolutePath() + " returned status " + stat
1023 + ", copying instead...");
1024 } catch (InterruptedException ex
) {
1025 System
.err
.println(ln
.getAbsolutePath() + " was interrupted, copying instead...");
1027 if (dest
.delete()) {
1028 System
.err
.println("ln failed but symlink was created, removed: " + dest
.getAbsolutePath());
1031 byte buffer
[] = new byte[1024];
1033 FileInputStream inStream
= new FileInputStream(source
);
1034 FileOutputStream outStream
= new FileOutputStream(dest
);
1036 readlen
= inStream
.read(buffer
);
1037 while (readlen
> 0) {
1038 outStream
.write(buffer
, 0, readlen
);
1039 readlen
= inStream
.read(buffer
);
1044 } catch (IOException ex
) {
1048 } catch (IOException ex
) {
1052 /** Copy (or link) one directory into another one.
1054 private void copyOrLinkDirectories(File sourceDir
, File destination
)
1055 throws IOException
{
1057 for (String name
: sourceDir
.list()) {
1058 File file
= new File(sourceDir
, name
);
1059 if (file
.isDirectory()) {
1060 copyOrLinkDirectories(file
, new File(destination
, name
));
1062 copyOrLinkFile(file
, new File(destination
, name
));
1067 /** deletes the staging directory, if one was created. */
1069 public void cleanStagingDirectory() {
1070 if (stageDir
!= null) {
1071 recursiveDelete(stageDir
);
1075 /** Recursive directory deletion. */
1076 public static void recursiveDelete(File dead
) {
1077 String
[] files
= dead
.list();
1078 if (files
!= null) {
1079 for (String name
: files
) {
1080 recursiveDelete(new File(dead
, name
));
1087 public void setListener(UpdateListener l
) {
1092 public void setDetailsWriter(PrintWriter detailsWriter
) {
1093 this.detailsWriter
= detailsWriter
;
1097 public void statusUpdate(String message
, int amount
) {
1098 updateProgress
+= progressAmount
;
1099 if (updateProgress
> 99) {
1100 updateProgress
= 99;
1102 progressAmount
= amount
;
1103 if (listener
!= null) {
1104 listener
.onProgress(new UpdateProgressEvent(
1105 Thread
.currentThread(), message
, updateProgress
));
1110 public void statusUpdate(String message
) {
1111 int amount
= progressAmount
/ 4;
1112 updateProgress
+= amount
;
1113 if (updateProgress
> 99) {
1114 updateProgress
= 99;
1116 progressAmount
-= amount
;
1117 if (listener
!= null) {
1118 listener
.onProgress(new UpdateProgressEvent(
1119 Thread
.currentThread(), message
, updateProgress
));
1123 private String
generateAppYaml(File stageDir
, String runtime
) {
1124 Set
<String
> staticFiles
= new HashSet
<String
>();
1125 for (File f
: new FileIterator(new File(stageDir
, "__static__"))) {
1126 staticFiles
.add(Utility
.calculatePath(f
, stageDir
));
1129 AppYamlTranslator translator
=
1130 new AppYamlTranslator(getAppEngineWebXml(), getWebXml(), getBackendsXml(),
1131 getApiVersion(), staticFiles
, null, runtime
, getSdkVersion());
1132 String yaml
= translator
.getYaml();
1133 logger
.fine("Generated app.yaml file:\n" + yaml
);
1138 * Returns the app.yaml string.
1140 * @throws IllegalStateException if createStagingDirectory has not been called.
1143 public String
getAppYaml() {
1144 if (appYaml
== null) {
1145 throw new IllegalStateException("Must call createStagingDirectory first.");