Revision created by MOE tool push_codebase.
[gae.git] / java / src / main / com / google / appengine / tools / admin / Application.java
blob9b4b33f3433d178f680f293d9b01b71d127a120b
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;
46 import java.io.File;
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;
53 import java.net.URL;
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;
59 import java.util.Set;
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;
73 /**
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(
91 JAVA_7_RUNTIME_ID);
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");
102 return sdkDocsDir;
105 private static Version sdkVersion;
106 public static synchronized Version getSdkVersion() {
107 if (null == sdkVersion) {
108 sdkVersion = SdkInfo.getLocalVersion();
110 return sdkVersion;
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);
172 if (appId == null) {
173 if (appEngineWebXml.getAppId() == null) {
174 throw new AppEngineConfigException(
175 "No app id supplied and XML files have no <application> element");
177 } else {
178 appEngineWebXml.setAppId(appId);
180 if (module != null) {
181 appEngineWebXml.setModule(module);
183 if (appVersion != null) {
184 appEngineWebXml.setMajorVersionId(appVersion);
187 webXml = webXmlReader.readWebXml();
188 webXml.validate();
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)
255 throws IOException {
256 return new Application(path, null, null, null);
260 * Sets the external resource directory. Call this method before invoking
261 * {@link #createStagingDirectory(ApplicationProcessingOptions, ResourceLimits)}.
262 * <p>
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
271 * directory.
273 public void setExternalResourceDir(String path) {
274 if (path == null) {
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);
282 if (!dir.exists()) {
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,
306 String appId,
307 String module,
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
316 @Override
317 public String getAppId() {
318 return appEngineWebXml.getAppId();
322 * Returns the application version, from the AppEngineWebXml config
323 * @return application version
325 @Override
326 public String getVersion() {
327 return appEngineWebXml.getMajorVersionId();
330 @Override
331 public String getSourceLanguage() {
332 return appEngineWebXml.getSourceLanguage();
335 @Override
336 public String getModule() {
337 return appEngineWebXml.getModule();
340 @Override
341 public String getInstanceClass() {
342 return appEngineWebXml.getInstanceClass();
345 @Override
346 public boolean isPrecompilationEnabled() {
347 return appEngineWebXml.getPrecompilationEnabled();
350 @Override
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;
357 @Override
358 public String getFile() {
359 return "__static__/" + errorHandler.getFile();
361 @Override
362 public String getErrorCode() {
363 return errorHandler.getErrorCode();
365 @Override
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;
377 @Override
378 public String getMimeTypeIfStatic(String path) {
379 if (!path.contains("__static__/")) {
380 return null;
382 String mimeType = webXml.getMimeTypeForPath(path);
383 if (mimeType != null) {
384 return mimeType;
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";
395 try {
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);
406 if (ret != null) {
407 return ret;
409 ret = URLConnection.guessContentTypeFromName(fileName);
410 if (ret != null) {
411 return ret;
413 return defaultValue;
414 } catch (Throwable t) {
415 logger.log(Level.WARNING, "Error identify mimetype for " + fileName, t);
416 return defaultValue;
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}
432 @Override
433 public CronXml getCronXml() {
434 return cronXml;
438 * Returns the QueueXml describing the applications' task queues.
439 * @return a queue descriptor, possibly empty or {@code null}
441 @Override
442 public QueueXml getQueueXml() {
443 return queueXml;
446 @Override
447 public DispatchXml getDispatchXml() {
448 return dispatchXml;
452 * Returns the DosXml describing the applications' DoS entries.
453 * @return a dos descriptor, possibly empty or {@code null}
455 @Override
456 public DosXml getDosXml() {
457 return dosXml;
461 * Returns the pagespeed.yaml describing the applications' PageSpeed configuration.
462 * @return a pagespeed.yaml string, possibly empty or {@code null}
464 @Override
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}
473 @Override
474 public IndexesXml getIndexesXml() {
475 return indexesXml;
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() {
485 return webXml;
488 @Override
489 public BackendsXml getBackendsXml() {
490 return backendsXml;
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.
499 @Override
500 public String getApiVersion() {
501 if (apiVersion == null) {
502 throw new IllegalStateException("Must call createStagingDirectory first.");
504 return apiVersion;
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
513 @Override
514 public String getPath() {
515 return baseDir.getAbsolutePath();
519 * Returns the staging directory, or {@code null} if none has been created.
521 @Override
522 public File getStagingDir() {
523 return stageDir;
526 @Override
527 public void resetProgress() {
528 updateProgress = 0;
529 progressAmount = 0;
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
540 @Override
541 public File createStagingDirectory(ApplicationProcessingOptions opts,
542 ResourceLimits resourceLimits) throws IOException {
543 if (stageDir != null) {
544 return stageDir;
547 int i = 0;
548 while (stageDir == null && i++ < 3) {
549 try {
550 stageDir = File.createTempFile(STAGEDIR_PREFIX, null);
551 } catch (IOException ex) {
552 continue;
554 stageDir.delete();
555 if (!stageDir.mkdir()) {
556 stageDir = null;
559 if (i == 3) {
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__");
565 staticDir.mkdir();
566 copyOrLink(baseDir, stageDir, staticDir, false, opts);
567 if (externalResourceDir != null) {
568 String previousPrefix = appEngineWebXml.getSourcePrefix();
569 String newPrefix = buildNormalizedPath(externalResourceDir);
570 try {
571 appEngineWebXml.setSourcePrefix(newPrefix);
572 copyOrLink(externalResourceDir, stageDir, staticDir, false, opts);
573 } finally {
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);
611 return 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);
622 fw.close();
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")) {
634 try {
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);
643 if (deleteApiJars) {
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.");
678 return runtime;
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);
693 if (!xml.exists()) {
694 return;
696 try {
697 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
698 try {
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)
714 throws IOException {
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[] {
736 javaCmd,
737 "-classpath", classpath,
738 JSPC_MAIN,
739 "-uriroot", stage.getPath(),
740 "-p", "org.apache.jsp",
741 "-l", "-v",
742 "-webinc", generatedWebXml.getPath(),
743 "-d", tempDir.getPath(),
744 "-javaEncoding", opts.getCompileEncoding(),
746 Process jspc = startProcess(args);
748 int status = 1;
749 try {
750 status = jspc.waitFor();
751 } catch (InterruptedException ex) { }
753 if (status != 0) {
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")) {
779 files.add(f);
782 if (files.isEmpty()) {
783 return;
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();
794 fileManager.close();
796 if (!success) {
797 throw new JspCompilationException("Failed to compile the generated JSP java files.",
798 JspCompilationException.Source.JSPC);
800 if (opts.isJarJSPsSet()) {
801 zipJasperGeneratedFiles(webInf, jspClassDir);
802 } else {
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")) {
808 f.delete();
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,
823 fileTypesToExclude);
824 jarTool.run();
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,
833 null);
834 jarTool.run();
835 recursiveDelete(classesDir);
836 classesDir.mkdir();
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();
871 return proc;
874 private String formatCommand(Iterable<String> args) {
875 StringBuilder command = new StringBuilder();
876 for (String chunk : args) {
877 command.append(chunk);
878 command.append(" ");
880 return command.toString();
884 * Scans a given directory tree, testing whether any file matches a given
885 * pattern.
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)) {
896 return true;
898 } else {
899 if (regex.matcher(file.getName()).matches()) {
900 return true;
904 return false;
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
910 * size.
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) {
919 return;
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();
928 subfile.delete();
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
946 * subdirectory
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))) {
966 continue;
969 if (file.isDirectory()) {
970 if (file.getName().equals("WEB-INF")) {
971 copyOrLink(file, new File(resDir, name), new File(staticDir, name), true, opts);
972 } else {
973 copyOrLink(file, new File(resDir, name), new File(staticDir, name), forceResource,
974 opts);
976 } else {
977 if (SKIP_FILES.matcher(path).matches()) {
978 continue;
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")) {
1006 try {
1007 dest.delete();
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());
1017 try {
1018 int stat = link.waitFor();
1019 if (stat == 0) {
1020 return;
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];
1032 int readlen;
1033 FileInputStream inStream = new FileInputStream(source);
1034 FileOutputStream outStream = new FileOutputStream(dest);
1035 try {
1036 readlen = inStream.read(buffer);
1037 while (readlen > 0) {
1038 outStream.write(buffer, 0, readlen);
1039 readlen = inStream.read(buffer);
1041 } finally {
1042 try {
1043 inStream.close();
1044 } catch (IOException ex) {
1046 try {
1047 outStream.close();
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));
1061 } else {
1062 copyOrLinkFile(file, new File(destination, name));
1067 /** deletes the staging directory, if one was created. */
1068 @Override
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));
1083 dead.delete();
1086 @Override
1087 public void setListener(UpdateListener l) {
1088 listener = l;
1091 @Override
1092 public void setDetailsWriter(PrintWriter detailsWriter) {
1093 this.detailsWriter = detailsWriter;
1096 @Override
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));
1109 @Override
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);
1134 return yaml;
1138 * Returns the app.yaml string.
1140 * @throws IllegalStateException if createStagingDirectory has not been called.
1142 @Override
1143 public String getAppYaml() {
1144 if (appYaml == null) {
1145 throw new IllegalStateException("Must call createStagingDirectory first.");
1147 return appYaml;