Saturday, December 5, 2015

Returning first successful result from CompletableFuture

Recently I wanted to get first non empty result from bunch of CompletableFutures. For my case, allOf - is bad because it runs all futures till end and returns nothing. AnyOf - is bad because it returns first result, even if it is empty. So there is no such function in Java API, but it is still very easy to implement, and maybe it is even more logical, because actually there are 2 cases: found or not found; and it can be easily solved with two CompletableFutures. There is example:

import java.util.concurrent.CompletableFuture

success = new CompletableFuture()

def futures = (1..10).collect { CompletableFuture.supplyAsync {
                                    if (val == 6) {
                                        success.complete(val)
                                    } else {
                                        Thread.sleep(1000)
                                    }
                                }
                          }

println CompletableFuture.allOf(futures as CompletableFuture[])
        .thenApply({ throw new RuntimeException("not found") })
        .applyToEither(success, {it}).get()


This way it will return result if there is any, or throw exception if all done and there is no result, and it can be easily adjusted to return default value, for example.

Saturday, November 28, 2015

Groovy framework for AWS lambda

I was playing with AWS lambda recently and I find it pretty exciting. It is cheap, does not require any maintenance and it is simple. The biggest problem I found so far, is lack of tooling. AWS has web UI which does what it supposed to do, but is far from pleasant. AWS command line tools and API are much better, but are AWS centric. So, I have created tool to work with AWS lambda. It uses some convention now, but can be adjusted to whatever feels right for specific situation, idea is that it is just one script with few lines of code. Basically, it does 2 things: uploads application and local testing. I have created small example that illustrates how and what it does.

Example is trivial application that increments number by clicking on button. It is SPA, with static client in S3 and two API functions add and get.

All lambda code is just single Groovy script. It consists of router function, dependencies and logic. Router function is what will be mapped to lambda. It is function that accepts map and returns map. Input map can be plain request JSON, or some additional parameters can be injected at API gateway. Even for this trivial case it was a good idea and I injected configuration parameters - AWS access and secret keys and region for DynamoDB access, so they are hidden at admin level and are environment specific. Simplest way to do routing is just by using some designated parameter, in this example, it is called "function". Doing it with real URI will need AWS configuration, and it is not very convenient and flexible.

In this simple example, router script does logic, but for more complex cases it is better to be just router and logic would be in dependencies.

During packaging Groovy script is compiled and packaged together with all dependencies into uberjar which is required by AWS. After that, it is uploaded via AWS API.

Development can be done and tested locally by using mock server. Mock server mimics AWS, parses input into JSON like lambda, injects parameters like API gateway, includes Access-Control-Allow-Origin and separates configuration via config.js, supports debug and reloading.

Saturday, October 17, 2015

Trim is not removing all whitespaces in Java

Java trim is removing only ASCII whitespace characters, but ignores unicode whitespaces. This is backward compatibility thing, and there is big and detailed explanation of this problem. It can be easily fixed by using regular expression that will remove all official unicode whitespaces:
Pattern TRIM_PATTERN = Pattern.compile("^\\s*(.*?)\\s*$", Pattern.UNICODE_CHARACTER_CLASS);
Matcher matcher = TRIM_PATTERN.matcher(input);
if (matcher.matches() && matcher.groupCount() > 0) {
    return matcher.group(1);
}
return input;

But for more extreme cases you may want to use also this pattern
"^[\\s\\u2060\\u200D\\u200C\\u200B\\u180E\\uFEFF\\u00AD]*(.*?)[\\s\\u2060\\u200D\\u200C\\u200B\\u180E\\uFEFF\\u00AD]*$"

besides whitespaces it will also remove other invisible symbols.

Wednesday, September 16, 2015

Using IDE scripting console in Intellij IDEA

Some time ago, Intellij added option to write simple scripts to automate it's functions, extract information and write simple plugins. It is located under Tools / IDE scripting console. It is very basic now, just scripting file that runs inside of Intellij JVM and has access to Intellij API.

 There is simple Groovy example that automatically adds non-suspending breakpoint with log expression:

import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.ProjectManager
import com.intellij.xdebugger.breakpoints.SuspendPolicy

def file = LocalFileSystem.getInstance().findFileByPath("/users/test/project/src/Test.java")
def doc = FileDocumentManager.getInstance().getDocument(file)
def bp = ProjectManager.getInstance().getOpenProjects()[0].getComponent("DebuggerManager").getBreakpointManager().addLineBreakpoint(doc, 11)
bp.getXBreakpoint().setLogExpression('"test"')
bp.getXBreakpoint().setSuspendPolicy(SuspendPolicy.NONE)


Of course, this basic task can be done through XML configuration, but IDE scripting has access to much more and can do trickier tasks. There is very cool demo. Generally, from what I have seen, API is pretty impressive, it is intuitive, powerful and easy to start with.

My biggest complains are that it is pretty verbose (as Java itself), it would be great if in future versions it would be solved at least at tooling levels - with auto imports for packages, autocompletion, and more convenience functions, like attaching to actions, getting projects or files quickly. Second problem is total lack of documentation. Basically, what I have found is only GitHub repo of Intellij community edition. It has multiple modules with API scattered across them, most generic classes are under Core API.

Friday, August 14, 2015

Adding custom hostname to docker-machine VirtualBox image

When boot2docker was changed to docker-machine, it added dubious feature of being read only container, so no changes to VirtualBox will be preserved after restart. Saving changes is still perfectly fine for Linux Docker users, but not docker-machine users anymore for some reason.

So, to add new hostname before, you could just go to VirtualBox, change /etc/hosts file, and this is it - this will not work with docker-machine, as hosts file will be erased after restart. You are luckier, if you are not using net:host in docker-compose, there is special property for that too. But, if you are using net:host, the only working option is to change VirtualBox image and add this configuration:

VBoxManage modifyvm "default" --natdnshostresolver1 on

In this case it will use host machine to resolve all dns requests, even those from /etc/hosts.

Thursday, July 23, 2015

How to add configuration parameters to AWS lambda with API gateway

Unfortunately, there is no easy way to add configuration parameters to AWS lambdas, there is almost nothing in context that you can configure; there is description, but besides being ambiguous, it is not accessible from function itself. Fortunately, it is possible to set additional values from API gateway, even it is not straightforward.

When you have created API gateway mapping, go to the method screen in gateway console, there is screen with multiple boxes, one of which is called Integration Request, click it and there will be section called Mapping Templates. Add new mapping template for type application/x-www-form-urlencoded, save it, edit value and change from default Input passthrough to Mapping template, then you can transform your original request, by adding additional parameters, it uses velocity for transformation, but there is basic example:


{
  "my-new-configuration" : "my value",
  "body" : "$input.path('$')",
  "params" : "$input.params()",
  "ip" : "$context.identity.sourceIp",
  "user-agent" : "$context.identity.userAgent"
}

Besides possibility to add anything to lambda function it also has access to interesting request data like headers, ip, client type, user agent, country, etc. - all will be available in your map or pojo as parameter for lambda function. And do not forget to click Deploy API after making changes to make them live.

Thursday, June 25, 2015

How to create executable JAR from single Groovy script

Groovy scripts are nice - they allow to use dependencies and write logic in small single file, but Groovy is mostly available on developers machine, but not on servers, so deploying them is a little more tricky. You can package them in uberjar with Gradle, but it requires additional build file and compatible structure, so it is more like project than script already.

To keep things simple, I have created Groovy script that converts other Groovy scripts into executable JARs. It packages all dependencies from Grab and compiles original script into Java main class with same name as script and sets it in manifest. So it is perfectly usable from empty JVM. JAR structure is also compatible with AWS lambda, so it can be launched from there too, just put logic in specific method. To convert your script, just download it from here and run like:

./scriptjar.groovy input.groovy output.jar

Script tries to find groovy libs via GROOVY_HOME, so set it or just hack it for your location, it is just one small Groovy script.