Capturing arguments with mockito

EncryptedFileInfo info = cut.storeEncryptedFile(encryptionSecret, plainContents, fileName);

ArgumentCaptor<byte[]> argument = ArgumentCaptor.forClass(byte[].class);

verify(cut).createFileAndAdd(eq(fileName), argument.capture());
byte[] encryptedContent = argument.getAllValues().get(0);

Where intercepted method is:

void createFileAndAdd(String fileName, byte[] encryptedContents);

Bootstraping Spring core using the context

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("tech.lacambra.prototype.statesmachine");
context.refresh();

At this point al found beans has been registered and can be used. As an example code would go further as follows, taking care that ExStateMachine.class  is annotated as @Component :

ExStateMachine machine = context.getBeanFactory().getBean(ExStateMachine.class);
machine.doSignals();

System.out.println("done!");

There are several available conext, all implementing the interface:

org.springframework.context.ApplicationContext
org.springframework.context:
ConfigurableApplicationContext.java

package org.springframework.context.annotation:
 AnnotationConfigApplicationContext.java

package org.springframework.context.support:
 AbstractApplicationContext.java
 AbstractRefreshableApplicationContext.java
 AbstractRefreshableConfigApplicationContext.java
 AbstractXmlApplicationContext.java
 ClassPathXmlApplicationContext.java
 FileSystemXmlApplicationContext.java
 GenericApplicationContext.java
 GenericGroovyApplicationContext.java
 GenericXmlApplicationContext.java
 StaticApplicationContext.java

package org.springframework.jca.context:
 ResourceAdapterApplicationContext.java

Apprenders and formating a default java.util.logger

handlers=java.util.logging.ConsoleHandler
.level=INFO
java.util.logging.FileHandler.level = INFO
java.util.logging.FileHandler.pattern = log.%u.%g.txt
java.util.logging.SimpleFormatter.format= %1$tl:%1$tM:%1$tS %1$Tp %2$s %4$s: %5$s%n
java.util.logging.ConsoleHandler.level=INFO
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

More info about SimpleFormatter: https://docs.oracle.com/javase/7/docs/api/java/util/logging/SimpleFormatter.html#SimpleFormatter()

More Info about formatting params:
https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

Pass parameters to java main method using graddle

To pass for example a param “-a” with value “192.168.99.100:7051” to the static void main method that tha graddle task will run,  you will need to :

  • add following entry to gradle.build file, or assert that it is already there:
    run {
        if (project.hasProperty("appArgs")) {
            args = Eval.me(appArgs)
        }
    }
  • run graddle on the following form:
    gradle  run  -PappArgs="['-a',  '192.168.99.100:7051']"

Create a correct 201 Created response with JAX-RS

@POST
@Path("project")
public Response createProject(@Context UriInfo uriInfo, JsonObject json) {
        Project project = projectConverter.fromJson(json);
        project.setWorkspace(getCurrentWorkspace());
        project = em.merge(project);

        URI uri = uriInfo.getBaseUriBuilder()
                .path(ProjectResource.class)
                .resolveTemplate(PathExpressions.workspaceId, getCurrentWorkspace().getId())
                .resolveTemplate(PathExpressions.projectId, project.getId())
                .build();

        return Response.created(uri).build();
The @Context UriInfo uriInfo provides information about the current URI. 
The .path(ProjectResource.class)  call will return the path used for the ProjectResource.class. 
The .resolveTemplate("{workspaceId:\\d+}", getCurrentWorkspace().getId())  will replace the workspaceId template variable for the actual wokspace id.

Once the whole path has been created, it is only needed to put it into a created response.

Collect into Jsonp JsonArray using without using foreach

Each collector has three parts:

  • A supplier: provides with instances of the accumulator.
  • An accumulator: accumulates the objects being collected. Several instances of accumulator can be used.
  • A combiner: combines all the accumulator putting all collected objects together.

For the JsonArray the combiner, accumulator  and combiener are respectively:

JsonArrayBuilder createArrayBuilder()
JsonArrayBuilder add(JsonValue value)
JsonArrayBuilder add(JsonArrayBuilder builder)

    public JsonArray getArray(Jsonable[] objects) {
        return Stream.of(objects).map(Jsonable::toJson)
                .collect(
                        Json::createArrayBuilder,
                        JsonArrayBuilder::add,
                        JsonArrayBuilder::add
                ).build();

    }

    public static class Jsonable {

        public JsonObject toJson() {
            return Json.createObjectBuilder().add("someId", LocalTime.now().toString()).build();
        }
    }

Get java.util.logging working on UnitTesting

If you need to active the java.util.logging on your test, you can achieve it just adding the vm option
-Djava.util.logging.config.file=/path/to/logging.properties

where logging.properties can be something like

handlers = java.util.logging.ConsoleHandler
.level=INFO
your.package.level = FINE
java.util.logging.ConsoleHandler.level = FINE

You can find a more complete example on https://svn.apache.org/repos/asf/river/jtsk/skunk/surrogate/testfiles/logging.properties

,

Run Vert.x app from intellij

To run Vert.x on intelliJ, it is only required to create a standard application Launcher with the following parameters:

  • Main class: the vert.x main class, i.e. io.vertx.core.Starter or whatever it is for your version.
  • VM options: whatever you need or empty
  • Program arguments: run de.lacambra.vertx.MyFirstVerticle
  • Working directory: normally your project directory