Code Snippets

Fast file or standard input processing

import java.io.*;
import java.util.StringTokenizer;

public class App {
    private static String TEST_FILE = "file.txt";
    private PrintWriter pw;
    private BufferedReader br;
    App(boolean skip) throws FileNotFoundException {
        this.pw = new PrintWriter(System.out);
        File file = new File(TEST_FILE);
        if (!skip && file.exists()) {
            br = new BufferedReader(new java.io.FileReader(TEST_FILE));
        } else {
            br = new BufferedReader(new InputStreamReader(System.in), 1 << 16);
        }
    }
    void doit() throws IllegalArgumentException, IOException {
        StringTokenizer s = new StringTokenizer(br.readLine());
        // do sth w/ s
        String result = "sth";
        pw.println(result);
        pw.flush();
    }
    public static void main(String[] args) throws IllegalArgumentException, IOException {
        new App(false).doit();
    }
}

How to create InputStream from String?

public InputStream stringInputStream(String payload) {
    return new ByteArrayInputStream(payload.getBytes(StandardCharsets.UTF_8));
}

How to create Mockito mock as Spring bean?

<bean id="dao" class="org.mockito.Mockito" factory-method="mock"> 
    <constructor-arg value="com.package.Dao" />
</bean>

Why Mockito @Captor is so good?

We want to create Captor for List type:

ArgumentCaptor<List> filterCaptor = ArgumentCaptor.forClass(List.class);
verify(listener).doSomething(eq("foo"), filterCaptor.capture());

The code compiles and works, but there is a warning about the unchecked assignment. @Captor annotation solves the problem:

@Captor
private ArgumentCaptor<List<EntityCriterion>> filterCaptor;

Spring context integration in Unit Tests

This snippet shows how integration test involving Spring contexts should be written. If you have numerous unit tests similar to the one below, the Spring context (given as the parameter of @ContextConfiguration annotation) will be read only once and re-used. This really improves the speed of running mvn test command.

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:spring-test-context.xml") 
public class FooImplTest {
  @Autowired
  private FooImpl fooImpl;
  @Test
  public void someWeirdTest {}
}

As you can notice @Autowired annotation is used for automatic loading of a bean. The context in this example should contain a bean of type FooImpl (in this case the wiring is made according to the bean type).

How to add TestNG to your project?

Add proper dependency to your pom.xml:

<dependencies>        
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.1.1</version>
    <scope>test</scope>
  </dependency>
</dependencies>

And Java code with Unit Test:

import org.testng.annotations.*;

public class SomeUnitTest {
  @Test(threadPoolSize = 3, invocationCount = 10, timeOut = 10000)
  public void basicTest() throws Exception {
     // given

     // when

     // then
     assertEquals(expected, result);
  }
}

Another useful set of methods to replace boilerplates

org.springframework.web.util.WebUtils class contains for example:

public static Cookie getCookie(HttpServletRequest request, String name) {
	Assert.notNull(request, "Request must not be null");
	Cookie cookies[] = request.getCookies();
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
				return cookie;
			}
		}
	}
	return null;
}

JavaScript: how to log JSON using console.log?

this.eventJson = {
    resource: {
        summary: this.configuration.eventName,
        description: this.configuration.eventDescription,
    }
};
console.log("and the JSON looks like this " + JSON.stringify(this.eventJson));

MongoDB: Convert collection to JS map

“Old-school” JS:

var usersDict = {};
db.getCollection("users").find().forEach(user => {
     usersDict[user._id] = user;
});

Wtih reduce():

var usersDict = db.getCollection("users").find().toArray().reduce(function(map, obj) {
    map[obj._id] = obj;
    return map;
}, {});

Recent Posts

[code snippet] How to cast types without warnings?

When we want to convert one type to another we usually cast it using round brackets:

 Object result = calculateResults();
 Foo foo = (Foo)result;
 // ...

This will cause IntelliJ to show Warning about casting. We could help it by adding condition with instanceof operator:

if (result instanceof Foo) {
   Foo foo = (Foo)result;
   // ...
}

Another way of casting can be done using cast() method:

Foo foo = Foo.class.cast(result);

And thisĀ  an be combined with isInstance() method:

if (Foo.class.isInstance(result)) {
   Foo foo = Foo.class.cast(result);
   //...
}
  1. How to add <base> element to page header in ZK Framework Comments Off on How to add <base> element to page header in ZK Framework
  2. [MongoDB] How to add a field to a subdocument of every document in a collection? Comments Off on [MongoDB] How to add a field to a subdocument of every document in a collection?
  3. How to mount a directory from QNAP NAS drive on Ubuntu Comments Off on How to mount a directory from QNAP NAS drive on Ubuntu
  4. git status shows that files are modified but.. they are not! Comments Off on git status shows that files are modified but.. they are not!
  5. Web components & Polymer how-to Comments Off on Web components & Polymer how-to
  6. UncheckedIOException Comments Off on UncheckedIOException
  7. Some handy code for JVM8 Comments Off on Some handy code for JVM8
  8. Cheap ONVIF camera hacking Comments Off on Cheap ONVIF camera hacking
  9. Do it online Comments Off on Do it online