miércoles, 27 de noviembre de 2019

Collections 2019 Java

Collections 2019 Java



https://github.com/jalbertomr/Collections2019Java.git

Datos Provider

public class Datos {

    List<String> listNombres = new ArrayList<>();
    String[] arrNombres;
    String nombresjuntos = "Álan     Jacinto Martinez Alicia     Jesús     Mirta Andrea     Josefina     Mónica " +
    "Andrés     Juan     Nicolás   Antonia     Juana     Noé    Antonio     Juano     Noelia    Azul     Julia     Paula " +
    "Bartolomé     Julián     Pomponio  Belén     Juliana     Renzo   Celeste     Julio     Rodrigo " +
    "Edgardo     Leandra     Rodriguez    Felicia     Luis     Romina     Florencia     Luisa     Rosario" +
    "Gaspar     Marcelo     Tato   Gerardo     Marcos     Tomás   Gimenez     María     Victor   Gonzalo     Mariano     Yayo "+
    "Gustavo     Martín     Zulema";
    String colores = "Rojo Naranga Amarillo Verde Azul Índigo Violeta";
    String[] arrColores;
    List<String> listColores = new ArrayList<>();

    public Datos() {
        StringTokenizer stoken = new StringTokenizer( nombresjuntos);
        //System.out.println( "stoken.countTokens(): " + stoken.countTokens());
        arrNombres = new String[ stoken.countTokens()];
        int i = 0;
        StringBuilder element = new StringBuilder();

        //System.out.println("Tokens");
        while( stoken.hasMoreTokens()){
            element.setLength(0); element.append( stoken.nextToken());
            //System.out.print( element + ", ");
            arrNombres[ i++ ] = element.toString();
        }
        //System.out.println();

        listNombres = Arrays.asList( arrNombres);
        // Display the filled String[] using Arrays.stream
        //Arrays.stream(arrNombres).forEach(s -> System.out.print(s + " "));

        stoken = new StringTokenizer( colores );
        arrColores = new String[ stoken.countTokens()];

        while(stoken.hasMoreTokens()){
            listColores.add( stoken.nextToken());
        }
        arrColores = listColores.toArray( arrColores);
        //Arrays.stream(arrColores).forEach(s -> System.out.println(s + " "));
    }
};


ArraysLab

public class ArraysLab {
    public ArraysLab() {
        int arrint[] = {10, 20, 30, 40, 50, 60, 70};
        int[] arrint2 = new int[8];
        int[] arrint3 = new int[]{1, 2, 3};
        String arrstr[] = {"cero", "uno", "dos", "tres", "cuatro"};
        String[] arrstr2 = {"cero", "uno", "dos", "tres", "cuatro"};
        String[] arrstr3 = new String[]{"cero", "uno", "dos", "tres", "cuatro"};

        String[][] arrarrStr = {{"cero", "uno", "dos", "tres", "cuatro"},
                {"alfa", "beta", "gamma", "delta", "epsilon"},
                {"000", "1111", "2222", "33333", "44444"}};
        Arrays.stream( arrarrStr).forEach( arrStr -> Arrays.stream( arrStr).forEach( s->System.out.print(s+" ") ) );
        System.out.println();
        Arrays.stream( arrarrStr).forEach( arrStr -> System.out.println(Arrays.stream( arrStr).map( s-> s.concat(" ")).collect(Collectors.toList()) ) );

        displayArrInt(arrint);
        displayArrInt(arrint2);
        displayArrInt(arrint3);

        Arrays.fill(arrint2, 123);
        displayArrInt(arrint2);

        System.out.println(Arrays.binarySearch(arrint, 40));   // 3
        System.out.println( "arrstr[ new Random().nextInt( arrstr.length) ] : " + arrstr[ new Random().nextInt( arrstr.length) ]);

        System.out.println("Fill witn Random");
        arrIntFillRandom(arrint);
        displayArrInt(arrint);
        Arrays.sort(arrint);
        displayArrInt(arrint);

        int[] arrint4 = Arrays.copyOf(arrint, arrint.length + 10);
        displayArrInt(arrint4);

        System.out.println(Arrays.equals(arrint, arrint2));
        System.out.println(Arrays.hashCode(arrint));
        System.out.println(Arrays.toString(arrint));

        // List<Integer>   <- int[]

        List<Integer> listInteger = new ArrayList<>();
        for (int i = 0; i < arrint.length; i++) {
            listInteger.add(arrint[i]);
        }
        System.out.println(listInteger.toString() + " size: " + listInteger.size());

        List<Integer> listInt2 = Arrays.asList(2, 3, 4, 5);
        System.out.println(listInt2.toString() + " size: " + listInt2.size());

        //List<String>
        List<String> listStr2 = Arrays.asList("luis", "juan");
        System.out.println(listStr2.toString());
    }

    private void displayArrInt(int[] arrint) {
        for (int i = 0; i < arrint.length; i++) {
            System.out.print(arrint[i] + ", ");
        }
        System.out.println();
    }

    private void arrIntFillRandom(int[] arrint) {
        for (int i = 0; i < arrint.length; i++){
            arrint[i] = (int) Math.round((Math.random() * 100));
        }
    }

}


ListLab

public class ArrayListLab {

    public ArrayListLab() {
        int intPrimitive = 12;
        Integer intObj = 130;
        double doublePrimitive = 234.33;
        Double doubleObj = 5434.654;

        intPrimitive = (int) doublePrimitive;
        intPrimitive = doubleObj.intValue();
        intPrimitive = (int) Math.round(doubleObj);

        intPrimitive = intObj.intValue();

        // Lists
        int[] arrint = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
        System.out.println(arrint.length);
        List<Integer> listInt = new ArrayList<>(); //                    ArrayList
        //List<Integer> listInt = Arrays.asList( 2, 3, 4, 7, 34, 21); // List
        for (int i = 0; i < arrint.length; i++){
            listInt.add( arrint[i]);
        }

        Integer[] arrInteger = { 23,54,2,24,65,33,23,66,98,65};
        List<Integer> listInt2 = new ArrayList<Integer>( Arrays.asList( arrInteger ) );

        displayListIntFor(listInt);
        displayListIterator(listInt);
        displayListStream(listInt);
        System.out.println("listInt2");
        displayListIntFor(listInt2);

        System.out.println("arrint[0]: " + arrint[0] );
        System.out.println("listInt.get(0): " + listInt.get(0));
        //remove
        listInt.remove( new Integer(3)); // remove object Integer 3
        displayListIntFor(listInt);
        listInt.remove( listInt.size() - 1 );  // remove index, the last element
        displayListIntFor(listInt);

        List<String> listStrA = new ArrayList<>();
        for (int i = 0; i < 6; i++){
            listStrA.add( String.valueOf( i ) );
            listStrA.add( Integer.toString( i ));
            displayListIterator( listStrA);
        }

/*
        List<String> listStr = Arrays.asList("A","E","I","O","U"); //List
        displayListIterator(listStr);
        listStr.remove("A");     //can not be accessed
*/
        //List.add() ArrayList.add()
        List<String> listStr = new ArrayList<>();
        listStr.add("A"); listStr.add("B");listStr.add("A");listStr.add("C");listStr.add("A");
        listStr.add("D"); listStr.add("A");listStr.add("E");listStr.add("A");listStr.add("F");
        displayListIterator(listStr);
        listStr.add(1,"addAtIndex1");
        displayListIterator(listStr);
        listStr.remove("addAtIndex1");
        displayListIterator(listStr);

        //List.addAll(index, collection)
        // create the Arraylist<String> filled from an array of string
        String[] arrStringBLOCK = {"B","L","O","C","K"};
        List<String> listStrBlock = new ArrayList<>( arrStringBLOCK.length);
        for (int i = 0; i < arrStringBLOCK.length; i++){
            listStrBlock.add(arrStringBLOCK[i]);
        }
        displayListIterator(listStrBlock);

        listStr.addAll(listStrBlock);
        displayListIterator(listStr);

        listStr.addAll(2,listStrBlock);
        displayListIterator(listStr);

        // List.get(index) , List.set(index, object)
        System.out.println( "listStr.get(0): " + listStr.get(0) );
        System.out.println( "listStr.get(19): " + listStr.get(19) );
        System.out.println("listStr.set(19,\"ZZ\") :" + listStr.set(19,"ZZ") );
        displayListIterator(listStr);

        System.out.println("listStr.lastIndexOf(\"A\"): " + listStr.lastIndexOf("A"));
        List<String> miSubListStr = listStr.subList(0, 4);
        System.out.println("listStr.subList(0, 4) : "); displayListIterator( miSubListStr);
        listStr.remove("A");
        displayListIterator(listStr);
/*
        listStr.add("A");
        displayListIterator(listStr);
        while (listStr.remove("A")){     //remove all the "A" and display the list each iteration
            displayListIterator(listStr);
        }
*/
    }

    private void displayListIterator(List list) {
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }

    private void displayListIntFor(List<Integer> list) {
        for ( int e : list)  {
            System.out.print( e + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }


    private void displayListIntForOld(List<Integer> list) {
        for ( int i = 0; i < list.size(); i++) {
            System.out.print( list.get(i) + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }

    private void displayListStream(List list) {
        list.stream().forEach(e -> System.out.print(e + ", "));
        System.out.print("size: " + list.size());
        System.out.println();
    }
}

LinkedListLab

public class LinkedListLab {
    LinkedListLab() throws InterruptedException {
        System.out.println("LinkedListLab");
        /*
        LinkedList.addFirst(Object E);
        LinkedList.addLast( Object E);
         */

        LinkedList<String> miLList = new LinkedList<>();
        LinkedList<String> miLListRESP = new LinkedList<>();
        //Collections.shuffle(list, new Random());
        displayListIterator(miLList);
        miLList.addFirst("addFirst1");
        miLList.addFirst("addFirst2");
        miLList.addFirst("addFirst3");
        miLList.addLast("addLast1");
        miLList.addLast("addLast2");
        miLList.addLast("addLast3");
        miLListRESP.addAll(miLList);
        displayListIterator(miLListRESP);
        displayListIterator(miLList);

        System.out.println("miLList.getFirst(): " + miLList.getFirst());
        System.out.println("miLList.getLast(): " + miLList.getLast());

        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());

        miLList.clear();
        miLList.addAll(miLListRESP);
        displayListIterator(miLList);
        System.out.println("miLList.set( 2,\"set(2,obj)\"): " + miLList.set(2, "set(2,obj)"));
        displayListIterator(miLList);
        System.out.println("miLList.get(3): " + miLList.get(3));

        System.out.println("miLList.add(\"add1\"): " + miLList.add("add1"));  //add at last
        System.out.println("miLList.add(\"add2\"): " + miLList.add("add2"));  //add at last
        displayListIterator(miLList);
        System.out.println("miLList.remove(2): " + miLList.remove(2));
        displayListIterator(miLList);

        miLList.clear();
        miLList.addAll(miLListRESP);
        displayListIterator(miLList);
        displayListIterator(miLListRESP);
        System.out.println("miLListRESP.containsAll( miLList): " + miLListRESP.containsAll(miLList));
        miLList.add("EXTRA");
        displayListIterator(miLList);
        displayListIterator(miLListRESP);
        System.out.println("miLListRESP.containsAll( miLList): " + miLListRESP.containsAll(miLList));

        Spliterator spliterator = miLList.spliterator();

        Datos datos = new Datos();
        miLList.clear();
        miLList.addAll(datos.listNombres.subList(0, 10));
        miLList.stream().forEach(s -> System.out.print(s + " "));
        System.out.println();

        miLList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return removeAccents(o1).compareTo(removeAccents(o2));
            }
        });
        miLList.stream().forEach(s -> System.out.print(s + " "));
        System.out.println();

        // LikedList  add , Remove  better performance than ArrayList
        //            get, set      lower perforance than ArrayList

        miLList.clear();
        miLList.addAll(datos.listNombres.subList(0, 5));
        displayLinkedList(miLList);
        ListIterator<String> listIterator = miLList.listIterator();
        System.out.println("ListIterator.hasNext()  ListIterator.next()");
        int i = 1;
        int showtime = 100;
        while (listIterator.hasNext()) {
            System.out.println(String.format("%" + 12 * i + "s", listIterator.next()));
            Tsleep(showtime);
            i++;
        }

        System.out.println("ListIterator.hasPrevious()  ListIterator.previous()");
        i--;
        while (listIterator.hasPrevious()) {
            System.out.println(String.format("%" + 12 * i + "s", listIterator.previous()));
            Tsleep(showtime);
            i--;
        }

        displayLinkedList(miLList);

        i = 1;
        while (listIterator.hasNext()) {
            if (listIterator.nextIndex() == 2) break;
            System.out.println(String.format("%" + 12 * i + "s", listIterator.next()));
            Tsleep(showtime);
            i++;
        }

/*
|      Álan||   Jacinto||  Martinez||    Alicia||     Jesús|
        Álan
                 Jacinto
 */
        System.out.println("listIterator.add(\"ADDIT\");");
        listIterator.add("ADDIT");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||     ADDIT||  Martinez||    Alicia||     Jesús|
 */
        System.out.println("if (listIterator.hasPrevious()) { listIterator.previous(); listIterator.remove(); }");
        if (listIterator.hasPrevious()) {
            listIterator.previous();
            listIterator.remove();
        }
        displayLinkedList(miLList);

        System.out.println("listIterator.nextIndex(): " + listIterator.nextIndex());
        System.out.println("listIterator.add(\"ADDagain\");");
        listIterator.add("ADDagain");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("listIterator move to the end");
        while (listIterator.hasNext()) {
            listIterator.next();
        }
        System.out.println("listIterator.add(\"AlFinal\");");
        listIterator.add("AlFinal");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús||   AlFinal|
 */

        System.out.println("if ( listIterator.hasPrevious() ) { listIterator.previous();  }");
        System.out.println("listIterator.remove();");
        if (listIterator.hasPrevious()) {
            listIterator.previous();
        }
        listIterator.remove();
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("move to the begining and add");
        while (listIterator.hasPrevious()) listIterator.previous();
        listIterator.add("addBegin");
        displayLinkedList(miLList);
/*
|  addBegin||      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("if (listIterator.hasPrevious()) listIterator.previous();");
        System.out.println("listIterator.remove();");
        if (listIterator.hasPrevious()) listIterator.previous();
        listIterator.remove();
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */
        System.out.println("miLList.remove(\"ADDagain\")" + miLList.remove("ADDagain"));
        miLList.remove("ADDagain");
        displayLinkedList(miLList);
    }

    public  static String removeAccents(String text) {
        return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD)
                .replaceAll("\\p{InCOMBINING_DIACRITICAL_MARKS}+","");
    }

    private void displayLinkedList( LinkedList linkedList) {
        int cellLength = 10;
        linkedList.stream()
                .map(s -> String.format("|%" + cellLength + "s|", s))
                .forEach( s -> System.out.print( s));
        System.out.println();
    };

    private void Tsleep(int miliseconds)  {
        try {
            Thread.sleep( miliseconds);
        } catch( InterruptedException ie) {
            System.err.format( "InterruptedException: %s%n" + ie);
        };
    }

    private void displayListIterator(List list) {
        System.out.print("size: " + list.size() + " ");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.println();
    }

    private void displayListIntFor(List<Integer> list) {
        System.out.print("size: " + list.size() + " ");
        for ( int i = 0; i < list.size(); i++) {
            System.out.print( list.get(i) + ", ");
        }
        System.out.println();
    }

    private void displayListStream(List list) {
        System.out.print("size: " + list.size() + " ");
        list.stream().forEach(e -> System.out.print(e + ", "));
        System.out.println();
    }
}

QueueLab

public class QueueLab {
    public QueueLab() {        System.out.println("QueueLab");
        /*

         */

        Queue<String> miQueue = new LinkedList<>();
        Queue<String> miQueueRESP = new LinkedList<>();
        //Collections.shuffle(list, new Random());
        displayQueueIterator(miQueue);
        miQueue.add("add1");
        displayQueueIterator(miQueue);
        miQueue.add("add2");
        displayQueueIterator(miQueue);
        miQueue.add("add3");
        displayQueueIterator(miQueue);
        miQueue.add("add4");
        displayQueueIterator(miQueue);
        miQueue.add("add5");
        displayQueueIterator(miQueue);
        miQueue.add("add6");
        displayQueueIterator(miQueue);
        miQueueRESP.addAll(miQueue);
        displayQueueIterator(miQueueRESP);
        displayQueueIterator( miQueue);

        System.out.println("miQueue.poll(): " + miQueue.poll());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.poll(): " + miQueue.poll());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueue);

        miQueue.clear();
        miQueue.addAll(miQueueRESP);
        displayQueueIterator(miQueue);
        System.out.println("miQueue.peek(): " + miQueue.peek());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.poll(): " + miQueue.poll() );
        displayQueueIterator(miQueue);

        System.out.println( "miQueue.add(\"add1\"): "  + miQueue.add("add1"));  //add at last
        System.out.println( "miQueue.add(\"add2\"): "  + miQueue.add("add2"));  //add at last
        displayQueueIterator(miQueue);
        System.out.println( "miQueue.remove(2): " + miQueue.remove(2));
        System.out.println( "miQueue.remove(\"add2\")" + miQueue.remove("add2"));

        displayQueueIterator(miQueue);

        miQueue.clear();
        miQueue.addAll( miQueueRESP);
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueueRESP);
        System.out.println( "miQueueRESP.containsAll( miQueue): " + miQueueRESP.containsAll( miQueue) );
        miQueue.add("EXTRA");
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueueRESP);
        System.out.println( "miQueueRESP.containsAll( miQueue): " + miQueueRESP.containsAll( miQueue) );

    }

    private void displayQueueIterator(Queue queue) {
        System.out.print("size: " + queue.size() + " ");
        Iterator iterator = queue.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.println();
    }

    private void displayQueueIntFor(Queue<Integer> queue) {
        System.out.print("size: " + queue.size() + " ");
        for ( int i = 0; i < queue.size(); i++) {
            System.out.print( "queue.get(i) NOT ENABLED");
        }
        System.out.println();
    }

    private void displayQueueStream(Queue queue) {
        System.out.print("size: " + queue.size() + " ");
        queue.stream().forEach(e -> System.out.print(e + ", "));
        System.out.println();
    }


}

SetLab

public class SetLab {
    public SetLab() {

        //int[] arrint = {1,4,2,5,7,11,12,75,23,76};
        Integer[] arrInt = {12,12,75,23,23,76,1,4,2,5,7,11,12,23};
        //HashSet<Integer> hashSet = new HashSet<>(Arrays.asList(1,4,2,5,7,11,12,75,23,76));
        HashSet<Integer> hashSet = new HashSet<>( Arrays.asList( arrInt));
        TreeSet<Integer> treeSet = new TreeSet<>( Arrays.asList( arrInt));

        System.out.print("ORIGINAL          : ");
        displayArr( arrInt);
        //displayIterator( hashSet);
        System.out.print("HashSet Sin Orden : ");
        displayFor( hashSet);
        System.out.print("TreeSet Con Orden : ");
        displayFor( treeSet);
        //displayForEach( hashSet);

        HashSet<Integer> hashSet2 = new HashSet<>();

        hashSet2.addAll( hashSet);

        System.out.println("hashSet2");
        displayFor( hashSet2);

        System.out.println("hashSet.equals(hashSet): " + hashSet.equals( hashSet));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        System.out.println("hashSet2.add( 11): " + hashSet2.add( 11));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        System.out.println("hashSet2.add( 99): " + hashSet2.add( 99));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        HashSet<Integer> hashSetResp = new HashSet<>( hashSet);
        HashSet<Integer> hashSet2Resp = new HashSet<>( hashSet2);
        displayFor( hashSetResp);
        displayFor( hashSet2Resp);

        System.out.println("hashSet.retainAll( hashSet2): " + hashSet.retainAll( hashSet2));
        System.out.println("hashSet2.retainAll( hashSet): " + hashSet2.retainAll( hashSet));

        hashSet.clear(); hashSet.addAll( hashSetResp);
        hashSet2.clear(); hashSet2.addAll( hashSet2Resp);

        System.out.println(hashSet2.removeAll( hashSet));
        displayFor(hashSet2);

        System.out.println("hashSet2.contains( 99): " + hashSet2.contains( 99));
        System.out.println("hashSet.contains( 99): " + hashSet.contains( 99));

        System.out.println( String.format("%3s", "2").replace(" ","0"));
        Set<String> set = new TreeSet<String>((o1, o2) ->  String.format("%3s", o1.substring( o1.indexOf(" ") + 1)).replace(" ","0")
                                         .compareTo(  String.format("%3s", o2.substring( o2.indexOf(" ") + 1)).replace(" ","0")
                                         ));
        //Set<String> set = new TreeSet<String>((o1, o2) ->  o1.substring( o1.indexOf(" ") + 1)
        //        .compareTo(  o2.substring( o2.indexOf(" ") + 1)));

        set.add("test 15");
        set.add("dfd 2");
        set.add("ersfd 20");
        set.add("asdt 10");
        set.stream().forEach(s -> System.out.println(s));


    }

    private void displayArr(Integer[] arrInt) {
        for (int i = 0; i < arrInt.length; i++){
           System.out.print( arrInt[i] + ", ");
        }
        System.out.print( "size: " + arrInt.length);
        System.out.println();
    }

    private void displayForEach(HashSet<Integer> hashSet) {
        hashSet.forEach(e -> System.out.print(e + ", ") );
        System.out.print( "size: " + hashSet.size());
        System.out.println();
    }

    private void displayFor(Set<Integer> set) {
        for( Integer e: set){
            System.out.print( e + ", ");
        }
        System.out.print( "size: " + set.size());
        System.out.println();
    }

    private void displayIterator(Set set) {
        Iterator iter = set.iterator();
        while ( iter.hasNext()){
            System.out.print( iter.next() + ", ");
        }
        System.out.print( "size: " + set.size());
        System.out.println();
    }
}

HashMapLab

public class HashMapLab {

    public HashMapLab() {
        HashMap<String, Integer> hashMapColor = new HashMap<>();

        String colores = "Rojo Naranga Amarillo Verde Azul Índigo Violeta";  //orden del arcoiris

        System.out.println(colores);
        StringTokenizer stringTokenizer = new StringTokenizer(colores);
        int i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            hashMapColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        //display hashMap
        hashMapColor.entrySet().stream()
                .map(s -> String.format("|%" + 10 + "s|", s))
                .forEach(s -> System.out.print(s));
        System.out.println();

        //display hashMap using BiConsumer
        hashMapColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        // TreeMap (alphabetic order) Order)
        System.out.println("TreeMap");
        Map<String, Integer> alphaOrderColor = new TreeMap<>();
        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            alphaOrderColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        alphaOrderColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        System.out.println("TreeMap order without accent");
        Map<String, Integer> alphawithoutAccentOrderColor = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return removeAccents(o1).compareTo(removeAccents(o2));
            }
        });

        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            alphawithoutAccentOrderColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        alphawithoutAccentOrderColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        // lambda y constructor TreeMap
        System.out.println("TreeMap order without accent Lambda in TreeMap constructor");
        Map<String, Integer> valueOrderLambdaColor = new TreeMap<>((o1, o2) -> removeAccents(o1).compareTo(o2));
        //Map<String, Integer> valueOrderLambdaColor = new TreeMap<>((o1, o2) -> o2.compareTo(o1));
        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            valueOrderLambdaColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        valueOrderLambdaColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        List<Map.Entry<String, Integer>> listSortbyValue;
        System.out.println("Map sorted by Value");
        listSortbyValue = sortMapByValue(valueOrderLambdaColor);
        listSortbyValue.stream().forEach(e -> System.out.print(String.format("|%" + 10 + "s", e.getKey()) + ":" + e.getValue() + "|"));

        Map<String, List<String>> sinonimos = new TreeMap<>();

/*
        witty "amusing, humorous, funny, clever, facetious, smart, entertaining, whimsical, jokey, jocular, droll, comedic"
        joker "comic, clown, comedian, funnyman"
        slum "ghetto , hood (Slang), skid row, shanty town, the wrong side of the tracks (informal), poor neighborhood"
                sloopy "disordered, disorderly, cluttered, disarranged, unkempt, disheveled"
        stink "stench , reek, funk , odor, odour (UK), smell , bad smell, bad odor"

        preclude "prevent , stave off, head off, ward off, avert , avoid , negate, neutralize"
        nuance "subtlety, distinction , difference , fine point, shade"
        weild "exercise , exert , apply , ply, use , effect , command , control , manage"
        fate "luck , chance , fortune , happenstance (mainly US), good luck, bad luck, misfortune, good fortune, bad fortune"
                apalled shock , amaze, horrify, dismay , surprise , disgust, offend, cause offense
        cripping disabled person, handicapped person (dated), the handicapped (dated), the disabled, amputee, paraplegic
                tenant renter, lessee, rent payer, lodger, boarder, leaseholder, holder
        rift fissure, split , crack , break , fracture, hole , tear , gap
                hail barrage , torrent, deluge, shower , salvo, volley, battery
        relay communicate , pass on, pass along, convey , send , deliver , forward , transmit, transfer , circulate


    squeaking squeal , shrill sound, shrill cry, narrow escape
    wee small , tiny , infinitesimal, little , minute , negligible
        screech shriek , yell , outcry , cry , scream , howl , wail

    swooping plunge , fall , drop , descent , dive , chute, slide
    warfare combat, war , conflict , armed conflict, hostilities, fighting
    meek subdued , weak , yielding, docile, submissive, compliant , resigned
    invoice bill , itemized bill, tab (informal), request for payment, bill of account
    relinquish give up, surrender , give away, renounce, abandon , waive , hand over, get rid of, shed
*/

    }

    private List<Map.Entry<String, Integer>> sortMapByValue(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> elements = new LinkedList<>( map.entrySet());
        Collections.sort( elements, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return elements;
    }

    private Map<String, Integer> countWords( List<String> words) {
        Map<String, Integer> mapWordCount = new TreeMap<>();
        for (String word: words) {
            if ( mapWordCount.containsKey( word)){
                int count = mapWordCount.get(word) + 1;
                mapWordCount.put( word, count);
            } else {
                mapWordCount.put( word, 1);
            }
        }
        return mapWordCount;
    }

    public  static String removeAccents(String text) {
        return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD)
                .replaceAll("\\p{InCOMBINING_DIACRITICAL_MARKS}+","");
    }

    private void displayKVformatted(String k, Integer v) {
        String str = String.format("%" + 10 + "s", k);
        System.out.println( str + " " + v);
    }

    //System.out.print( String.format("|%" + 10 + "k|", k.toString()) + " " + v)
}

StreamLab


public class StreamLab {
    public StreamLab() {

        //reduceStreamMayor();
        reductions();
    }

    private void reductions() {

/*   https://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/reduction.html
    Returns
       Single Value:   min(), max(),  count(), sum(),  average(), summaryStatistics()
       Collections:    collect(), toArray()

       fold operations uses binary function ( accumulator ) whose first argument is the
       value returned from the last excecution of the same function, second argunent is the
       current stream element
       (a, b) ->
       a previos result, b current element of the stream

       BiFunction
          |
       BinaryOperator
 */
        // (1) Optional<T>  reduce( BinaryOperator<T> accumulator)

        int i = IntStream.range(1, 6)
                .reduce((a, b) -> a * b)
                .orElse(-1);
        System.out.println("product:" + i);

        i = IntStream.range(1, 6).sum();
        System.out.println("sum:" + i);

        // (2) T reduce ( T Identity, BunaryOperator<T> accumulator)
        // Identity is the initial value of reduction
        i = IntStream.range(1, 6)
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100: " + i);

        i = IntStream.empty()
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100 with empty stream: " + i);

        i = IntStream.range(1, 6)
                .parallel()
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100 paralelized (identity taken many times (wrong answer)): " + i);

        //(3) <U> U reduce(U identity,
        //                 Bifunction<U, ? super T,U> accumulator,
        //                 BinaryOperator<U> combiner)
        //  this is a combination of map() and reduce()
        // the identity value must be an identity for the combiner function
        // combiner(identity, u) == u
        // also combiner must be compatible with accumulator
        // combiner.apply( u, accumulator.apply( identity, t)) == accumulator.apply( u, t)

        i = Stream.of("2","3","4","5")     // using anonymous classes
                .parallel()
                .reduce(0, new BiFunction<Integer, String, Integer>() {
                    @Override
                    public Integer apply(Integer integer, String s) {
                        return Integer.sum(integer, Integer.parseInt(s));
                    }
                }, new BinaryOperator<Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2) {
                        return Integer.sum( integer, integer2);
                    }
                });
        System.out.println("string values converted and sumed: " +  i );

        i = Stream.of("2","3","4","5")     // using anonymous classes
                .parallel()
                .reduce( 0, ( integer, s) -> Integer.sum(integer, Integer.parseInt( s )),
                        ((integer, integer2) -> Integer.sum( integer, integer2)));
        System.out.println("string values converted and sumed: " +  i );

        // Stream min()
        // Optional<T> min( Comparator<? super T> comparator)

        String miStr = Stream.of("Perro","zanahoria","caballo")
                    .min(String::compareTo)
                    .get();
        System.out.println(miStr);

        miStr = Stream.of("Perro","zanahoria","caballo")
                .filter(e -> e.length() == 3)
                .min(String::compareTo)
                .orElse("Ninguno");
        System.out.println(miStr);

        Optional<String> miReduce = Stream.of("Perro","zanahoria","caballo")
                .reduce( (s, s2) -> s.compareTo(s2) <= 0 ? s : s2);
        System.out.println(miReduce);

         miStr = Stream.of("Perro","zanahoria","caballo")
                .max(String::compareTo)
                .get();
        System.out.println(miStr);

        miReduce = Stream.of("Perro","zanahoria","caballo")
                .reduce((s,s2)-> s.compareTo(s2) > 0 ? s :s2);
        System.out.println(miStr);

        double midouble = DoubleStream.of( 1.3, 2.5, 3, 5.4)
                .sum();
        System.out.println(midouble);

        midouble = DoubleStream.of(1.3, 2.5, 3, 5.4)
                .reduce( 0 , Double::sum);
        System.out.println(midouble);

        double average = LongStream.range(1, 10)
                .average()
                .orElse(-1);
        System.out.println( average);

        long micount = Stream.of("Perro","zanahoria","caballo")
                .count();
        System.out.println( micount);

        micount = Stream.of("Perro","zanahoria","caballo")
                .mapToLong( s -> 1L)
                .sum();

        System.out.println( micount);

        IntSummaryStatistics miStat = IntStream.rangeClosed(1,10)
                .summaryStatistics();
        System.out.println(miStat);


    }

    private void reduceStreamMayor() {
        //List<String> words = new ArrayList<>();   // If we want it Empty
        List<String> words = Arrays.asList("Esta","es","una","prueba","para","obtener","la","palabra","mayor","o","menor");

        System.out.println(words.toString());

        Optional<String> longestWord = words.stream()
                .reduce( (word1, word2 )-> word1.length() > word2.length() ? word1 : word2);
        System.out.println( "longestWord: " + longestWord);

        Optional<String> shortestWord = words.stream()
                .reduce( ( word1, word2) -> word1.length() < word2.length() ? word1 : word2);
        System.out.println( "shortestWord: " + shortestWord);
        if (shortestWord.isPresent()) System.out.println(shortestWord.get());

        // Array <- list
        String[] arrString = new String[ words.size() ];
        arrString = words.toArray( arrString );
        Arrays.stream( arrString).forEach(a-> System.out.print(a + " "));
        //String[] arrString = {"Esta","es","una","prueba","para","obtener","la","palabra","mayor","o","menor"};

        Optional<String> joinedWords = Arrays.stream( arrString)
                .reduce( (word1, word2) -> word1 + "-" + word2 );
        if ( joinedWords.isPresent()) {
            System.out.println( joinedWords.get());
        }

        // Stream reduce sum a list of integers
        Integer[] arrInt = {-2, 0, 200, 12, 23, -45};

        List<Integer> listInt = new ArrayList<>( Arrays.asList( arrInt));
        listInt.stream().forEach( e -> System.out.print(e + " "));
        System.out.println();

        Optional<Integer> sumArrInt = Arrays.stream( arrInt)   // arrInt to stream.reduce
                .reduce( (a, b) -> a + b);
        if ( sumArrInt.isPresent()) {
            System.out.println( "sumArrInt: " + sumArrInt );
        }

        LongStream.range( 2,10).forEach(a-> System.out.print(a + " "));  // LongStream.range  reduce   .orElse exclude the right most element
        long product = LongStream.range( 2, 10)
                .reduce( (a, b) -> a * b)
                .orElse(-1);
        System.out.println("product: " + product );

        LongStream.range( 2,10).forEach(a-> System.out.print(a + " "));  // LongStream.range  reduce   .orElse exclude the right most element
        long sumaA = LongStream.range( 2, 10)
                .reduce( (a, b) -> a + b).getAsLong();
                //.orElse(-1);
        System.out.println("sumaA: " + sumaA );

        long sumaB = LongStream.of(1L, 1L, 1L, 1L, 1L)
                .reduce( (a, b) -> a + b)
                .orElse( -1);
        //.orElse(-1);
        System.out.println("sumaB: " + sumaB );  // sumaB: 5


    }
}


eot

lunes, 25 de noviembre de 2019

Class Relationship UML (PlantUML)

Class Relationship UML (PlantUML)

UML   Unified Model Language

https://plantuml.com/es/class-diagram

PlantUML uses Graphviz as library to get work.

 Relations

@startuml

Class01 <|-- Class02:extends
Class03 <|.. Class04:implements
@enduml

@startuml

ClassA <-- ClassB:Association
ClassC <|-- ClassD:Inheritance
ClassE <|.. ClassF:"Realization/\nImplementation"
ClassG <.. ClassH:"Dependency"
ClassI o-- ClassJ:"Aggregation"
ClassK *-- ClassL:"Composition"
@enduml



@startuml

ClassE <|.. ClassF:"Implementation"
ClassA --> ClassB:"Association"
ClassC ..> ClassD:"Dependency"
ClassG <.. ClassH:"Dependency"
ClassI ..|>  ClassJ:"Implementation"

@enduml



@startuml

ClassA #-- ClassB
ClassC x-- ClassD
ClassE }-- ClassF
ClassG +-- ClassH
ClassI ^-- ClassJ
ClassParent --> ClassParent
@enduml


@startuml

Bank <--  Account:"registrer"

OrderItem "0..*" --> "1" Item:refers
_OrderItem "0..*" <-- "1" _Item:describes
Class OrderItem_ {
 List<Item> item
}
@enduml



Aggregation


@startuml

Group "1" o--> "0..*" Person
Class ClassGroup {
     // Aggregation
    List<ClassPerson> person
    addPerson( Person person)
    { person.add( person); }
}
@enduml



 Composition


@startuml
House "1" *--> "has 1..*" Room
Class ClassHouse {
     // Composition
    List<ClassRoom> room
    addRoom()
    { room.add( new ClassRoom()) ; }
}

class Car
Driver - Car : drives >
Car *-- Wheel : have 4 >
Car -- Person : < owns

@enduml




Practical Example of Log4J2 Architecture

@startuml
interface Configuration
interface "Filter"
interface " Filter"
interface "  Filter"

interface Logger
interface Appender

interface Layout
interface StrLookup
interface LogEvent


class StrSubstitutor

class LoggerContext

interface Logger
class LoggerConfig


LoggerContext "1" -> "1" Configuration:has active
LoggerContext "1" o--> "0..*" Logger:contains

Logger "0..*" -> "1" LoggerConfig:asociates
Configuration "1" -> "1" StrSubstitutor:references

Configuration "1" o--> "1..*" LoggerConfig:contains
Configuration "1" o-up-> "0..*" "  Filter":contains

StrSubstitutor "1" o-up-> "1..*" StrLookup:"evaluate variables"
LoggerConfig "0..*" -right-> "0..*" Appender:contains
LoggerConfig "1" o--> "0..*" Filter:contains

Appender "1" o--> "0..*" " Filter":contains
Appender - Layout:asociates
Appender --> LogEvent:deliver

LogEvent <-down- Layout:format

Filter --() LogEvent:filters
" Filter" --() LogEvent:filters
"  Filter" -() LogEvent:filters


enum StandardLevel {
ALL
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
OFF
}

@enduml


An Activity example

@startuml

:Application to be logged;
startpartition Configuration

fork

:Log4J2 Events;
partition Filter {
:status="FATAL"]
}
fork againpartition Properties {
:filename=target/test.log]
}
:App LogEvent;
partition "Filter 1 (type, level)" {
}
partition "Filter ...N (type, level)" {
}

end forkpartition Appenders {
 note :Appender1 type, name..\n  Layout..\n  Filter..\nAppender..N type, name..\n  Layout..\n  Filter..
}

forkpartition "logger Root: level" {
note right: refers to appender
:appenderRef 1->;
:"appenderRef ..N"->;
}

fork againpartition "logger1 name, level" {
:appenderRef 1->;
:appenderRef ..N"->;
}
fork againpartition "logger..N name, level"{
:appenderRef 1->;
:appenderRef ..N"->;

}
end forkstop@enduml



eot

Log4J2 Architecture, Configuration


Log4J2 Architecture

  Extended diagram of architecture accord to the description and source code.

reference https://logging.apache.org/log4j/2.x/index.html


The original diagram that is on the official web page is


Why Log4j2



Alternatives: SLF4J, LogBack
Why Log4j2
1.- Log4J1 and Logback loss events while reconfigurating. Log4j2 Don’t.
     Appenders can be configurated to allow exception
2.- Next generation Asyncronous Loggers based on LMAX Disruptor Library. Multi-threaded scenarios Asynchronous Logger have 10 times higher throughput, low latency.
3.- Log4j2 is garbage free.
4.- Plugin system for easy extend the framework by adding new Appenders, Filters, Layouts, Lookups.
6.- Support custom log levels.
7.- Support Lambd Expressions.
8.- Support Message object, for passing it though logging system. Message Types can be custom also the Layouts, Filters, Lookups to manipulate them.
9.- Support Filters can be configurated  to process events before they are handled by a Logger. Or Appender.
10.- Appenders accept a Layout, allowing the data to be transported in any format desired.
11.- Layout always return a byte array, can by used on any Appender, not only those of OutputStream
12.- Syslog appender supports TCP, UDP

Architecture description


  The diagram UML is self explanatory, following the relations and the cardinality.
  Consider that exists also a AsyncAppender.

Configuration Example

  The posibilities of configurations are so many, on diferent file formats like XML, JSON, YAML, properties. To Start in a Simple maner is described on next picture the flow control of logEvent generated on the Application.


The program to be used for test log4j2
Main App for Test

public class Scheduler {
    final static Logger logger = LogManager.getLogger(); 
    //final static Logger logger = LogManager.getLogger( Scheduler.class);   // same
    public static void main(String... args) {
        LoggerContext loggerContext = LoggerContext.getContext(); 
        System.out.println( String.format("logger.getName(), getLevel() = %s, %s", logger.getName(), logger.getLevel()));    //com.bext.Scheduler 
        System.out.println( "loggerContext.getName(): " + loggerContext.getName()); // Default 
        System.out.println( "Congifuration.toString(): " + LoggerContext.getContext().getConfiguration().toString());   
        //Configurator.setRootLevel( Level.ALL); 
        logger.trace("Scheduler  [..."); 
        if (!logger.isTraceEnabled()) System.out.println("Scheduler Trace is Disabled"); 
        if (!logger.isInfoEnabled()) System.out.println("Scheduler Info id Disabled"); 
        if (!logger.isDebugEnabled()) System.out.println("Scheduler Debug is Disabled");
        if (!logger.isWarnEnabled()) System.out.println("Scheduler Warn is Disabled"); 
        if (!logger.isErrorEnabled()) System.out.println("Scheduler Error is Disabled"); 
        if (!logger.isFatalEnabled()) System.out.println("Scheduler Fatal is Disabled"); 
        logger.debug("Scheduler logging debug"); 
        logger.info("Scheduler logging info"); 
        logger.warn("Scheduler logging warn "); 
        logger.error("Scheduler logging error "); 
        logger.fatal("Scheduler logging fatal ");
        ServiceA serviceA = new ServiceA();        serviceA.info();
        logger.trace("Scheduler  ...]");
    }
}

Auxiliar class ServiceA

public class ServiceA {
    final static Logger logger = LogManager.getLogger(); 
  //final static Logger logger = LogManager.getLogger( ServiceA.class);
    public String info() {
        System.out.println( String.format("logger.getName(), getLevel() = %s, %s", logger.getName(), logger.getLevel()));         
        logger.trace("ServiceA.info()  [..."); 
        if (!logger.isTraceEnabled()) System.out.println("ServiceA Trace is Disabled"); 
        if (!logger.isInfoEnabled()) System.out.println("ServiceA Info id Disabled"); 
        if (!logger.isDebugEnabled()) System.out.println("ServiceA Debug is Disabled"); 
        if (!logger.isWarnEnabled()) System.out.println("ServiceA Warn is Disabled"); 
        if (!logger.isErrorEnabled()) System.out.println("ServiceA Error is Disabled"); 
        if (!logger.isFatalEnabled()) System.out.println("ServiceA Fatal is Disabled"); 
        logger.debug("logging debug"); 
        logger.info("logging info"); 
        logger.warn("logging warn "); 
        logger.error("logging error "); 
        logger.fatal("logging fatal "); 
        logger.trace("ServiceA.info()  ...]"); 
   return "MessageSerivice.info Junit5";    }
}


Lets Start with a simle config file which generates an output of a simple scheduler that calls a simple service. this outpus goes to STDOUT

log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> 
<Configuration status="TRACE" strict="true" name="XMLConfigTest"               packages="">
     <Appenders> 
       <Appender type="Console" name="STDOUT">
          <Layout type="PatternLayout" pattern="%d{HH:mm:ss.SSS} |%-5p | %-15c{1} | %m%n"/>
       </Appender> 
     </Appenders> 
     <Loggers>  
        <Root level="TRACE"> 
           <AppenderRef ref="STDOUT"/>  
        </Root> 
     </Loggers>
 </Configuration>


We get lots of info, before and after the info we are interested on, that's because the Configuration status is on TRACE, So let filter to FATAL to discard the info related to the log4j2 framework.

...
2019-11-27 13:41:15,057 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=*,subtype=RingBuffer'
2019-11-27 13:41:15,057 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2
2019-11-27 13:41:15,058 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=StatusLogger
2019-11-27 13:41:15,058 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=ContextSelector
2019-11-27 13:41:15,058 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=
2019-11-27 13:41:15,058 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=STDOUT
2019-11-27 13:41:15,058 main TRACE Using DummyNanoClock for nanosecond timestamps.
2019-11-27 13:41:15,059 main DEBUG Reconfiguration complete for context[name=Default] at URI D:\proy\junit5Log4j\target\classes\log4j2.xml (org.apache.logging.log4j.core.LoggerContext@3590fc5b) with optional ClassLoader: null
2019-11-27 13:41:15,059 main DEBUG Shutdown hook enabled. Registering a new one.
2019-11-27 13:41:15,059 main DEBUG LoggerContext[name=Default, org.apache.logging.log4j.core.LoggerContext@3590fc5b] started OK.
logger.getName(), getLevel() = com.bext.Scheduler, TRACE
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
13:41:15.061 |TRACE | Scheduler       | Scheduler  [...
13:41:15.063 |DEBUG | Scheduler       | Scheduler logging debug
13:41:15.063 |INFO  | Scheduler       | Scheduler logging info
13:41:15.063 |WARN  | Scheduler       | Scheduler logging warn
13:41:15.063 |ERROR | Scheduler       | Scheduler logging error
13:41:15.063 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, TRACE
13:41:15.064 |TRACE | ServiceA        | ServiceA.info()  [...
13:41:15.064 |DEBUG | ServiceA        | logging debug
13:41:15.064 |INFO  | ServiceA        | logging info
13:41:15.064 |WARN  | ServiceA        | logging warn
13:41:15.064 |ERROR | ServiceA        | logging error
13:41:15.064 |FATAL | ServiceA        | logging fatal
13:41:15.064 |TRACE | ServiceA        | ServiceA.info()  ...]
13:41:15.064 |TRACE | Scheduler       | Scheduler  ...]
2019-11-27 13:41:15,065 pool-1-thread-1 DEBUG Stopping LoggerContext[name=18b4aac2, org.apache.logging.log4j.core.LoggerContext@689604d9]
2019-11-27 13:41:15,065 pool-1-thread-1 DEBUG Stopping LoggerContext[name=18b4aac2, org.apache.logging.log4j.core.LoggerContext@689604d9]...
2019-11-27 13:41:15,065 pool-1-thread-1 TRACE Unregistering 1 MBeans: [org.apache.logging.log4j2:type=18b4aac2]
2019-11-27 13:41:15,065 pool-1-thread-1 TRACE Unregistering 1 MBeans: [org.apache.logging.log4j2:type=18b4aac2,component=StatusLogger]
2019-11-27 13:41:15,066 pool-1-thread-1 TRACE Unregistering 1 MBeans: [org.apache.logging.log4j2:type=18b4aac2,component=ContextSelector]
2019-11-27 13:41:15,066 pool-1-thread-1 TRACE Unregistering 1 MBeans: [org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=]
2019-11-27 13:41:15,066 pool-1-thread-1 TRACE Unregistering 1 MBeans: [org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=STDOUT]
2019-11-27 13:41:15,067 pool-1-thread-1 TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=AsyncAppenders,name=*'
2019-11-27 13:41:15,067 pool-1-thread-1 TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=AsyncLoggerRingBuffer'
2019-11-27 13:41:15,067 pool-1-thread-1 TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=*,subtype=RingBuffer'
2019-11-27 13:41:15,067 pool-1-thread-1 TRACE Stopping XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]...

...

Setting the Configuration status ="FATAL" only get the log info of our interest. also lets filter the logger root to ALL.

<?xml version="1.0" encoding="UTF-8"?> 
<Configuration status="FATAL" strict="true" name="XMLConfigTest"               packages=""> 
    <Appenders> 
       <Appender type="Console" name="STDOUT">
             <Layout type="PatternLayout" pattern="%d{HH:mm:ss.SSS} |%-5p | %-15c{1} | %m%n"/> 
       </Appender>  
    </Appenders> 
    <Loggers>         
       <Root level="ALL"> 
            <AppenderRef ref="STDOUT"/>  
       </Root> 
    </Loggers>

Now we just get

com.bext.Scheduler
logger.getName(), getLevel() = com.bext.Scheduler, ALL
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
13:53:16.840 |TRACE | Scheduler       | Scheduler  [...
13:53:16.843 |DEBUG | Scheduler       | Scheduler logging debug
13:53:16.843 |INFO  | Scheduler       | Scheduler logging info
13:53:16.843 |WARN  | Scheduler       | Scheduler logging warn
13:53:16.843 |ERROR | Scheduler       | Scheduler logging error
13:53:16.843 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, ALL
13:53:16.844 |TRACE | ServiceA        | ServiceA.info()  [...
13:53:16.844 |DEBUG | ServiceA        | logging debug
13:53:16.844 |INFO  | ServiceA        | logging info
13:53:16.844 |WARN  | ServiceA        | logging warn
13:53:16.844 |ERROR | ServiceA        | logging error
13:53:16.844 |FATAL | ServiceA        | logging fatal
13:53:16.844 |TRACE | ServiceA        | ServiceA.info()  ...]
13:53:16.844 |TRACE | Scheduler       | Scheduler  ...]

Process finished with exit code 0


Lets Apply filter to logger root to ERROR, we just get the info from ERROR TO FATAL.

logger.getName(), getLevel() = com.bext.Scheduler, ERROR
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
Scheduler Trace is Disabled
Scheduler Info id Disabled
Scheduler Debug is Disabled
Scheduler Warn is Disabled
13:57:09.101 |ERROR | Scheduler       | Scheduler logging error
13:57:09.103 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, ERROR
ServiceA Trace is Disabled
ServiceA Info id Disabled
ServiceA Debug is Disabled
ServiceA Warn is Disabled
13:57:09.104 |ERROR | ServiceA        | logging error
13:57:09.104 |FATAL | ServiceA        | logging fatal


Now Lets create Two loggers, One that capture the events of the Scheduler class and send it to STDOUT, and other Logger to capture the events of the ServiceA to a file.

<?xml version="1.0" encoding="UTF-8"?>
 <Configuration status="FATAL" strict="true" name="XMLConfigTest"  packages=""> 
 <Properties> 
    <Property name="filename">target/test.log</Property> 
 </Properties> 
 <!-- <Filter type="ThresholdFilter" level="ERROR"/> --> 
 <Appenders> 
    <Appender type="Console" name="STDOUT"> 
       <Layout type="PatternLayout" pattern="%d{HH:mm:ss.SSS} |%-5p | %-15c{1} | %m%n"/> 
    </Appender> 
    <Appender type="File" name="File" fileName="${filename}" append="false"> 
       <Layout type="PatternLayout"> 
           <Pattern>%d{HH:mm:ss.SSS}| %-5p | %-15c{1} | %m%n</Pattern> 
       </Layout> 
    </Appender> 
</Appenders>
<Loggers> 
    <Logger name="com.bext.Scheduler"  > 
       <AppenderRef ref="STDOUT"/> 
    </Logger> 
    <Logger name="com.bext.ServiceA"   > 
       <AppenderRef ref="File"/> 
    </Logger>
    <Root level="ERROR"> 
       <!--  <AppenderRef ref="STDOUT"/>  --> 
       <!--  <AppenderRef ref="File"/> -->  
    </Root> 
 </Loggers> 
</Configuration>

Observe the events are filtered at ERROR level by Logger Root over the others to loggers, so we get

STDOUT
logger.getName(), getLevel() = com.bext.Scheduler, ERROR
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
Scheduler Trace is Disabled
Scheduler Info id Disabled
Scheduler Debug is Disabled
Scheduler Warn is Disabled
14:07:53.900 |ERROR | Scheduler       | Scheduler logging error
14:07:53.902 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, ERROR

ServiceA Trace is Disabled
ServiceA Info id Disabled
ServiceA Debug is Disabled
ServiceA Warn is Disabled


FILE log
14:07:53.903| ERROR | ServiceA        | logging error 
14:07:53.903| FATAL | ServiceA        | logging fatal 

We adjust the logger STDOUT to trace the events of com.bext.*, this will include Schedurer and ServiceA class.

<Loggers> 
   <Logger name="com.bext"  > 
      <AppenderRef ref="STDOUT"/> 
   </Logger> 
   <Logger name="com.bext.ServiceA"   > 
      <AppenderRef ref="File"/> 
   </Logger>
 

We get from ERROR .. FATAL
STDOUT
logger.getName(), getLevel() = com.bext.Scheduler, ERROR
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
Scheduler Trace is Disabled
Scheduler Info id Disabled
Scheduler Debug is Disabled
Scheduler Warn is Disabled
14:17:39.724 |ERROR | Scheduler       | Scheduler logging error
14:17:39.726 |FATAL | Scheduler       | Scheduler logging fatal

logger.getName(), getLevel() = com.bext.ServiceA, ERROR
ServiceA Trace is Disabled
ServiceA Info id Disabled
ServiceA Debug is Disabled
ServiceA Warn is Disabled
14:17:39.727 |ERROR | ServiceA        | logging error
14:17:39.727 |FATAL | ServiceA        | logging fatal


Now override the filter ERROR on logger root, to specific lever on Schedure logger, and ServiceA logger.

<Loggers> 
   <Logger name="com.bext.Scheduler" level="TRACE"  > 
      <AppenderRef ref="STDOUT"/> 
   </Logger> 
   <Logger name="com.bext.ServiceA" level="DEBUG"  > 
     <AppenderRef ref="File"/> 
   </Logger>
     <Root level="ERROR"> 
     <!--  <AppenderRef ref="STDOUT"/>  --> 
     <!--  <AppenderRef ref="File"/> --> 
     </Root>
</Loggers>

STDOUT  We get from TRACE...FATAL
logger.getName(), getLevel() = com.bext.Scheduler, TRACE
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
14:21:52.145 |TRACE | Scheduler       | Scheduler  [...
14:21:52.148 |DEBUG | Scheduler       | Scheduler logging debug
14:21:52.148 |INFO  | Scheduler       | Scheduler logging info
14:21:52.148 |WARN  | Scheduler       | Scheduler logging warn
14:21:52.148 |ERROR | Scheduler       | Scheduler logging error
14:21:52.148 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, DEBUG
ServiceA Trace is Disabled
14:21:52.150 |TRACE | Scheduler       | Scheduler  ...]



Log FILE we get from DEBUG...FATAL
14:21:52.149| DEBUG | ServiceA        | logging debug
14:21:52.149| INFO  | ServiceA        | logging info
14:21:52.150| WARN  | ServiceA        | logging warn 
14:21:52.150| ERROR | ServiceA        | logging error 
14:21:52.150| FATAL | ServiceA        | logging fatal 


Now on the logger to STDOUT change name from com.bext.Scheduler to com.bext, we get
<Loggers>    <Logger name="com.bext" level="TRACE"  >        <AppenderRef ref="STDOUT"/>    </Logger>    <Logger name="com.bext.ServiceA" level="DEBUG"  >        <AppenderRef ref="File"/>    </Logger>
    <Root level="ERROR">
 <!-- <AppenderRef ref="STDOUT"/> -->
 <!--  <AppenderRef ref="File"/> -->
 </Root>
 </Loggers>

 So we get on STDOUT all the classes down to com.bext, mean Scheduler, and ServiceA

13:15:27.508 |TRACE | Scheduler       | Scheduler  [...
13:15:27.510 |DEBUG | Scheduler       | Scheduler logging debug
13:15:27.510 |INFO  | Scheduler       | Scheduler logging info
13:15:27.510 |WARN  | Scheduler       | Scheduler logging warn
13:15:27.510 |ERROR | Scheduler       | Scheduler logging error
13:15:27.511 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, DEBUG
ServiceA Trace is Disabled
13:15:27.511 |DEBUG | ServiceA        | logging debug
13:15:27.511 |INFO  | ServiceA        | logging info
13:15:27.511 |WARN  | ServiceA        | logging warn
13:15:27.511 |ERROR | ServiceA        | logging error
13:15:27.512 |FATAL | ServiceA        | logging fatal
13:15:27.512 |TRACE | Scheduler       | Scheduler  ...]


What happen when integrate the STDOUT logger to root logger
<Loggers> 
   <Logger name="com.bext.Scheduler" level="TRACE"  > 
     <AppenderRef ref="STDOUT"/> 
   </Logger> 
   <Logger name="com.bext.ServiceA" level="DEBUG"  > 
     <AppenderRef ref="File"/> 
   </Logger>
   <Root level="ERROR"> 
      <AppenderRef ref="STDOUT"/> 
<!--  <AppenderRef ref="File"/> --> 
}  </Root>
</Loggers>

STDOUT Log
logger.getName(), getLevel() = com.bext.Scheduler, TRACE
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
13:26:57.014 |TRACE | Scheduler       | Scheduler  [...
13:26:57.014 |TRACE | Scheduler       | Scheduler  [...
13:26:57.016 |DEBUG | Scheduler       | Scheduler logging debug
13:26:57.016 |DEBUG | Scheduler       | Scheduler logging debug
13:26:57.016 |INFO  | Scheduler       | Scheduler logging info
13:26:57.016 |INFO  | Scheduler       | Scheduler logging info
13:26:57.016 |WARN  | Scheduler       | Scheduler logging warn
13:26:57.016 |WARN  | Scheduler       | Scheduler logging warn
13:26:57.016 |ERROR | Scheduler       | Scheduler logging error
13:26:57.016 |ERROR | Scheduler       | Scheduler logging error
13:26:57.016 |FATAL | Scheduler       | Scheduler logging fatal
13:26:57.016 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, DEBUG
ServiceA Trace is Disabled
13:26:57.017 |DEBUG | ServiceA        | logging debug
13:26:57.017 |INFO  | ServiceA        | logging info
13:26:57.017 |WARN  | ServiceA        | logging warn
13:26:57.017 |ERROR | ServiceA        | logging error
13:26:57.017 |FATAL | ServiceA        | logging fatal
13:26:57.018 |TRACE | Scheduler       | Scheduler  ...]
13:26:57.018 |TRACE | Scheduler       | Scheduler  ...]


By some reason also we get the ServiceA logs. and also is repeated the info of com.bext.Schedule logger, it can be corrected with additivity="false"

<Loggers> 
   <Logger name="com.bext.Scheduler" level="TRACE" additivity="false" > 
     <AppenderRef ref="STDOUT"/> 
   </Logger> 
   <Logger name="com.bext.ServiceA" level="DEBUG"  > 
     <AppenderRef ref="File"/> 
   </Logger> 
   <Root level="ERROR"> 
      <AppenderRef ref="STDOUT"/> 
 <!--  <AppenderRef ref="File"/> --> 
   </Root>
</Loggers>

 STDOUT log, the repeated info of Scheduler has gone.
logger.getName(), getLevel() = com.bext.Scheduler, TRACE
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
13:31:12.049 |TRACE | Scheduler       | Scheduler  [...
13:31:12.052 |DEBUG | Scheduler       | Scheduler logging debug
13:31:12.052 |INFO  | Scheduler       | Scheduler logging info
13:31:12.052 |WARN  | Scheduler       | Scheduler logging warn
13:31:12.052 |ERROR | Scheduler       | Scheduler logging error
13:31:12.052 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, DEBUG
ServiceA Trace is Disabled
13:31:12.053 |DEBUG | ServiceA        | logging debug
13:31:12.053 |INFO  | ServiceA        | logging info
13:31:12.054 |WARN  | ServiceA        | logging warn
13:31:12.054 |ERROR | ServiceA        | logging error
13:31:12.054 |FATAL | ServiceA        | logging fatal
13:31:12.054 |TRACE | Scheduler       | Scheduler  ...]


Adding File to root logger
<Loggers> 
   <Logger name="com.bext.Scheduler" level="TRACE" additivity="false" > 
      <AppenderRef ref="STDOUT"/> 
   </Logger> 
   <Logger name="com.bext.ServiceA" level="DEBUG"  > 
     <AppenderRef ref="File"/> 
   </Logger> 
   <Root level="ERROR"> 
     <AppenderRef ref="STDOUT"/> 
     <AppenderRef ref="File"/> 
     </Root> 
</Loggers>

STDOUT log, same
logger.getName(), getLevel() = com.bext.Scheduler, TRACE
loggerContext.getName(): Default
Congifuration.toString(): XmlConfiguration[location=D:\proy\junit5Log4j\target\classes\log4j2.xml]
13:33:05.933 |TRACE | Scheduler       | Scheduler  [...
13:33:05.935 |DEBUG | Scheduler       | Scheduler logging debug
13:33:05.935 |INFO  | Scheduler       | Scheduler logging info
13:33:05.935 |WARN  | Scheduler       | Scheduler logging warn
13:33:05.935 |ERROR | Scheduler       | Scheduler logging error
13:33:05.935 |FATAL | Scheduler       | Scheduler logging fatal
logger.getName(), getLevel() = com.bext.ServiceA, DEBUG
ServiceA Trace is Disabled
13:33:05.936 |DEBUG | ServiceA        | logging debug
13:33:05.936 |INFO  | ServiceA        | logging info
13:33:05.936 |WARN  | ServiceA        | logging warn
13:33:05.936 |ERROR | ServiceA        | logging error
13:33:05.937 |FATAL | ServiceA        | logging fatal
13:33:05.937 |TRACE | Scheduler       | Scheduler  ...]


FILE log, just ServiceA and repeated, could be corrected with additivity="false"
13:33:05.936| DEBUG | ServiceA        | logging debug
13:33:05.936| DEBUG | ServiceA        | logging debug
13:33:05.936| INFO  | ServiceA        | logging info
13:33:05.936| INFO  | ServiceA        | logging info
13:33:05.936| WARN  | ServiceA        | logging warn 
13:33:05.936| WARN  | ServiceA        | logging warn 
13:33:05.936| ERROR | ServiceA        | logging error 
13:33:05.936| ERROR | ServiceA        | logging error 
13:33:05.937| FATAL | ServiceA        | logging fatal 
13:33:05.937| FATAL | ServiceA        | logging fatal 

Create a Rolling File

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" strict="true" name="XMLConfigTest"
               packages="">
    <Properties>
        <Property name="filename">target/test.log</Property>
        <Property name="rollingfilename">target/logs/app.log</Property>
    </Properties>
    <!-- <Filter type="ThresholdFilter" level="ERROR"/> -->
    <Appenders>
        <Appender type="Console" name="STDOUT">
            <Layout type="PatternLayout" pattern="%d{HH:mm:ss.SSS} |%-5p | %-15c{1} | %m%n"/>
        </Appender>
        <Appender type="File" name="File" fileName="${filename}" append="false">
            <Layout type="PatternLayout">
                <Pattern>%d{HH:mm:ss.SSS}| %-5p | %-15c{1} | %m%n</Pattern>
            </Layout>
        </Appender>
        <RollingFile name="RollingFile" fileName="${rollingfilename}"
                     filePattern="target/logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <pattern>%d %p %c{1.} [%t] %m%n</pattern>
            </PatternLayout>
            <Policies>
               <!-- <OnStartupTriggeringPolicy/> -->
               <TimeBasedTriggeringPolicy/>
               <SizeBasedTriggeringPolicy size="1KB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Logger name="com.bext.Scheduler" level="TRACE" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </Logger>
        <Logger name="com.bext.Scheduler" level="TRACE" additivity="false">
            <AppenderRef ref="RollingFile"/>
        </Logger>
        <Logger name="com.bext.ServiceA" level="DEBUG" additivity="false">
            <AppenderRef ref="File"/>
        </Logger>
        <Root level="ERROR">
            <!-- <AppenderRef ref="STDOUT"/> -->
        </Root>
    </Loggers>
</Configuration>


File structure generated after tree runs.



eot