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

simple idea for a Java developer interview

Let’s say that you need to interview a candidate for a Java developer position and address his technical skills (as a developer).
The candidate is given a simple programming task – let’s say that there is an array of 1M integers from the range [0..100000] and the question what algorithm would you use for sorting it with the minimal complexity?
The simplest answer would be to use Arrays.sort(). Some would say it can be done with quick-sort with logarithmic complexity.
But perhaps some of the candidates would be able to identify algorithms with better big-O complexity – assuming the specific conditions for the input.

  1. [code snippet] How to cast types without warnings? Comments Off on [code snippet] How to cast types without warnings?
  2. 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
  3. [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?
  4. 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
  5. 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!
  6. Web components & Polymer how-to Comments Off on Web components & Polymer how-to
  7. UncheckedIOException Comments Off on UncheckedIOException
  8. Some handy code for JVM8 Comments Off on Some handy code for JVM8
  9. Cheap ONVIF camera hacking Comments Off on Cheap ONVIF camera hacking