Category Archives: Java

Generate assertEquals(xxx, bean.getXxx()) for all the properties of a javabean

In intellij, create such a live template:

    public static void main(String args[]) {
        Class<?> clazz = $Bean$.class;
        String object = "$bean$";
        java.lang.reflect.Method[] methods = clazz.getMethods();
        for (java.lang.reflect.Method m : methods) {
            if ((m.getName().startsWith("get") || m.getName().startsWith("is") )&&  (!m.getName().equals("getClass")) &&  m.getParameterTypes().length == 0) {
                System.out.println(
                    "assertEquals(\"xxx\"," + object + "." + m.getName() + "()); "
                );
            }
        }

    }

Make sure chromedriver can run with Java selenium code, both in a real machine and in docker

Install chromedriver

You want to make the following line of code run successfully.

ChromeDriver driver = new ChromeDriver();

In windows, you need to download chrome driver from https://chromedriver.chromium.org/downloads and put it in system’s path (An alternative is to set the executable file’s path as a system property “webdriver.chrome.driver”, not beautiful)

In *nix or linux-based Docker, you can

apt update
apt install chromedriver -y   #for debian-based systems 

Options needed for ChromeDriver

        ChromeDriverService chromeDriverService = new ChromeDriverService.Builder().withWhitelistedIps("").build();//without this you may see " bind() returned an error, errno=99: Cannot assign requested address (99) "

...
        // without the following you may see "DevToolsActivePort file doesn't exist" 
        ChromeOptions chromeOptions = new ChromeOptions();
        if(isUnixBased()) {
            chromeOptions.addArguments("--headless");
            chromeOptions.addArguments("--no-sandbox");
            chromeOptions.addArguments("--disable-dev-shm-usage");
        }

...
        ChromeDriver driver = new ChromeDriver(chromeDriverService, chromeOptions);

					

Use spring +aspectj in Spring boot

compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.aspectj:aspectjrt')
compile('org.aspectj:aspectjweaver')
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class YourApplication ...{
...
}
@Component
@Aspect
public class YourAspect {

	@Before("execution(public * com..*Manager.*(..))")
	public void doAdvice(JoinPoint joinPoint) {...}
	 
}

Springfox for 204 response

What you need to,

  • Return ResponseEntity<Void>
  • Set the @ResponseStatus for your rest controller’s method

If you don’t do that, you will get ResponseEntity as the response class in your swagger json, and you will get both 200 and 204 as your successful response code, which is not correct because your method only returns 204, no 200.

    @RequestMapping(value = "...", method = RequestMethod.POST)
    @ApiOperation(value = "...")
    @ApiResponses(value = {
            @ApiResponse(code = 204, message = "success")
    })
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ResponseEntity<Void> someMethod(){}

Jetty’s start.jar forks a new JVM to run the app if logback module is enabled

Jetty is too smart. If there is any JVM option provided, Jetty will spawn a new JVM instance to do the real work, even if you don’t use “–exec” option in start.ini

And jetty’s logback module introduces a JVM option. See here

You will see:

-Dorg.eclipse.jetty.util.log.class?=org.eclipse.jetty.util.log.Slf4jLog 

So does it matter?

It matters a lot because all the JVM options you passed to start.jar will stay on the process of start.jar. They are not passed to the forked JVM process.

What’s the solution ?

Since you have to let it fork a new JVM because of logback, you can just put all the JVM options in start.ini. Like,


--exec
-server
-Xms2g
-Xmx2g
-XX:+UseZGC


Code snippet: Swagger + Spring Boot

compile 'io.springfox:springfox-swagger2:2.9.2'
compile 'io.springfox:springfox-swagger-ui:2.9.2'
/**
 See https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
 */
 @Configuration
 @EnableSwagger2
 public class SwaggerConfig {
 @Value("${enable.swagger}")  //You may want to disabled it in PROD
 boolean enableSwagger;
 @Bean
 public Docket api() {
     Docket api = new Docket(DocumentationType.SWAGGER_2)
             .select()
             .apis(RequestHandlerSelectors.basePackage("your.package"))
             .paths(PathSelectors.any())
             .build();
        ApiInfo apiInfo = new ApiInfoBuilder()		
                .version("xxx")
                .description("xxx")
                .termsOfServiceUrl("xxx")
                .title("Xxx Doc")
                .build();

        api.useDefaultResponseMessages(false).apiInfo(apiInfo);

        api.enable(enableSwagger);

        return api;
    }
}


Generate PDF from server side using Java

You can use OpenPDF to draw a PDF (the open source fork of iText). However, the learning curve of creating PDF with layouts and stuff is very high.

A more cost-effective solution is create an HTML version of it and convert it using Flying Saucer with its OpenPDF component

. As a Java developer you are already familiar with html + css, so doing that is quick.

There are some limitations and side effects of this approach

  • Your html must be XML/XHTML
  • Styles’ version must be no more than CSS 2.1. (So you can’t use flexbox layout)
  • No javascript
  • More: https://flyingsaucerproject.github.io/flyingsaucer/r8/guide/users-guide-R8.html#xil_6
  • The image quality seems worse than what you see on the html page, if there is any

And to create a PDF, your html can’t be too wide, otherwise content may be lost.

Typically, say you are creating an A4 PDF with margin of 0.1 inch on both left and right, the width of your html should not be more than (A4’s paper width – margin) * pixe density = (8.27inch – 0.1 inch * 2) * 96 DPI = 774 pixels

And here is how to set up the size and margin of the PDF in your html:

<head>
    <style>
        @page {
            margin-left: 9px;   /* about 0.1 inch */ 
            margin-right: 9px; 
            size: A4;
        }
    </style>
   ...

Gradle upload a custom-generated jar file to Nexus

Do this:

apply plugin: 'maven-publish'


   publishing {
        publications {
            maven( MavenPublication ) {
                artifact theTaskThatGeneratesJar
            }
        }
        repositories {
            maven {
                def releasesRepoUrl = http://.../repositories/releases/'
                def snapshotsRepoUrl = 'http://.../repositories/snapshots/'
                url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl
                credentials {
                    username 'xxx'
                    password 'xxx'
                }
            }
        }

    }


Read process output in Java without hanging the main thread

/**
 * 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.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
 * 
 * @author chenjianjx (Copied from CXF)
 *
 */
public class StreamPrinter extends Thread {
  InputStream is;
  String msg;
  OutputStream os;

  public StreamPrinter(InputStream stream, String type) {
    this(stream, type, null);
  }

  public StreamPrinter(InputStream stream, String type, OutputStream redirect) {
    is = stream;
    msg = type;
    os = redirect;
  }

  public void run() {
    try {
      PrintWriter pw = null;
      if (os != null) {
        pw = new PrintWriter(os);
      }
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line = br.readLine();
      while (line != null) {
        if (pw != null) {
          pw.println(msg + " " + line);
        }
        line = br.readLine();
      }
      if (pw != null) {
        pw.flush();
      }
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }
}
/**
 * 
 * @author chenjianjx
 * 
 */

public class SystemProcessException extends Exception {

  private int returnCode;
  private String consoleOutput;

  /**
   * 
   */
  private static final long serialVersionUID = -6904952219344675845L;

  public SystemProcessException(int returnCode, String consoleOutput) {
    super();
    this.returnCode = returnCode;
    this.consoleOutput = consoleOutput;
  }

  public int getReturnCode() {
    return returnCode;
  }

  public String getConsoleOutput() {
    return consoleOutput;
  }

}
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jaxws.util.io.StreamPrinter;

/**
 * Spawning a process from the OS
 * 
 * @author chenjianjx
 * 
 */
public class SystemProcessUtils {

  /**
   * execture a program and returns console output
   */
  public static String exec(String[] cmdArray) throws SystemProcessException {

    try {
      Process p = Runtime.getRuntime().exec(cmdArray);
      ByteArrayOutputStream output = new ByteArrayOutputStream();
      Thread errStreamThread = collectErrorStream(p, output);
      Thread inputStreamThread = collectInputStream(p, output);
      int returningCode = p.waitFor();
      int timeout = 60000;
      if (errStreamThread != null) {
        errStreamThread.join(timeout);
      }
      if (inputStreamThread != null) {
        inputStreamThread.join(timeout);
      }
      String consoleOutput = new String(output.toByteArray());
      System.out.println(consoleOutput);
      if (returningCode != 0) {
        throw new SystemProcessException(returningCode, consoleOutput);
      }
      return consoleOutput;
    } catch (IOException e) {
      throw new IllegalStateException(e);
    } catch (InterruptedException e) {
      throw new IllegalStateException(e);
    }
  }

  private static StreamPrinter collectInputStream(Process p, OutputStream out) {
    if (p.getInputStream() != null) {
      StreamPrinter infoStreamPrinter = new StreamPrinter(p.getInputStream(), "[INFO]", out);
      infoStreamPrinter.start();
      return infoStreamPrinter;
    }
    return null;
  }

  private static StreamPrinter collectErrorStream(Process p, OutputStream out) {
    if (p.getErrorStream() != null) {
      StreamPrinter errorStreamPrinter = new StreamPrinter(p.getErrorStream(), "[ERROR]", out);
      errorStreamPrinter.start();
      return errorStreamPrinter;
    }
    return null;
  }

}