com.google.gwt.core.ext.UnableToCompleteException Java Examples

The following examples show how to use com.google.gwt.core.ext.UnableToCompleteException. 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: BeanJsonSerializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private JSerializerType getJsonSerializerFromProperty( PropertyInfo propertyInfo ) throws UnableToCompleteException {
    if ( null != propertyInfo && propertyInfo.getGetterAccessor().isPresent() && !propertyInfo.isIgnored() ) {
        if ( propertyInfo.isRawValue() ) {
            return new JSerializerType.Builder().type( propertyInfo.getType() ).instance( CodeBlock.builder()
                    .add( "$T.<$T>getInstance()", RawValueJsonSerializer.class, typeName( propertyInfo.getType() ) ).build() )
                    .build();
        } else {
            try {
                return getJsonSerializerFromType( propertyInfo.getType() );
            } catch ( UnsupportedTypeException e ) {
                logger.log( Type.WARN, "Property '" + propertyInfo.getPropertyName() + "' is ignored." );
            }
        }
    }
    return null;
}
 
Example #2
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 #3
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 #4
Source File: BeanJsonDeserializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private List<MethodSpec> buildCommonPropertyDeserializerMethods( PropertyInfo property, JDeserializerType deserializerType )
        throws UnableToCompleteException {
    List<MethodSpec> result = new ArrayList<MethodSpec>();

    result.add( MethodSpec.methodBuilder( "newDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get( ClassName.get( JsonDeserializer.class ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", deserializerType.getInstance() )
            .build() );

    Optional<MethodSpec> paramMethod = buildPropertyDeserializerParameters( property, deserializerType );
    if ( paramMethod.isPresent() ) {
        result.add( paramMethod.get() );
    }

    return result;
}
 
Example #5
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Consumes and returns all child elements selected by the interpreter. Note
 * that text nodes are not elements, and so are not presented for
 * interpretation, and are not consumed.
 * 
 * @param interpreter Should return true for any child that should be consumed
 *          and returned by the consumeChildElements call
 * @throws UnableToCompleteException
 */
public Collection<XMLElement> consumeChildElements(Interpreter<Boolean> interpreter)
    throws UnableToCompleteException {
  List<XMLElement> elements = new ArrayList<XMLElement>();
  List<Node> doomed = new ArrayList<Node>();

  NodeList childNodes = elem.getChildNodes();
  for (int i = 0; i < childNodes.getLength(); ++i) {
    Node childNode = childNodes.item(i);
    if (childNode.getNodeType() == Node.ELEMENT_NODE) {
      XMLElement childElement = provider.get((Element) childNode);
      if (interpreter.interpretElement(childElement)) {
        elements.add(childElement);
        doomed.add(childNode);
      }
    }
  }

  for (Node n : doomed) {
    elem.removeChild(n);
  }
  return elements;
}
 
Example #6
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Like {@link #consumeAttributeWithDefault(String, String, JType)}, but
 * accommodates more complex type signatures.
 */
public String consumeAttributeWithDefault(String name, String defaultValue, JType... types)
    throws UnableToCompleteException {

  if (!hasAttribute(name)) {
    if (defaultValue != null) {
      designTime.putAttribute(this, name + ".default", defaultValue);
    }
    return defaultValue;
  }

  AttributeParser parser = attributeParsers.getParser(types);
  if (parser == null) {
    logger.die("Attribute '" + name + "' cannot be parsed, null parser. " +
        "Please ensure the content of this attribute matches its assignment method.");
  }
  return consumeAttributeWithParser(name, parser);
}
 
Example #7
Source File: AbstractBeanJsonCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an implementation of {@link AbstractBeanJsonSerializer} for the type given in
 * parameter
 *
 * @return the information about the created class
 * @throws com.google.gwt.core.ext.UnableToCompleteException if any.
 * @throws com.github.nmorel.gwtjackson.rebind.exception.UnsupportedTypeException if any.
 */
public final BeanJsonMapperInfo create() throws UnableToCompleteException, UnsupportedTypeException {

    final String simpleClassName = isSerializer() ? mapperInfo
            .getSimpleSerializerClassName() : mapperInfo.getSimpleDeserializerClassName();

    PrintWriter printWriter = getPrintWriter( mapperInfo.getPackageName(), simpleClassName );
    // the class already exists, no need to continue
    if ( printWriter == null ) {
        return mapperInfo;
    }

    try {
        TypeSpec type = buildClass( simpleClassName );
        write( mapperInfo.getPackageName(), type, printWriter );
    } finally {
        printWriter.close();
    }

    return mapperInfo;
}
 
Example #8
Source File: AppcacheLinker.java    From gwt-appcache with Apache License 2.0 6 votes vote down vote up
@Override
public ArtifactSet link( @Nonnull final TreeLogger logger,
                         @Nonnull final LinkerContext context,
                         @Nonnull final ArtifactSet artifacts,
                         final boolean onePermutation )
  throws UnableToCompleteException
{
  if ( onePermutation )
  {
    return perPermutationLink( logger, context, artifacts );
  }
  else
  {
    return perCompileLink( logger, context, artifacts );
  }
}
 
Example #9
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 6 votes vote down vote up
/**
 * Consumes a single child element, ignoring any text nodes and throwing an
 * exception if no child is found, or more than one child element is found.
 * 
 * @throws UnableToCompleteException on no children, or too many
 */
public XMLElement consumeSingleChildElement() throws UnableToCompleteException {
  XMLElement ret = null;
  for (XMLElement child : consumeChildElements()) {
    if (ret != null) {
      logger.die(this, "Element may only contain a single child element, but "
          + "found %s and %s.", ret, child);
    }

    ret = child;
  }

  if (ret == null) {
    logger.die(this, "Element must have a single child element");
  }

  return ret;
}
 
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: AbstractInjectorGenerator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
	TypeOracle typeOracle = context.getTypeOracle();
	assert typeOracle != null;

	JClassType viewType = typeOracle.findType(typeName);
	if (viewType == null) {
		logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
		throw new UnableToCompleteException();
	}

	C injectorCreator = this.newCreator(viewType);
	if (injectorCreator.shallRebind()) {
		return injectorCreator.create(logger, context);
	}
	return typeName;
}
 
Example #12
Source File: ObjectMapperCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
/**
 * Build the new deserializer method.
 *
 * @param mappedTypeClass the type to map
 *
 * @return the method
 */
private MethodSpec buildNewDeserializerMethod( JClassType mappedTypeClass ) throws UnableToCompleteException {
    JDeserializerType type;
    try {
        type = getJsonDeserializerFromType( mappedTypeClass );
    } catch ( UnsupportedTypeException e ) {
        logger.log( Type.ERROR, "Cannot generate mapper due to previous errors : " + e.getMessage() );
        throw new UnableToCompleteException();
    }

    return MethodSpec.methodBuilder( "newDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( parameterizedName( JsonDeserializer.class, mappedTypeClass ) )
            .addStatement( "return $L", type.getInstance() )
            .build();
}
 
Example #13
Source File: BeanJsonDeserializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private Optional<MethodSpec> buildInitAnySetterDeserializerMethod( PropertyInfo anySetterPropertyInfo )
        throws UnableToCompleteException {

    FieldAccessor fieldAccessor = anySetterPropertyInfo.getSetterAccessor().get();
    JType type = fieldAccessor.getMethod().get().getParameterTypes()[1];

    JDeserializerType deserializerType;
    try {
        deserializerType = getJsonDeserializerFromType( type );
    } catch ( UnsupportedTypeException e ) {
        logger.log( Type.WARN, "Method '" + fieldAccessor.getMethod().get()
                .getName() + "' annotated with @JsonAnySetter has an unsupported type" );
        return Optional.absent();
    }

    return Optional.of( MethodSpec.methodBuilder( "initAnySetterDeserializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( ParameterizedTypeName.get(
                    ClassName.get( AnySetterDeserializer.class ), typeName( beanInfo.getType() ), DEFAULT_WILDCARD ) )
            .addStatement( "return $L", buildDeserializer( anySetterPropertyInfo, type, deserializerType ) )
            .build() );
}
 
Example #14
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
private List<String> finalizeTree(CssTree cssTree) throws UnableToCompleteException {
  new CheckDependencyNodes(cssTree.getMutatingVisitController(), errorManager, false).runPass();

  // Don't continue if errors exist
  checkErrors();

  new CreateStandardAtRuleNodes(cssTree.getMutatingVisitController(), errorManager).runPass();
  new CreateMixins(cssTree.getMutatingVisitController(), errorManager).runPass();
  new CreateDefinitionNodes(cssTree.getMutatingVisitController(), errorManager).runPass();
  new CreateConstantReferences(cssTree.getMutatingVisitController()).runPass();
  new CreateConditionalNodes(cssTree.getMutatingVisitController(), errorManager).runPass();
  new CreateRuntimeConditionalNodes(cssTree.getMutatingVisitController()).runPass();
  new CreateComponentNodes(cssTree.getMutatingVisitController(), errorManager).runPass();

  new HandleUnknownAtRuleNodes(cssTree.getMutatingVisitController(), errorManager,
      allowedAtRules, true, false).runPass();
  new ProcessKeyframes(cssTree.getMutatingVisitController(), errorManager, true, true).runPass();
  new ProcessRefiners(cssTree.getMutatingVisitController(), errorManager, true).runPass();

  PermutationsCollector permutationsCollector = new PermutationsCollector(cssTree
      .getMutatingVisitController(), errorManager);
  permutationsCollector.runPass();

  return permutationsCollector.getPermutationAxes();
}
 
Example #15
Source File: BeanJsonDeserializerCreator.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private MethodSpec buildInitIdentityInfoMethod( BeanIdentityInfo identityInfo )
        throws UnableToCompleteException, UnsupportedTypeException {

    MethodSpec.Builder builder = MethodSpec.methodBuilder( "initIdentityInfo" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .returns( parameterizedName( IdentityDeserializationInfo.class, beanInfo.getType() ) );

    if ( identityInfo.isIdABeanProperty() ) {
        builder.addStatement( "return $L", buildPropertyIdentifierDeserializationInfo( beanInfo.getType(), identityInfo ) );
    } else {
        builder.addStatement( "return $L",
                buildIdentifierDeserializationInfo( beanInfo.getType(), identityInfo,
                        getJsonDeserializerFromType( identityInfo.getType().get() ) ) );
    }

    return builder.build();
}
 
Example #16
Source File: ProductConfigGenerator.java    From core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();

    try {
        // get classType and save instance variables
        JClassType classType = typeOracle.getType(typeName);
        packageName = classType.getPackage().getName();
        className = classType.getSimpleSourceName() + "Impl";

        // Generate class source code
        generateClass(logger, context);

    } catch (Throwable e) {
        // record to logger that Map generation threw an exception
        e.printStackTrace(System.out);
        logger.log(TreeLogger.ERROR, "Failed to generate product config", e);
    }

    // return the fully qualified name of the class generated
    return packageName + "." + className;
}
 
Example #17
Source File: JsonGwtJacksonGenerator.java    From requestor with Apache License 2.0 5 votes vote down vote up
@Override
public String generate(TreeLogger logger, GeneratorContext ctx, String typeName) throws UnableToCompleteException {
    TypeOracle typeOracle = ctx.getTypeOracle();
    assert typeOracle != null;

    JClassType intfType = typeOracle.findType(typeName);
    if (intfType == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }

    if (intfType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, intfType.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }

    // TODO: check if type was already generated and reuse it
    TreeLogger typeLogger = logger.branch(TreeLogger.ALL, "Generating Json SerDes powered by Gwt Jackson...", null);
    final SourceWriter sourceWriter = getSourceWriter(typeLogger, ctx, intfType);

    if (sourceWriter != null) {
        sourceWriter.println();

        final ArrayList<String> serdes = new ArrayList<String>();
        for (JClassType type : typeOracle.getTypes()) {
            Json annotation = type.getAnnotation(Json.class);
            if (annotation != null) {
                serdes.add(generateSerdes(sourceWriter, type, annotation));
            }
        }

        generateFields(sourceWriter);
        generateConstructor(sourceWriter, serdes);
        generateMethods(sourceWriter);

        sourceWriter.commit(typeLogger);
    }

    return typeName + "Impl";
}
 
Example #18
Source File: Css2GssTest.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private void assertFileContentEqualsAfterConversion(String inputCssFile,
    String expectedGssFile, boolean lenient) throws IOException, UnableToCompleteException {
  URL resource = Css2GssTest.class.getResource(inputCssFile);
  InputStream stream = Css2GssTest.class.getResourceAsStream(expectedGssFile);
  String convertedGss = new Css2Gss(resource, lenient).toGss();
  String gss = IOUtils.toString(stream, "UTF-8");
  Assert.assertEquals(gss, convertedGss);
}
 
Example #19
Source File: AppcacheLinkerTest.java    From gwt-appcache with Apache License 2.0 5 votes vote down vote up
@Test
public void createPermutationMap()
  throws UnableToCompleteException, IOException
{
  final AppcacheLinker linker = new AppcacheLinker();
  final ArrayList<PermutationArtifact> artifacts1 = new ArrayList<>();
  final Permutation permutation = new Permutation( "X" );

  artifacts1.add( new PermutationArtifact( AppcacheLinker.class, permutation ) );
  final List<BindingProperty> configs2 = new ArrayList<>();
  bp( configs2, "user.agent", "ie9" );
  permutation.getSelectors().add( new SelectionDescriptor( "X", configs2 ) );

  final LinkerContext linkerContext = mock( LinkerContext.class );
  when( linkerContext.getModuleName() ).thenReturn( "myapp" );

  final EmittedArtifact artifacts = linker.createPermutationMap( TreeLogger.NULL, artifacts1 );
  assertEquals( artifacts.getVisibility(), Visibility.Public );
  assertEquals( artifacts.getPartialPath(), "permutations.xml" );
  assertTrue( ( artifacts.getLastModified() - System.currentTimeMillis() < 1000L ) );
  final String content = toContents( artifacts );
  assertEquals( content, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
                         "<permutations>\n" +
                         "<permutation name=\"X\">\n" +
                         "<user.agent>ie9</user.agent>\n" +
                         "</permutation>\n" +
                         "</permutations>\n" );
}
 
Example #20
Source File: RestServiceBinderGenerator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String generate(TreeLogger logger, GeneratorContext context, String restServiceClassName)
	throws UnableToCompleteException {
	TypeOracle typeOracle = context.getTypeOracle();
	assert typeOracle != null;

	JClassType restServiceType = typeOracle.findType(restServiceClassName);
	if (restServiceType == null) {
		logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + restServiceClassName + "'", null);
		throw new UnableToCompleteException();
	}

	JClassType handlerType = null;
	JClassType serviceType = null;
	for (JClassType interfaceType : restServiceType.getImplementedInterfaces()) {
		if (interfaceType.getQualifiedSourceName().equals(ServiceProxy.class.getCanonicalName())
			&& interfaceType instanceof JParameterizedType) {
			JParameterizedType paramType = (JParameterizedType) interfaceType;
			handlerType = paramType.getTypeArgs()[0];
			serviceType = paramType.getTypeArgs()[1];
		}
	}
	if (serviceType == null) {
		logger.log(TreeLogger.ERROR,
			restServiceType.getQualifiedSourceName() + " must implement " + ServiceProxy.class.getCanonicalName()
				+ " with explicit Type Parameters", null);
		throw new UnableToCompleteException();
	}

	RestServiceBinderCreator serviceBinderCreator =
		new RestServiceBinderCreator(restServiceType, serviceType, handlerType);
	return serviceBinderCreator.create(logger, context);
}
 
Example #21
Source File: ServiceBinderCreator.java    From putnami-web-toolkit with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void generateServiceImplementation(TreeLogger logger, SourceWriter srcWriter)
	throws UnableToCompleteException {
	Set<String> addedMethods = Sets.newHashSet();
	for (JMethod method : this.serviceType.getOverridableMethods()) {
		if (!addedMethods.contains(method.getName())) {
			addedMethods.add(method.getName());
			this.writeStartMethod(srcWriter, method);
			this.writeCommandDefinition(logger, srcWriter, method, null);
			this.writeCommandParam(srcWriter, method, this.listCallbackMethods(logger, method), null);
			this.writeEndMethod(srcWriter, method);
		}
	}
}
 
Example #22
Source File: BeanProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static String extractTypeMetadata( TreeLogger logger, RebindConfiguration configuration, JClassType baseType, JClassType
        subtype, JsonTypeInfo typeInfo, Optional<JsonSubTypes> propertySubTypes, Optional<JsonSubTypes> baseSubTypes,
                                           ImmutableList<JClassType> allSubtypes ) throws UnableToCompleteException {
    switch ( typeInfo.use() ) {
        case NAME:
            // we first look the name on JsonSubTypes annotations. Top ones override the bottom ones.
            String name = findNameOnJsonSubTypes( baseType, subtype, allSubtypes, propertySubTypes, baseSubTypes );
            if ( null != name && !"".equals( name ) ) {
                return name;
            }

            // we look if the name is defined on the type with JsonTypeName
            Optional<JsonTypeName> typeName = findFirstEncounteredAnnotationsOnAllHierarchy( configuration, subtype, JsonTypeName
                    .class );
            if ( typeName.isPresent() && !Strings.isNullOrEmpty( typeName.get().value() ) ) {
                return typeName.get().value();
            }

            // we use the default name (ie simple name of the class)
            String simpleBinaryName = subtype.getQualifiedBinaryName();
            int indexLastDot = simpleBinaryName.lastIndexOf( '.' );
            if ( indexLastDot != -1 ) {
                simpleBinaryName = simpleBinaryName.substring( indexLastDot + 1 );
            }
            return simpleBinaryName;
        case MINIMAL_CLASS:
            if ( !baseType.getPackage().isDefault() ) {
                String basePackage = baseType.getPackage().getName();
                if ( subtype.getQualifiedBinaryName().startsWith( basePackage + "." ) ) {
                    return subtype.getQualifiedBinaryName().substring( basePackage.length() );
                }
            }
        case CLASS:
            return subtype.getQualifiedBinaryName();
        default:
            logger.log( TreeLogger.Type.ERROR, "JsonTypeInfo.Id." + typeInfo.use() + " is not supported" );
            throw new UnableToCompleteException();
    }
}
 
Example #23
Source File: ObjectMapperCreator.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the parameter's type.
 *
 * @param clazz the name of the interface
 * @param parameterizedType the parameterized type
 *
 * @return the extracted type
 * @throws UnableToCompleteException if the type contains zero or more than one parameter
 */
private JClassType extractParameterizedType( String clazz, JParameterizedType parameterizedType ) throws UnableToCompleteException {
    if ( parameterizedType == null ) {
        logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify a parameterized type." );
        throw new UnableToCompleteException();
    }
    JClassType[] typeParameters = parameterizedType.getTypeArgs();
    if ( typeParameters == null || typeParameters.length != 1 ) {
        logger.log( TreeLogger.Type.ERROR, "Expected the " + clazz + " declaration to specify 1 parameterized type." );
        throw new UnableToCompleteException();
    }
    return typeParameters[0];
}
 
Example #24
Source File: EventBinderWriterTest.java    From gwteventbinder with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFailOnTwoParameters() throws Exception {
  JMethod method = newMethod("myMethod", mock(JType.class), mock(JType.class));
  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 #25
Source File: BeanJsonSerializerCreator.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private void buildBeanPropertySerializerBody( TypeSpec.Builder builder, JClassType beanType, PropertyInfo property, JSerializerType
        serializerType ) throws UnableToCompleteException {
    String paramName = "bean";
    Accessor getterAccessor = property.getGetterAccessor().get().getAccessor( paramName );

    MethodSpec.Builder newSerializerMethodBuilder = MethodSpec.methodBuilder( "newSerializer" )
            .addModifiers( Modifier.PROTECTED )
            .addAnnotation( Override.class )
            .addStatement( "return $L", serializerType.getInstance() );
    if ( property.isAnyGetter() ) {
        newSerializerMethodBuilder.returns( MapJsonSerializer.class );
    } else {
        newSerializerMethodBuilder.returns( ParameterizedTypeName.get( ClassName.get( JsonSerializer.class ), DEFAULT_WILDCARD ) );
    }
    builder.addMethod( newSerializerMethodBuilder.build() );

    Optional<MethodSpec> paramMethod = generatePropertySerializerParameters( property, serializerType );
    if ( paramMethod.isPresent() ) {
        builder.addMethod( paramMethod.get() );
    }

    builder.addMethod( MethodSpec.methodBuilder( "getValue" )
                    .addModifiers( Modifier.PUBLIC )
                    .addAnnotation( Override.class )
                    .returns( typeName( true, property.getType() ) ) // the boxed type is specified so we can't return a primitive
                    .addParameter( typeName( beanType ), paramName )
                    .addParameter( JsonSerializationContext.class, "ctx" )
                    .addStatement( "return $L", getterAccessor.getAccessor() )
                    .build()
    );

    if ( getterAccessor.getAdditionalMethod().isPresent() ) {
        builder.addMethod( getterAccessor.getAdditionalMethod().get() );
    }
}
 
Example #26
Source File: Css2Gss.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
public String toGss() throws UnableToCompleteException {
    try {
      CssStylesheet sheet = GenerateCssAst.exec(treeLogger, cssFile);


      DefCollectorVisitor defCollectorVisitor = new DefCollectorVisitor(lenient, treeLogger);
      defCollectorVisitor.accept(sheet);
      defNameMapping = defCollectorVisitor.getDefMapping();

      new UndefinedConstantVisitor(new HashSet<String>(defNameMapping.values()),
          lenient, treeLogger).accept(sheet);

      new ElseNodeCreator().accept(sheet);

      new AlternateAnnotationCreatorVisitor().accept(sheet);

      new FontFamilyVisitor().accept(sheet);

      GssGenerationVisitor gssGenerationVisitor = new GssGenerationVisitor(
          new DefaultTextOutput(false), defNameMapping, lenient, treeLogger);
      gssGenerationVisitor.accept(sheet);

      return gssGenerationVisitor.getContent();
    } finally {
      if (printWriter != null) {
        printWriter.flush();
      }
    }
}
 
Example #27
Source File: Offline.java    From gwtbootstrap3-extras with Apache License 2.0 5 votes vote down vote up
@Override
public ArtifactSet link(final TreeLogger logger, final LinkerContext context, final ArtifactSet artifacts) throws UnableToCompleteException {

    final ArtifactSet artifactset = new ArtifactSet(artifacts);

    final HashSet<String> resources = new HashSet<String>();
    for (final EmittedArtifact emitted : artifacts.find(EmittedArtifact.class)) {

        if (skipArtifact(emitted))
            continue;
        resources.add(emitted.getPartialPath());
    }

    final SortedSet<ConfigurationProperty> staticFileProperties = context.getConfigurationProperties();
    for (final ConfigurationProperty configurationProperty : staticFileProperties) {
        final String name = configurationProperty.getName();
        if (CACHEMANIFEST_STATIC_FILES_PROPERTY.equals(name)) {
            for (final String value : configurationProperty.getValues()) {
                resources.add(value);
            }
        }
    }

    final String manifestString = buildManifestContents(resources);
    if (manifestString != null) {
        final EmittedArtifact manifest = emitString(logger, manifestString, "appcache.manifest");
        artifactset.add(manifest);
    }
    return artifactset;
}
 
Example #28
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 5 votes vote down vote up
/**
 * Consumes the named attribute and parses it to an array of String
 * expressions. The strings in the attribute may be comma or space separated
 * (or a mix of both).
 * 
 * @return array of String expressions, empty if the attribute was not set.
 * @throws UnableToCompleteException on unparseable value
 */
public String[] consumeStringArrayAttribute(String name) throws UnableToCompleteException {
  AttributeParser parser = attributeParsers.getParser(getStringType());

  String[] strings = consumeRawArrayAttribute(name);
  for (int i = 0; i < strings.length; i++) {
    strings[i] = parser.parse(this, strings[i]);
  }
  designTime.putAttribute(this, name, strings);
  return strings;
}
 
Example #29
Source File: AppcacheLinkerTest.java    From gwt-appcache with Apache License 2.0 5 votes vote down vote up
private String toContents( final EmittedArtifact artifacts )
  throws UnableToCompleteException, IOException
{
  final InputStream contents = artifacts.getContents( TreeLogger.NULL );
  final StringBuilder sb = new StringBuilder();
  int ch;
  while ( -1 != ( ch = contents.read() ) )
  {
    sb.append( (char) ch );
  }
  return sb.toString();
}
 
Example #30
Source File: XMLElement.java    From gwt-material-demo with Apache License 2.0 5 votes vote down vote up
/**
 * Consumes the named attribute, or dies if it is missing.
 */
public String consumeRequiredRawAttribute(String name) throws UnableToCompleteException {
  String value = consumeRawAttribute(name);
  if (value == null) {
    failRequired(name);
  }
  return value;
}