Monday, 13 June 2016

How to make Jackson to avoid excaping backslash?

Create declare mapper:
private static final ObjectMapper mapper = new ObjectMapper(new ObjectMapper().getFactory().setCharacterEscapes(new CharacterEscapes() {
    @Override
    public int[] getEscapeCodesForAscii() {
      // add standard set of escaping characters
      int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
      // don't escape backslash (not to corrupt windows path)
      esc['\\'] = CharacterEscapes.ESCAPE_NONE;
      return esc;
    }

    @Override
    public SerializableString getEscapeSequence(int i) {
      // no further escaping (beyond ASCII chars) needed
      return null;
    }
  })).enable(INDENT_OUTPUT);


Usage:
mapper.writeValueAsString(configMap)

Tuesday, 7 June 2016

How call shell from Java?

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ExecuteShellComand {

 public static void main(String[] args) {

  ExecuteShellComand obj = new ExecuteShellComand();

  String domainName = "google.com";
  
  //in mac oxs
  String command = "ping -c 3 " + domainName;
  
  //in windows
  //String command = "ping -n 3 " + domainName;
  
  String output = obj.executeCommand(command);

  System.out.println(output);

 }

 private String executeCommand(String command) {

  StringBuffer output = new StringBuffer();

  Process p;
  try {
   p = Runtime.getRuntime().exec(command);
   p.waitFor();
   BufferedReader reader = 
                            new BufferedReader(new InputStreamReader(p.getInputStream()));

                        String line = "";   
   while ((line = reader.readLine())!= null) {
    output.append(line + "\n");
   }

  } catch (Exception e) {
   e.printStackTrace();
  }

  return output.toString();

 }
PING google.com (74.125.135.x): 56 data bytes
RESULT:
64 bytes from 74.125.135.x: icmp_seq=0 ttl=53 time=8.289 ms
64 bytes from 74.125.135.x: icmp_seq=1 ttl=53 time=7.733 ms
64 bytes from 74.125.135.x: icmp_seq=2 ttl=53 time=8.343 ms

--- google.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 7.733/8.122/8.343/0.276 ms
null

Tuesday, 31 May 2016

Guava Magic: ArrayListMultimap

import com.google.common.collect.ArrayListMultimap;

public class TestGuavaMultiMaps {

  public static void main(String[] args) {
    ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
    multimap.put("A", "1");
    multimap.put("B", "1");
    multimap.put("C", "1");
    multimap.put("A", "2");
    multimap.put("B", "2");
    multimap.put("C", "2");
    multimap.put("A", "3");
    multimap.put("B", "3");
    System.out.println(multimap); // {A=[1, 2, 3], B=[1, 2, 3], C=[1, 2]}

    multimap.asMap().remove("A");
    System.out.println(multimap); // {B=[1, 2, 3], C=[1, 2]}

    multimap.get("B").remove("1");
    System.out.println(multimap); // {B=[2, 3], C=[1, 2]}

    multimap.get("B").remove("2");
    multimap.get("B").remove("3");
    System.out.println(multimap); // {C=[1, 2]}

  }
}

Tuesday, 17 May 2016

How JMockit mocks static methods?

Dependency:
* Using old version

    <!-- jmockit should be before Junit -->
    <dependency>
      <groupId>com.googlecode.jmockit</groupId>
      <artifactId>jmockit</artifactId>
      <version>1.7</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

Code:

import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.junit.Before;
import org.junit.Test;

import static mockit.Deencapsulation.invoke;
import static org.junit.Assert.assertEquals;

public class JMockitStaticMethod {

  @Mocked({"getenv"})
  private System system;

  @Before
  public void init()
  {
    // allow to return mock value any number of times
    new NonStrictExpectations(system)
    {
      {
        invoke(System.class, "getenv", "MOCKED_VALUE");
        returns("MOCKED");
      }
    };
  }

  @Test
  public void testJMockitStatic() {
    assertEquals("MOCKED", System.getenv("MOCKED_VALUE"));
  }

}


Dependency:
* Using new version:

  <!-- jmockit should be before Junit -->
    <dependency>
      <groupId>org.jmockit</groupId>
      <artifactId>jmockit</artifactId>
      <version>1.23</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>


Code (mocks easier):

import mockit.Expectations;

import org.junit.Before;
import org.junit.Test;

import static mockit.Deencapsulation.invoke;
import static org.junit.Assert.assertEquals;

public class JMockitStaticMethod {


  @Before
  public void init()
  {
    new Expectations(System.class)
    {
      {
        invoke(System.class, "getenv", "MOCKED_VALUE");
// returns("MOCKED")
        result = new ClassCastException();
      }
    };
  }

  @Test(expected = ClassCastException.class)
  public void testJMockitStatic() {
    assertEquals("MOCKED", System.getenv("MOCKED_VALUE"));
  }

}

How to add jar into classpath at runtime?

  // pathToJar -> /path/to/jar/MyJarName.jar

  public void addToClassPath(String pathToJar) throws Exception {
    File file = new File(pathToJar);
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), file.toURI().toURL());
  }

TemporaryFolder in Junit

Dependencies:

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>19.0</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

Code:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;

public class TestTempFolder {

  // create temporary folder using Junit, it will be deleted automatically upon test success or failure
  // restriction: cannot be static
 // should be public
  @Rule
  public TemporaryFolder testFolder = new TemporaryFolder();

  @Test
  public void testTempFolder() throws Exception {
    // create file inside of temporary folder
    File mainFile = testFolder.newFile("main.csv");
    // write data into newly created file using guava lib
    Files.write("main data", mainFile, Charsets.UTF_8);
    // create folder inside of temporary folder
    File nestedFolder = testFolder.newFolder("nested");
    // create file inside of nested folder
    File nestedFile = new File(nestedFolder, "nested.csv");
    // write data into newly created file using guava lib
    Files.write("nested data", nestedFile, Charsets.UTF_8);
  }

}

Monday, 16 May 2016

3 ways to get file name without extension

Using apache commons
import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);

                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
Using Google Guava (If u already using it)
import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);
Or using Core Java
String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0) {
    fileName = fileName.substring(0, pos);
}