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