Wednesday, September 26, 2018

How to execute Storedproc along side JPA - Springboot 2.0





Define Data sources in application.yaml

app:  datasource:     oracle-local:        url: jdbc:oracle:thin:@localhost:10152/test
        username: wrkday_apps
        password: bread4all
        driver-class: oracle.jdbc.driver.OracleDriver
     postgres-local:        url: jdbc:postgresql://localhost:5432/
        username: postgres
        password: postgres
        driver-class: org.postgresql.Driver



crate a config file


@Configurationpublic class DatasourceConfig {

    @Bean    @Primary    @ConfigurationProperties("app.datasource.oracle-local")
    public DataSourceProperties oracleDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean    @Primary    @ConfigurationProperties("app.datasource.oracle-local")
    public DataSource oracleDataSource() {
        return oracleDataSourceProperties().initializeDataSourceBuilder().build();
    }


    @Bean(name = "oracleEntityManagerFactory")
    @Primary    public LocalContainerEntityManagerFactoryBean oracleEntityManagerFactory(
            EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(oracleDataSource())
                .packages(Audit.class, Audit1.class)
                .persistenceUnit("local1")
                .build();
    }


    @Configuration    @EnableJpaRepositories(basePackages= "com.jlabs.repo",
            entityManagerFactoryRef = "oracleEntityManagerFactory")
    public class oracleConfiguration {
    }




    @Bean    @ConfigurationProperties("app.datasource.postgres-local")
    public DataSourceProperties localDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "localDataSource")
    @ConfigurationProperties("app.datasource.postgres-local")
    public DataSource localDataSource() {
        return localDataSourceProperties().initializeDataSourceBuilder().build();
    }


    @Bean(name = "jdbcMaster")
    public SimpleJdbcCall masterJdbcTemplate() {
        return new SimpleJdbcCall( localDataSource()) .withSchemaName("public")
                .withFunctionName("test_pkg");
    }
}


to Execute the store proc

@Componentpublic class LocalTestDAO {

    private static Logger LOGGER = LoggerFactory.getLogger(LocalTestDAO.class);

    @Autowired    public SimpleJdbcCall jdbcMaster;

    @Transactional    public Integer savetoLocalTestPkg() {
        LOGGER.info("Saving to TestPkg {}" );
        try {


            final Map<String, Object> params = new HashMap<>();
            params.put("_sno", 8);
            params.put("_eid", 104);
            params.put("_ename", "jim");
            params.put("_sd", new Date());
            params.put("_ed", new Date());
            params.put("_sid", 150000);
            Map<String, Object> out = jdbcMaster.execute(params);


            return 1;
        } catch (Exception e) {
            LOGGER.error("Saving to EDW TestPkg failed {}", e);
            return -1;
        }
    }

}



Steps to create the stored proc

CREATE TABLE app_for_leave
(
  sno INTEGER NOT NULL,
  eid INTEGER,
  ename VARCHAR(20),
  sd DATE,
  ed DATE,
  sid INTEGER,
  status BOOLEAN DEFAULT FALSE,
  CONSTRAINT pk_snoa PRIMARY KEY (sno)
);


CREATE OR REPLACE FUNCTION insert_into_table(_sno INTEGER, _eid INTEGER, _ename VARCHAR(20), _sd DATE, _ed DATE, _sid INTEGER)
RETURNS void AS
$BODY$
BEGIN
 INSERT INTO app_for_leave(sno, eid, ename, sd, ed, sid)
  VALUES(_sno, _eid, _ename, _sd, _ed, _sid);
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
 COST 100;

To manually execure the proc - 
SELECT * FROM insert_into_table(2,102,'Jimmy','2013-08-16','2013-08-17',12);

Tuesday, July 10, 2018

Enable Auto start - Springboot Dev Tool - Intelij

To Enable Auto Restart for Springboot App anytime something is changed on the class path

Add below dependency to pom:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>



Set your Intelij build settings to build project automatically




Applications that use spring-boot-devtools automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE, as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder is monitored for changes. Note that certain resources, such as static assets and view templates, do not need to restart the application.


Enable automatic compilation
Get an improved JRebel development experience by enabling automatic compilation:
  1. Access Settings (Preferences on macOS).
  2. Select Build, Execution, Deployment > Compiler. Enable Build project automatically.
  3. Select Appearance & Behavior > System Settings. Enable Save files automatically if application is idle for. We recommend setting it to 10 seconds. (This is already enabled by default on IntelliJ 2018.1 and earlier.)
  4. Press OK.
  5. Press Ctrl+Shift+A (Cmd+Shift+A on macOS) and search for Registry. Open it to find and enable compiler.automake.allow.when.app.running (IntelliJ IDEA 15 and newer).


Friday, May 11, 2018

Kubernetes

Minikube is a tool that makes it easy to run Kubernetes locally. Minikube runs a single-node Kubernetes cluster inside a VM on your laptop for users looking to try out Kubernetes or develop with it day-to-day.

kubectl is a command line interface for running commands against Kubernetes clusters. This overview covers kubectl syntax, describes the command operations, and provides common examples. For details about each command, including all the supported flags and subcommands, see the kubectl reference documentation. For installation instructions see installing kubectl.


To create deployment app -
kubectl run kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1 --port=8080

To Get all Deploymnets :
kubectl get deployments


 A Pod is a Kubernetes abstraction that represents a group of one or more application containers (such as Docker or rkt), and some shared resources
When we create a Deployment on Kubernetes, that Deployment creates Pods with containers inside them (as opposed to creating containers directly). Each Pod is tied to the Node where it is scheduled, and remains there until termination (according to restart policy) or deletion. In case of failures identical Pods are scheduled on other available Nodes.
kubectl get pods
kubectl desribe pods




Thursday, May 3, 2018

Interface Vs Abstract Class

1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class.

2. Interface are used to represent adjective or behavior e.g. RunnableClonableSerializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time.

3. On time critical application prefer abstract class is slightly faster than interface.

4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class.


class SmartPhone
  brand: String
  year
  model
 message():abstract
calling():abstract
--------------------------------------------------

inteface Camera
interface Music  
interface AppleWatch

Iphone extends SmartPhone implements Camera, Music, AppleWatch
Android extends SmartPhone implements Camera, Music
windows extends SmartPhone implements Camera, Music

Thursday, April 19, 2018

Round number with Angular 5



@Pipe({name: 'round'})
export class RoundPipe implements PipeTransform {
    /**     *     * @param value     * @returns {number}     */    
 transform(value: number): number {
        // return Math.round(value);  
      return parseFloat(value.toFixed(2));
    }
}

Monday, March 19, 2018

Create Custom Maven ArcheType


https://github.com/sapan-s2/custom-ArcheType

Steps :


  • Generate Archetype


mvn archetype:generate -B -DarchetypeArtifactId=maven-archetype-archetype  -DgroupId=com.MyCompany.archetype -DartifactId=Test-ArcheType -Dversion=1.0-SNAPSHOT


  • Rename archetype.xml to archetype-metadata under META-INF/maven(it;s autogenerated by the above command)

  • Now Add your default directory structures needed for this ArcheType

In order to use this ArcheType to create a new Project

mvn archetype:generate -DarchetypeCatalog=local
-DarchetypeArtifactId=<new-app-Artifact-name>
-DarchetypeGroupId=<new-app-group-id>
 -DarchetypeVersion=<version>

ex - mvn archetype:generate -DarchetypeCatalog=local
 -DarchetypeArtifactId=Test-ArcheType
-DarchetypeGroupId=com.MyCompany.archetype 
-DarchetypeVersion=1.0-SNAPSHOT







Refrences:
https://maven.apache.org/plugins-archives/maven-archetype-plugin-1.0-alpha-7/examples/archetype.html

https://maven.apache.org/guides/mini/guide-creating-archetypes.html



Tuesday, March 6, 2018

JSON

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Structure


JSON Object diagram

JSON Array diagram

JSON Value diagram

JSON String diagram

JSON Number diagram
Here is an example of JSON data:
{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

JSON Structure


JSON Object diagram

JSON Array diagram

JSON Value diagram

JSON String diagram

JSON Number diagram
Here is an example of JSON data:
{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

JSON in JavaScript

JSON (in Javascript) is a string!
People ofetn assume all Javascript objects is JSON and JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'x is an object of type string not an object in it's own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');x is now an object but this is not JSON anymore.

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
Example on how to use the JSON Parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

References