Package com.google.gwt.user.rebind

Examples of com.google.gwt.user.rebind.SourceWriter


   
    cf.addImplementedInterface(userType.getQualifiedSourceName());
   
    PrintWriter pw=context.tryCreate(logger, packageName, implClassName);
    if(pw!=null){
      SourceWriter sw=cf.createSourceWriter(context, pw);
     
      logger.log(Type.INFO, "Start generating assets bundle...");
      sw.println("@Override");
      sw.println("public ResourcePrototype[] getResources() {");
      sw.indent();
      sw.print("return MyClientBundleWithLookup.INSTANCE.getResources();");
      sw.outdent();
      sw.println("}");
     
      sw.println("static interface MyClientBundleWithLookup extends ClientBundleWithLookup{");
      sw.indent();
      sw.println("MyClientBundleWithLookup INSTANCE=GWT.create(MyClientBundleWithLookup.class);");
     
      for(File file:files){
        String sourcePath=file.getPath().replace(baseDir.getPath()+"\\","").replace('\\', '/');
        Class<? extends ResourcePrototype> returnType=matchReturnType(file.getName());
        if(returnType==null){
          continue;
        }
        String methodName=stripExtension(file.getName());
       
        if(!isValidMethodName(methodName)){
          logger.log(TreeLogger.WARN, "Skipping invalid method name (" + methodName + ") due to: "
                      + sourcePath);
                  continue;
        }else if(!methodNames.add(methodName)){
          logger.log(TreeLogger.WARN, "Skipping duplicate method name :"+methodName+
              ". Maybe you have the files with the same name in different directories.");
        }
        logger.log(TreeLogger.DEBUG, "Generating method for: " + sourcePath+", and method name is: "+methodName);
        sw.println("@Source(\""+sourcePath+"\")");
        sw.println("public "+returnType.getName()+" "+methodName+"();");
      }
     
      sw.outdent();
      sw.println("}");
     
      sw.commit(logger);
      logger.log(Type.INFO, "Generated assets bundle successfully.");
    }
    return cf.getCreatedClassName();
  }
View Full Code Here


    final BlockBuilder<?> blockBuilder =
        classStructureBuilder.publicMethod(BootstrapperInjectionContext.class, "bootstrapContainer")
            .methodComment("The main IOC bootstrap method.");

    final SourceWriter sourceWriter = new StringSourceWriter();

    final IOCProcessingContext.Builder iocProcContextBuilder
        = IOCProcessingContext.Builder.create();

    iocProcContextBuilder.blockBuilder(blockBuilder);
    iocProcContextBuilder.generatorContext(context);
    iocProcContextBuilder.context(buildContext);
    iocProcContextBuilder.bootstrapClassInstance(bootStrapClass);
    iocProcContextBuilder.bootstrapBuilder(classStructureBuilder);
    iocProcContextBuilder.logger(logger);
    iocProcContextBuilder.sourceWriter(sourceWriter);
    iocProcContextBuilder.gwtTarget(!useReflectionStubs);

    final InjectionContext.Builder injectionContextBuilder
        = InjectionContext.Builder.create();

    final MetaDataScanner scanner = ScannerSingleton.getOrCreateInstance();
    final Multimap<String, String> props = scanner.getErraiProperties();

    if (props != null) {
      logger.log(TreeLogger.Type.INFO, "Checking ErraiApp.properties for configured types ...");

      final Collection<String> qualifyingMetadataFactoryProperties = props.get(QUALIFYING_METADATA_FACTORY_PROPERTY);

      if (qualifyingMetadataFactoryProperties.size() > 1) {
        throw new RuntimeException("the property '" + QUALIFYING_METADATA_FACTORY_PROPERTY + "' is set in more than one place");
      }
      else if (qualifyingMetadataFactoryProperties.size() == 1) {
        final String fqcnQualifyingMetadataFactory = qualifyingMetadataFactoryProperties.iterator().next().trim();

        try {
          final QualifyingMetadataFactory factory = (QualifyingMetadataFactory)
              Class.forName
                  (fqcnQualifyingMetadataFactory).newInstance();

          iocProcContextBuilder.qualifyingMetadata(factory);
        }
        catch (ClassNotFoundException e) {
          e.printStackTrace();
        }
        catch (InstantiationException e) {
          e.printStackTrace();
        }
        catch (IllegalAccessException e) {
          e.printStackTrace();
        }
      }

      final Collection<String> enabledAlternativesProperties = props.get(ENABLED_ALTERNATIVES_PROPERTY);

      for (final String prop : enabledAlternativesProperties) {
          final String[] alternatives = prop.split("\\s");
          for (final String alternative : alternatives) {
            injectionContextBuilder.enabledAlternative(alternative.trim());
          }
      }
    }

    iocProcContextBuilder.packages(packages);

    final IOCProcessingContext procContext = iocProcContextBuilder.build();

    injectionContextBuilder.processingContext(procContext);
    injectionContextBuilder.reachableTypes(allDeps);
    final InjectionContext injectionContext = injectionContextBuilder.build();

    defaultConfigureProcessor(injectionContext);

    // generator constructor source code
    final IOCProcessorFactory procFactory = new IOCProcessorFactory(injectionContext);
    processExtensions(context, procContext, injectionContext, procFactory, beforeTasks, afterTasks);
    generateExtensions(procContext, procFactory, injectionContext, sourceWriter, classStructureBuilder, blockBuilder);

    // close generated class
    return sourceWriter.toString();
  }
View Full Code Here

      String qualName = packageName + "." + superClassName;
      ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(
          packageName, superClassName);
      factory.setSuperclass(targetClass.getQualifiedSourceName());
      factory.addImport("com.google.gwt.core.client.JavaScriptObject");
      SourceWriter writer = factory.createSourceWriter(context, pw);
      writer.println("private JavaScriptObject nativeDisplayNames;");
      writer.println();
      writer.println("@Override");
      writer.println("public String[] getAvailableLocaleNames() {");
      writer.println("  return new String[] {");
      boolean hasAnyRtl = false;
      for (GwtLocaleImpl possibleLocale : allLocales) {
        writer.println("    \""
            + possibleLocale.toString().replaceAll("\"", "\\\"") + "\",");
        if (RTL_LOCALES.contains(
            possibleLocale.getCanonicalForm().getLanguage())) {
          hasAnyRtl = true;
        }
      }
      writer.println("  };");
      writer.println("}");
      writer.println();
      writer.println("@Override");
      writer.println("public native String getLocaleNativeDisplayName(String localeName) /*-{");
      writer.println("  this.@" + qualName + "::ensureNativeDisplayNames()();");
      writer.println("  return this.@" + qualName
          + "::nativeDisplayNames[localeName];");
      writer.println("}-*/;");
      writer.println();
      writer.println("@Override");
      writer.println("public boolean hasAnyRTL() {");
      writer.println("  return " + hasAnyRtl + ";");
      writer.println("}");
      writer.println();
      writer.println("private native void ensureNativeDisplayNames() /*-{");
      writer.println("  if (this.@" + qualName
          + "::nativeDisplayNames != null) {");
      writer.println("    return;");
      writer.println("  }");
      writer.println("  this.@" + qualName + "::nativeDisplayNames = {");
      LocalizedProperties displayNames = new LocalizedProperties();
      LocalizedProperties displayNamesManual = new LocalizedProperties();
      LocalizedProperties displayNamesOverride = new LocalizedProperties();
      ClassLoader classLoader = getClass().getClassLoader();
      try {
        InputStream str = classLoader.getResourceAsStream(GENERATED_LOCALE_NATIVE_DISPLAY_NAMES);
        if (str != null) {
          displayNames.load(str, "UTF-8");
        }
        str = classLoader.getResourceAsStream(MANUAL_LOCALE_NATIVE_DISPLAY_NAMES);
        if (str != null) {
          displayNamesManual.load(str, "UTF-8");
        }
        str = classLoader.getResourceAsStream(OVERRIDE_LOCALE_NATIVE_DISPLAY_NAMES);
        if (str != null) {
          displayNamesOverride.load(str, "UTF-8");
        }
      } catch (UnsupportedEncodingException e) {
        // UTF-8 should always be defined
        logger.log(TreeLogger.ERROR, "UTF-8 encoding is not defined", e);
        throw new UnableToCompleteException();
      } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "Exception reading locale display names",
            e);
        throw new UnableToCompleteException();
      }
      boolean needComma = false;
      for (GwtLocaleImpl possibleLocale : allLocales) {
        String localeName = possibleLocale.toString();
        String displayName = displayNamesOverride.getProperty(localeName);
        if (displayName == null) {
          displayName = displayNamesManual.getProperty(localeName);
        }
        if (displayName == null) {
          displayName = displayNames.getProperty(localeName);
        }
        if (displayName != null && displayName.length() != 0) {
          localeName = quoteQuotes(localeName);
          displayName = quoteQuotes(displayName);
          if (needComma) {
            writer.println(",");
          }
          writer.print("    \"" + localeName + "\": \"" + displayName + "\"");
          needComma = true;
        }
      }
      if (needComma) {
        writer.println();
      }
      writer.println("  };");
      writer.println("}-*/;");
      writer.commit(logger);
    }
    GwtLocale locale = localeUtils.getCompileLocale();
    String className = targetClass.getName().replace('.', '_') + "_"
        + locale.getAsString();
    Set<GwtLocale> runtimeLocales = localeUtils.getRuntimeLocales();
    if (!runtimeLocales.isEmpty()) {
      className += "_runtimeSelection";
    }

    pw = context.tryCreate(logger, packageName, className);
    if (pw != null) {
      ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(
          packageName, className);
      factory.setSuperclass(superClassName);
      factory.addImport("com.google.gwt.core.client.GWT");
      factory.addImport("com.google.gwt.i18n.client.LocaleInfo");
      factory.addImport("com.google.gwt.i18n.client.constants.NumberConstants");
      factory.addImport("com.google.gwt.i18n.client.constants.NumberConstantsImpl");
      factory.addImport("com.google.gwt.i18n.client.constants.DateTimeConstants");
      factory.addImport("com.google.gwt.i18n.client.constants.DateTimeConstantsImpl");
      SourceWriter writer = factory.createSourceWriter(context, pw);
      writer.println("@Override");
      writer.println("public String getLocaleName() {");
      if (runtimeLocales.isEmpty()) {
        writer.println("  return \"" + locale + "\";");
      } else {
        writer.println("  String rtLocale = getRuntimeLocale();");
        writer.println("  return rtLocale != null ? rtLocale : \"" + locale
            + "\";");
      }
      writer.println("}");
      writer.println();
      writer.println("@Override");
      writer.println("public DateTimeConstants getDateTimeConstants() {");
      LocalizableGenerator localizableGenerator = new LocalizableGenerator();
      // Avoid warnings for trying to create the same type multiple times
      GeneratorContext subContext = new CachedGeneratorContext(context);
      generateConstantsLookup(logger, subContext, writer, localizableGenerator,
          runtimeLocales, locale,
          "com.google.gwt.i18n.client.constants.DateTimeConstantsImpl");
      writer.println("}");
      writer.println();
      writer.println("@Override");
      writer.println("public NumberConstants getNumberConstants() {");
      generateConstantsLookup(logger, subContext, writer, localizableGenerator,
          runtimeLocales, locale,
          "com.google.gwt.i18n.client.constants.NumberConstantsImpl");
      writer.println("}");
      writer.commit(logger);
    }
    return packageName + "." + className;
  }
View Full Code Here

      // The whole point of this exercise
      f.addImplementedInterface(sourceType.getQualifiedSourceName());

      // All source gets written through this Writer
      SourceWriter sw = f.createSourceWriter(generatorContext, out);

      // Set the now-calculated simple source name
      resourceContext.setSimpleSourceName(generatedSimpleSourceName);

      // Write the generated code to disk
      createFieldsAndAssignments(logger, sw, generators, resourceContext,
          fields);

      // Print the accumulated field definitions
      sw.println(fields.getCode());

      /*
       * The map-accessor methods use JSNI and need a fully-qualified class
       * name, but should not include any sub-bundles.
       */
      taskList.remove(BundleResourceGenerator.class);
      writeMapMethods(logger, createdClassName, sw, taskList);

      sw.commit(logger);
    }

    finish(logger, resourceContext, generators.keySet());
    doFinish(logger);

View Full Code Here

      RemoteServiceAsyncValidator.logValidAsyncInterfaceDeclaration(logger,
          serviceIntf);
      throw new UnableToCompleteException();
    }

    SourceWriter srcWriter = getSourceWriter(logger, context, serviceAsync);
    if (srcWriter == null) {
      return getProxyQualifiedName();
    }

    // Make sure that the async and synchronous versions of the RemoteService
    // agree with one another
    //
    RemoteServiceAsyncValidator rsav = new RemoteServiceAsyncValidator(logger,
        typeOracle);
    Map<JMethod, JMethod> syncMethToAsyncMethMap = rsav.validate(logger,
        serviceIntf, serviceAsync);

    final PropertyOracle propertyOracle = context.getPropertyOracle();

    // Load the blacklist/whitelist
    TypeFilter blacklistTypeFilter = new BlacklistTypeFilter(logger,
        propertyOracle);

    // Determine the set of serializable types
    SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(
        logger, propertyOracle, typeOracle);
    typesSentFromBrowserBuilder.setTypeFilter(blacklistTypeFilter);
    SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(
        logger, propertyOracle, typeOracle);
    typesSentToBrowserBuilder.setTypeFilter(blacklistTypeFilter);

    addRoots(logger, typeOracle, typesSentFromBrowserBuilder,
        typesSentToBrowserBuilder);

    try {
      ConfigurationProperty prop = context.getPropertyOracle().getConfigurationProperty(
          TypeSerializerCreator.GWT_ELIDE_TYPE_NAMES_FROM_RPC);
      elideTypeNames = Boolean.parseBoolean(prop.getValues().get(0));
    } catch (BadPropertyValueException e) {
      logger.log(TreeLogger.ERROR, "Configuration property "
          + TypeSerializerCreator.GWT_ELIDE_TYPE_NAMES_FROM_RPC
          + " is not defined. Is RemoteService.gwt.xml inherited?");
      throw new UnableToCompleteException();
    }

    // Decide what types to send in each direction.
    // Log the decisions to a string that will be written later in this method
    SerializableTypeOracle typesSentFromBrowser;
    SerializableTypeOracle typesSentToBrowser;
    String rpcLog;
    {
      StringWriter stringWriter = new StringWriter();
      PrintWriter writer = new PrintWriter(stringWriter);

      typesSentFromBrowserBuilder.setLogOutputWriter(writer);
      typesSentToBrowserBuilder.setLogOutputWriter(writer);

      writer.write("====================================\n");
      writer.write("Types potentially sent from browser:\n");
      writer.write("====================================\n\n");
      writer.flush();
      typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);

      writer.write("===================================\n");
      writer.write("Types potentially sent from server:\n");
      writer.write("===================================\n\n");
      writer.flush();
      typesSentToBrowser = typesSentToBrowserBuilder.build(logger);

      writer.close();
      rpcLog = stringWriter.toString();
    }

    generateTypeHandlers(logger, context, typesSentFromBrowser,
        typesSentToBrowser);

    String serializationPolicyStrongName = writeSerializationPolicyFile(logger,
        context, typesSentFromBrowser, typesSentToBrowser);

    String remoteServiceInterfaceName = elideTypeNames
        ? TypeNameObfuscator.SERVICE_INTERFACE_ID
        : TypeOracleMediator.computeBinaryClassName(serviceIntf);
    generateProxyFields(srcWriter, typesSentFromBrowser,
        serializationPolicyStrongName, remoteServiceInterfaceName);

    generateProxyContructor(srcWriter);

    generateProxyMethods(srcWriter, typesSentFromBrowser,
        syncMethToAsyncMethMap);

    if (elideTypeNames) {
      generateStreamWriterOverride(srcWriter);
    }

    srcWriter.commit(logger);

    // Create an artifact explaining STOB's decisions. It will be emitted by
    // RpcLogLinker
    context.commitArtifact(logger, new RpcLogArtifact(
        serviceIntf.getQualifiedSourceName(), serializationPolicyStrongName,
View Full Code Here

  @Override
  public String createAssignment(TreeLogger logger, ResourceContext context,
      JMethod method) throws UnableToCompleteException {

    TypeOracle typeOracle = context.getGeneratorContext().getTypeOracle();
    SourceWriter sw = new StringSourceWriter();
    // Write the expression to create the subtype.
    sw.println("new " + method.getReturnType().getQualifiedSourceName()
        + "() {");
    sw.indent();

    JClassType cssResourceSubtype = method.getReturnType().isInterface();
    assert cssResourceSubtype != null;
    Map<String, Map<JMethod, String>> replacementsWithPrefix = new HashMap<String, Map<JMethod, String>>();

    replacementsWithPrefix.put("",
        computeReplacementsForType(cssResourceSubtype));
    Import imp = method.getAnnotation(Import.class);
    if (imp != null) {
      boolean fail = false;
      for (Class<? extends CssResource> clazz : imp.value()) {
        JClassType importType = typeOracle.findType(clazz.getName().replace(
            '$', '.'));
        assert importType != null : "TypeOracle does not have type "
            + clazz.getName();

        String prefix = getImportPrefix(importType);

        if (replacementsWithPrefix.put(prefix,
            computeReplacementsForType(importType)) != null) {
          logger.log(TreeLogger.ERROR,
              "Multiple imports that would use the prefix " + prefix);
          fail = true;
        }
      }
      if (fail) {
        throw new UnableToCompleteException();
      }
    }

    // Methods defined by CssResource interface
    writeEnsureInjected(sw);
    writeGetName(method, sw);

    sw.println("public String getText() {");
    sw.indent();
    boolean strict = isStrict(logger, method);
    Map<JMethod, String> actualReplacements = new IdentityHashMap<JMethod, String>();
    String cssExpression = makeExpression(logger, context, cssResourceSubtype,
        stylesheetMap.get(method), replacementsWithPrefix, strict,
        actualReplacements);
    sw.println("return " + cssExpression + ";");
    sw.outdent();
    sw.println("}");

    /*
     * getOverridableMethods is used to handle CssResources extending
     * non-CssResource types. See the discussion in computeReplacementsForType.
     */
    writeUserMethods(logger, sw, stylesheetMap.get(method),
        cssResourceSubtype.getOverridableMethods(), actualReplacements);

    sw.outdent();
    sw.println("}");

    return sw.toString();
  }
View Full Code Here

  @Override
  public String createAssignment(TreeLogger logger, ResourceContext context,
      JMethod method) throws UnableToCompleteException {
    String name = method.getName();

    SourceWriter sw = new StringSourceWriter();
    sw.println("new " + ImageResourcePrototype.class.getName() + "(");
    sw.indent();
    sw.println('"' + name + "\",");

    ImageRect rect = shared.imageRectsByName.get(name);
    assert rect != null : "No ImageRect ever computed for " + name;

    String[] urlExpressions = local.urlExpressionsByImageRect.get(rect);
    assert urlExpressions != null : "No URL expression for " + name;
    assert urlExpressions.length == 2;

    if (urlExpressions[1] == null) {
      sw.println(urlExpressions[0] + ",");
    } else {
      sw.println("com.google.gwt.i18n.client.LocaleInfo.getCurrentLocale().isRTL() ?"
          + urlExpressions[1] + " : " + urlExpressions[0] + ",");
    }
    sw.println(rect.getLeft() + ", " + rect.getTop() + ", " + rect.getWidth()
        + ", " + rect.getHeight() + ", " + rect.isAnimated() + ", "
        + rect.isLossy());

    sw.outdent();
    sw.print(")");

    return sw.toString();
  }
View Full Code Here

        composer = new ClassSourceFileComposerFactory(packageName, className);
        composer.addImport("com.google.gwt.core.client.GWT");
        composer.addImport("java.util.HashMap");
        composer.addImport("com.google.gwt.core.client.RunAsyncCallback");
        composer.setSuperclass("com.vaadin.terminal.gwt.client.WidgetMap");
        SourceWriter sourceWriter = composer.createSourceWriter(context,
                printWriter);

        Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation = getUsedPaintables();

        validatePaintables(logger, context, paintablesHavingWidgetAnnotation);

        // generator constructor source code
        generateImplementationDetector(sourceWriter,
                paintablesHavingWidgetAnnotation);
        generateInstantiatorMethod(sourceWriter,
                paintablesHavingWidgetAnnotation);
        // close generated class
        sourceWriter.outdent();
        sourceWriter.println("}");
        // commit generated class
        context.commit(logger, printWriter);
        logger.log(Type.INFO,
                "Done. (" + (new Date().getTime() - date.getTime()) / 1000
                        + "seconds)");
View Full Code Here

        composerFactory.addImport(Serializer.class.getName());
        composerFactory.addImport(SerialMode.class.getName());
       
        composerFactory.setSuperclass(typeName);
        // TODO is the SERIALIZER required for DE RPC?
        SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
        sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
        sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
        sourceWriter.print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
        sourceWriter.commit(logger);
       
        if (annotation.mode() == SerialMode.DE_RPC) {
          RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
          for (JType t : typesSentToBrowser.getSerializableTypes()) {
            if (!(t instanceof JClassType)) {
View Full Code Here

      composer.addImport(FastMap.class.getName());

      PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

      if (pw != null) {
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("private Map<String, BeanModelFactory> m;");

        sw.println("public BeanModelFactory getFactory(Class b) {");
        sw.indent();
        sw.println("String n = b.getName();");
        sw.println("if (m == null) {");
        sw.indentln("m = new FastMap<BeanModelFactory>();");
        sw.println("}");
        sw.println("if (m.get(n) == null) {");
        sw.indent();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < beans.size(); i++) {
          JClassType bean = beans.get(i);
          String name = createBean(bean, logger, context);
          String factory = createFactory(bean, name, logger, context);

          if (i > 0) {
            sw.print(" else ");
          }
          sw.println("if (" + bean.getQualifiedSourceName() + ".class.getName().equals(n)) {");
          sw.indentln("m" + i + "();");

          sb.append("private void m" + i + "() {\n");
          sb.append("  m.put(" + bean.getQualifiedSourceName() + ".class.getName(), new " + factory + "());\n");
          sb.append("}\n");

          sw.print("}");
        }
        sw.outdent();
        sw.println("}");
        sw.println("return m.get(n);");
        sw.outdent();
        sw.println("}");

        sw.println(sb.toString());
        sw.commit(logger);
      }

      return composer.getCreatedClassName();

    } catch (Exception e) {
View Full Code Here

TOP

Related Classes of com.google.gwt.user.rebind.SourceWriter

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.