Search code examples
javamavenloggingcxfwsdl2java

CXF: How to generate @Logging annotation with wsdl2java?


We use CXF for SOAP cients and generate client with cxf-codegen-plugin (wsdl2java) maven plugin (which is I think just a wrapper around wsd2java). We usually used to add @Logging(pretty=true) annotation to every service every time after the generation.

Is there a way to automatically generate this annotation somehow?


Solution

  • No Idea if there are any plugins to change Log statements, however I guess easiest way is to create plugin which will run after cxf- code gen plugin.

    Here is the steps to follow if you are using eclipse.

    1. Select new project->maven project-> and in new maven project select archetypes

       groupId:org.apache.maven.achetypes
       artifactId:maven-achetype-plugin
      
    2. Add commons-io dependecny and change version to 1.0.0.0

      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
      </dependency>
      
    3. Edit MyMojo.java

      package com.kp.plugin.logcodegen;
      
      import java.io.File;
      import java.io.IOException;
      import java.util.Iterator;
      import java.util.List;
      import java.util.ListIterator;
      import java.util.regex.Matcher;
      import java.util.regex.Pattern;
      
      import org.apache.commons.io.FileUtils;
      import org.apache.commons.io.filefilter.FileFileFilter;
      import org.apache.commons.io.filefilter.TrueFileFilter;
      import org.apache.maven.plugin.AbstractMojo;
      import org.apache.maven.plugin.MojoExecutionException;
      import org.apache.maven.plugins.annotations.LifecyclePhase;
      import org.apache.maven.plugins.annotations.Mojo;
      import org.apache.maven.plugins.annotations.Parameter;
      
      @Mojo(name = "code-gen", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
      public class MyMojo extends AbstractMojo {
      
      @Parameter(defaultValue = "${project.build.directory}")
      private File outputDirectory;
      
      @Parameter(defaultValue = "${basedir}")
      private File baseDir;
      
      @Parameter(defaultValue = "src/main/java", property = "sourceDirecory")
      private String sourceDirectory;
      
      @Parameter(defaultValue = "", property = "packageNames")
      private String packageNames;
      
      @Parameter(defaultValue = "", property = "addImport")
      private String addImport;
      
      @Parameter(defaultValue = "", property = "removeImport")
      private String removeImport;
      
      @Parameter(defaultValue = "", property = "defineLogInstance")
      private String defineLogInstance;
      
      @Parameter(defaultValue = "", property = "removeLogInstance")
      private String removeLogInstance;
      
      public void execute() throws MojoExecutionException {
          System.out.println("-------------------");
          System.out.println("Adding logs to java classes");
          System.out.println("--------------------");
          System.out.println("Input package is:" + packageNames);
          System.out.println("BaseDir is " + baseDir.getAbsolutePath());
      
          StringBuilder sourceDir = new StringBuilder(baseDir.getAbsolutePath());
          sourceDir.append("/");
          sourceDir.append(sourceDirectory);
          if (!packageNames.isEmpty()) {
              sourceDir.append("/");
              for (final String packageName : packageNames.split(",")) {
                  String path = sourceDir.toString() + packageName.replaceAll("\\.", "/");
                  File dest = new File(path);
                  if (dest.isDirectory()) {
                      Iterator<File> it = FileUtils.iterateFiles(dest, FileFileFilter.FILE, TrueFileFilter.INSTANCE);
                      while (it.hasNext()) {
                          try {
                              processFile(it.next());
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
                      }
                  } else {
                      System.out.append("Path is not directory " + path);
                  }
              }
          } else {
              System.out.println("No packages to parse");
          }
      
      }
      
      private void processFile(final File file) throws IOException {
          List<String> contents = FileUtils.readLines(file);
          ListIterator<String> it = contents.listIterator();
          String className = "";
          while (it.hasNext()) {
              String str = it.next();
              // Remove import
              if (str != null && !str.isEmpty() && str.contains(removeImport)) {
                  it.remove();
                  it.add(addImport);
              }
      
      
      
              if (str != null && !str.isEmpty()) {
                  Pattern pat = Pattern.compile("\\s*(public|private)\\s+class\\s+(\\w+)");
                  Matcher matcher = pat.matcher(str);
                  if (matcher.find()) {
                      className = matcher.group(2);
                  }
              }
              // change the instance
              if (str != null && !str.isEmpty() && str.contains(removeLogInstance)) {
                  it.remove();
                  it.add(defineLogInstance + className + ".class);");
              }
          }
          FileUtils.writeLines(file, contents, false);
      }
      

      }

    4. run maven install

    5. Now add the plugin to your porject

      <pluginManagement>
              <plugins>
                  <plugin>
                      <groupId>org.eclipse.m2e</groupId>
                      <artifactId>lifecycle-mapping</artifactId>
                      <version>1.0.0</version>
                      <configuration>
                          <lifecycleMappingMetadata>
                              <pluginExecutions>
                                  <pluginExecution>
                                      <pluginExecutionFilter>
                                          <groupId>org.apache.cxf</groupId>
                                          <artifactId>cxf-codegen-plugin</artifactId>
                                          <versionRange>[2.7,)</versionRange>
                                          <goals>
                                              <goal>wsdl2java</goal>
                                          </goals>
                                      </pluginExecutionFilter>
                                      <action>
                                          <execute />
                                      </action>
                                  </pluginExecution>
                                  <pluginExecution>
                                      <pluginExecutionFilter>
                                          <groupId>com.kp.plugin</groupId>
                                          <artifactId>logcode-gen</artifactId>
                                          <versionRange>[1.0.0.0,)</versionRange>
                                          <goals>
                                              <goal>code-gen</goal>
                                          </goals>
                                      </pluginExecutionFilter>
                                      <action>
                                          <execute />
                                      </action>
                                  </pluginExecution>
                              </pluginExecutions>
                          </lifecycleMappingMetadata>
                      </configuration>
                  </plugin>
      
              </plugins>
          </pluginManagement>
          <plugins>
              <plugin>
                  <groupId>org.apache.maven.plugins</groupId>
                  <artifactId>maven-compiler-plugin</artifactId>
                  <version>${maven-compiler.version}</version>
                  <configuration>
                      <source>${jdk.version}</source>
                      <target>${jdk.version}</target>
                      <encoding></encoding>
                  </configuration>
              </plugin>
              <plugin>
                  <groupId>org.apache.cxf</groupId>
                  <artifactId>cxf-codegen-plugin</artifactId>
                  <version>${cxf.version}</version>
                  <executions>
                      <execution>
                          <id>generate-sources</id>
                          <phase>generate-sources</phase>
                          <configuration>
                              <sourceRoot>${basedir}/src/main/java</sourceRoot>
                              <wsdlOptions>
                                  <wsdlOption>
                                      <wsdl>${basedir}/src/main/resources/wsdl/kpws.wsdl</wsdl>
                                      <extraargs>
                                          <extraarg>-impl</extraarg>
                                      </extraargs>
                                  </wsdlOption>
                              </wsdlOptions>
                          </configuration>
                          <goals>
                              <goal>wsdl2java</goal>
                          </goals>
                      </execution>
                  </executions>
              </plugin>
      
              <plugin>
                  <groupId>com.kp.plugin</groupId>
                  <artifactId>logcode-gen</artifactId>
                  <version>1.0.0.0</version>
                  <executions>
                      <execution>
                          <id>codegen-resouces</id>
                          <phase>generate-sources</phase>
                          <goals>
                              <goal>code-gen</goal>
                          </goals>
                      </execution>
                  </executions>
                  <configuration>
                      <packageNames>com.kp.webservices.services</packageNames>
                      <addImport>import org.slf4j.Logger;</addImport>
                      <removeImport>java.util.logging.Logger</removeImport>
                      <removeLogInstance>private static final Logger LOG</removeLogInstance>
                      <defineLogInstance>private static final Logger LOG = org.slf4j.LoggerFactory.getLogger(</defineLogInstance>
                  </configuration>
              </plugin>
          </plugins>
      

    Note

    1. I've given basic sample to replace the text.
    2. I've given groupId and atrifactId of my convience change it accordingly.
    3. And finally the order of the plugin should be maintained 1->cxf 2. custom plugin in pom.xml and it works only in maven 3.0.2 or later.