Automation for Java Developers - tips and snippets
Tags: java, developer, automation, snippets
Published: 2019-02-01 00:29:00

---
title: Automation for Java Developers - tips and snippets
published: true
description: Automation for Java Developers - tips and snippets - at least the one that I am using the most
tags: java, developer, automation, snippets
---

<!-- wp:paragraph -->
<p>Automation is something that can save your future self a lot of time. It is not an urgent thing, but it is very important. It will give you the time to work on business logic, execute certain boring stuff, protect you from yourself and others when the code is changed, get notified early when something is broken, bring better experience to the User (with less bugs) and at last will give you freedom not to worry about low level technical shit and enjoy life more. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Leveraging flavors</strong>. These are predefined constants, parameters, even code (although it better be minimal) for the different <a href="http://tomavelev.com/blog/Software%20Environments?en_US">environments </a>your application will run. On Java Desktop and Server the Standard way of doing this is mostly with .properties files. Everything that is different - database connections, paths on the file systems, JVM parameters, commands etc could be placed outside of the code. This later minimizes the need for extra changes when moving the app to a new place (although this is less of a problem with containers).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>On <a href="https://developer.android.com/studio/build/build-variants">Android - flavors</a> are first class citizens. The run-time system chooses resources, images, menus, layout files, values, colors from the settings of the current operating system environment. At compile time flavor can also be defined. Making the same file structure  from the main source folder - with some specific files overwritten, it could replace URL endpoints, data access credentials, signing certificates, resources, and code. And when you compile, you choose with which flavor to be bundled to the installation package. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Lets get to some specific technical snippets that I'm using: </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I have used SSHJ <a href="https://github.com/hierynomus/sshj">https://github.com/hierynomus/sshj</a> to download or upload files to remote servers: <br></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>try (SSHClient ssh = new SSHClient()) {
 ssh.loadKnownHosts();        
 ssh.addHostKeyVerifier("some-key");
 ssh.connect(host);
 ssh.authPassword(user, pass);
 ssh.newSCPFileTransfer().upload(localFilePath, remoteFilePath);
 ssh.disconnect();
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>I have used sshxcute <a href="https://code.google.com/archive/p/sshxcute/">https://code.google.com/archive/p/sshxcute/</a> to do bunch of tasks on the server - copy specific files to their needed location, zip directories, trigger a database backup, delete old files, etc.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>CustomTask task = new ExecCommand("some command");
ConnBean cb = new ConnBean(host, user, pass);
SSHExec ssh1 = SSHExec.getInstance(cb);
ssh1.connect();
ssh1.exec(task);
ssh1.disconnect();</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>I have used the Java Process API to execute some script or command in a sub process and from the returned result, depending on the need, I have executed different code afterwards. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>processBuilder = new ProcessBuilder(list of commands);
processBuilder.directory(working directory);
processBuilder.inheritIO();
process = processBuilder.start();
int waitFor = process.waitFor();
if (waitFor == 0) {
//something
} else {
//something else 
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>While doing builds or in several other places, I am replacing configuration files with different flavors for the different environments with this snippet: <br></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>Files.copy(sourceFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Builds themselves are done with Gradle, Maven and/or Ant. The location of these tools and sometimes their parameters are flavored in properties files, so, migrating the build to a new machine is just a matter of replacing some lines in a .properties file. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>From these 3 tools I mostly like Ant, because it gives you full control over the build process without hiding too much of it. The others are very good at managing dependencies but their building process is with plugins and sometimes some of the steps remain hidden which may be good, but sometimes it may be bad (especially if something is not working) or you want to customize something. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>I've used in several places the Eclipse JGit API to access local and remote repositories. <a href="https://www.eclipse.org/jgit/">https://www.eclipse.org/jgit/ </a></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>    SshSessionFactory.setInstance(new JschConfigSessionFactory()
    {
        @Override
        protected void configure(Host arg0, Session session)
        {
            session.setPassword("the password of a user");
        }
    });
    File file = new File("local directory");
    delete(file);
    Git.cloneRepository().setURI("user@someaddr:/remoteaddr")
    .setDirectory(file).call();</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>I have used the Java Zip API to package some files into zip.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>    Path sourceDir = Paths.get(dirPath);
    String zipFileName = "some file name;
    try {
        ZipOutputStream outputStream = new 
ZipOutputStream(new FileOutputStream(zipFileName));
        Files.walkFileTree(sourceDir, new SimpleFileVisitor&lt;Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
                try {
                    Path targetFile = sourceDir.relativize(file);
                    outputStream.putNextEntry(new ZipEntry(targetFile.toString()));
                    byte[] bytes = Files.readAllBytes(file);
                    outputStream.write(bytes, 0, bytes.length);
                    outputStream.closeEntry();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return FileVisitResult.CONTINUE;
            }
        });
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Some of the above stuff may be done with little configuration using the <a href="https://jenkins.io/">Jenkins </a>application or some command from the tools( for example I've used Ant in some cases for some of the stuff), but I find it useful to mix jenkins features with standard commands and java executable applications - coded by me, doing what i needed to do when I could find the feature or the plugin in this tool. In the task configuration of this CI/CD app I have especially used: <br><br></p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Start building every X minutes/at some period of time using the Cron Task Scheduler. </li><li>Executing build with git commit hook <a href="https://stackoverflow.com/questions/12794568/how-to-configure-git-post-commit-hook">https://stackoverflow.com/questions/12794568/how-to-configure-git-post-commit-hook</a></li><li>Execute command from the terminal after the build finishes successfully </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Probably a lot more could be automated with some configuration, some small code snippets or with some additional tools. But that is for me for now. If you know and use some cool stuff for automation, please let me know. </p>
<!-- /wp:paragraph -->