Example usage for com.google.gwt.user.rebind SourceWriter print

List of usage examples for com.google.gwt.user.rebind SourceWriter print

Introduction

In this page you can find the example usage for com.google.gwt.user.rebind SourceWriter print.

Prototype

void print(String s);

Source Link

Usage

From source file:com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator.java

License:Open Source License

private void generateInstantiatorMethod(SourceWriter sourceWriter,
        Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation) {

    Collection<Class<?>> deferredWidgets = new LinkedList<Class<?>>();

    // TODO detect if it would be noticably faster to instantiate with a
    // lookup with index than with the hashmap

    sourceWriter.println("public void ensureInstantiator(Class<? extends Paintable> classType) {");
    sourceWriter.println("if(!instmap.containsKey(classType)){");
    boolean first = true;

    ArrayList<Class<? extends Paintable>> lazyLoadedWidgets = new ArrayList<Class<? extends Paintable>>();

    HashSet<Class<? extends com.vaadin.terminal.gwt.client.Paintable>> widgetsWithInstantiator = new HashSet<Class<? extends com.vaadin.terminal.gwt.client.Paintable>>();

    for (Class<? extends Paintable> class1 : paintablesHavingWidgetAnnotation) {
        ClientWidget annotation = class1.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> clientClass = annotation.value();
        if (widgetsWithInstantiator.contains(clientClass)) {
            continue;
        }// w  w  w.ja v a 2  s.c  o  m
        if (clientClass == VView.class) {
            // VView's are not instantiated by widgetset
            continue;
        }
        if (!first) {
            sourceWriter.print(" else ");
        } else {
            first = false;
        }
        sourceWriter.print("if( classType == " + clientClass.getName() + ".class) {");

        String instantiator = "new WidgetInstantiator() {\n public Paintable get() {\n return GWT.create("
                + clientClass.getName() + ".class );\n}\n}\n";

        LoadStyle loadStyle = getLoadStyle(class1);

        if (loadStyle != LoadStyle.EAGER) {
            sourceWriter.print("ApplicationConfiguration.startWidgetLoading();\n" + "GWT.runAsync( \n"
                    + "new WidgetLoader() { void addInstantiator() {instmap.put(" + clientClass.getName()
                    + ".class," + instantiator + ");}});\n");
            lazyLoadedWidgets.add(class1);

            if (loadStyle == LoadStyle.DEFERRED) {
                deferredWidgets.add(class1);
            }

        } else {
            // widget implementation in initially loaded js script
            sourceWriter.print("instmap.put(");
            sourceWriter.print(clientClass.getName());
            sourceWriter.print(".class, ");
            sourceWriter.print(instantiator);
            sourceWriter.print(");");
        }
        sourceWriter.print("}");
        widgetsWithInstantiator.add(clientClass);
    }

    sourceWriter.println("}");

    sourceWriter.println("}");

    sourceWriter.println("public Class<? extends Paintable>[] getDeferredLoadedWidgets() {");

    sourceWriter.println("return new Class[] {");
    first = true;
    for (Class<?> class2 : deferredWidgets) {
        if (!first) {
            sourceWriter.println(",");
        }
        first = false;
        ClientWidget annotation = class2.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> value = annotation.value();
        sourceWriter.print(value.getName() + ".class");
    }

    sourceWriter.println("};");
    sourceWriter.println("}");

    // in constructor add a "thread" that lazyly loads lazy loaded widgets
    // if communication to server idles

    // TODO an array of lazy loaded widgets

    // TODO an index of last ensured widget in array

    sourceWriter.println("public Paintable instantiate(Class<? extends Paintable> classType) {");
    sourceWriter.indent();
    sourceWriter.println("Paintable p = super.instantiate(classType); if(p!= null) return p;");
    sourceWriter.println("return instmap.get(classType).get();");

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

}

From source file:com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator.java

License:Open Source License

/**
 * //from   w w  w . ja va 2s. com
 * @param sourceWriter
 *            Source writer to output source code
 * @param paintablesHavingWidgetAnnotation
 */
private void generateImplementationDetector(SourceWriter sourceWriter,
        Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation) {
    sourceWriter.println("public Class<? extends Paintable> "
            + "getImplementationByServerSideClassName(String fullyQualifiedName) {");
    sourceWriter.indent();
    sourceWriter.println("fullyQualifiedName = fullyQualifiedName.intern();");

    for (Class<? extends Paintable> class1 : paintablesHavingWidgetAnnotation) {
        ClientWidget annotation = class1.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> clientClass = annotation.value();
        sourceWriter.print("if ( fullyQualifiedName == \"");
        sourceWriter.print(class1.getName());
        sourceWriter.print("\" ) { ensureInstantiator(" + clientClass.getName() + ".class); return ");
        sourceWriter.print(clientClass.getName());
        sourceWriter.println(".class;}");
        sourceWriter.print("else ");
    }
    sourceWriter.println("return com.vaadin.terminal.gwt.client.ui.VUnknownComponent.class;");
    sourceWriter.outdent();
    sourceWriter.println("}");

}

From source file:cz.muni.ucn.opsi.wui.gwt.rebind.beanModel.BeanModelGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    oracle = context.getTypeOracle();//w  ww .  j  av  a 2  s  . c o  m
    beanModelMarkerType = oracle.findType(BeanModelMarker.class.getName());
    beanModelTagType = oracle.findType(BeanModelTag.class.getName());

    try {
        // final all beans and bean markers
        beans = new ArrayList<JClassType>();
        JClassType[] types = oracle.getTypes();
        for (JClassType type : types) {
            if (isBeanMarker(type)) {
                beans.add(getMarkerBean(type));
            } else if (isBean(type)) {
                beans.add(type);
            }
        }

        final String genPackageName = BeanModelLookup.class.getPackage().getName();
        final String genClassName = "BeanModelLookupImpl";

        ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName,
                genClassName);
        composer.setSuperclass(BeanModelLookup.class.getCanonicalName());
        composer.addImport(BeanModelFactory.class.getName());
        composer.addImport(Map.class.getName());
        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(String n) {");
            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_NAME.equals(n)) {");
                sw.indentln("m" + i + "();");

                sb.append("private void m" + i + "() {\n");
                sb.append(
                        "  m.put(" + bean.getQualifiedSourceName() + ".CLASS_NAME, 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) {
        logger.log(TreeLogger.ERROR, "Class " + typeName + " not found.", e);
        throw new UnableToCompleteException();
    }

}

From source file:de.csenk.gwt.ws.rebind.filter.serialization.GWTSerializerGenerator.java

License:Open Source License

/**
 * Generate the proxy constructor and delegate to the superclass constructor
 * using the default address for the//from   w  w w. j ava  2  s  .  c o m
 * {@link com.google.gwt.user.client.rpc.RemoteService RemoteService}.
 */
private void generateContructor(SourceWriter srcWriter, JClassType serializerInterface,
        Map<JType, String> typeStrings) {
    srcWriter.println("public " + getImplementationSimpleName(serializerInterface) + "() {");
    srcWriter.indent();
    srcWriter.println("super(GWT.getModuleBaseURL(),");
    srcWriter.indent();
    srcWriter.println("SERIALIZATION_POLICY, ");
    srcWriter.println("SERIALIZER);");
    srcWriter.outdent();

    srcWriter.println();
    for (Entry<JType, String> typeEntry : typeStrings.entrySet()) {
        srcWriter.print("typeStringMap.put(\"");
        srcWriter.print(typeEntry.getKey().getQualifiedSourceName() + "\", \"");
        srcWriter.print(typeEntry.getValue());
        srcWriter.println("\");");
    }

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

From source file:de.knightsoftnet.validators.rebind.BeanHelperCache.java

License:Apache License

/**
 * Write an Empty Interface implementing
 * {@link de.knightsoftnet.validators.client.impl.GwtSpecificValidator} with Generic parameter of
 * the bean type./*from   w w w.  j  a v a 2 s.com*/
 */
private void writeInterface(final GeneratorContext context, final TreeLogger logger, final BeanHelper bean) {
    final PrintWriter pw = context.tryCreate(logger, bean.getPackage(), bean.getValidatorName());
    if (pw != null) {
        final TreeLogger interfaceLogger = logger.branch(TreeLogger.TRACE,
                "Creating the interface for " + bean.getFullyQualifiedValidatorName());

        final ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(bean.getPackage(),
                bean.getValidatorName());
        factory.addImplementedInterface(
                GwtSpecificValidator.class.getCanonicalName() + " <" + bean.getTypeCanonicalName() + ">");
        factory.addImport(GWT.class.getCanonicalName());
        factory.makeInterface();
        final SourceWriter sw = factory.createSourceWriter(context, pw);

        // static MyValidator INSTANCE = GWT.create(MyValidator.class);
        sw.print("static ");
        sw.print(bean.getValidatorName());
        sw.print(" INSTANCE = GWT.create(");
        sw.print(bean.getValidatorName());
        sw.println(".class);");

        sw.commit(interfaceLogger);
        pw.close();
    }
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

License:Apache License

protected void writeUnsafeNativeLongIfNeeded(final SourceWriter sw, final JType jtype) {
    if (JPrimitiveType.LONG.equals(jtype)) {
        // @com.google.gwt.core.client.UnsafeNativeLong
        sw.print("@");
        sw.println(UnsafeNativeLong.class.getCanonicalName());
    }/*  ww  w .  java 2 s.  c o  m*/
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

License:Apache License

private void writeBeanDescriptor(final SourceWriter sw) {
    final BeanDescriptor beanDescriptor = this.beanHelper.getBeanDescriptor();

    // private final GwtBeanDescriptor <MyBean> beanDescriptor =
    sw.print("private final ");
    sw.print(GwtBeanDescriptor.class.getCanonicalName());
    sw.print("<" + this.beanHelper.getTypeCanonicalName() + ">");
    sw.println(" beanDescriptor = ");
    sw.indent();//from  w w w  .  j  ava 2s  .co  m
    sw.indent();

    // GwtBeanDescriptorImpl.builder(Order.class)
    sw.print(GwtBeanDescriptorImpl.class.getCanonicalName());
    sw.println(".builder(" + this.beanHelper.getTypeCanonicalName() + ".class)");
    sw.indent();
    sw.indent();

    // .setConstrained(true)
    sw.println(".setConstrained(" + beanDescriptor.isBeanConstrained() + ")");

    int count = 0;
    for (final ConstraintDescriptor<?> constraint : beanDescriptor.getConstraintDescriptors()) {
        if (this.areConstraintDescriptorGroupsValid(constraint)) {
            // .add(c0)
            sw.println(".add(" + this.constraintDescriptorVar("this", count) + ")");
            count++;
        }
    }

    // .put("myProperty", myProperty_pd)
    for (final PropertyDescriptor p : beanDescriptor.getConstrainedProperties()) {
        sw.print(".put(\"");
        sw.print(p.getPropertyName());
        sw.print("\", ");
        sw.print(p.getPropertyName());
        sw.println("_pd)");
    }

    // .setBeanMetadata(beanMetadata)
    sw.println(".setBeanMetadata(beanMetadata)");

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

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

License:Apache License

private void writeBeanMetadata(final SourceWriter sw) throws UnableToCompleteException {
    // private final BeanMetadata beanMetadata =
    sw.println("private final BeanMetadata beanMetadata =");
    sw.indent();/*w  w  w. j  av  a2  s. c om*/
    sw.indent();

    // new BeanMetadata(
    sw.println("new " + BeanMetadata.class.getSimpleName() + "(");
    sw.indent();
    sw.indent();

    // <<bean class>>, <<default group seq class 1>>, <<default group seq class 2>>, ...
    final Class<?> beanClazz = this.beanHelper.getClazz();
    sw.print(asLiteral(beanClazz));
    final GroupSequence groupSeqAnnotation = beanClazz.getAnnotation(GroupSequence.class);
    final List<Class<?>> groupSequence = new ArrayList<>();
    if (groupSeqAnnotation == null) {
        groupSequence.add(beanClazz);
    } else {
        groupSequence.addAll(Arrays.asList(groupSeqAnnotation.value()));
    }
    boolean groupSequenceContainsDefault = false;
    for (final Class<?> group : groupSequence) {
        sw.println(",");
        if (group.getName().equals(beanClazz.getName())) {
            sw.print(asLiteral(Default.class));
            groupSequenceContainsDefault = true;
        } else if (group.getName().equals(Default.class.getName())) {
            throw error(this.logger, "'Default.class' cannot appear in default group sequence list.");
        } else {
            sw.print(asLiteral(group));
        }
    }
    if (!groupSequenceContainsDefault) {
        throw error(this.logger,
                beanClazz.getName() + " must be part of the redefined default group " + "sequence.");
    }

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

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

License:Apache License

private void writeClassLevelConstraintsValidation(final SourceWriter sw, final String groupsVarName)
        throws UnableToCompleteException {
    // all class level constraints
    int count = 0;
    final Class<?> clazz = this.beanHelper.getClazz();
    for (final ConstraintDescriptor<?> constraint : this.beanHelper.getBeanDescriptor()
            .getConstraintDescriptors()) {
        if (this.areConstraintDescriptorGroupsValid(constraint)) {
            if (this.hasMatchingAnnotation(constraint)) {

                if (!constraint.getConstraintValidatorClasses().isEmpty()) { // NOPMD
                    final Class<? extends ConstraintValidator<? extends Annotation, ?>> validatorClass = getValidatorForType(
                            constraint, clazz);

                    // validate(context, violations, null, object,
                    sw.print("validate(context, violations, null, object, ");

                    // new MyValidtor(),
                    sw.print("new ");
                    sw.print(validatorClass.getCanonicalName());
                    sw.print("(), "); // TODO(nchalko) use ConstraintValidatorFactory

                    // this.aConstraintDescriptor, groups);
                    sw.print(this.constraintDescriptorVar("this", count));
                    sw.print(", ");
                    sw.print(groupsVarName);
                    sw.println(");");
                } else if (constraint.getComposingConstraints().isEmpty()) {
                    // TODO(nchalko) What does the spec say to do here.
                    this.logger.log(TreeLogger.WARN,
                            "No ConstraintValidator of " + constraint + " for type " + clazz);
                }// w w  w.ja v a  2  s  .c  o  m
                // TODO(nchalko) handle constraint.isReportAsSingleViolation() and
                // hasComposingConstraints
            }
            count++;
        }
    }
}

From source file:de.knightsoftnet.validators.rebind.GwtSpecificValidatorCreator.java

License:Apache License

private void writeConstraintDescriptor(final SourceWriter sw,
        final ConstraintDescriptor<? extends Annotation> constraint, final ElementType elementType,
        final ConstraintOrigin origin, final String constraintDescripotorVar) throws UnableToCompleteException {
    final Class<? extends Annotation> annotationType = constraint.getAnnotation().annotationType();

    // First list all composing constraints
    int count = 0;
    for (final ConstraintDescriptor<?> composingConstraint : constraint.getComposingConstraints()) {
        this.writeConstraintDescriptor(sw, composingConstraint, elementType, origin,
                constraintDescripotorVar + "_" + count++);
    }//from ww  w . j  a  v  a  2 s.c  o m

    // private final ConstraintDescriptorImpl<MyAnnotation> constraintDescriptor = ;
    sw.print("private final ");
    sw.print(ConstraintDescriptorImpl.class.getCanonicalName());
    sw.print("<");

    sw.print(annotationType.getCanonicalName());
    sw.print(">");

    sw.println(" " + constraintDescripotorVar + "  = ");
    sw.indent();
    sw.indent();

    // ConstraintDescriptorImpl.<MyConstraint> builder()
    sw.print(ConstraintDescriptorImpl.class.getCanonicalName());
    sw.print(".<");

    sw.print(annotationType.getCanonicalName());
    sw.println("> builder()");
    sw.indent();
    sw.indent();

    // .setAnnotation(new MyAnnotation )
    sw.println(".setAnnotation( ");
    sw.indent();
    sw.indent();
    this.writeNewAnnotation(sw, constraint);
    sw.println(")");
    sw.outdent();
    sw.outdent();

    // .setAttributes(builder()
    sw.println(".setAttributes(attributeBuilder()");
    sw.indent();

    for (final Map.Entry<String, Object> entry : constraint.getAttributes().entrySet()) {
        // .put(key, value)
        sw.print(".put(");
        final String key = entry.getKey();
        sw.print(asLiteral(key));
        sw.print(", ");
        Object value = entry.getValue();
        // Add the Default group if it is not already present
        if ("groups".equals(key) && value instanceof Class[] && ((Class[]) value).length == 0) {
            value = new Class[] { Default.class };
        }
        sw.print(asLiteral(value));
        sw.println(")");
    }

    // .build())
    sw.println(".build())");
    sw.outdent();

    // .setConstraintValidatorClasses(classes )
    sw.print(".setConstraintValidatorClasses(");
    sw.print(asLiteral(this.asArray(constraint.getConstraintValidatorClasses(), new Class[0])));
    sw.println(")");

    final int ccCount = constraint.getComposingConstraints().size();
    for (int i = 0; i < ccCount; i++) {
        // .addComposingConstraint(cX_X)
        sw.print(".addComposingConstraint(");
        sw.print(constraintDescripotorVar + "_" + i);
        sw.println(")");
    }

    // .getGroups(groups)
    sw.print(".setGroups(");
    final Set<Class<?>> groups = constraint.getGroups();
    sw.print(asLiteral(this.asArray(groups, new Class<?>[0])));
    sw.println(")");

    // .setPayload(payload)
    sw.print(".setPayload(");
    final Set<Class<? extends Payload>> payload = constraint.getPayload();
    sw.print(asLiteral(this.asArray(payload, new Class[0])));
    sw.println(")");

    // .setReportAsSingleViolation(boolean )
    sw.print(".setReportAsSingleViolation(");
    sw.print(Boolean.toString(constraint.isReportAsSingleViolation()));
    sw.println(")");

    // .setElementType(elementType)
    sw.print(".setElementType(");
    sw.print(asLiteral(elementType));
    sw.println(")");

    // .setDefinedOn(origin)
    sw.print(".setDefinedOn(");
    sw.print(asLiteral(origin));
    sw.println(")");

    // .build();
    sw.println(".build();");
    sw.outdent();
    sw.outdent();

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