com.google.gwt.core.ext.typeinfo.JMethod Java Examples

The following examples show how to use com.google.gwt.core.ext.typeinfo.JMethod. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailOnPrimitiveParameter() throws Exception {
  JClassType paramType = mock(JClassType.class);
  when(paramType.isClassOrInterface()).thenReturn(null);

  JMethod method = newMethod("myMethod", paramType);
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});

  try {
    writer.writeDoBindEventHandlers(target, output, typeOracle);
    fail("Exception not thrown");
  } catch (UnableToCompleteException expected) {}

  verify(logger).log(
      eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class));
}
 
Example #2
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
private void writeMethods(TreeLogger logger, ResourceContext context, JMethod method,
    SourceWriter sw, ConstantDefinitions constantDefinitions,
    Map<String, String> originalConstantNameMapping, Map<String, String> substitutionMap)
    throws UnableToCompleteException {
  JClassType gssResource = method.getReturnType().isInterface();

  boolean success = true;

  for (JMethod toImplement : gssResource.getOverridableMethods()) {
    if (toImplement == getTextMethod) {
      writeGetText(logger, context, method, sw);
    } else if (toImplement == ensuredInjectedMethod) {
      writeEnsureInjected(sw);
    } else if (toImplement == getNameMethod) {
      writeGetName(method, sw);
    } else {
      success &= writeUserMethod(logger, toImplement, sw, constantDefinitions,
          originalConstantNameMapping, substitutionMap);
    }
  }

  if (!success) {
    throw new UnableToCompleteException();
  }
}
 
Example #3
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
@Override
protected String getCssExpression(TreeLogger logger, ResourceContext context,
    JMethod method) throws UnableToCompleteException {
  CssTree cssTree = cssTreeMap.get(method).tree;

  String standard = printCssTree(cssTree);

  // TODO add configuration properties for swapLtrRtlInUrl, swapLeftRightInUrl and
  // shouldFlipConstantReferences booleans
  RecordingBidiFlipper recordingBidiFlipper =
      new RecordingBidiFlipper(cssTree.getMutatingVisitController(), false, false, true);
  recordingBidiFlipper.runPass();

  if (recordingBidiFlipper.nodeFlipped()) {
    String reversed = printCssTree(cssTree);
    return LocaleInfo.class.getName() + ".getCurrentLocale().isRTL() ? "
        + reversed + " : " + standard;
  } else {
    return standard;
  }
}
 
Example #4
Source File: EventsAnnotationsLoader.java    From mvp4g with Apache License 2.0 6 votes vote down vote up
private String[] buildChildModules(JClassType c,
                                   JMethod method,
                                   Event event,
                                   Mvp4gConfiguration configuration)
  throws Mvp4gAnnotationException {
  Set<ChildModuleElement> loadedChildModules = configuration.getChildModules();

  Class<?>[] childModuleClasses = event.forwardToModules();
  String[] childModules = new String[childModuleClasses.length];

  String moduleName = null;
  int index = 0;
  for (Class<?> moduleClass : childModuleClasses) {
    moduleName = getElementName(loadedChildModules,
                                moduleClass.getCanonicalName());
    //it's not a child module, could be a siblings, in this case name == class name
    if (moduleName == null) {
      moduleName = moduleClass.getCanonicalName();
    }
    childModules[index] = moduleName;
    index++;
  }

  return childModules;
}
 
Example #5
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void generateServiceImplementationWithCallback(TreeLogger logger, SourceWriter srcWriter)
	throws UnableToCompleteException {
	for (JMethod method : this.serviceBinderType.getMethods()) {
		JParameter[] methodParams = method.getParameters();
		JParameter callbackParam = null;
		if (methodParams != null && methodParams.length > 0) {
			callbackParam = methodParams[methodParams.length - 1];
		}
		if (callbackParam == null) {
			break;
		}
		this.writeStartMethod(srcWriter, method);
		this.writeCommandDefinition(logger, srcWriter, method, callbackParam);
		this.writeCommandParam(srcWriter, method, null, callbackParam);
		this.writeEndMethod(srcWriter, method);
	}
}
 
Example #6
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
private void validateExternalClasses(Set<String> externalClasses,
    Set<String> externalClassCandidates, JMethod method,
    TreeLogger logger) throws UnableToCompleteException {
  if (!isStrictResource(method)) {
    return;
  }

  boolean hasError = false;

  for (String candidate : externalClassCandidates) {
    if (!externalClasses.contains(candidate)) {
      logger.log(Type.ERROR, "The following non-obfuscated class is present in a strict " +
          "CssResource: " + candidate);
      hasError = true;
    }
  }

  if (hasError) {
    throw new UnableToCompleteException();
  }
}
 
Example #7
Source File: EventsAnnotationsLoader.java    From mvp4g with Apache License 2.0 6 votes vote down vote up
/**
 * Build history converter of an event. If the converter class name is given, first it tries to
 * find an instance of this class, and if none is found, create one.
 *
 * @param c             annoted class
 * @param method        method that defines the event
 * @param annotation    Event annotation
 * @param element       Event element
 * @param configuration configuration containing loaded elements of the application
 * @throws Mvp4gAnnotationException
 */
private void loadHistory(JClassType c,
                         JMethod method,
                         Event annotation,
                         EventElement element,
                         Mvp4gConfiguration configuration)
  throws Mvp4gAnnotationException {
  String hcName = annotation.historyConverterName();
  Class<?> hcClass = annotation.historyConverter();
  if ((hcName != null) && (hcName.length() > 0)) {
    element.setHistory(hcName);
  } else if (!Event.NoHistoryConverter.class.equals(hcClass)) {
    String hcClassName = hcClass.getCanonicalName();
    Set<HistoryConverterElement> historyConverters = configuration.getHistoryConverters();
    hcName = getElementName(historyConverters,
                            hcClassName);
    if (hcName == null) {
      String err = "No instance of " + hcClassName + " is defined. Have you forgotten to annotate your history converter with @History?";
      throw new Mvp4gAnnotationException(c.getQualifiedSourceName(),
                                         method.getName(),
                                         err);
    }
    element.setHistory(hcName);
  }
}
 
Example #8
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void collectImports() {
	Collection<JType> toImports = Sets.newHashSet();
	for (JMethod method : this.serviceType.getOverridableMethods()) {
		toImports.add(method.getReturnType());
		for (JParameter parameter : method.getParameters()) {
			toImports.add(parameter.getType());
		}
	}
	this.imports.addAll(toImports);
	for (JType importType : this.imports) {
		if (importType instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) importType;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				toImports.add(paramType);
			}
		}
	}
	this.imports.addAll(toImports);
}
 
Example #9
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailOnAbstractParameter() throws Exception {
  JClassType paramType = getEventType(AbstractEvent.class);
  when(paramType.isAbstract()).thenReturn(true);
  
  JMethod method = newMethod("myMethod", paramType);
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});
  
  try {
    writer.writeDoBindEventHandlers(target, output, typeOracle);
    fail("Exception not thrown");
  } catch (UnableToCompleteException expected) {}
  
  verify(logger).log(
      eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class));
}
 
Example #10
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void writeCommandDefinition(TreeLogger logger, SourceWriter srcWriter, JMethod method,
	JParameter callbackParameter) throws UnableToCompleteException {
	srcWriter.print("CommandDefinition commandDefinition  = new CommandDefinition(");
	srcWriter.print("\"%s\", ", this.serviceType.getQualifiedSourceName());
	srcWriter.print("\"%s\", ", method.getName());
	if (callbackParameter != null) {
		JParameterizedType parameterizedCallback = callbackParameter.getType().isParameterized();
		if (parameterizedCallback != null) {
			srcWriter.print("\"%s\" ", parameterizedCallback.getTypeArgs()[0].getQualifiedSourceName());
		} else {
			logger.branch(TreeLogger.ERROR, "Callback argument type for method " + method.getName()
				+ " is not parametrized", null);
			throw new UnableToCompleteException();
		}

	} else {
		srcWriter.print("\"%s\" ", method.getReturnType().getQualifiedSourceName());
	}
	for (JParameter parameter : method.getParameters()) {
		if (!parameter.equals(callbackParameter)) {
			srcWriter.print(", \"%s\"", parameter.getType().getQualifiedSourceName());
		}
	}
	srcWriter.println(");");
}
 
Example #11
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldFailOnInvalidParameter() throws Exception {
  JClassType paramType = mock(JClassType.class);
  when(paramType.isAssignableTo(genericEventType)).thenReturn(false);
  when(paramType.isClassOrInterface()).thenReturn(paramType);

  JMethod method = newMethod("myMethod", paramType);
  when(target.getInheritableMethods()).thenReturn(new JMethod[] {method});

  try {
    writer.writeDoBindEventHandlers(target, output, typeOracle);
    fail("Exception not thrown");
  } catch (UnableToCompleteException expected) {}

  verify(logger).log(
      eq(Type.ERROR), contains("myMethod"), isNull(Throwable.class), isNull(HelpInfo.class));
}
 
Example #12
Source File: InjectErrorManagerCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void writeEntryPoint(SourceWriter srcWriter) {
	srcWriter.println("ErrorManager.get();");
	if (!ErrorDisplayer.class.equals(this.errorDisplay)) {
		srcWriter.println("ErrorManager.get().setErrorDisplayer(GWT.<ErrorDisplayer> create(%s.class));",
			InjectCreatorUtil.toClassName(this.errorDisplay));
	}
	if (this.errorHandlers != null) {
		for (Class<? extends ErrorHandler> handlerClass : this.errorHandlers) {
			srcWriter.println("ErrorManager.get().registerErrorHandler(new %s());",
				InjectCreatorUtil.toClassName(handlerClass));
		}
	}
	if (this.errorHandlers != null) {
		for (JMethod handlerMethod : this.handlerMethods) {
			srcWriter.println("ErrorManager.get().registerErrorHandler("
				+ "new fr.putnami.pwt.core.error.client.ErrorHandler() {");
			srcWriter.indent();
			srcWriter.println("@Override public boolean handle(Throwable error) { return %s.this.%s(error); }",
				this.injectorName, handlerMethod.getName());
			srcWriter.println("@Override public int getPriority() { return HIGH_PRIORITY; }");
			srcWriter.outdent();
			srcWriter.println("});");
		}
	}
}
 
Example #13
Source File: InjectPresenterCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void initComposer(ClassSourceFileComposerFactory composerFactory) {
	composerFactory.addImport(Place.class.getName());
	composerFactory.addImport(Presenter.class.getName());
	for (JMethod presenterMethod : this.presenterMethods) {
		if (presenterMethod.getParameters().length > 0) {
			JType placeType = presenterMethod.getParameters()[0].getType();
			composerFactory.addImport(placeType.getQualifiedSourceName());
			if (placeType instanceof JParameterizedType) {
				JParameterizedType parameterizedType = (JParameterizedType) placeType;
				for (JType paramType : parameterizedType.getTypeArgs()) {
					composerFactory.addImport(paramType.getQualifiedSourceName());
				}
			}
		}
	}

	composerFactory.addImplementedInterface(Presenter.class.getSimpleName());
	composerFactory.addImport(AcceptsOneWidget.class.getName());
}
 
Example #14
Source File: FieldAccessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Constructor for FieldAccessor.</p>
 *
 * @param propertyName a {@link java.lang.String} object.
 * @param samePackage a boolean.
 * @param fieldAutoDetect a boolean.
 * @param fieldAutoDetect a boolean.
 * @param field a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 * @param methodAutoDetect a boolean.
 * @param methodAutoDetect a boolean.
 * @param method a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 */
protected FieldAccessor( String propertyName, boolean samePackage, boolean fieldAutoDetect, Optional<JField> field,
                         boolean methodAutoDetect, Optional<JMethod> method ) {
    Preconditions.checkNotNull( propertyName );
    Preconditions.checkArgument( field.isPresent() || method.isPresent(), "At least one of the field or method must be given" );

    this.propertyName = propertyName;
    this.samePackage = samePackage;
    this.field = field;
    this.method = method;

    // We first test if we can use the method
    if ( method.isPresent() && (methodAutoDetect || !fieldAutoDetect || !field.isPresent()) ) {
        useMethod = true;
    }
    // else use the field
    else {
        useMethod = false;
    }
}
 
Example #15
Source File: InjectMayStopActivityCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void writePresent(SourceWriter srcWriter) {
	srcWriter
		.println("final HandlerRegistrationCollection mayStopRegistrations = new HandlerRegistrationCollection();");
	for (JMethod mayStopMethod : this.presenterMethods) {
		srcWriter.println("mayStopRegistrations.add(EventBus.get()"
			+ ".addHandlerToSource(MayStopActivityEvent.TYPE, place, new MayStopActivityEvent.Handler() {");
		srcWriter.indent();
		srcWriter.println("@Override public void onMayStopActivity(MayStopActivityEvent event) {");
		srcWriter.indent();
		srcWriter.println("if (event.getMessage() == null) { event.setMessage(%s.this.%s()); }", this.injectorName,
			mayStopMethod.getName());
		srcWriter.outdent();
		srcWriter.outdent();
		srcWriter.println("}}));");
	}
	srcWriter.println("mayStopRegistrations.add(EventBus.get()"
		+ ".addHandlerToSource(StopActivityEvent.TYPE, place, new StopActivityEvent.Handler() {");
	srcWriter.indent();
	srcWriter.println("@Override public void onStopActivity(StopActivityEvent event) {");
	srcWriter.indent();
	srcWriter.println("mayStopRegistrations.removeHandler();");
	srcWriter.outdent();
	srcWriter.outdent();
	srcWriter.println("}}));");
}
 
Example #16
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private static boolean isSetterAutoDetected( RebindConfiguration configuration, PropertyAccessors propertyAccessors, BeanInfo info ) {
    if ( !propertyAccessors.getSetter().isPresent() ) {
        return false;
    }

    for ( Class<? extends Annotation> annotation : AUTO_DISCOVERY_ANNOTATIONS ) {
        if ( propertyAccessors.isAnnotationPresentOnSetter( annotation ) ) {
            return true;
        }
    }

    JMethod setter = propertyAccessors.getSetter().get();

    String methodName = setter.getName();
    if ( !methodName.startsWith( "set" ) || methodName.length() <= 3 ) {
        // no annotation on method and the method does not follow naming convention
        return false;
    }

    JsonAutoDetect.Visibility visibility = info.getSetterVisibility();
    if ( Visibility.DEFAULT == visibility ) {
        visibility = configuration.getDefaultSetterVisibility();
    }
    return isAutoDetected( visibility, setter.isPrivate(), setter.isProtected(), setter.isPublic(), setter
            .isDefaultAccess() );
}
 
Example #17
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void collectImports() {
	Collection<JType> toImports = Sets.newHashSet();
	for (JMethod method : this.serviceType.getOverridableMethods()) {
		toImports.add(method.getReturnType());
		for (JParameter parameter : method.getParameters()) {
			toImports.add(parameter.getType());
		}
	}
	this.imports.addAll(toImports);
	for (JType importType : this.imports) {
		if (importType instanceof JParameterizedType) {
			JParameterizedType parameterizedType = (JParameterizedType) importType;
			for (JType paramType : parameterizedType.getTypeArgs()) {
				toImports.add(paramType);
			}
		}
	}
	this.imports.addAll(toImports);
}
 
Example #18
Source File: InjectStopActivityCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void writePresent(SourceWriter srcWriter) {
	srcWriter.println("final HandlerRegistrationCollection stopRegistrations = new HandlerRegistrationCollection();");
	for (JMethod mayStopMethod : this.presenterMethods) {
		srcWriter.println("stopRegistrations.add(EventBus.get()"
			+ ".addHandlerToSource(StopActivityEvent.TYPE, place, new StopActivityEvent.Handler() {");
		srcWriter.indent();
		srcWriter.println("@Override public void onStopActivity(StopActivityEvent event) {");
		srcWriter.indent();
		srcWriter.println("%s.this.%s();", this.injectorName, mayStopMethod.getName());
		srcWriter.outdent();
		srcWriter.outdent();
		srcWriter.println("}}));");
	}
	srcWriter.println("stopRegistrations.add(EventBus.get()"
		+ ".addHandlerToSource(StopActivityEvent.TYPE, place, new StopActivityEvent.Handler() {");
	srcWriter.indent();
	srcWriter.println("@Override public void onStopActivity(StopActivityEvent event) {");
	srcWriter.indent();
	srcWriter.println("stopRegistrations.removeHandler();");
	srcWriter.outdent();
	srcWriter.outdent();
	srcWriter.println("}}));");
}
 
Example #19
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void generateServiceImplementationWithCallback(SourceWriter srcWriter) {
	for (JMethod method : this.serviceBinderType.getMethods()) {
		JParameter[] methodParams = method.getParameters();
		JParameter callbackParam = null;
		if (methodParams != null && methodParams.length > 0) {
			callbackParam = methodParams[methodParams.length - 1];
		}
		if (callbackParam == null) {
			break;
		}
		this.writeStartMethod(srcWriter, method);
		this.writeMethodCallback(srcWriter, method, null, callbackParam);
		this.writeMethodCall(srcWriter, method, callbackParam);
		this.writeEndMethod(srcWriter, method);
	}
}
 
Example #20
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeStartMethod(SourceWriter srcWriter, JMethod method) {
	srcWriter.print("public %s %s(", this.typeAsString(method.getReturnType(), false), method.getName());
	int i = 0;
	for (JParameter parameter : method.getParameters()) {
		if (i++ > 0) {
			srcWriter.print(", ");
		}
		srcWriter.print("%s $%d_%s", this.typeAsString(parameter.getType(), false), i, parameter.getName());
	}
	srcWriter.println("){");
	srcWriter.indent();
}
 
Example #21
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private void initReplacement(ResourceContext context) {
  if (context.getCachedData(KEY_HAS_CACHED_DATA, Boolean.class) != Boolean.TRUE) {

    context.putCachedData(KEY_SHARED_METHODS, new IdentityHashMap<JMethod, String>());
    context.putCachedData(KEY_BY_CLASS_AND_METHOD, new IdentityHashMap<JClassType, Map<String,
        String>>());
    context.putCachedData(KEY_HAS_CACHED_DATA, Boolean.TRUE);
  }

  replacementsByClassAndMethod = context.getCachedData(KEY_BY_CLASS_AND_METHOD, Map.class);
  replacementsForSharedMethods = context.getCachedData(KEY_SHARED_METHODS,
      Map.class);
}
 
Example #22
Source File: PropertyAccessors.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
PropertyAccessors( String propertyName, Optional<JField> field, Optional<JMethod> getter, Optional<JMethod> setter,
                   Optional<JParameter> parameter, ImmutableList<JField> fields, ImmutableList<JMethod> getters,
                   ImmutableList<JMethod> setters, ImmutableList<HasAnnotations> accessors ) {

    this.propertyName = propertyName;
    this.field = field;
    this.getter = getter;
    this.setter = setter;
    this.parameter = parameter;
    this.fields = fields;
    this.getters = getters;
    this.setters = setters;
    this.accessors = accessors;
}
 
Example #23
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private String getClassName(JMethod method) {
  String name = method.getName();

  ClassName classNameOverride = method.getAnnotation(ClassName.class);
  if (classNameOverride != null) {
    name = classNameOverride.value();
  }
  return name;
}
 
Example #24
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static boolean isGetterAutoDetected( RebindConfiguration configuration, PropertyAccessors propertyAccessors, BeanInfo info ) {
    if ( !propertyAccessors.getGetter().isPresent() ) {
        return false;
    }

    for ( Class<? extends Annotation> annotation : AUTO_DISCOVERY_ANNOTATIONS ) {
        if ( propertyAccessors.isAnnotationPresentOnGetter( annotation ) ) {
            return true;
        }
    }

    JMethod getter = propertyAccessors.getGetter().get();

    String methodName = getter.getName();
    JsonAutoDetect.Visibility visibility;
    if ( methodName.startsWith( "is" ) && methodName.length() > 2 && JPrimitiveType.BOOLEAN.equals( getter.getReturnType()
            .isPrimitive() ) ) {

        // getter method for a boolean
        visibility = info.getIsGetterVisibility();
        if ( Visibility.DEFAULT == visibility ) {
            visibility = configuration.getDefaultIsGetterVisibility();
        }

    } else if ( methodName.startsWith( "get" ) && methodName.length() > 3 ) {

        visibility = info.getGetterVisibility();
        if ( Visibility.DEFAULT == visibility ) {
            visibility = configuration.getDefaultGetterVisibility();
        }

    } else {
        // no annotation on method and the method does not follow naming convention
        return false;
    }
    return isAutoDetected( visibility, getter.isPrivate(), getter.isProtected(), getter.isPublic(), getter.isDefaultAccess() );
}
 
Example #25
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private boolean writeUserMethod(TreeLogger logger, JMethod userMethod,
    SourceWriter sw, ConstantDefinitions constantDefinitions,
    Map<String, String> originalConstantNameMapping, Map<String, String> substitutionMap)
    throws UnableToCompleteException {

  String className = getClassName(userMethod);
  // method to access style class ?
  if (substitutionMap.containsKey(className)) {
    return writeClassMethod(logger, userMethod, substitutionMap, sw);
  }

  // method to access constant value ?
  CssDefinitionNode definitionNode;
  String methodName = userMethod.getName();

  if (originalConstantNameMapping.containsKey(methodName)) {
    // method name maps a constant that has been renamed during the auto conversion
    String constantName = originalConstantNameMapping.get(methodName);
    definitionNode = constantDefinitions.getConstantDefinition(constantName);
  } else {
    definitionNode = constantDefinitions.getConstantDefinition(methodName);

    if (definitionNode == null) {
      // try with upper case
      definitionNode = constantDefinitions.getConstantDefinition(toUpperCase(methodName));
    }
  }

  if (definitionNode != null) {
    return writeDefMethod(definitionNode, logger, userMethod, sw);
  }

  // the method doesn't match a style class nor a constant
  logger.log(Type.ERROR,
      "The following method [" + userMethod.getName() + "()] doesn't match a constant" +
          " nor a style class. You could fix that by adding ." + className + " {}"
  );
  return false;
}
 
Example #26
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private Map<String, Map<String, String>> computeReplacements(JMethod method, TreeLogger logger,
    ResourceContext context) throws UnableToCompleteException {
  Map<String, Map<String, String>> replacementsWithPrefix = new HashMap<String, Map<String,
      String>>();

  replacementsWithPrefix
      .put("", computeReplacementsForType(method.getReturnType().isInterface()));

  // Process the Import annotation if any
  Import imp = method.getAnnotation(Import.class);

  if (imp != null) {
    boolean fail = false;
    TypeOracle typeOracle = context.getGeneratorContext().getTypeOracle();

    for (Class<? extends CssResource> clazz : imp.value()) {
      JClassType importType = typeOracle.findType(clazz.getName().replace('$', '.'));
      assert importType != null : "TypeOracle does not have type " + clazz.getName();

      // add this import type as a requirement for this generator
      context.getRequirements().addTypeHierarchy(importType);

      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();
    }
  }

  return replacementsWithPrefix;
}
 
Example #27
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeEndMethod(SourceWriter srcWriter, JMethod method) {
	if (method.getReturnType().equals(JPrimitiveType.BOOLEAN)) {
		srcWriter.println("return false;");
	} else if (method.getReturnType().equals(JPrimitiveType.BYTE) || method.getReturnType().equals(JPrimitiveType.CHAR)
		|| method.getReturnType().equals(JPrimitiveType.DOUBLE) || method.getReturnType().equals(JPrimitiveType.FLOAT)
		|| method.getReturnType().equals(JPrimitiveType.INT) || method.getReturnType().equals(JPrimitiveType.LONG)
		|| method.getReturnType().equals(JPrimitiveType.SHORT)) {
		srcWriter.println("return 0;");
	} else if (!method.getReturnType().equals(JPrimitiveType.VOID)) {
		srcWriter.println("return null;");
	}
	srcWriter.outdent();
	srcWriter.println("}");
}
 
Example #28
Source File: RestServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeMethodCall(SourceWriter srcWriter, JMethod method, JParameter callbackParam) {
	srcWriter.print("REST.<%s> withCallback(compositeCallback).call(restService).%s(", this.typeAsString(method
		.getReturnType(), true), method.getName());
	int i = 0;
	for (JParameter parameter : method.getParameters()) {
		if (!parameter.equals(callbackParam)) {
			if (i++ > 0) {
				srcWriter.print(", ");
			}
			srcWriter.print("$%d_%s", i, parameter.getName());
		}
	}
	srcWriter.println(");");
}
 
Example #29
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private Map<String, String> computeReplacementsForType(JClassType cssResource) {
  Map<String, String> replacements = replacementsByClassAndMethod.get(cssResource);

  if (replacements == null) {
    replacements = new HashMap<String, String>();
    replacementsByClassAndMethod.put(cssResource, replacements);

    String resourcePrefix = resourcePrefixBuilder.get(cssResource.getQualifiedSourceName());

    // This substitution map will prefix each renamed class with the resource prefix and use a
    // MinimalSubstitutionMap for computing the obfuscated name.
    SubstitutionMap prefixingSubstitutionMap = new PrefixingSubstitutionMap(
        new MinimalSubstitutionMap(), obfuscationPrefix + resourcePrefix + "-");

    for (JMethod method : cssResource.getOverridableMethods()) {
      if (method == getNameMethod || method == getTextMethod || method == ensuredInjectedMethod) {
        continue;
      }

      String styleClass = getClassName(method);

      if (replacementsForSharedMethods.containsKey(method)) {
        replacements.put(styleClass, replacementsForSharedMethods.get(method));
      } else {
        String obfuscatedClassName = prefixingSubstitutionMap.get(styleClass);
        String replacement = obfuscationStyle.getPrettyName(styleClass, cssResource,
            obfuscatedClassName);

        replacements.put(styleClass, replacement);
        maybeHandleSharedMethod(method, replacement);
      }
    }
  }

  return replacements;
}
 
Example #30
Source File: PropertyAccessorsBuilder.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
void addSetter( JMethod setter, boolean mixin ) {
    if ( !mixin && !this.setter.isPresent() ) {
        this.setter = Optional.of( setter );
    }
    this.setters.add( setter );
    this.accessors.add( setter );
}