Example usage for com.google.gwt.core.ext Generator escape

List of usage examples for com.google.gwt.core.ext Generator escape

Introduction

In this page you can find the example usage for com.google.gwt.core.ext Generator escape.

Prototype

public static String escape(String unescaped) 

Source Link

Document

Escapes string content to be a valid string literal.

Usage

From source file:cc.alcina.framework.entity.gen.SimpleCssResourceGenerator.java

License:Apache License

@Override
public String createAssignment(TreeLogger logger, ResourceContext context, JMethod method)
        throws UnableToCompleteException {
    try {//from  w  w  w .  j  a v  a  2s.  c  o  m
        ConfigurationProperty cp = context.getGeneratorContext().getPropertyOracle()
                .getConfigurationProperty(IGNORE_DATA_URLS);
        logMissingUrlResources = !Boolean.valueOf(cp.getValues().get(0));
    } catch (BadPropertyValueException e1) {
        e1.printStackTrace();
    }
    URL[] resources = ResourceGeneratorUtil.findResources(logger, context, method);
    if (resources.length != 1) {
        logger.log(TreeLogger.ERROR, "Exactly one resource must be specified", null);
        throw new UnableToCompleteException();
    }
    URL resource = resources[0];
    SourceWriter sw = new StringSourceWriter();
    // Write the expression to create the subtype.
    sw.println("new " + SimpleCssResource.class.getName() + "() {");
    sw.indent();
    if (!AbstractResourceGenerator.STRIP_COMMENTS) {
        // Convenience when examining the generated code.
        sw.println("// " + resource.toExternalForm());
    }
    sw.println("public String getText() {");
    sw.indent();
    String toWrite = Util.readURLAsString(resource);
    if (context.supportsDataUrls()) {
        try {
            toWrite = replaceWithDataUrls(context, toWrite);
        } catch (Exception e) {
            logger.log(Type.ERROR, "css data url gen", e);
            throw new UnableToCompleteException();
        }
    }
    if (toWrite.length() > MAX_STRING_CHUNK) {
        writeLongString(sw, toWrite);
    } else {
        sw.println("return \"" + Generator.escape(toWrite) + "\";");
    }
    sw.outdent();
    sw.println("}");
    sw.println("public String getName() {");
    sw.indent();
    sw.println("return \"" + method.getName() + "\";");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    return sw.toString();
}

From source file:cc.alcina.framework.entity.gen.SimpleCssResourceGenerator.java

License:Apache License

/**
 * A single constant that is too long will crash the compiler with an out of
 * memory error. Break up the constant and generate code that appends using
 * a buffer./*from   w w  w  . j a  v  a  2  s.  co m*/
 */
private void writeLongString(SourceWriter sw, String toWrite) {
    sw.println("StringBuilder builder = new StringBuilder();");
    int offset = 0;
    int length = toWrite.length();
    while (offset < length - 1) {
        int subLength = Math.min(MAX_STRING_CHUNK, length - offset);
        sw.print("builder.append(\"");
        sw.print(Generator.escape(toWrite.substring(offset, offset + subLength)));
        sw.println("\");");
        offset += subLength;
    }
    sw.println("return builder.toString();");
}

From source file:com.chrome.gwt.linker.ComponentGenerator.java

License:Apache License

private static void emitIcons(List<String> iconNames, List<String> iconPaths, SourceWriter sw) {
    // Fill in the methods for kicking back the BrowserAction Icons.
    for (int i = 0; i < iconNames.size(); i++) {
        String iconName = Generator.escape(iconNames.get(i));
        String iconField = Generator.escape(iconName) + "_field";
        sw.println("private " + ICON_USER_TYPE + " " + iconField + " = null;");
        sw.println("public " + ICON_USER_TYPE + " " + iconName + "() {");
        sw.println("  if (" + iconField + " == null) {");
        sw.println("    " + iconField + " = new " + ICON_USER_TYPE + "(" + i + ", \""
                + Generator.escape(iconPaths.get(i)) + "\");");
        sw.println("  }");
        sw.println("  return " + iconField + ";");
        sw.println("}");
    }//  www  .j av  a 2s  .c  om
}

From source file:com.google.code.gwt.database.rebind.SqlProxyCreator.java

License:Apache License

/**
 * Generates the {@link BaseDataService#openDatabase()} method
 *///from ww w  . j av a2s  .c o  m
private void generateProxyOpenDatabaseMethod() {
    Connection con = dataService.getAnnotation(Connection.class);
    sw.beginJavaDocComment();
    sw.print("Opens the '" + con.name() + "' Database version " + con.version());
    sw.endJavaDocComment();
    sw.println("public final " + genUtils.getClassName(Database.class) + " openDatabase() throws "
            + genUtils.getClassName(DatabaseException.class) + " {");
    sw.indentln("return " + genUtils.getClassName(Database.class) + ".openDatabase(\""
            + Generator.escape(con.name()) + "\", \"" + Generator.escape(con.version()) + "\", \""
            + Generator.escape(con.description()) + "\", " + con.maxsize() + ");");
    sw.println("}");
}

From source file:com.google.code.gwt.database.rebind.SqlProxyCreator.java

License:Apache License

/**
 * Generates the {@link BaseDataService#getDatabaseDetails()} method.
 *//*from w  w w. j av  a 2 s .com*/
private void generateProxyGetDatabaseDetailsMethod() {
    Connection con = dataService.getAnnotation(Connection.class);
    String toReturn = "'" + Generator.escape(con.name()) + "' version " + Generator.escape(con.version());
    sw.beginJavaDocComment();
    sw.print("Returns the <code>" + toReturn + "</code> string.");
    sw.endJavaDocComment();
    sw.println("public final String getDatabaseDetails() {");
    sw.indentln("return \"" + toReturn + "\";");
    sw.println("}");
}

From source file:com.google.web.bindery.requestfactory.gwt.rebind.RequestFactoryGenerator.java

License:Apache License

private void writeContextImplementations() {
    for (ContextMethod method : model.getMethods()) {
        PrintWriter pw = context.tryCreate(logger, method.getPackageName(), method.getSimpleSourceName());
        if (pw == null) {
            // Already generated
            continue;
        }/*www.j a  va 2  s . c  o m*/

        ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(method.getPackageName(),
                method.getSimpleSourceName());
        factory.setSuperclass(AbstractRequestContext.class.getCanonicalName());
        factory.addImplementedInterface(method.getImplementedInterfaceQualifiedSourceName());
        SourceWriter sw = factory.createSourceWriter(context, pw);

        // Constructor that accepts the parent RequestFactory
        sw.println("public %s(%s requestFactory) {super(requestFactory, %s.%s);}", method.getSimpleSourceName(),
                AbstractRequestFactory.class.getCanonicalName(), Dialect.class.getCanonicalName(),
                method.getDialect().name());

        Set<EntityProxyModel> models = findReferencedEntities(method);
        Set<JEnumType> extraEnumTypes = findExtraEnums(method);
        writeAutoBeanFactory(sw, models, extraEnumTypes);

        // Write each Request method
        for (RequestMethod request : method.getRequestMethods()) {
            JMethod jmethod = request.getDeclarationMethod();
            String operation = request.getOperation();

            // foo, bar, baz
            StringBuilder parameterArray = new StringBuilder();
            // final Foo foo, final Bar bar, final Baz baz
            StringBuilder parameterDeclaration = new StringBuilder();
            // <P extends Blah>
            StringBuilder typeParameterDeclaration = new StringBuilder();

            if (request.isInstance()) {
                // Leave a spot for the using() method to fill in later
                parameterArray.append(",null");
            }
            for (JTypeParameter param : jmethod.getTypeParameters()) {
                typeParameterDeclaration.append(",").append(param.getQualifiedSourceName());
            }
            for (JParameter param : jmethod.getParameters()) {
                parameterArray.append(",").append(param.getName());
                parameterDeclaration.append(",final ")
                        .append(param.getType().getParameterizedQualifiedSourceName()).append(" ")
                        .append(param.getName());
            }
            if (parameterArray.length() > 0) {
                parameterArray.deleteCharAt(0);
            }
            if (parameterDeclaration.length() > 0) {
                parameterDeclaration.deleteCharAt(0);
            }
            if (typeParameterDeclaration.length() > 0) {
                typeParameterDeclaration.deleteCharAt(0).insert(0, "<").append(">");
            }

            // public Request<Foo> doFoo(final Foo foo) {
            sw.println("public %s %s %s(%s) {", typeParameterDeclaration,
                    jmethod.getReturnType().getParameterizedQualifiedSourceName(), jmethod.getName(),
                    parameterDeclaration);
            sw.indent();
            // The implements clause covers InstanceRequest
            // class X extends AbstractRequest<Return> implements Request<Return> {
            sw.println("class X extends %s<%s> implements %s {", AbstractRequest.class.getCanonicalName(),
                    request.getDataType().getParameterizedQualifiedSourceName(),
                    jmethod.getReturnType().getParameterizedQualifiedSourceName());
            sw.indent();

            // public X() { super(FooRequestContext.this); }
            sw.println("public X() { super(%s.this);}", method.getSimpleSourceName());

            // This could also be gotten rid of by having only Request /
            // InstanceRequest
            sw.println("@Override public X with(String... paths) {super.with(paths); return this;}");

            // makeRequestData()
            sw.println("@Override protected %s makeRequestData() {", RequestData.class.getCanonicalName());
            String elementType = request.isCollectionType()
                    ? request.getCollectionElementType().getQualifiedSourceName() + ".class"
                    : "null";
            String returnTypeBaseQualifiedName = ModelUtils.ensureBaseType(request.getDataType())
                    .getQualifiedSourceName();
            // return new RequestData("ABC123", {parameters}, propertyRefs,
            // List.class, FooProxy.class);
            sw.indentln("return new %s(\"%s\", new Object[] {%s}, propertyRefs, %s.class, %s);",
                    RequestData.class.getCanonicalName(), operation, parameterArray,
                    returnTypeBaseQualifiedName, elementType);
            sw.println("}");

            /*
             * Only support extra properties in JSON-RPC payloads. Could add this to
             * standard requests to provide out-of-band data.
             */
            if (method.getDialect().equals(Dialect.JSON_RPC)) {
                for (JMethod setter : request.getExtraSetters()) {
                    PropertyName propertyNameAnnotation = setter.getAnnotation(PropertyName.class);
                    String propertyName = propertyNameAnnotation == null ? JBeanMethod.SET.inferName(setter)
                            : propertyNameAnnotation.value();
                    String maybeReturn = JBeanMethod.SET_BUILDER.matches(setter) ? "return this;" : "";
                    sw.println("%s { getRequestData().setNamedParameter(\"%s\", %s); %s}",
                            setter.getReadableDeclaration(false, false, false, false, true), propertyName,
                            setter.getParameters()[0].getName(), maybeReturn);
                }
            }

            // end class X{}
            sw.outdent();
            sw.println("}");

            // Instantiate, enqueue, and return
            sw.println("X x = new X();");

            if (request.getApiVersion() != null) {
                sw.println("x.getRequestData().setApiVersion(\"%s\");",
                        Generator.escape(request.getApiVersion()));
            }

            // JSON-RPC payloads send their parameters in a by-name fashion
            if (method.getDialect().equals(Dialect.JSON_RPC)) {
                for (JParameter param : jmethod.getParameters()) {
                    PropertyName annotation = param.getAnnotation(PropertyName.class);
                    String propertyName = annotation == null ? param.getName() : annotation.value();
                    boolean isContent = param.isAnnotationPresent(JsonRpcContent.class);
                    if (isContent) {
                        sw.println("x.getRequestData().setRequestContent(%s);", param.getName());
                    } else {
                        sw.println("x.getRequestData().setNamedParameter(\"%s\", %s);", propertyName,
                                param.getName());
                    }
                }
            }

            // See comment in AbstractRequest.using(EntityProxy)
            if (!request.isInstance()) {
                sw.println("addInvocation(x);");
            }
            sw.println("return x;");
            sw.outdent();
            sw.println("}");
        }

        sw.commit(logger);
    }
}

From source file:com.jawspeak.gwt.verysimpletemplate.rebind.VerySimpleGwtTemplateGenerator.java

License:Apache License

private void generateMethodsForEachHtmlTemplate(TreeLogger logger, SourceWriter sourceWriter)
        throws SecurityException, ClassNotFoundException, IOException, CouldNotParseTemplateException {
    String folderPrefix = packageName.replace(".", "/");
    for (Method method : Class.forName(typeName).getMethods()) {
        String methodName = method.getName();
        if (!methodName.startsWith("get")) {
            break;
        }/*from w  ww  .  ja  v  a  2 s . co  m*/
        String path = folderPrefix + "/" + methodName.substring(3) + ".html";
        String template = Utility.getFileFromClassPath(path);
        String parameters = getParameters(method);
        sourceWriter.println("public VerySimpleGwtTemplate " + methodName + "(" + parameters + ") {");
        sourceWriter.indent();
        sourceWriter.println("VerySimpleGwtTemplate template = new VerySimpleGwtTemplate(\""
                + Generator.escape(template) + "\");");
        for (Map.Entry<String, String> entry : getTemplateReplaceables(template).entrySet()) {
            // TODO(jwolter): look for the getter method, and throw an exception if it doesn't exist
            // TODO(jwolter): look at the getter's return type, and do nice null checking then "" + or call toString()
            // TODO(jwolter): allow an arbitrary way to "pipe" subsequent options to the setter, so that you can for a date i.e. call a date formatter on it.
            // TODO(jwolter): basically look at the features of FreeMarker, and see how to integrate the best ones in here. Or adopt to FreemarkerGWT.

            // as for now, we simply turn each value into a String by prepending a "" + to the value.
            // also for the time being, remember you can have a $${token} that will not get replaced, so you can set it manually. So,
            // you should only have ${token}'s that you are comfortable getting them set literally as Strings.
            sourceWriter
                    .println("template.set(\"" + entry.getKey() + "\", " + "\"\" + " + entry.getValue() + ");");
        }
        sourceWriter.println("return template;");
        sourceWriter.outdent();
        sourceWriter.println("}");
    }
    sourceWriter.outdent();
}

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

License:Apache License

/**
 * Returns the literal value of an object that is suitable for inclusion in Java Source code.
 *
 * <p>/*from  w  w  w  . j a v  a  2  s .co  m*/
 * Supports all types that {@link Annotation} value can have.
 * </p>
 *
 *
 * @throws IllegalArgumentException if the type of the object does not have a java literal form.
 */
public static String asLiteral(final Object value) throws IllegalArgumentException {
    final Class<?> clazz = value.getClass();

    if (clazz.isArray()) {
        final StringBuilder sb = new StringBuilder();
        final Object[] array = (Object[]) value;

        sb.append("new " + clazz.getComponentType().getCanonicalName() + "[] {");
        boolean first = true;
        for (final Object object : array) {
            if (first) {
                first = false;
            } else {
                sb.append(',');
            }
            sb.append(asLiteral(object));
        }
        sb.append('}');
        return sb.toString();
    }

    if (value instanceof Boolean) {
        return JBooleanLiteral.get(((Boolean) value).booleanValue()).toSource();
    } else if (value instanceof Byte) {
        return JIntLiteral.get(((Byte) value).byteValue()).toSource();
    } else if (value instanceof Character) {
        return JCharLiteral.get(((Character) value).charValue()).toSource();
    } else if (value instanceof Class<?>) {
        return ((Class<?>) (Class<?>) value).getCanonicalName() + ".class";
    } else if (value instanceof Double) {
        return JDoubleLiteral.get(((Double) value).doubleValue()).toSource();
    } else if (value instanceof Enum) {
        return value.getClass().getCanonicalName() + "." + ((Enum<?>) value).name();
    } else if (value instanceof Float) {
        return JFloatLiteral.get(((Float) value).floatValue()).toSource();
    } else if (value instanceof Integer) {
        return JIntLiteral.get(((Integer) value).intValue()).toSource();
    } else if (value instanceof Long) {
        return JLongLiteral.get(((Long) value).longValue()).toSource();
    } else if (value instanceof String) {
        return '"' + Generator.escape((String) value) + '"';
    } else {
        // TODO(nchalko) handle Annotation types
        throw new IllegalArgumentException(value.getClass() + " can not be represented as a Java Literal.");
    }
}

From source file:geogebra.vectomatic.SVGResourceGenerator.java

License:Open Source License

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

    // Extract the SVG name from the @Source annotation
    URL[] resources = ResourceGeneratorUtil.findResources(logger, context, method);
    if (resources.length != 1) {
        logger.log(TreeLogger.ERROR, "Exactly one resource must be specified", null);
        throw new UnableToCompleteException();
    }// www .  jav  a 2 s . c o m
    URL resource = resources[0];

    // The SVGResource is implemented as an anonymous inner class
    // xxx = new SVGResource() {
    // public OMSVGSVGElement getSvg() {
    // return OMSVGParser.parse("...");
    // }
    // };
    String toWrite = Util.readURLAsString(resource);
    /*
     * if (getValidated(method)) { SVGValidator.validate(toWrite,
     * resource.toExternalForm(), logger, null); }
     */

    SourceWriter sw = new StringSourceWriter();
    sw.println("new " + SVGResource.class.getName() + "() {");
    sw.indent();
    sw.println("private String svg=\"" + Generator.escape(toWrite) + "\";");

    // Convenience when examining the generated code.
    sw.println("// " + resource.toExternalForm());

    sw.println("@Override");
    sw.println("public String getName() {");
    sw.indent();
    sw.println("return \"" + method.getName() + "\";");
    sw.outdent();
    sw.println("}");

    sw.println("@Override");
    sw.println("public String getUrl() {");
    sw.indent();
    sw.println("return \"data:image/svg+xml;base64,\" + " + Browser.class.getName() + ".base64encode(svg);");
    sw.outdent();
    sw.println("}");

    sw.println("@Override");
    sw.println("public " + SafeUri.class.getName() + " getSafeUri() {");
    sw.indent();
    sw.println("return " + UriUtils.class.getName() + ".fromSafeConstant(\"data:image/svg+xml;base64,\" + "
            + Browser.class.getName() + ".base64encode(svg));");
    sw.outdent();
    sw.println("}");

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

    return sw.toString();
}

From source file:gwt.g3d.resources.ShaderResourceGenerator.java

License:Apache License

@Override
public String createAssignment(TreeLogger logger, ResourceContext context, JMethod method)
        throws UnableToCompleteException {
    URL[] resources = ResourceGeneratorUtil.findResources(logger, context, method);

    if (resources.length != 2) {
        logger.log(TreeLogger.ERROR, "Exactly two resources must be specified", null);
        throw new UnableToCompleteException();
    }//www  .  j a  v  a2s . c  om

    SourceWriter sw = new StringSourceWriter();
    sw.println("new " + ShaderResource.class.getName() + "() {");
    sw.indent();

    sw.println("public String getVertexShaderSource() {");
    sw.indent();
    String vertexSource = Generator.escape(Util.readURLAsString(resources[0]));
    sw.println("return \"" + vertexSource + "\";");
    sw.outdent();
    sw.println("}");

    sw.println("public String getFragmentShaderSource() {");
    sw.indent();
    String fragmentSource = Generator.escape(Util.readURLAsString(resources[1]));
    sw.println("return \"" + fragmentSource + "\";");
    sw.outdent();
    sw.println("}");

    sw.println(String.format("public %s createShader(%s gl) throws %s {", AbstractShader.class.getName(),
            GL2.class.getName(), ShaderException.class.getName()));
    sw.indent();
    sw.println(String.format("%s shader = %s;", AbstractShader.class.getName(),
            createAbstractShader(logger, context, method)));
    sw.println("shader.init(gl);");
    sw.println("return shader;");
    sw.outdent();
    sw.println("}");

    sw.println("public String getName() {");
    sw.indent();
    sw.println("return \"" + method.getName() + "\";");
    sw.outdent();
    sw.println("}");

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

    return sw.toString();
}