Java Code Examples for com.google.gwt.core.ext.TreeLogger#log()

The following examples show how to use com.google.gwt.core.ext.TreeLogger#log() . 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: AppcacheLinker.java    From gwt-appcache with Apache License 2.0 6 votes vote down vote up
@Nonnull
final Map<String, String> parseFallbackResources( @Nonnull final TreeLogger logger,
                                                  @Nonnull final Set<String> values )
  throws UnableToCompleteException
{
  final HashMap<String, String> fallbackFiles = new HashMap<>();
  for ( final String line : values )
  {
    final String[] elements = line.trim().split( " +" );
    if ( 2 != elements.length )
    {
      final String message = FALLBACK_FILES_CONFIGURATION_PROPERTY_NAME + " property value '" +
                             line + "' should have two url paths separated by whitespace";
      logger.log( Type.ERROR, message );
      throw new UnableToCompleteException();
    }
    fallbackFiles.put( elements[ 0 ], elements[ 1 ] );
  }

  return fallbackFiles;
}
 
Example 2
Source File: EventBinderGenerator.java    From gwteventbinder with Apache License 2.0 6 votes vote down vote up
@Override
public String generate(TreeLogger logger, GeneratorContext context,
    String typeName) throws UnableToCompleteException {
  try {
    JClassType eventBinderType = context.getTypeOracle().getType(typeName);
    JClassType targetType = getTargetType(eventBinderType, context.getTypeOracle());
    SourceWriter writer = createSourceWriter(logger, context, eventBinderType, targetType);
    if (writer != null) { // Otherwise the class was already created
      new EventBinderWriter(
          logger,
          context.getTypeOracle().getType(GenericEvent.class.getCanonicalName()))
              .writeDoBindEventHandlers(targetType, writer, context.getTypeOracle());
      writer.commit(logger);
    }
    return getFullyQualifiedGeneratedClassName(eventBinderType);
  } catch (NotFoundException e) {
    logger.log(Type.ERROR, "Error generating " + typeName, e);
    throw new UnableToCompleteException();
  }
}
 
Example 3
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 4
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 5
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 6 votes vote down vote up
private String concatCssFiles(List<URL> resources, TreeLogger logger)
    throws UnableToCompleteException {
  StringBuffer buffer = new StringBuffer();
  for (URL stylesheet : resources) {
    try {
      String fileContent = Resources.asByteSource(stylesheet).asCharSource(Charsets.UTF_8)
          .read();
      buffer.append(fileContent);
      buffer.append("\n");

    } catch (IOException e) {
      logger.log(TreeLogger.ERROR, "Unable to parse CSS", e);
      throw new UnableToCompleteException();
    }
  }
  return buffer.toString();
}
 
Example 6
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 6 votes vote down vote up
private static JType findType( TreeLogger logger, PropertyAccessors fieldAccessors, JacksonTypeOracle typeOracle,
		boolean getterAutoDetected, boolean setterAutoDetected, boolean fieldAutoDetected ) throws UnableToCompleteException {
    JType type;
    if ( getterAutoDetected && fieldAccessors.getGetter().isPresent() ) {
        type = fieldAccessors.getGetter().get().getReturnType();
    } else if ( setterAutoDetected && fieldAccessors.getSetter().isPresent() ) {
        type = fieldAccessors.getSetter().get().getParameters()[0].getType();
    } else if ( fieldAutoDetected && fieldAccessors.getField().isPresent() ) {
        type = fieldAccessors.getField().get().getType();
    } else if ( fieldAccessors.getParameter().isPresent() ) {
        type = fieldAccessors.getParameter().get().getType();
    } else {
        logger.log( Type.ERROR, "Cannot find the type of the property " + fieldAccessors.getPropertyName() );
        throw new UnableToCompleteException();
    }

    Optional<Annotation> jd = fieldAccessors.getAnnotation( "com.fasterxml.jackson.databind.annotation.JsonDeserialize" );
    if ( jd.isPresent() ) {
        return typeOracle.replaceType( logger, type, jd.get() );
    }

    return type;
}
 
Example 7
Source File: TextBinderGenerator.java    From EasyML with Apache License 2.0 5 votes vote down vote up
/**
 * Generate method bind
 */
private void composeBindMethod(TreeLogger logger, SourceWriter sourceWriter) {

	logger.log(TreeLogger.INFO, "");
	String line = "public void bind("
			+ parameterizedType1.getQualifiedSourceName() + " text, "
			+ parameterizedType2.getQualifiedSourceName() + " obj){";
	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

	line = "  System.out.println(\"Implement it now:)\");";
	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

	ArrayList<JField> fields = new ArrayList<JField>();

	JClassType curtype = parameterizedType2;
	do {

		for (JField filed : curtype.getFields()) {
			fields.add(filed);
		}
		curtype = curtype.getSuperclass();
	} while (!curtype.getName().equals("Object"));

	for (JField field : fields) {
		String name = field.getName();
		String Name = name.substring(0, 1).toUpperCase() + name.substring(1);
		line = " text.setText(\"" + name + "\", obj.get" + Name
				+ "().toString() );";
		sourceWriter.println(line);
		logger.log(TreeLogger.INFO, line);

	}
	line = "}";

	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

}
 
Example 8
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 9
Source File: JacksonTypeOracle.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
/**
 * <p>getClassFromJsonDeserializeAnnotation</p>
 *
 * @param logger a {@link com.google.gwt.core.ext.TreeLogger} object.
 * @param annotation a {@link java.lang.annotation.Annotation} object.
 * @param name a {@link java.lang.String} object.
 * @return a {@link com.google.gwt.thirdparty.guava.common.base.Optional} object.
 */
public Optional<JClassType> getClassFromJsonDeserializeAnnotation( TreeLogger logger, Annotation annotation, String name ) {
    try {
        Class asClass = (Class) annotation.getClass().getDeclaredMethod( name ).invoke( annotation );
        if ( asClass != Void.class ) {
            return Optional.fromNullable( getType( asClass.getCanonicalName() ) );
        }
    } catch ( Exception e ) {
        logger.log( Type.ERROR, "Cannot find method " + name + " on JsonDeserialize annotation", e );
    }
    return Optional.absent();
}
 
Example 10
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
private static void processBeanAnnotation( TreeLogger logger, JacksonTypeOracle typeOracle, RebindConfiguration configuration, JType
        type, PropertyAccessors propertyAccessors, PropertyInfoBuilder builder ) throws UnableToCompleteException {

    // identity
    Optional<JsonIdentityInfo> jsonIdentityInfo = propertyAccessors.getAnnotation( JsonIdentityInfo.class );
    Optional<JsonIdentityReference> jsonIdentityReference = propertyAccessors.getAnnotation( JsonIdentityReference.class );

    // type info
    Optional<JsonTypeInfo> jsonTypeInfo = propertyAccessors.getAnnotation( JsonTypeInfo.class );
    Optional<JsonSubTypes> propertySubTypes = propertyAccessors.getAnnotation( JsonSubTypes.class );

    // if no annotation is present that overrides bean processing, we just stop now
    if ( !jsonIdentityInfo.isPresent() && !jsonIdentityReference.isPresent() && !jsonTypeInfo.isPresent() && !propertySubTypes
            .isPresent() ) {
        // no override on field
        return;
    }

    // we need to find the bean to apply annotation on
    Optional<JClassType> beanType = extractBeanType( logger, typeOracle, type, builder.getPropertyName() );

    if ( beanType.isPresent() ) {
        if ( jsonIdentityInfo.isPresent() || jsonIdentityReference.isPresent() ) {
            builder.setIdentityInfo( BeanProcessor.processIdentity( logger, typeOracle, configuration, beanType
                    .get(), jsonIdentityInfo, jsonIdentityReference ) );
        }

        if ( jsonTypeInfo.isPresent() || propertySubTypes.isPresent() ) {
            builder.setTypeInfo( BeanProcessor.processType( logger, typeOracle, configuration, beanType
                    .get(), jsonTypeInfo, propertySubTypes ) );
        }
    } else {
        logger.log( Type.WARN, "Annotation present on property " + builder.getPropertyName() + " but no valid bean has been found." );
    }
}
 
Example 11
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 12
Source File: Mvp4gGenerator.java    From mvp4g with Apache License 2.0 5 votes vote down vote up
@Override
public RebindResult generateIncrementally(TreeLogger logger,
                                          GeneratorContext generatorContext,
                                          String moduleClass)
  throws UnableToCompleteException {

  TypeOracle typeOracle = generatorContext.getTypeOracle();
  assert (typeOracle != null);

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

  if (module.isInterface() == null) {
    logger.log(TreeLogger.ERROR,
               "'" + moduleClass + "' is not a interface");
    throw new UnableToCompleteException();
  }

  TreeLogger moduleLogger = logger.branch(TreeLogger.DEBUG,
                                          "Generating mvp4g configuration for module class '" + module.getQualifiedSourceName() + "'",
                                          null);

  return create(moduleLogger,
                generatorContext,
                moduleClass);
}
 
Example 13
Source File: ClientEngineLinker.java    From flow with Apache License 2.0 5 votes vote down vote up
private Script getScript(TreeLogger logger, ArtifactSet artifacts)
        throws UnableToCompleteException {
    Set<Script> results = artifacts.find(Script.class);
    if (results.size() != 1) {
        logger.log(TreeLogger.ERROR,
                "The module must have exactly one distinct"
                        + " permutation when using the " + getDescription()
                        + " Linker; found " + results.size(),
                null);
        throw new UnableToCompleteException();
    }
    return results.iterator().next();
}
 
Example 14
Source File: GadgetLinker.java    From shortyz with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected EmittedArtifact emitSelectionScript(TreeLogger logger,
    LinkerContext context, ArtifactSet artifacts)
    throws UnableToCompleteException {
    logger = logger.branch(TreeLogger.DEBUG, "Building gadget manifest",
            null);

    String bootstrap = "<script>" +
        context.optimizeJavaScript(logger,
            generateSelectionScript(logger, context, artifacts)) +
        "</script>\n" + "<div id=\"__gwt_gadget_content_div\"></div>";

    // Read the content
    StringBuffer manifest = new StringBuffer();

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(
                    manifestArtifact.getContents(logger)));

        for (String line = in.readLine(); line != null;
                line = in.readLine()) {
            manifest.append(line).append("\n");
        }

        in.close();
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "Unable to read manifest stub", e);
        throw new UnableToCompleteException();
    }

    replaceAll(manifest, "__BOOTSTRAP__", bootstrap);

    return emitString(logger, manifest.toString(),
        manifestArtifact.getPartialPath());
}
 
Example 15
Source File: GssResourceGenerator.java    From gss.gwt with Apache License 2.0 5 votes vote down vote up
private boolean writeClassMethod(TreeLogger logger, JMethod userMethod,
    Map<String, String> substitutionMap, SourceWriter sw) throws
    UnableToCompleteException {

  if (!isReturnTypeString(userMethod.getReturnType().isClass())) {
    logger.log(Type.ERROR, "The return type of the method [" + userMethod.getName() + "] must " +
        "be java.lang.String.");
    throw new UnableToCompleteException();
  }

  if (userMethod.getParameters().length > 0) {
    logger.log(Type.ERROR, "The method [" + userMethod.getName() + "] shouldn't contain any " +
        "parameters");
    throw new UnableToCompleteException();
  }

  String name = getClassName(userMethod);

  String value = substitutionMap.get(name);

  if (value == null) {
    logger.log(Type.ERROR, "The following style class [" + name + "] is missing from the source" +
        " CSS file");
    return false;
  } else {
    writeSimpleGetter(userMethod, "\"" + value + "\"", sw);
  }

  return true;
}
 
Example 16
Source File: Mvp4gGenerator.java    From mvp4g with Apache License 2.0 4 votes vote down vote up
private RebindResult create(TreeLogger logger,
                            GeneratorContext context,
                            String moduleName)
  throws UnableToCompleteException {

  Date start = new Date();

  String generatedClassQualifiedName;

  try {
    TypeOracle typeOracle = context.getTypeOracle();

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

    @SuppressWarnings("unchecked") Map<Class<? extends Annotation>, List<JClassType>> scanResult = AnnotationScanner.scan(logger,
                                                                                                                          typeOracle,
                                                                                                                          new Class[] { Presenter.class,
                                                                                                                                        History.class,
                                                                                                                                        Events.class,
                                                                                                                                        Service.class,
                                                                                                                                        EventHandler.class });

    Mvp4gConfiguration configuration = new Mvp4gConfiguration(logger,
                                                              context);

    String suffix = "Impl" +
                    configuration.load(module,
                                       scanResult);

    generatedClassQualifiedName = module.getParameterizedQualifiedSourceName() + suffix;

    String packageName = module.getPackage()
                               .getName();
    String originalClassName  = module.getSimpleSourceName();
    String generatedClassName = originalClassName + suffix;

    // check weather there is a usual version or not.
    if (checkAlreadyGenerated(logger,
                              context,
                              configuration)) {
      // Log
      logger.log(TreeLogger.INFO,
                 "Reuse already generated files",
                 null);
      // stop generating
      return new RebindResult(RebindMode.USE_EXISTING,
                              packageName + "." + generatedClassName);
    }

    // Log
    logger.log(TreeLogger.INFO,
               "Start generate files ... ",
               null);

    // No, there is non. Create a new one.
    SourceWriter sourceWriter = getSourceWriter(logger,
                                                context,
                                                module,
                                                packageName,
                                                generatedClassName);

    if (sourceWriter != null) {
      logger.log(TreeLogger.INFO,
                 "Generating source for " + generatedClassQualifiedName + " ",
                 null);
      Mvp4gConfigurationFileWriter writer = new Mvp4gConfigurationFileWriter(sourceWriter,
                                                                             configuration);
      writer.writeConf();
      sourceWriter.commit(logger);
    } else {
      // don't expect this to occur, but could happen if an instance was
      // recently generated but not yet committed
      new RebindResult(RebindMode.USE_EXISTING,
                       generatedClassQualifiedName);
    }

    Date end = new Date();

    logger.log(TreeLogger.INFO,
               "Mvp4g Compilation: " + (end.getTime() - start.getTime()) + "ms.");

    return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING,
                            packageName + "." + generatedClassName);
  } catch (InvalidMvp4gConfigurationException e) {
    logger.log(TreeLogger.ERROR,
               e.getMessage(),
               e);
    throw new UnableToCompleteException();
  }
}
 
Example 17
Source File: PropertyProcessor.java    From gwt-jackson with Apache License 2.0 4 votes vote down vote up
/**
 * Extract the bean type from the type given in parameter. For {@link java.util.Collection}, it gives the bounded type. For {@link
 * java.util.Map}, it gives the second bounded type. Otherwise, it gives the type given in parameter.
 *
 * @param type type to extract the bean type
 * @param propertyName name of the property
 *
 * @return the extracted type
 */
private static Optional<JClassType> extractBeanType( TreeLogger logger, JacksonTypeOracle typeOracle, JType type, String propertyName
) {
    if ( null != type.isWildcard() ) {
        // we use the base type to find the serializer to use
        type = type.isWildcard().getBaseType();
    }

    if ( null != type.isRawType() ) {
        type = type.isRawType().getBaseType();
    }

    JArrayType arrayType = type.isArray();
    if ( null != arrayType ) {
        return extractBeanType( logger, typeOracle, arrayType.getComponentType(), propertyName );
    }

    JClassType classType = type.isClassOrInterface();
    if ( null == classType ) {
        return Optional.absent();
    } else if ( typeOracle.isIterable( classType ) ) {
        if ( (null == classType.isParameterized() || classType.isParameterized().getTypeArgs().length != 1) && (null == classType
                .isGenericType() || classType.isGenericType().getTypeParameters().length != 1) ) {
            logger.log( Type.INFO, "Expected one argument for the java.lang.Iterable '" + propertyName + "'. Applying annotations to " +
                    "type " + classType.getParameterizedQualifiedSourceName() );
            return Optional.of( classType );
        }
        if ( null != classType.isParameterized() ) {
            return extractBeanType( logger, typeOracle, classType.isParameterized().getTypeArgs()[0], propertyName );
        } else {
            return extractBeanType( logger, typeOracle, classType.isGenericType().getTypeParameters()[0].getBaseType(), propertyName );
        }
    } else if ( typeOracle.isMap( classType ) ) {
        if ( (null == classType.isParameterized() || classType.isParameterized().getTypeArgs().length != 2) && (null == classType
                .isGenericType() || classType.isGenericType().getTypeParameters().length != 2) ) {
            logger.log( Type.INFO, "Expected two arguments for the java.util.Map '" + propertyName + "'. Applying annotations to " +
                    "type " + classType.getParameterizedQualifiedSourceName() );
            return Optional.of( classType );
        }
        if ( null != classType.isParameterized() ) {
            return extractBeanType( logger, typeOracle, classType.isParameterized().getTypeArgs()[1], propertyName );
        } else {
            return extractBeanType( logger, typeOracle, classType.isGenericType().getTypeParameters()[1].getBaseType(), propertyName );
        }
    } else {
        return Optional.of( classType );
    }
}
 
Example 18
Source File: AppcacheLinker.java    From gwt-appcache with Apache License 2.0 4 votes vote down vote up
/**
 * Return the permutation for a single link step.
 */
@Nullable
final Permutation calculatePermutation( @Nonnull final TreeLogger logger,
                                        @Nonnull final LinkerContext context,
                                        @Nonnull final ArtifactSet artifacts )
  throws UnableToCompleteException
{
  Permutation permutation = null;

  for ( final SelectionInformation result : artifacts.find( SelectionInformation.class ) )
  {
    final String strongName = result.getStrongName();
    if ( null != permutation && !permutation.getPermutationName().equals( strongName ) )
    {
      throw new UnableToCompleteException();
    }
    if ( null == permutation )
    {
      permutation = new Permutation( strongName );
      final Set<String> artifactsForCompilation = getArtifactsForCompilation( context, artifacts );
      permutation.getPermutationFiles().addAll( artifactsForCompilation );
    }
    final List<BindingProperty> list = new ArrayList<>();
    for ( final SelectionProperty property : context.getProperties() )
    {
      if ( !property.isDerived() )
      {
        final String name = property.getName();
        final String value = result.getPropMap().get( name );
        if ( null != value )
        {
          list.add( new BindingProperty( name, value ) );
        }
      }
    }
    final SelectionDescriptor selection = new SelectionDescriptor( strongName, list );
    final List<SelectionDescriptor> selectors = permutation.getSelectors();
    if ( !selectors.contains( selection ) )
    {
      selectors.add( selection );
    }
  }
  if ( null != permutation )
  {
    logger.log( Type.DEBUG, "Calculated Permutation: " + permutation.getPermutationName() +
                            " Selectors: " + permutation.getSelectors() );
  }
  return permutation;
}
 
Example 19
Source File: TextBinderGenerator.java    From EasyML with Apache License 2.0 4 votes vote down vote up
/**
 * Generate method sync
 */
private void composeSyncMethod(TreeLogger logger, SourceWriter sourceWriter) {

	logger.log(TreeLogger.INFO, "");
	String line = "public void sync("
			+ parameterizedType1.getQualifiedSourceName() + " text, "
			+ parameterizedType2.getQualifiedSourceName() + " obj){";
	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

	line = "  System.out.println(\"Implement it now:)\");";
	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

	ArrayList<JField> fields = new ArrayList<JField>();

	JClassType curtype = parameterizedType2;
	do {

		for (JField filed : curtype.getFields()) {
			fields.add(filed);
		}
		curtype = curtype.getSuperclass();
	} while (!curtype.getName().equals("Object"));

	for (JField field : fields) {
		String name = field.getName();
		String Name = name.substring(0, 1).toUpperCase() + name.substring(1);
		String type = field.getType().getQualifiedSourceName();
		String simType = field.getType().getSimpleSourceName();
		if ("java.lang.String".equals(type))
			line = " if( text.getText(\"" + name + "\") != null )obj.set" + Name
			+ "( text.getText(\"" + name + "\") );";
		else
			line = " if( text.getText(\"" + name + "\") != null )obj.set" + Name
			+ "( " + type + ".parse" + simType + "( text.getText(\"" + name
			+ "\")) );";

		sourceWriter.println(line);
		logger.log(TreeLogger.INFO, line);

	}
	line = "}";

	sourceWriter.println(line);
	logger.log(TreeLogger.INFO, line);

}
 
Example 20
Source File: TextBinderGenerator.java    From EasyML with Apache License 2.0 4 votes vote down vote up
@Override
public String generate(TreeLogger logger, GeneratorContext context,
		String requestedClass) throws UnableToCompleteException {

	TypeOracle typeOracle = context.getTypeOracle();

	JClassType objectType = typeOracle.findType(requestedClass);
	if (objectType == null) {
		logger.log(TreeLogger.ERROR, "Could not find type: " + requestedClass);
		throw new UnableToCompleteException();
	}

	implTypeName = objectType.getSimpleSourceName() + "Impl";

	implPackageName = objectType.getPackage().getName();

	JClassType[] implementedTypes = objectType.getImplementedInterfaces();

	// Can only implement one interface
	if (implementedTypes == null
			|| implementedTypes.length != 1
			|| !implementedTypes[0].getQualifiedSourceName().equals(
					TextBinder.class.getName())) {
		logger
		.log(
				TreeLogger.ERROR,
				"The type: " + requestedClass
				+ " Must implement only one interface: "
				+ TextBinder.class.getName());
		throw new UnableToCompleteException();
	}

	// Get parameterized type
	JParameterizedType parameterType = implementedTypes[0].isParameterized();
	if (parameterType == null) {
		logger.log(TreeLogger.ERROR, "The type: " + requestedClass
				+ " Must implement only one parameterized interface: "
				+ TextBinder.class.getName());
		throw new UnableToCompleteException();
	}

	if (parameterType.getTypeArgs() == null

			|| parameterType.getTypeArgs().length != 2) {
		logger.log(TreeLogger.ERROR,
				"The type: " + requestedClass
				+ " Must implement two parameterized interface: "
				+ TextBinder.class.getName() + " with two Parameter");
		throw new UnableToCompleteException();

	}

	parameterizedType1 = parameterType.getTypeArgs()[0];
	parameterizedType2 = parameterType.getTypeArgs()[1];
	// logger.log(TreeLogger.INFO ,
	// parameterizedType2.getParameterizedQualifiedSourceName() +"\n"
	// + parameterizedType2.getQualifiedSourceName());

	ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(
			implPackageName, implTypeName);

	composerFactory.addImport(Map.class.getCanonicalName());
	composerFactory.addImport(List.class.getCanonicalName());
	// composerFactory.addImport(Field.class.getCanonicalName());
	composerFactory
	.addImplementedInterface(objectType.getQualifiedSourceName());

	PrintWriter printWriter = context.tryCreate(logger, implPackageName,
			implTypeName);
	if (printWriter != null) {

		SourceWriter sourceWriter = composerFactory.createSourceWriter(context,
				printWriter);

		composeBindMethod(logger, sourceWriter);
		composeSyncMethod(logger, sourceWriter);
		sourceWriter.commit(logger);

	}
	return implPackageName + "." + implTypeName;
}