Thursday, June 13, 2019

Java Program to check federal holidays in US using ZonedDateTime API java8

This is the program n=in java where it checks whether the given zoneddatetime is holidays or not.
It uses java8 ZonedDateTime to determine the zoned date and time.


Code to check whether a given date falls on weekend or holidays

Saturday, May 4, 2019

Filter Cryillic file from the folder in python


Wednesday, March 20, 2019

Returning the permutation of the string to find the number just greater number formed by the given digits in java

Problem:

Find the number  just greater than given number  which is formed by the available digits?

eg. if number is 86435, the number just greater than 86435 must be 86453.

Solution1:

public class QuestionB {
    public static ArrayList<String> getPerms(String remainder) {
        int len = remainder.length();
        ArrayList<String> result = new ArrayList<String>();

        /* Base case. */        if (len == 0) {
            result.add(""); // Be sure to return empty string!  
          return result;
        }


        for (int i = 0; i < len; i++) {
            /* Remove char i and find permutations of remaining characters.*/   
         String before = remainder.substring(0, i);
            String after = remainder.substring(i + 1, len);
            ArrayList<String> partials = getPerms(before + after);

            /* Prepend char i to each permutation.*/        
            for (String s : partials) {
                result.add(remainder.charAt(i) + s);
            }
        }

        return result;
    }

    public static void main(String[] args) {
        ArrayList<String> list = getPerms("abc");
        System.out.println("There are " + list.size() + " permutations.");
        for (String s : list) {
            System.out.println(s);
        }
    }

}

Solution2:

public class GeneralizedSolution {
  public static void main(String[] args) {
    String s = "86435";
//    System.out.println("\nString " + s + ":\nPermutations: " + Permutation(s)); 
 Set<Integer> set = Permutation(s).stream().map(a -> Integer.parseInt(a))
.collect(Collectors.toSet());
    List<Integer> list = new ArrayList<>(set);
    Collections.sort(list);
//    System.out.println(list);    int index = list.indexOf(Integer.parseInt(s));
    if (index == list.size() - 1) {
      System.out.println("there is no number greatet than " + s);
    } else {
      System.out.println("The number just greater than " + s + "is :" + list.get(index + 1));

    }
  }

  public static Set<String> Permutation(String str) {
    Set<String> Result = new HashSet<String>();
    if (str == null) {
      return null;
    } else if (str.length() == 0) {
      Result.add("");
      return Result;
    }

    char firstChar = str.charAt(0);
    String rem = str.substring(1);
    Set<String> words = Permutation(rem);
    for (String newString : words) {
      for (int i = 0; i <= newString.length(); i++) {
        Result.add(CharAdd(newString, firstChar, i));
      }
    }
    return Result;
  }

  public static String CharAdd(String str, char c, int j) {
    String first = str.substring(0, j);
    String last = str.substring(j);
    return first + c + last;
  }

}


solution 3rd:
of permutation with finding permutation with making first element constant and
finding permutation of remaining:


class Permutations
{
 // Recursive function to generate all permutations of a String
 private static void permutations(String candidate, String remaining)
 {
  if (remaining.length() == 0) {
   System.out.println(candidate);
  }

  for (int i = 0; i < remaining.length(); i++)
  {
   String newCandidate = candidate + remaining.charAt(i);

   String newRemaining = remaining.substring(0, i) +
          remaining.substring(i + 1);

   permutations(newCandidate, newRemaining);
  }
 }

 // Find Permutations of a String in Java
 public static void main(String[] args)
 {
  String s = "ABC";
  permutations("", s);
 }
}

Sunday, March 17, 2019

Get key with maximum value in hashmap in java

static String findMax(HashMap<String,Integer> hm){
    Map.Entry<String,Integer> maxEntry = null;
    for(Map.Entry<String ,Integer>entry: hm.entrySet()){
        if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) >= 0)
        {
            maxEntry = entry;
        }


    }
    return maxEntry.getKey();

Tuesday, December 4, 2018

PowerMockito: Mocking static method

Mocking Static method and invoking private static method:

PowerMockito.mockStatic(ClassWithPrivateStaticMethods.class);
PowerMockito.when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString()).thenReturn("dummy");

but the best way is

PowerMockito.spy(ClassWithPrivateStaticMethods.class);
PowerMockito.doReturn("dummy").when(ClassWithPrivateStaticMethods.class, "getParam", Mockito.anyString())
String finalResult = Whitebox.invokeMethod(ClassWithPrivateStaticMethods.class, "getDetail", Mockito.anyString());


More details on:

https://initcodes.blogspot.com/2018/05/powermockito-mocking-one-static-method.html


We can Invoke the private static methods with whitebox from mockito which uses reflection api


public void testLoadLanguageCodeFile()
          throws WorldlingoException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    //testing correct file path    String path = "/webapps/worldlingo/conf/settings/";
    PowerMockito.mockStatic(SystemSettings.class);
    HashMap<String, String> hash_map = new HashMap<String, String>();
    SystemSettings ssmock = Mockito.mock(SystemSettings.class);
    Mockito.when(SystemSettings.GetInstance()).thenReturn(ssmock);
    Mockito.when(ssmock.getLangCodePath()).thenReturn(path);
    Method m = Whitebox.getMethod(MicrosoftEngine.class,"loadLanguageCodeFile", HashMap.class);
    m.invoke(null, hash_map);
    assertTrue((hash_map.containsKey("de") && hash_map.containsKey("ar")) || hash_map.isEmpty());

    //testing incorrect file path    path = "/webapps/worldlingo/conf";
    Mockito.when(ssmock.getLangCodePath()).thenReturn(path);
    hash_map = new HashMap<String, String>();
    try {
      m = Whitebox.getMethod(MicrosoftEngine.class, "loadLanguageCodeFile", HashMap.class);
      m.invoke(null, hash_map);
    }
    catch (InvocationTargetException e){
      String result =  e.getTargetException().toString();
      assertEquals("java.lang.NullPointerException",result);
    }
  }

} // MicrosoftEngineTest



Mockito important tips:

do answer:
      @Test
 public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
 }



Mockito.doAnswer(new Answer() {
      @Override
      public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
        // this will be used to assert the status response
        key[0] =  (String)invocationOnMock.getArguments()[0];
        value[0] =  (String) invocationOnMock.getArguments()[1];
        return null;
      }
    }).when(robMock).addHeader(Mockito.anyString(),Mockito.anyString());


    PowerMokito:
       PowerMockito.whenNew(SFramework.class).withNoArguments().thenReturn(sfMock);

       https://github.com/powermock/powermock/wiki/Mockito#mocking-static-method


    https://initcodes.blogspot.com/2018/07/powermockito-javasecuritynosuchalgorith.html


Monday, July 30, 2018

searching of digit from string using regex and replace from Java String.

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class regex{

public static void main(String []args){
    System.out.println("Hello World");
    String s = "214投資者、43発行者";
    Pattern p = Pattern.compile("([0-9]+)");
    Matcher m = p.matcher(s);
    int index = 0;
    StringBuffer str = new StringBuffer();
    while (m.find()){

        String match = m.group();
        m.appendReplacement(str,"replace"+">");

    }
    m.appendTail(str);
    String result = str.toString();
    System.out.println(result);


   }
}