Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.codehaus.mojo.gwt;
  
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
 
Goal which generate Asyn interface.

Author(s):
Nicolas De Loof
Version:
$Id$
Goal:
generateAsync
Phase:
generate-sources
RequiresDependencyResolution:
compile
 
 public class GenerateAsyncMojo
     extends AbstractGwtMojo
 {
     private static final String REMOTE_SERVICE_INTERFACE = "com.google.gwt.user.client.rpc.RemoteService";
 
     private final static Map<StringStringWRAPPERS = new HashMap<StringString>();
     static
     {
         .put"boolean"Boolean.class.getName() );
         .put"byte"Byte.class.getName() );
         .put"char"Character.class.getName() );
         .put"short"Short.class.getName() );
         .put"int"Integer.class.getName() );
         .put"long"Long.class.getName() );
         .put"float"Float.class.getName() );
         .put"double"Double.class.getName() );
     }

    
Pattern for GWT service interface

Parameter:
default-value="**\/*Service.java"
 
     private String servicePattern;

    
Return a com.google.gwt.http.client.Request on async interface to allow cancellation.

Parameter:
default-value="false"
 
     private boolean returnRequest;

    
A (MessageFormat) Pattern to get the GWT-RPC servlet URL based on service interface name. For example to "{0}.rpc" if you want to map GWT-RPC calls to "*.rpc" in web.xml, for example when using Spring dispatch servlet to handle RPC requests.

Parameter:
default-value="{0}" expression="${gwt.rpcPattern}"
 
     private String rpcPattern;

    
Stop the build on error

Parameter:
default-value="true" expression="${maven.gwt.failOnError}"
    private boolean failOnError;

    
Pattern for GWT service interface

Parameter:
default-value="false" expression="${generateAsync.force}"
    private boolean force;

    

Parameter:
expression="${project.build.sourceEncoding}"
    private String encoding;

    
    @SuppressWarnings"unchecked" )
    public void execute()
        throws MojoExecutionException
    {
        getLog().debug"GenerateAsyncMojo#execute()" );
        if ( "pom".equalsgetProject().getPackaging() ) )
        {
    		getLog().info"GWT generateAsync is skipped" );
    		return;
    	}
        if (  == null )
        {
            getLog().warn"Encoding is not set, your build will be platform dependent" );
             = Charset.defaultCharset().name();
        }
        JavaDocBuilder builder = createJavaDocBuilder();
        List<StringsourceRoots = getProject().getCompileSourceRoots();
        boolean generated = false;
        for ( String sourceRoot : sourceRoots )
        {
            try
            {
                generated |= scanAndGenerateAsyncnew FilesourceRoot ), builder );
            }
            catch ( Throwable e )
            {
                getLog().error"Failed to generate Async interface"e );
                if (  )
                {
                    throw new MojoExecutionException"Failed to generate Async interface"e );
                }
            }
        }
        if ( generated )
        {
            getLog().debug"add compile source root " + getGenerateDirectory() );
            addCompileSourceRootgetGenerateDirectory() );
        }
    }

    

Parameters:
sourceRoot the base directory to scan for RPC services
Returns:
true if some file have been generated
Throws:
java.lang.Exception generation failure
    private boolean scanAndGenerateAsyncFile sourceRootJavaDocBuilder builder )
        throws Exception
    {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedirsourceRoot );
        scanner.setIncludesnew String[] {  } );
        scanner.scan();
        String[] sources = scanner.getIncludedFiles();
        if ( sources.length == 0 )
        {
            return false;
        }
        boolean fileGenerated = false;
        for ( String source : sources )
        {
            File sourceFile = new FilesourceRootsource );
            File targetFile = getTargetFilesource );
            if ( isUpToDatesourceFiletargetFile ) )
            {
                getLog().debugtargetFile.getAbsolutePath() + " is up to date. Generation skipped" );
                // up to date, but still need to report generated-sources directory as sourceRoot
                fileGenerated = true;
                continue;
            }
            String className = getTopLevelClassNamesource );
            JavaClass clazz = builder.getClassByNameclassName );
            if ( isEligibleForGenerationclazz ) )
            {
                targetFile.getParentFile().mkdirs();
                generateAsyncclazztargetFile );
                fileGenerated = true;
            }
        }
        return fileGenerated;
    }
    private boolean isUpToDateFile sourceFileFile targetFile )
    {
        return ! && targetFile.exists() && targetFile.lastModified() > sourceFile.lastModified();
    }
    private File getTargetFileString source )
    {
        String targetFileName = source.substring( 0, source.length() - 5 ) + "Async.java";
        File targetFile = new FilegetGenerateDirectory(), targetFileName );
        return targetFile;
    }

    

Parameters:
clazz the RPC service java class
targetFile RemoteAsync file to generate
Throws:
java.lang.Exception generation failure
    private void generateAsyncJavaClass clazzFile targetFile )
        throws IOException
    {
        PrintWriter writer = new PrintWritertargetFile );
        String className = clazz.getName();
        if ( clazz.getPackage() != null )
        {
            writer.println"package " + clazz.getPackageName() + ";" );
            writer.println();
        }
        writer.println"import com.google.gwt.core.client.GWT;" );
        writer.println"import com.google.gwt.user.client.rpc.AsyncCallback;" );
        writer.println"import com.google.gwt.user.client.rpc.ServiceDefTarget;" );
        writer.println();
        writer.println"public interface " + className + "Async" );
        writer.println"{" );
        JavaMethod[] methods = clazz.getMethodstrue );
        for ( JavaMethod method : methods )
        {
            writer.println"" );
            writer.println"    /**" );
            writer.println"     * GWT-RPC service  asynchronous (client-side) interface" );
            writer.println"     * @see " + clazz.getFullyQualifiedName() );
            writer.println"     */" );
            if (  )
            {
                writer.print"    com.google.gwt.http.client.Request " + method.getName() + "( " );
            }
            else
            {
                writer.print"    void " + method.getName() + "( " );
            }
            JavaParameter[] params = method.getParameters();
            for ( int j = 0; j < params.lengthj++ )
            {
                JavaParameter param = params[j];
                if ( j > 0 )
                {
                    writer.print", " );
                }
                writer.printmethod.getParameterTypestrue )[j].getGenericValue() );
                if ( param.getType().getDimensions() != method.getParameterTypestrue )[j].getDimensions() )
                {
                    for ( int dimensions = 0 ; dimensions < param.getType().getDimensions(); dimensions++ )
                    {
                        writer.print"[]" );
                    }
                }
                writer.print" " + param.getName() );
            }
            if ( params.length > 0 )
            {
                writer.print", " );
            }
            if ( method.getReturnType().isVoid() )
            {
                writer.println"AsyncCallback<Void> callback );" );
            }
            else if ( method.getReturnType().isPrimitive() )
            {
                String primitive = method.getReturnType().getGenericValue();
                writer.println"AsyncCallback<" + .getprimitive ) + "> callback );" );
            }
            else
            {
                Type returnType = method.getReturnTypetrue );
                String type = returnType.getGenericValue();
                if ( method.getReturnType().getDimensions() != method.getReturnTypetrue ).getDimensions() )
                {
                    for ( int dimensions = 0; dimensions < method.getReturnType().getDimensions(); dimensions++ )
                    {
                        type += "[]";
                    }
                }
                writer.println"AsyncCallback<" + type + "> callback );" );
            }
            writer.println();
        }
        writer.println();
        String uri = MessageFormat.formatclassName );
        if ( clazz.getAnnotations() != null )
        {
            for ( Annotation annotation : clazz.getAnnotations() )
            {
                getLog().debug"annotation found on service interface " + annotation );
                if ( annotation.getType().getValue().equals"com.google.gwt.user.client.rpc.RemoteServiceRelativePath" ) )
                {
                    uri = annotation.getNamedParameter"value" ).toString();
                    // remove quotes
                    uri = uri.substring( 1, uri.length() - 1 );
                    getLog().debug"@RemoteServiceRelativePath annotation found on service interface " + uri );
                }
            }
        }
        writer.println"    /**" );
        writer.println"     * Utility class to get the RPC Async interface from client-side code" );
        writer.println"     */" );
        writer.println"    public static final class Util " );
        writer.println"    { " );
        writer.println"        private static " + className + "Async instance;" );
        writer.println();
        writer.println"        public static final " + className + "Async getInstance()" );
        writer.println"        {" );
        writer.println"            if ( instance == null )" );
        writer.println"            {" );
        writer.println"                instance = (" + className + "Async) GWT.create( " + className + ".class );" );
        writer.println"                ServiceDefTarget target = (ServiceDefTarget) instance;" );
        writer.println"                target.setServiceEntryPoint( GWT.getModuleBaseURL() + \"" + uri + "\" );" );
        writer.println"            }" );
        writer.println"            return instance;" );
        writer.println"        }" );
        writer.println"" );
        writer.println"        private Util()" );
        writer.println"        {" );
        writer.println"            // Utility class should not be instanciated" );
        writer.println"        }" );
        writer.println"    }" );
        writer.println"}" );
        writer.close();
    }
    private boolean isEligibleForGenerationJavaClass javaClass )
    {
        return javaClass.isInterface() && javaClass.isPublic() && javaClass.isA );
    }
    @SuppressWarnings("unchecked")
        throws MojoExecutionException
    {
        try
        {
            JavaDocBuilder builder = new JavaDocBuilder();
            builder.setEncoding );
            builder.getClassLibrary().addClassLoadergetProjectClassLoader() );
            for ( String sourceRoot : ( List < String > ) getProject().getCompileSourceRoots() )
            {
                builder.getClassLibrary().addSourceFoldernew FilesourceRoot ) );
            }
            return builder;
        }
        catch ( MalformedURLException e )
        {
            throw new MojoExecutionException"Failed to resolve project classpath"e );
        }
        catch ( DependencyResolutionRequiredException e )
        {
            throw new MojoExecutionException"Failed to resolve project classpath"e );
        }
    }
    private String getTopLevelClassNameString sourceFile )
    {
        String className = sourceFile.substring( 0, sourceFile.length() - 5 ); // strip ".java"
        return className.replace.'.' );
    }

    

Returns:
the project classloader
Throws:
org.apache.maven.artifact.DependencyResolutionRequiredException failed to resolve project dependencies
java.net.MalformedURLException configuration issue ?
    {
        getLog().debug"AbstractMojo#getProjectClassLoader()" );
        List<?> compile = getProject().getCompileClasspathElements();
        URL[] urls = new URL[compile.size()];
        int i = 0;
        for ( Object object : compile )
        {
            if ( object instanceof Artifact )
            {
                urls[i] = ( (Artifactobject ).getFile().toURI().toURL();
            }
            else
            {
                urls[i] = new File( (Stringobject ).toURI().toURL();
            }
            i++;
        }
        return new URLClassLoaderurls, ClassLoader.getSystemClassLoader() );
    }
New to GrepCode? Check out our FAQ X