Monday

postMessage API >> send messages & call parent's js function: between jsp and react app (in iframe)

I tried to:
- open a react app in an iframe from jsp
- send message by postMessage API>> from jsp to react, from react to jsp
- call parent's function by postMessage API inside iframe(react app)

http://localhost:8080 >> jsp 
http://localhost:3000 >> react

jsp example:
 ....
<tiles:put name="body" type="string">
   
 <div id="reactIframeLoading" style="height:50px; color:red; font-size:12px; 
      margin-left:2px;">
      React Iframe Loading...<br> 
      <a href="javascript:loadReactIframe()">Retry</a>
 </div> 

 <iframe 
      id="reactIframe" 
      style="display:none;"
      onload="reactIframePostMessage(); reactIframeLoaded();"
      src="http://localhost:3000/"
      width="100%" height="200" border="0" marginwidth="0"
      marginheight="0" scrolling="no">
 </iframe> 
  
 <script type="text/javascript">    
     const dataForReactPostMessage = {
           isReadOnly: false,
           someData: {
               someDataChild: 'eda'
          }
      }

     function callMeFromReact(msg) {
         console.log('callMeFromReact: params: ' + msg);
     }
  
     function reactIframeLoaded() {
        document.getElementById("reactIframe").style.display='';
        document.getElementById("reactIframeLoading").style.display='none';
     }  
  
     function loadReactIframe(){
         document.getElementById("reactIframe").src="http://localhost:3000/";
     }
  
     function reactIframePostMessage(){
         document.getElementById("reactIframe").contentWindow.postMessage(
              dataForReactPostMessage, 'http://localhost:3000/'
         );
     }
  
    window.addEventListener('message', handleFrameTasks);

    //get messages from iframe or run function given by iframe  
     function handleFrameTasks(event) {
           if(event.origin !== "http://localhost:3000") {
              return;
           }

           //if function is given
           var data = event.data;
           if(typeof(window[data.func]) == "function") {
                 window[data.func].call(null, data.params[0]);

          //if data is given
          } else if(data.event_id === 'my_first_message') {
                console.log('post message from react to jsp // event_id: my_first_message= ' + JSON.stringify(event.data));
          }
     }
  </script>
</tiles:put>

react example:
import React, { Component } from 'react'

class Example extends Component {

    constructor(props) {
        super(props);
        this.handleFrameTasks = this.handleFrameTasks.bind(this);
        this.sendParentPostMessage = this.sendParentPostMessage.bind();
    }

    componentWillMount() {
        window.addEventListener('message', this.handleFrameTasks);
    }

    componentWillUnmount() {
        window.removeEventListener("message", this.handleFrameTasks);
    }

    handleFrameTasks(event) {
        if(event.origin !== "http://localhost:8080") {
           return;
        }
        console.log('postmessage from jsp to react // event.data= ' + JSON.stringify(event.data));
    }

    sendParentPostMessage() {
        const dataForJspPostMessage = {
            event_id: 'my_first_message',
            someData: {
                someDataChild1: 'eda 1', 
                someDataChild2: 'eda 2'
            }
        } 
        //send data to parent
        window.parent.postMessage(dataForJspPostMessage, 'http://localhost:8080'); 

        //call js function named as 'callMeFromReact' in parent
        window.parent.postMessage(
            {'func':'callMeFromReact','params':['SomeMessages']}, 
            'http://localhost:8080'
        ); 

        window.parent.postMessage(
            {'func':'nonExistingMethod','params':['SomeMessages']}, 
            'http://localhost:8080'
        );
    }

    render() {
        return (
            <div>
                <h1>Hello, world!</h1>
                <button onClick={this.sendParentPostMessage}>sendParentPostMessage</button>
            </div>
        );
    }

}

export default Example

UPDATE: last version for post message listener:
window.addEventListener('message',  function (event) {
      if(event.origin != null && event.origin.includes(".int.teb.com.tr")) {
            var data = event.data;
            if(data != null && typeof(window[data.func]) == "function"){
                if(data.params != null && data.params.length > 1) {
                  var args = new Array();
                  for(var i = 0; i < data.params.length; i++){
                       args.push(data.params[i]);
                  }

                  window[data.func].apply(this, args);
                  
                } else {
                  window[data.func].call(null, data.params);
                }
            }
      }
}); 

Javascript tips

Some important concepts:

1.  "hoisting" : Javascript moves all declarations to the top before executing the code. It other words, a variable can be used before it is declared.

Advice: If you want to avoid confusion, declare variables at the beginning of the function.
Note: Javascipt does this only for declarations. Initializations aren't hoisting to the top.
<script>
    var x = 3;  
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y;
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    y = 4;  
    //result: x is 3 and y is undefined
</script>



<script>
    var x = 3; 
    var y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    //result: x is 3 and y is 4
</script>


<script>
    x = 3; 
    y = 4; 
    elem = document.getElementById("demo");      
    elem.innerHTML = "x is " + x + " and y is " + y; 
    var x, y;
    //result: x is 3 and y is 4
</script>

2.  
var a = 1 >> declares the variable in the current scope which can be local or global.
       a = 1 >> if the variable couldn't be found anywhere in the scope chain, it becomes global.This usage is very bad practice!!!

3.  Arrow functions aren't same with regular functions. 'this' keyword not bound to the element when it is used in arrow functions.
Try not to use arrow functions with constructors, click handlers, class/object methods!



react-booststrap-table example


npm install react-bootstrap-table --save
npm install bootstrap --save

import React from 'react';
import ReactDOM from 'react-dom';
import BootstrapTableTest from './bootstrap/BootstrapTableTest';
import './index.css';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<BootstrapTableTest />, document.getElementById('root'));

serviceWorker.unregister();

getSprintList rest service json example:

[{"sprintNo":"2","sprintBeginDate":"2019-04-15","sprintEndDate":"2019-04-15","active":"Y"},
{"sprintNo":"4","sprintBeginDate":"2019-04-15","sprintEndDate":"2019-04-15","active":"N"}]

 I used fetchings in the same class without separating to middleware layer, it is a simple example.
import React, { Component } from 'react'
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import '../../node_modules/bootstrap/dist/css/bootstrap.min.css';
import '../../node_modules/react-bootstrap-table/dist/react-bootstrap-table.min.css';

class BootstrapTableTest extends Component {
    constructor(props) {
        super(props)
        this.state = {
            sprints: [],
            error: null
        }
    }   

    componentDidMount() {
        fetch(`http://localhost:8080/agile/getSprintList`, {
            method: "GET"
        })
        .then(response => {
            console.log('sprint componentDidMount', response)
            if(response.ok) {
                console.log('Successfully fetch sprintList')
                return response.json();
            } else {
                throw new Error('Cant fetch sprint list. Something went wrong.')
            }
        })
        .then(data => 
            this.setState({sprints: data})
        )
        .catch(err => this.setState({error: err}))
    }

    updateRow(row, cellName, cellValue) {
        const rowJson = JSON.stringify({
            sprintNo: row.sprintNo,
            sprintBeginDate: row.sprintBeginDate,
            sprintEndDate: row.sprintEndDate,
            active: row.active
        })
        console.log('sprint updateRow', rowJson)

        fetch(`http://localhost:8080/agile/updateSprint`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: rowJson
        })
       .then(response => {
            console.log('sprint updateRow', response)
            if (response.ok) {
               console.log('Successfully updated sprint')
            } else {
               throw new Error('Somthing happened wrong while updating sprint')
           }
       })
       .catch(err => this.setState({error: err}))
    }

    addRow(row) {
        const rowJson = JSON.stringify({
            sprintNo: row.sprintNo,
            sprintBeginDate: row.sprintBeginDate,
            sprintEndDate: row.sprintEndDate,
            active: row.active
        })
        console.log('sprint addRow', rowJson)

        fetch(`http://localhost:8080/agile/addSprint`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: rowJson
        })
        .then(response => {
            console.log('sprint addRow', response)
            if (response.ok) {
               console.log('Successfully added sprint')
            } else {
               throw new Error('Somthing happened wrong while adding sprint')
            }
        })
        .catch(err => this.setState({error: err}))
    }

    deleteRow(rowKeys) {
        fetch(`http://localhost:8080/agile/deleteSprint?sprintNo=${rowKeys}`, {
            method: 'POST',
            headers: {
               'Content-Type': 'application/json'
            },
        })
        .then(response => {
            console.log('sprint deleteRow', response)
            if (response.ok) {
                console.log('Successfully removed sprint', rowKeys)
            } else {
               throw new Error('Somthing happened wrong while deleting sprint')
            }
        })
        .catch(err => this.setState({error: err}))
    }

    numericValidator(value, row) {
        const nan = isNaN(parseInt(value, 10))
        if(nan) {
            return 'Enter numeric values.'
        }
        return true;
    }

    createCustomModalHeader(onClose, onSave) {
        const headerStyle = {
            fontWeight: 'bold',
            padding: '2px 2px',
            margin: '5px',
            fontSize: 'medium',
            textAlign: 'center',
            display: 'initial',
            backgroundColor: '#eeeeee'
        };
        return (
            <div className='modal-header' style={ headerStyle }>
                <h3>Add New Sprint</h3>
            </div>
        );
    }

    render() {
        if(this.state.error) {
            return <p>{this.state.error.message}</p>
        }

        const jobTypes = [ 'Y', 'N' ];

        const selectRow = {
            mode: 'checkbox',
            clickToSelect: true
        };

        const cellEditProp = {
            mode: 'click',
            blurToSave: true,
            afterSaveCell: this.updateRow
        };

        const options = {
            afterDeleteRow: this.deleteRow,
            afterInsertRow: this.addRow,
            deleteText: 'Delete',
            insertText: 'Insert',
            paginationSize: 1,
            prePage: 'Previous',
            nextPage: 'Next',
            firstPage: 'First Page',
            lastPage: 'Last Page',
            defaultSortName: 'sprintNo',
            defaultSortOrder: 'desc',
            insertModalHeader: this.createCustomModalHeader
        };

        return(
            <BootstrapTable data={this.state.sprints} 
                striped hover pagination search multiColumnSearch ignoreSinglePage 
                selectRow={ selectRow }
                cellEdit={ cellEditProp }
                options={ options }
                height='750' scrollTop={ 'Bottom' }
                deleteRow insertRow 
                exportCSV csvFileName='sprint.csv'
            >
                <TableHeaderColumn 
                    isKey dataField='sprintNo' dataAlign='right' dataSort={ true }
                    editable={ {validator: this.numericValidator} } >
                    Sprint Number
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='sprintBeginDate' 
                    editable={ { type: 'date' } }>
                    Sprint Begin Date
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='sprintEndDate' 
                    editable={ { type: 'date' } }>
                    Sprint End Date
                </TableHeaderColumn>
                <TableHeaderColumn  
                    dataField='active' 
                    editable={ { type: 'select', options: { values: jobTypes } } }>
                    Is Active
                </TableHeaderColumn>
            </BootstrapTable >
        )
    }

}
export default BootstrapTableTest

Sunday

react-bootstrap-table does not have style

I use react-bootstrap-table but there is no styling.
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
import '../node_modules/react-bootstrap-table/dist/react-bootstrap-table.min.css';

.....

<BootstrapTable data={this.state.sprints} striped hover>
      <TableHeaderColumn isKey dataField='sprintNo'>Sprint no</TableHeaderColumn>
</BootstrapTable>

FIX: 
Firstly run the following npm command:
npm install bootstrap --save

Then add this css import to your .js file:
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

Monday

Change default port for React App

Default port is 3000 for react app. To change it modify the following part of package.json:
     "start": "react-scripts start"

For windows:
"start": "set PORT=8086 && react-scripts start"

For Linux and MacOS to:
"start": "PORT=8086 react-scripts start"

import error >> using react-icons FaPencil

I try to install react-icons as following command:
             >> npm --loglevel info install --save react-icons

And try to use as follow:
import { FaPencil } from 'react-icons/fa'
import { FaTrash } from 'react-icons/fa'

...
 <button><FaPencil /></button>  
 <button><FaTrash /></button>

But I got following error:
Attempted import error: 'FaPencil' is not exported from 'react-icons/fa'.

FIX:
fa icons are free except for pencil. It needs pro license.
So you can use free version as follow:
import { FaPencilAlt } from 'react-icons/fa'
import { FaTrash } from 'react-icons/fa'

...
 <button><FaPencilAlt /></button>
 <button><FaTrash /></button>

How can I upgrade npm on Windows?

Firstly, Run PowerShell as Administrator. Then run the following commands with order.

Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
npm install -g npm-windows-upgrade
npm-windows-upgrade


Friday

String literal && String pool


/*  String object created with using new() operator.
    This always create a new object in heap memory.
    At the below, object and object2 have different references.
*/
String object = new String("Eda"); 
String object2 = new String("Eda"); 
System.out.println(object == object2); // false

/* String object created with using String literal syntax.
   If an object exists in string pool then returns it. Otherwise, creates a new string object and puts into string pool.
   At the below, literal and literal2 have the same reference.
*/
String literal = "Eda";
String literal2 = "Eda";
System.out.println(literal == literal2); // true

NOTE: While comparing two string, we can't know which string parameter has created with new() or literal. So use always equals().

Strings which has created with literal syntax, is cached. This cache is known as "String pool".

If an object exists in string pool then returns it. Otherwise, creates a new string object and puts into string pool. This is called as "interning".
     Interning can be manually, as follows.
          -manually intern in Java 6 is not a good practice. Just because pool has a fixed memory.

String literal = "Eda";
String object = new String("Eda"); 
String internedObject = object.intern();
System.out.println(literal == internedObject); // true

Just before java 7, that cache was in PermGen space. With java 7, it is in heap space.
     permgen space >> has fixed size && can not expanded at runtime, you had to change JVM option(-XX:MaxPermSize=1G) && risk of getting OutOfMemory error.
     heap space >> unreferenced strings has removed from pool && it is garbage collected which means strings with no references  will gone.

There is more JVM options for pool sizing: (your pool size should be high enough)
-XX:StringTableSize=4901 //The default pool size is: 1009 to the Java7u40, after that 60013, alsa java 8 is the same. 
-XX:+PrintStringTableStatistics //print string pool usage statistics when the program finish execution

Wednesday

Some advices on using Optional

//DON'T
Optional<User> user = null;
//DO
Optional<User> user =  Optional.empty();

//Don't confuse Optional.of() and Optional.ofNullable(). Choose the right one.

//DON'T
return Optional.ofNullable("EDA");
//DO
return Optional.of("EDA"); //no risk for NPE of using of() method so choose this.

//DON'T
String parameterToMethod = ...; // can be null
return Optional.of(parameterToMethod);//can throw NPE if parameter is null
//DO
String parameterToMethod = ...; // can be null
return Optional.ofNullable(parameterToMethod);//no risk for NPE

//DON'T
String userName = ... ;
return Optional.ofNullable(userName).orElse("EDA");
//DO
String userName = ... ;
return userName == null ? "EDA" : userName; // choose always the simplest one for such easy cases

//DON'T
Optional<String> user = ...; //can be empty
String myUser = user.get(); // can throw NoSuchElementException if user is empty
//DO
Optional<String> user = ...; //can be empty
if(user.isPresent()) {
 String myUser = user.get();
}


//DON'T
Optional<String> userName = ...;
if(userName.isPresent()) {
   return userName.get();
} else {
   return "Unknown person";
}
//DO
Optional<String> userName = ...;
return userName.orElse("Unknown person");

// DON'T
Optional<String> parameterUserName = ... ;
Optional<String> userName = Optional.of("EDA");
if(parameterUserName.isPresent()) {
 return parameterUserName;
} else {
 return userName;
}
//DO
Optional<String> parameterUserName = ... ;
Optional<String> userName = Optional.of("EDA");
return parameterUserName.or(() -> userName); // with java 9

// DON'T
Optional<String> userName = ... ;
if(userName.isPresent()) {
    System.out.println("userName: " + userName.get());
} else {
    System.out.println("User not found");
}
//DO - java 9
Optional<String> userName = ... ;
userName.ifPresentOrElse(
    System::out::println, 
    () -> System.out.println("User not found")
};

//DON'T
Optional<String> userName = ...;
if (userName.isPresent()) {
    System.out.println("userName: " + userName.get());
}
//DO
Optional<String> userName = ...;
userName.ifPresent(System.out::println);

//DON'T
Optional<String> userName = ...;
if(userName.isPresent()) {
 return userName.get();
} else {
 throw new NoSuchElementException(); 
}
//DO
Optional<String> userName = ...;
return userName.orElseThrow(); //java 10
return userName.orElseThrow(YourException::new);//java 8-9 

//DON'T
 .......
 .filter(Optional::isPresent)
        .map(Optional::get)
 .collect(toList());
//DO
 .......
 .flatMap(Optional::stream)
 .collect(toList());

// AVOID
Optional<Integer> opt = Optional.of(10);
Optional<Long> opt = Optional.of(20L);
Optional<Double> opt = Optional.of(20.53d);

// PREFER
OptionalInt opt = OptionalInt.of(10);           // opt.getAsInt()
OptionalLong opt = OptionalLong.of(20L);        // opt.getAsLong()
OptionalDouble opt = OptionalDouble.of(20.53d); // opt.getAsDouble()

Monday

Optional in java 8 & 9

I'll try to give example for Optional class which has came up for NullPointerException. It is a wrapper class, it can contain any other Object or it can be empty. Java 8 features:

Create Optional instances:
//You can create an empty Optional instance.
Optional.empty();
 
//of() method will throw NullPointerException if the user is null
//you should use of() method only if you are sure that your object is not null
Optional<User> opt = Optional.of(user);

//ofNullable() method can be use if the user object is null or not null.
Optional<User> opt = Optional.ofNullable(user);

Retrieve the actual object inside Optional instance:
//you can use get() method but if the user object is null then it will throw NoSuchElementException.
Optional<User> opt = Optional.ofNullable(user);
User myUser = opt.get();

//so, you should first check the value is present or not
//isPresent() method can be use
Optional<User> opt = Optional.ofNullable(user);
if(opt.isPresent()) {
 User myUser = opt.get();
 //your other jobs
}

//There is also ifPresent() method which combines isPresent() and get()
//lambda expression is used
Optional<User> opt = Optional.ofNullable(user);
opt.ifPresent(myUser -> {
    ///your other jobs
})

Return values:
//orElse() method returns the values if it's present, if not present then returns the other argument
//if user is not null then returns it. Otherwise returns user2.
User myUser = Optional.ofNullable(user).orElse(user2);


//orElseGet() method returns the values if it's present,
//if not present then executes Supplier interface
User myUser = Optional.ofNullable(user).orElseGet( () -> user2);

Lets see the difference between orElse() and orElseGet().
In the following example object is null and both return the other object. There is no difference as you see but....
User user = null; 
System.out.log("orElse>> ");
User myUser = Optional.ofNullable(user).orElse(createUser());
System.out.log(myUser.getName());
System.out.log("orElseGet>> ");
User myUser = Optional.ofNullable(user).orElseGet( () -> createUser());
System.out.log(myUser.getName());

...
private User createUser() {
    logger.debug("createUser method inside");
    return new User("eda2");
}

/*
 Output:
  orElse>>
  createUser method inside
  eda2
  orElseGet>>
  createUser method inside
  eda2
*/

In the following example object is not null.
But even if object is not null orElse() method has gone createUser() method.
orElse() always will call the given function() but orElseGet() will call only if optional is not present.
So orElse() is very expensive for the resources!!!!!!
User user = new User("eda"); 
System.out.log("orElse>> ");
User myUser = Optional.ofNullable(user).orElse(createUser());
System.out.log(myUser.getName());
System.out.log("orElseGet>> ");
User myUser = Optional.ofNullable(user).orElseGet( () -> createUser());
System.out.log(myUser.getName());

...
private User createUser() {
    logger.debug("createUser method inside");
    return new User("eda2");
}

/*
 Output:
  orElse>>
  createUser method inside
  eda
  orElseGet>>
  eda
*/

Return exception:
//orElseThrow() throws an exception if the object is empty:
User myUser = Optional.ofNullable(user).orElseThrow(() -> new UserDoesNotExist());

Mapping:
//map() method applies the functional argument to the value and returns the result.
User user = new User("eda"); 
String userName = Optional.ofNullable(user)
 .map(myUser -> myUser.getName()).orElse("DEFAULT NAME");

//if the get method returns an Optional value you can use flatMap() and return unwrapped String value.
public class User {    
    private String name;

    public Optional<String> getName() {
        return Optional.ofNullable(name);
    }

}

User user = new User("eda");
String userName = Optional.ofNullable(user)
 .flatMap(myUser -> myUser.getName()).orElse("DEFAULT NAME");

Filtering:
//filter() method
//optUser will not contain a null name value.
User user = new User(null);
Optional<User> optUser = Optional.ofNullable(user)
  .filter(myUser -> myUser.getName() != null);

//optUser.isPresent() is false, in this case filter returns empty Optional.

Features that come with Java 9 to Optional class:
Java 9 added 3 more methods to the Optional class:  or(), ifPresentOrElse() and stream().
or() method:
//orElse() and orElseGet() methods returns unwrapped values.
//or() method is similar with them but it returns Optional object.
User user = "eda"; 
Optional<User> myUser = Optional.ofNullable(user).or(() -> createUser());
//User myUser = Optional.ofNullable(user).or(() -> createUser()).get();
System.out.log(myUser.get().getName());
System.out.log("**");
...

User user = null; 
Optional<User> myUser = Optional.ofNullable(user).or(() -> createUser());
System.out.log(myUser.get().getName());
...

private Optional<User>  createUser() {
    logger.debug("createUser method inside");
    return Optional.of(new User("eda2"));
}

/*
 Output:
  eda
  **
  createUser method inside
  eda2
*/

ifPresentOrElse() method:
It gives us a change to run a function if the optional is empty.
Optional<User> opt = Optional.ofNullable(user);
opt.ifPresentOrElse(myUser -> 
    ///your other jobs, myUser.getName()
 , () -> logger.info("User not found")
);

stream() method:
I'll mention about stream in an another writing.
User user = new User("eda");
List<String> nameList = Optional.ofNullable(user)
   .stream()
   .filter(u -> u.getName() != null)
   .map(u -> u.getName())
   .collect(Collectors.toList());