예제 #1
0
 @Override
 protected void doCreateBundleForPermutation(
     TreeLogger logger,
     GeneratorContext generatorContext,
     FieldsImpl fields,
     String generatedSimpleSourceName)
     throws UnableToCompleteException {
   String partialPath =
       Util.computeStrongName(Util.getBytes(generatedSimpleSourceName)) + BUNDLE_EXTENSION;
   resourceContext.setPartialPath(partialPath);
   fields.setInitializer(
       bundleBaseIdent, "\"mhtml:\" + GWT.getModuleBaseURL() + \"" + partialPath + "!cid:\"");
 }
예제 #2
0
  public void testDeletion() {
    File f = null;
    try {
      f = File.createTempFile("com.google.gwt.dev.javac.impl.FileResourceTest", ".tmp");
      f.deleteOnExit();
      Util.writeStringAsFile(f, "contents 1");
    } catch (IOException e) {
      fail("Failed to create test file");
    }

    File dir = f.getParentFile();
    DirectoryClassPathEntry cpe = new DirectoryClassPathEntry(dir);
    FileResource r = new FileResource(cpe, f.getName(), f);
    assertEquals(f.getAbsoluteFile().toURI().toString(), r.getLocation());

    /*
     * In this case, there's no subdirectory, so the path should match the
     * simple filename.
     */
    assertEquals(f.getName(), r.getPath());

    // Delete the file.
    f.delete();

    /*
     *  The resource is no longer available.  Check to make sure we can't access its contents
     *  through the API.
     */
    InputStream in = null;
    try {
      in = r.openContents();
      fail("Open contents unexpectedly succeeded.");
    } catch (IOException expected) {
    }
  }
예제 #3
0
  private void emitPolicyFileArtifact(
      TreeLogger logger, GeneratorContextExt context, String partialPath)
      throws UnableToCompleteException {
    try {
      String qualifiedSourceName = serviceIntf.getQualifiedSourceName();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      Writer writer;
      writer =
          new OutputStreamWriter(
              baos, SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING);
      writer.write("serviceClass: " + qualifiedSourceName + "\n");
      writer.write("path: " + partialPath + "\n");
      writer.close();

      byte[] manifestBytes = baos.toByteArray();
      String md5 = Util.computeStrongName(manifestBytes);
      OutputStream os =
          context.tryCreateResource(logger, MANIFEST_ARTIFACT_DIR + "/" + md5 + ".txt");
      os.write(manifestBytes);

      GeneratedResource resource = context.commitResource(logger, os);
      // TODO: change to Deploy when possible
      resource.setVisibility(Visibility.LegacyDeploy);
    } catch (UnsupportedEncodingException e) {
      logger.log(
          TreeLogger.ERROR,
          SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING + " is not supported",
          e);
      throw new UnableToCompleteException();
    } catch (IOException e) {
      logger.log(TreeLogger.ERROR, null, e);
      throw new UnableToCompleteException();
    }
  }
예제 #4
0
  private Document getW3cDoc(
      MortalLogger logger,
      DesignTimeUtils designTime,
      ResourceOracle resourceOracle,
      String templatePath)
      throws UnableToCompleteException {

    Resource resource = resourceOracle.getResourceMap().get(templatePath);
    if (null == resource) {
      logger.die("Unable to find resource: " + templatePath);
    }

    Document doc = null;
    try {
      String content = designTime.getTemplateContent(templatePath);
      if (content == null) {
        content = Util.readStreamAsString(resource.openContents());
      }
      doc =
          new W3cDomHelper(logger.getTreeLogger(), resourceOracle)
              .documentFor(content, resource.getPath());
    } catch (IOException iex) {
      logger.die("Error opening resource:" + resource.getLocation(), iex);
    } catch (SAXParseException e) {
      logger.die("Error parsing XML (line " + e.getLineNumber() + "): " + e.getMessage(), e);
    }
    return doc;
  }
예제 #5
0
 /**
  * Finds a JDT CUD for a given top-level type, generating it if needed.
  *
  * @param topType top-level JClassType
  * @return CUD instance or null if no source found
  */
 private synchronized CompilationUnitDeclaration getCudForTopLevelType(JClassType topType) {
   CompilationUnitDeclaration cud = null;
   if (cudCache.containsKey(topType)) {
     SoftReference<CompilationUnitDeclaration> cudRef = cudCache.get(topType);
     if (cudRef != null) {
       cud = cudRef.get();
     }
   }
   if (cud == null) {
     Resource classSource = classSources.get(topType);
     String source = null;
     if (classSource != null) {
       try {
         InputStream stream = classSource.openContents();
         source = Util.readStreamAsString(stream);
       } catch (IOException ex) {
         throw new InternalCompilerException(
             "Problem reading resource: " + classSource.getLocation(), ex);
       }
     }
     if (source == null) {
       // cache negative result so we don't try again
       cudCache.put(topType, null);
     } else {
       cud = parseJava(source);
       cudCache.put(topType, new SoftReference<CompilationUnitDeclaration>(cud));
     }
   }
   return cud;
 }
  @Override
  protected void doShutDownServer() {
    if (server != null) {
      try {
        server.stop();
      } catch (UnableToCompleteException e) {
        // Already logged.
      }
      server = null;
    }

    if (tempWorkDir) {
      Util.recursiveDelete(options.getWorkDir(), false);
    }
  }
예제 #7
0
  public void testBasic() {
    File f = null;
    try {
      f = File.createTempFile("com.google.gwt.dev.javac.impl.FileResourceTest", ".tmp");
      f.deleteOnExit();
      Util.writeStringAsFile(f, "contents 1");
    } catch (IOException e) {
      fail("Failed to create test file");
    }

    File dir = f.getParentFile();
    DirectoryClassPathEntry cpe = new DirectoryClassPathEntry(dir);
    FileResource r = new FileResource(cpe, f.getName(), f);
    assertEquals(f.getAbsoluteFile().toURI().toString(), r.getLocation());

    /*
     * In this case, there's no subdirectory, so the path should match the
     * simple filename.
     */
    assertEquals(f.getName(), r.getPath());
  }
예제 #8
0
  public boolean run(TreeLogger logger, ModuleDef... modules) throws UnableToCompleteException {
    boolean tempWorkDir = false;
    try {
      if (options.getWorkDir() == null) {
        options.setWorkDir(Utility.makeTemporaryDirectory(null, "gwtc"));
        tempWorkDir = true;
      }
      if (options.isSoycEnabled() && options.getExtraDir() == null) {
        options.setExtraDir(new File("extras"));
      }

      File persistentUnitCacheDir = null;
      if (options.getWarDir() != null && !options.getWarDir().getName().endsWith(".jar")) {
        persistentUnitCacheDir = new File(options.getWarDir(), "../");
      }
      CompilationStateBuilder.init(logger, persistentUnitCacheDir);

      for (ModuleDef module : modules) {
        String moduleName = module.getCanonicalName();
        if (options.isValidateOnly()) {
          if (!Precompile.validate(logger, options, module, options.getGenDir())) {
            return false;
          }
        } else {
          long compileStart = System.currentTimeMillis();
          TreeLogger branch = logger.branch(TreeLogger.INFO, "Compiling module " + moduleName);

          // Optimize early since permutation compiles will run in process.
          options.setOptimizePrecompile(true);
          Precompilation precompilation =
              Precompile.precompile(branch, options, module, options.getGenDir());
          if (precompilation == null) {
            return false;
          }

          Event compilePermutationsEvent =
              SpeedTracerLogger.start(CompilerEventType.COMPILE_PERMUTATIONS);
          Permutation[] allPerms = precompilation.getPermutations();
          List<FileBackedObject<PermutationResult>> resultFiles =
              CompilePerms.makeResultFiles(options.getCompilerWorkDir(moduleName), allPerms);
          CompilePerms.compile(
              branch, precompilation, allPerms, options.getLocalWorkers(), resultFiles);
          compilePermutationsEvent.end();

          ArtifactSet generatedArtifacts = precompilation.getGeneratedArtifacts();
          JJSOptions precompileOptions = precompilation.getUnifiedAst().getOptions();

          precompilation = null; // No longer needed, so save the memory

          Event linkEvent = SpeedTracerLogger.start(CompilerEventType.LINK);
          File absPath = new File(options.getWarDir(), module.getName());
          absPath = absPath.getAbsoluteFile();

          String logMessage = "Linking into " + absPath;
          if (options.getExtraDir() != null) {
            File absExtrasPath = new File(options.getExtraDir(), module.getName());
            absExtrasPath = absExtrasPath.getAbsoluteFile();
            logMessage += "; Writing extras to " + absExtrasPath;
          }
          Link.link(
              logger.branch(TreeLogger.TRACE, logMessage),
              module,
              generatedArtifacts,
              allPerms,
              resultFiles,
              options.getWarDir(),
              options.getDeployDir(),
              options.getExtraDir(),
              precompileOptions);

          linkEvent.end();
          long compileDone = System.currentTimeMillis();
          long delta = compileDone - compileStart;
          if (branch.isLoggable(TreeLogger.INFO)) {
            branch.log(
                TreeLogger.INFO,
                "Compilation succeeded -- " + String.format("%.3f", delta / 1000d) + "s");
          }
        }
      }

    } catch (IOException e) {
      logger.log(TreeLogger.ERROR, "Unable to create compiler work directory", e);
      return false;
    } finally {
      if (tempWorkDir) {
        Util.recursiveDelete(options.getWorkDir(), false);
      }
    }
    return true;
  }
예제 #9
0
  protected String writeSerializationPolicyFile(
      TreeLogger logger,
      GeneratorContextExt ctx,
      SerializableTypeOracle serializationSto,
      SerializableTypeOracle deserializationSto)
      throws UnableToCompleteException {
    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw =
          new OutputStreamWriter(
              baos, SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING);
      TypeOracle oracle = ctx.getTypeOracle();
      PrintWriter pw = new PrintWriter(osw);

      JType[] serializableTypes =
          unionOfTypeArrays(
              serializationSto.getSerializableTypes(),
              deserializationSto.getSerializableTypes(),
              new JType[] {serviceIntf});

      for (int i = 0; i < serializableTypes.length; ++i) {
        JType type = serializableTypes[i];
        String binaryTypeName = SerializationUtils.getRpcTypeName(type);
        pw.print(binaryTypeName);
        pw.print(", " + Boolean.toString(deserializationSto.isSerializable(type)));
        pw.print(", " + Boolean.toString(deserializationSto.maybeInstantiated(type)));
        pw.print(", " + Boolean.toString(serializationSto.isSerializable(type)));
        pw.print(", " + Boolean.toString(serializationSto.maybeInstantiated(type)));
        pw.print(", " + typeStrings.get(type));

        /*
         * Include the serialization signature to bump the RPC file name if
         * obfuscated identifiers are used.
         */
        pw.print(", " + SerializationUtils.getSerializationSignature(oracle, type));
        pw.print('\n');

        /*
         * Emit client-side field information for classes that may be enhanced
         * on the server. Each line consists of a comma-separated list
         * containing the keyword '@ClientFields', the class name, and a list of
         * all potentially serializable client-visible fields.
         */
        if ((type instanceof JClassType) && ((JClassType) type).isEnhanced()) {
          JField[] fields = ((JClassType) type).getFields();
          JField[] rpcFields = new JField[fields.length];
          int numRpcFields = 0;
          for (JField f : fields) {
            if (f.isTransient() || f.isStatic() || f.isFinal()) {
              continue;
            }
            rpcFields[numRpcFields++] = f;
          }

          pw.print(SerializationPolicyLoader.CLIENT_FIELDS_KEYWORD);
          pw.print(',');
          pw.print(binaryTypeName);
          for (int idx = 0; idx < numRpcFields; idx++) {
            pw.print(',');
            pw.print(rpcFields[idx].getName());
          }
          pw.print('\n');
        }
      }

      // Closes the wrapped streams.
      pw.close();

      byte[] serializationPolicyFileContents = baos.toByteArray();
      String serializationPolicyName = Util.computeStrongName(serializationPolicyFileContents);

      String serializationPolicyFileName =
          SerializationPolicyLoader.getSerializationPolicyFileName(serializationPolicyName);
      OutputStream os = ctx.tryCreateResource(logger, serializationPolicyFileName);
      if (os != null) {
        os.write(serializationPolicyFileContents);
        GeneratedResource resource = ctx.commitResource(logger, os);

        /*
         * Record which proxy class created the resource. A manifest will be
         * emitted by the RpcPolicyManifestLinker.
         */
        emitPolicyFileArtifact(logger, ctx, resource.getPartialPath());
      } else {
        if (logger.isLoggable(TreeLogger.TRACE)) {
          logger.log(
              TreeLogger.TRACE,
              "SerializationPolicy file for RemoteService '"
                  + serviceIntf.getQualifiedSourceName()
                  + "' already exists; no need to rewrite it.",
              null);
        }
      }

      return serializationPolicyName;
    } catch (UnsupportedEncodingException e) {
      logger.log(
          TreeLogger.ERROR,
          SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING + " is not supported",
          e);
      throw new UnableToCompleteException();
    } catch (IOException e) {
      logger.log(TreeLogger.ERROR, null, e);
      throw new UnableToCompleteException();
    }
  }