List of usage examples for com.google.gwt.core.ext TreeLogger isLoggable
public abstract boolean isLoggable(TreeLogger.Type type);
From source file:com.google.code.gwt.appcache.rebind.ApplicationCacheNetworkSectionGenerator.java
License:Apache License
@Override public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { // Invoke the regular RPC generator: String result = rebindTypeByInheritedModule("com.google.gwt.user.RemoteService", logger, context, typeName); TypeOracle typeOracle = context.getTypeOracle(); JClassType remoteService = typeOracle.findType(typeName); RemoteServiceRelativePath moduleRelativeUrl = remoteService.getAnnotation(RemoteServiceRelativePath.class); if (moduleRelativeUrl != null) { // add URL to network section: if (logger.isLoggable(Type.INFO)) { logger.log(Type.DEBUG, "Found URL for NETWORK: section in cache-manifest: '" + moduleRelativeUrl.value() + "'"); }//from w w w .j a v a 2 s. c om NetworkSectionArtifact artifact = new NetworkSectionArtifact(IFrameAppCacheLinker.class, moduleRelativeUrl.value()); context.commitArtifact(logger, artifact); } return result; }
From source file:org.bonitasoft.tools.gwt.jetty.JettyLauncher.java
License:Open Source License
protected AbstractConnector getConnector(TreeLogger logger) { if (useSsl) { TreeLogger sslLogger = logger.branch(TreeLogger.INFO, "Listening for SSL connections"); if (sslLogger.isLoggable(TreeLogger.TRACE)) { sslLogger.log(TreeLogger.TRACE, "Using keystore " + keyStore); }// w w w.j a v a 2 s . com SslSocketConnector conn = new SslSocketConnector(); if (clientAuth != null) { switch (clientAuth) { case NONE: conn.setWantClientAuth(false); conn.setNeedClientAuth(false); break; case WANT: sslLogger.log(TreeLogger.TRACE, "Requesting client certificates"); conn.setWantClientAuth(true); conn.setNeedClientAuth(false); break; case REQUIRE: sslLogger.log(TreeLogger.TRACE, "Requiring client certificates"); conn.setWantClientAuth(true); conn.setNeedClientAuth(true); break; } } conn.setKeystore(keyStore); conn.setTruststore(keyStore); conn.setKeyPassword(keyStorePassword); conn.setTrustPassword(keyStorePassword); return conn; } return new SelectChannelConnector(); }
From source file:xapi.dev.generators.GwtDevInjectionGenerator.java
License:Open Source License
@Override public RebindResult generateIncrementally(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException { String simpleName = "JsInjector"; String generatedClassName = packageName + "." + simpleName; logger.log(Type.DEBUG, "Generating X_Inject platform"); // only ever do this extremely expensive operation (iterating all Types) once GwtInjectionMap gwtInjectionMap = getInjectionMap(logger, context); PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName); if (printWriter == null) { return new RebindResult(RebindMode.USE_EXISTING, generatedClassName); }//from w ww . j a v a2 s .c o m SourceBuilder<GwtInjectionMap> sb = new SourceBuilder<GwtInjectionMap>( "public class " + simpleName + " implements " + Injector.class.getName()) .setPayload(gwtInjectionMap).setPackage(packageName); sb.getImports().addImports("xapi.util.api.ReceivesValue", HashMap.class.getName(), Provider.class.getName(), GWT.class.getName()); //Let's disable this for now; we can write META-INF manually outside of gwt compile // for (Entry<Class<?>, JClassType> entry : gwtInjectionMap.getJavaSingletons()) { // Class<?> cls = entry.getKey(); // JClassType impl = entry.getValue(); // // write meta info for each class during gwt compile; // // necessary for gwt users who forego regular dev mode. // tryWriteMetaInf(logger, cls, impl, context); // } Set<Entry<Class<?>, JClassType>> gwtSingletons = gwtInjectionMap.getGwtSingletons(); for (Entry<Class<?>, JClassType> entry : gwtSingletons) { Class<?> cls = entry.getKey(); JClassType impl = entry.getValue(); // make sure our provider class is available ensureProviderClass(logger, cls.getPackage().getName(), cls.getSimpleName(), cls.getCanonicalName(), SourceUtil.toSourceName(impl.getQualifiedSourceName()), context); ensureAsyncInjected(logger, cls.getPackage().getName(), cls.getName(), impl.getQualifiedSourceName(), context); // ensureCallbackClass(logger, cls.getPackage().getName(),cls.getCanonicalName(), cls.getSimpleName(), impl // .getQualifiedSourceName(), context); } ClassBuffer cb = sb.getClassBuffer(); cb.createMethod("private static final void throwNotFound(boolean type, Class<?> cls)") .println("String typeName = type?\"Singleton\":\"Instance\";") //TODO use a debug level flag to use much smaller strings here... .println("throw new RuntimeException(\"JsInjector did not have a registered \"+" + "typeName+\" for \"+cls.getName()+\".\\n\"+") .println("\"Please ensure you have at least one class which implements or extends \"" + "+cls.getName()+\" and it is marked with either @\"+type+\"Default or @" + "\"+type+\"Override.\"+") .println("\"Also, be sure to check for invalidated units " + "that may have removed your injection target from compile.\");"); ; // Since gwt dev is the only user of this service, // we try to avoid jsni, and instead just use a hash map to provider instance cb.println("private final HashMap<Class<?>, Provider<?>> singletons;") .println("private final HashMap<Class<?>, Provider<?>> instances;").println() // We setup all known injection types in the constructor, // which will load all the classes eagerly. // The runtime hit is better than anomalies from using jsni and lazy loading .println("public " + simpleName + "() {").indent() .println("singletons = new HashMap<Class<?>, Provider<?>>();") .println("instances = new HashMap<Class<?>, Provider<?>>();"); for (Entry<Class<?>, JClassType> entry : gwtSingletons) { Class<?> cls = entry.getKey(); cb.println("setSingletonFactory(" + cls.getCanonicalName() + ".class, ") .indentln(cls.getPackage().getName() + "." + InjectionUtils.generatedProviderName(cls.getSimpleName()) + ".theProvider);"); } for (Entry<Class<?>, JClassType> entry : gwtInjectionMap.getGwtInstances()) { cb.println("setInstanceFactory(" + entry.getKey().getCanonicalName() + ".class, ").indent() .println("new Provider() {").indent().println("public Object get() {") .indentln("return GWT.create(" + entry.getValue().getQualifiedSourceName() + ".class);") .println("}").outdent().println("}").outdent().println(");"); } // End our constructor cb.outdent().println("}"); // Print setters for factories, to allow runtime injection support. cb.createMethod("public <T> void setSingletonFactory(Class<T> cls, Provider<T> provider)") .addAnnotation("Override").println("singletons.put(cls, provider);"); cb.createMethod("public <T> void setInstanceFactory(Class<T> cls, Provider<T> provider)") .addAnnotation("Override").println("instances.put(cls, provider);"); // Print the factory provider methods, which throw exception instead of return null cb.createMethod("public <T> Provider<T> getSingletonFactory(Class<? super T> cls)") // .addAnnotation("Override") .addAnnotation("SuppressWarnings({\"rawtypes\", \"unchecked\"})") .println("Provider p = singletons.get(cls);").println("if (p == null) throwNotFound(true, cls);") .println("return (Provider<T>)p;"); cb.createMethod("public <T> Provider<T> getInstanceFactory(Class<? super T> cls)") // .addAnnotation("Override") .addAnnotation("SuppressWarnings({\"rawtypes\", \"unchecked\"})") .println("Provider p = instances.get(cls);").println("if (p == null) throwNotFound(false, cls);") .println("return (Provider<T>)p;"); cb.createMethod("public final <T> T provide(Class<? super T> cls)").addAnnotation("@Override") .println("return getSingletonFactory(cls).get();"); cb.createMethod("public final <T> T create(Class<? super T> cls)").addAnnotation("@Override") .println("return getInstanceFactory(cls).get();"); if (X_Runtime.isDebug()) { logger.log(Type.INFO, "Dumping javascript injector (trace level logging)"); if (logger.isLoggable(Type.TRACE)) logger.log(Type.TRACE, sb.toString()); } printWriter.append(sb.toString()); context.commit(logger, printWriter); return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, generatedClassName); }
From source file:xapi.dev.generators.InstanceInjectionGenerator.java
License:Open Source License
/** * @throws ClassNotFoundException//w w w . jav a 2s . c o m */ public static RebindResult execImpl(TreeLogger logger, GeneratorContext context, JClassType type) throws ClassNotFoundException { JClassType targetType = type; InstanceOverride winningOverride = null; JClassType winningType = null; // Step one: determine what platform we are targeting. Set<Class<? extends Annotation>> allowedPlatforms = getPlatforms(context); boolean trace = logger.isLoggable(Type.TRACE); if (trace) { logger.log(Type.TRACE, "Allowed platforms: " + allowedPlatforms); logger.log(Type.TRACE, "All Subtypes: " + Arrays.asList(type.getSubtypes())); } for (JClassType subtype : type.getSubtypes()) { if (trace) logger.log(Type.TRACE, "Type " + subtype.getJNISignature()); InstanceDefault def = subtype.getAnnotation(InstanceDefault.class); if (def != null) { if (winningType != null) continue; // a default cannot possibly override anything. // Make sure this type is not excluded by being part of a disallowed platform boolean useType = true; for (Annotation anno : def.annotationType().getAnnotations()) { if (anno.annotationType().getAnnotation(Platform.class) != null) { if (allowedPlatforms.contains(anno.annotationType())) { winningType = subtype; continue; } useType = false; } } // If we made it through without continue, or setting useType to false, // then there is no platform specified, and this is a global default type. if (useType) winningType = subtype; } InstanceOverride override = subtype.getAnnotation(InstanceOverride.class); if (override != null) { // Prefer GwtPlatform or GwtDevPlatform, // and blacklist any types that are of a foreign platform type (non-gwt). boolean hasGwt = false, hasOther = false; for (Annotation annotation : subtype.getAnnotations()) { // check each annotation to see if it is qualified with @Platform. Platform platform = annotation.annotationType().getAnnotation(Platform.class); if (platform != null) { // When platform is non-null, we only want to use it if it's in our allowed list. if (allowedPlatforms.contains(annotation.annotationType())) { hasGwt = true; break; } else { hasOther = true; } } } // if hasOther is false, or hasGwt is true, we want to use this type. if (hasOther && !hasGwt) { continue; } if (trace) logger.log(Type.DEBUG, "Test subtype match " + subtype + " - prodMode: " + context.isProdMode()); if (winningOverride != null) { if (winningOverride.priority() > override.priority()) continue; } winningOverride = override; winningType = subtype; } } if (winningType == null) { winningType = targetType;// no matches, resort to instantiate the class sent. if (trace) logger.log(Type.TRACE, "No match made; resorting to GWT.create() on " + winningType + " : "); } String packageName = type.getPackage().getName(); ensureProviderClass(logger, packageName, type.getSimpleSourceName(), type.getQualifiedSourceName(), SourceUtil.toSourceName(winningType.getQualifiedSourceName()), context); logger.log(Type.INFO, "Instance injection: " + type.getQualifiedSourceName() + " -> " + winningType.getQualifiedSourceName()); return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, winningType.getQualifiedSourceName()); }
From source file:xapi.dev.generators.SyncInjectionGenerator.java
License:Open Source License
/** * @throws ClassNotFoundException/*from w w w . j ava2s . c o m*/ */ public static RebindResult execImpl(TreeLogger logger, GeneratorContext context, JClassType type) throws ClassNotFoundException { PlatformSet allowed = CurrentGwtPlatform.getPlatforms(context); JClassType targetType = type; String simpleName = "SingletonFor_" + type.getSimpleSourceName(); SingletonOverride winningOverride = null; JClassType winningType = null; boolean trace = logger.isLoggable(Type.TRACE); for (JClassType subtype : type.getSubtypes()) { if (winningType == null) { SingletonDefault singletonDefault = subtype.getAnnotation(SingletonDefault.class); if (singletonDefault != null) { if (allowed.isAllowedType(subtype)) winningType = subtype; continue; } } SingletonOverride override = subtype.getAnnotation(SingletonOverride.class); if (override != null) { if (trace) logger.log(Type.DEBUG, "Got subtype " + subtype + " : " + " - prodMode: " + context.isProdMode()); if (allowed.isAllowedType(subtype)) { if (winningOverride != null) { if (winningOverride.priority() > override.priority()) continue; } winningOverride = override; winningType = subtype; } } } if (winningType == null) { winningType = targetType;//no matches, resort to instantiate the class sent. //TODO sanity check here } if (trace) X_Log.info("Singleton Injection Winner: " + winningType.getName()); String packageName = type.getPackage().getName(); ensureProviderClass(logger, packageName, type.getSimpleSourceName(), type.getQualifiedSourceName(), SourceUtil.toSourceName(winningType.getQualifiedSourceName()), context); packageName = packageName + ".impl"; PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName); if (printWriter == null) { return new RebindResult(RebindMode.USE_EXISTING, packageName + "." + simpleName); } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName); composer.setSuperclass(SingletonInitializer.class.getName() + "<" + type.getQualifiedSourceName() + ">"); composer.addImport(ReceivesValue.class.getName()); SourceWriter sw = composer.createSourceWriter(context, printWriter); sw.println(); //TODO: also check if compile is set to async = false //if async is already generated when this singleton access occurs, //but we haven't yet injected the callback which accesses the global singleton, //we'll have to route our get() through the existing async callback block //to prevents code splitting from falling apart. This will, at worst, //cause providers to return null until the service is actually initialized. if (context.isProdMode() && isAsyncProvided(logger, packageName, type.getSimpleSourceName(), context) && !isCallbackInjected(logger, packageName, type.getSimpleSourceName(), context)) { //this edge case happens when a service is accessed synchronously //inside of its own asynchronous callback //TODO use GWT's AsyncProxy class to queue up requests... logger.log(Type.WARN, "Generating interim singleton provider"); sw.indent(); sw.println("private static " + type.getQualifiedSourceName() + " value = null;"); sw.println("@Override"); sw.println("public final " + type.getQualifiedSourceName() + " initialValue(){"); sw.indent(); sw.println("if (value!=null)return value;"); sw.println(packageName + "." + InjectionUtils.generatedAsyncProviderName(type.getSimpleSourceName())); sw.indent(); sw.print(".request(new ReceivesValue<"); sw.println(type.getQualifiedSourceName() + ">(){"); sw.indent(); sw.println("@Override"); sw.print("public void set("); sw.println(type.getQualifiedSourceName() + " x){"); sw.indent(); sw.println("value=x;"); sw.outdent(); sw.println("}"); sw.outdent(); sw.println("});"); sw.outdent(); sw.println("return value;"); } else { //all non-prod or non-async providers can safely access the singleton directly sw.println("@Override"); sw.println("public final " + type.getQualifiedSourceName() + " initialValue(){"); sw.indent(); //normal operation; just wrap the static final singleton provider. sw.print("return " + type.getPackage().getName() + "." + InjectionUtils.generatedProviderName(type.getSimpleSourceName())); sw.println(".theProvider.get();"); } sw.outdent(); sw.println("}"); sw.println(); sw.commit(logger); //TODO: implement caching once this code is finalized return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, packageName + "." + simpleName); }
From source file:xapi.dev.inject.MagicMethods.java
License:Open Source License
/** * Replaces a call from {@link X_Inject#singletonAsync(Class, xapi.util.api.ReceivesValue)} by first a) * generating an async provider, and then b) sending the value receiver into the async provider as a * callback. See the {@link AsyncProxy} class and {@link AsyncInjectionGenerator} for implementation. * * @param logger - The logger to log to. * @param methodCall - The method call we are overwriting * @param currentMethod - The encapsulated method itself * @param context - The method call context, so you can insert clinits / whatnot * @param ast - A view over UnifyAst, exposing our basic needs * @return - A JExpression to replace this method call with * @throws UnableToCompleteException/* ww w . j a va 2 s. c om*/ */ public static JExpression rebindSingletonAsync(TreeLogger logger, JMethodCall methodCall, JMethod currentMethod, Context context, UnifyAstView ast) throws UnableToCompleteException { assert (methodCall.getArgs().size() == 2); JExpression classParam = methodCall.getArgs().get(0); JExpression receiverParam = methodCall.getArgs().get(1); if (!(classParam instanceof JClassLiteral)) { ast.error(methodCall, "Only class literals may be used as arguments to X_Inject.singletonAsync; you sent " + classParam.getClass() + " - " + classParam); return null; } logger.log(logLevel(), receiverParam.toString() + " : " + receiverParam.getClass() + " : " + receiverParam.toSource()); JClassLiteral classLiteral = (JClassLiteral) classParam; JDeclaredType answerType = injectSingletonAsync(logger, classLiteral, methodCall, ast); JDeclaredType receiverType = ast.searchForTypeBySource("xapi.util.api.ReceivesValue"); for (JMethod method : receiverType.getMethods()) { if (method.getName().equals("set")) { SourceInfo info = methodCall.getSourceInfo().makeChild(SourceOrigin.UNKNOWN); JExpression result; result = JGwtCreate.createInstantiationExpression(methodCall.getSourceInfo(), (JClassType) answerType); if (result == null) { ast.error(methodCall, "Rebind result '" + answerType + "' has no default (zero argument) constructors"); return null; } JMethodCall call = new JMethodCall(info, result, method); call.addArg(receiverParam); if (logger.isLoggable(logLevel())) { TreeLogger branch = logger.branch(logLevel(), "Generated asynchronous magic singleton: "); for (String str : call.toSource().split("\n")) { branch.log(logLevel(), str); } } return call; } } throw new InternalCompilerException("Unable to generate asynchronous class injector"); }
From source file:xapi.dev.inject.MagicMethods.java
License:Open Source License
private static JExpression injectSingleton(TreeLogger logger, JClassLiteral classLiteral, JNode x, UnifyAstView ast) throws UnableToCompleteException { // check for cached result. // inject our provider class JDeclaredType type = (JDeclaredType) classLiteral.getRefType(); if (cachedProviders.containsKey(type)) return cachedProviders.get(type); JExpression expr = injectLazySingleton(logger, classLiteral, x, type, ast); String[] names = type.getShortName().split("[$]"); String answer = classLiteral.getRefType().getName(); answer = answer.substring(0, answer.lastIndexOf('.') + 1) + "impl.SingletonFor_" + names[names.length - 1]; JDeclaredType enclosing = ast.searchForTypeBySource(answer); JDeclaredType lazyProvider = ast.searchForTypeBySource(SingletonProvider.class.getName()); for (JMethod method : lazyProvider.getMethods()) { if (method.getName().equals("get")) { // Create a new method for each singleton to access the desired provider SourceInfo info = null;//from ww w . j a va 2 s .c o m JMethod getSingleton = null; String targetName = "singleton" + type.getShortName().replaceAll("[$]", "_"); for (JMethod existingMethod : enclosing.getMethods()) { if (existingMethod.getName().equals(existingMethod)) { getSingleton = existingMethod; info = getSingleton.getSourceInfo(); logger.log(logLevel(), "Reusing generated method " + getSingleton.toSource()); break; } } if (getSingleton == null) { info = expr.getSourceInfo().makeChild(SourceOrigin.UNKNOWN); JMethodBody body = new JMethodBody(info); getSingleton = new JMethod(info, targetName, enclosing, type, false, true, true, AccessModifier.PRIVATE); // insert our generated method into the enclosing type; needed for super dev mode enclosing.addMethod(getSingleton); // freeze this method getSingleton.setBody(body); getSingleton.freezeParamTypes(); getSingleton.setSynthetic(); info.addCorrelation(info.getCorrelator().by(getSingleton)); JMethodCall call = new JMethodCall(info, expr, method); JReturnStatement value = new JReturnStatement(x.getSourceInfo(), call); if (enclosing.getClinitTarget() != null) { JDeclaredType clinit = enclosing.getClinitTarget(); JMethod clinitMethod = clinit.getMethods().get(0); assert (JProgram.isClinit(clinitMethod)); JMethodCall doClinit = new JMethodCall(clinit.getSourceInfo(), null, clinitMethod); body.getBlock().addStmt(doClinit.makeStatement()); } body.getBlock().addStmt(value); if (logger.isLoggable(Type.DEBUG)) { logger = logger.branch(Type.DEBUG, "Generated magic singleton: "); for (String str : getSingleton.toSource().split("\n")) { logger.branch(Type.DEBUG, str); } } } expr = new JMethodCall(info, null, getSingleton); cachedProviders.put(type, expr); return expr; } } throw new InternalCompilerException("Unable to generate synchronous injected class access"); }
From source file:xapi.dev.util.GwtInjectionMap.java
License:Open Source License
protected void init(TreeLogger logger, GeneratorContext context) { TypeOracle oracle = context.getTypeOracle(); JClassType[] types = oracle.getTypes(); for (JClassType type : types) { SingletonDefault defaultSingleton = type.getAnnotation(SingletonDefault.class); if (defaultSingleton != null && platforms.isAllowedType(type)) { JClassType old = defaultSingletons.get(defaultSingleton.implFor()); if (old == null) { defaultSingletons.put(defaultSingleton.implFor(), type); } else { JClassType better = platforms.prefer(type, old, SingletonDefault.class); if (better == type) { defaultSingletons.put(defaultSingleton.implFor(), type); }/* w w w. j a v a 2s . c o m*/ } } InstanceDefault instanceDefault = type.getAnnotation(InstanceDefault.class); if (instanceDefault != null && platforms.isAllowedType(type)) { JClassType old = defaultInstances.get(instanceDefault.implFor()); if (old == null) { defaultInstances.put(instanceDefault.implFor(), type); } else { JClassType better = platforms.prefer(type, old, InstanceDefault.class); if (better == type) { defaultInstances.put(instanceDefault.implFor(), type); } } } extractSingletonOverrides(logger, type, context); extractInstanceOverrides(logger, type, context); } if (logger.isLoggable(Type.TRACE)) { dumpMaps(logger); } }