Java!

I am a solution architect, designer and corporate trainer. I have 11 years of experience in java j2ee development and I like designing solution and teaching.

When I am not working; I love spending time with family, watching movies and travelling and exploring new places.

Advertisements

MySql Setup on AWS Cloud

Following are the sequential list of screen shots to setup MySQL DB on AWS and steps to connect to the database from your machine.

pic1

pic2.jpg

pic3.jpg

pic4.jpg

pic5.jpg

pic6.jpg

pic7.jpg

pic8.jpg

pic9.jpg

pic10.jpg

pic11.jpg

Now create Data Base Security Groups to attache to the created DB instance.

pic12.jpg

pic13.jpg

 

pic14.jpg

 

 

pic15.jpg

Tag It with the name for easy identification.

pic16.jpg

 

pic17.jpg

Now Go back and check the instance. Endpoint is created and status is Available.
pic18.jpg

Now apply the created security group to this instance.

pic19.jpg

pic20.jpg

pic21.jpg

pic22.jpg

pic23.jpg

Data base instance is setup and ready for use. Lets connect to it from your local machine.

vfroot@INMHPUUBUNTU14:~$ mysql

The program ‘mysql’ can be found in the following packages:

* mysql-client-core-5.5

* mariadb-client-core-5.5

* mysql-client-core-5.6

* percona-xtradb-cluster-client-5.5

Try: sudo apt-get install <selected package>

vfroot@INMHPUUBUNTU14:~$ sudo apt-get install mysql-client-core-5.6

Install the mysql client package—>

Now open the terminal and connect to host (-h <host – mysql db instance name>, -u <username> -p <password>)

vfroot@INMHPUUBUNTU14:~$ mysql -h smjdbinstance.cqu7dugsvxvo.ap-south-1.rds.amazonaws.com -u waqarsyed23 -p

—————————>

vfroot@INMHPUUBUNTU14:~$ mysql -h <hostname of the db instance – refer above screens for the same> -u <db user name> -p

Enter password:

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 25

Server version: 5.6.34-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the current input statement.

mysql> show databases;

+——————–+

| Database |

+——————–+

| information_schema |

| innodb |

| mysql |

| pdhcdb |

| performance_schema |

+——————–+

5 rows in set (0.12 sec)

mysql> use pdhcdb;

Database changed

mysql> show tables;

mysql> exit;

 

Spring Boot With AngularJS Example

Hi,

Below is the working source code which demonstrate use of AngulaJS with Spring Boot.

https://github.com/waqarsyed23/SpringBootWithAngularJsSample

“DemoController” returns random data in Map object which is read by Angular JS controller “hello.js” to render it on the “index.html”

DemoController

@RestController
public class DemoController {

@RequestMapping(“/resource”)
public Map<String,Object> home() {
Map<String,Object> model = new HashMap<String,Object>();
model.put(“id”, UUID.randomUUID().toString());
model.put(“content”, “Waqar Syed Sample Demo”);
return model;
}
}

app.js

angular.module('hello', []).controller('home', function($http) {
   var self = this;
   $http.get('resource/').then(function(response) {
      self.greeting = response.data;
   })
});



index.html
<!doctype html>
<html>
<head>
<title>Spring Boot with AngularJS</title>
<link href="css/angular-bootstrap.css" rel="stylesheet">
<style type="text/css">
[ng\:cloak], [ng-cloak], .ng-cloak {
   display: none !important;
}
</style>
</head>
<body ng-app="hello">
   div class="container"
      <h1// Spring Boot With AngularJS Demo</h1>
      div ng-controller="home as home" ng-cloak class="ng-cloak"
        <p>This ID Coming from SpringBoot Controller: {{home.greeting.id}}</p>
         <p>Content From Controller- {{home.greeting.content}}</p>
      div
  /div
   script src="js/angular-bootstrap.js" type="text/javascript" /script
   script src="js/hello.js" /script
</body>
</html>

 

For the purpose of this sample, I am going to use http://alexo.github.io/wro4j/%5Bwro4j%5D, which is a Java-based tool chain for preprocessing and packaging front end assets. It can be used as a JIT (Just in Time) `Filter` in any Servlet application, but it also has good support for build tools like Maven and Eclipse. So I am going to build static resource files and bundle them in application JAR.

Wro4j is controlled from an XML configuration file that doesn’t know about your build classpath, and only understand absolute file paths, so we have to create an absolute file location and insert it in `wro.xml`. For that purpose we use Maven resource filtering and that is why there is an explicit “maven-resources-plugin” declaration.

Refer to pom.xml for the dependency added as well as wro configuration

Wro4j Source Files

There are only 3 files (and one of those is empty, ready for later customization):
* ‘wro.properties` is a configuration file for the preprocessing and rendering engine in wro4j.
You can use it to switch on and off various parts of the toolchain. In this case we use it to compile CSS from http://lesscss.org/%5BLess%5D and to minify JavaScript, ultimately combining the sources from all the libraries we need in two files.
* ‘wro.xml` declares a single “group” of resources called “angular-bootstrap”, and this ends up being the base name of the static resources that are generated. It includes references to `&lt;css&gt;` and `&lt;js&gt;` elements in the webjars we added, and also to a local source file `main.less`.
* `main.less` is empty in the sample code, but could be used to customise the look and feel, changing the default settings in Twitter Bootstrap. E.g. to change the colours from default blue to light pink you could add a single line.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>

   <groupId>org.test</groupId>
   <artifactId>basic</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>

   <name>basic</name>
   <description>Demo project for Spring Boot</description>

   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>1.4.2.RELEASE</version>
      <relativePath /> <!-- lookup parent from repository -->
   </parent>

   <dependencies>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.webjars</groupId>
         <artifactId>angularjs</artifactId>
         <version>1.4.9</version>
         <scope>test</scope>
      </dependency>

   </dependencies>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <wro4j.version>1.8.0</wro4j.version>
      <java.version>1.8</java.version>
   </properties>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <plugin>
            <groupId>ro.isdc.wro4j</groupId>
            <artifactId>wro4j-maven-plugin</artifactId>
            <version>${wro4j.version}</version>
            <executions>
               <execution>
                  <phase>generate-resources</phase>
                  <goals>
                     <goal>run</goal>
                  </goals>
               </execution>
            </executions>
            <configuration>
               <wroManagerFactory>ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory</wroManagerFactory>
               <cssDestinationFolder>${project.build.directory}/classes/static/css</cssDestinationFolder>
               <jsDestinationFolder>${project.build.directory}/classes/static/js</jsDestinationFolder>
               <wroFile>${basedir}/src/main/wro/wro.xml</wroFile>
               <extraConfigFile>${basedir}/src/main/wro/wro.properties</extraConfigFile>
               <contextFolder>${basedir}/src/main/wro</contextFolder>
            </configuration>
            <dependencies>
               <dependency>
                  <groupId>org.webjars</groupId>
                  <artifactId>jquery</artifactId>
                  <version>2.2.4</version>
               </dependency>
               <dependency>
                  <groupId>org.webjars</groupId>
                  <artifactId>angularjs</artifactId>
                  <version>1.4.9</version>
               </dependency>
               <dependency>
                  <groupId>org.webjars</groupId>
                  <artifactId>bootstrap</artifactId>
                  <version>3.3.7-1</version>
               </dependency>
            </dependencies>
         </plugin>

      </plugins>
   </build>

</project>

Complete working source code is located below:

https://github.com/waqarsyed23/SpringBootWithAngularJsSample

 

 

 

Ehcache With SpringBoot Example

This sample example demonstrates use of Ehchache in SpringBoot application.

https://github.com/waqarsyed23/EhcacheWithSpringBoot

  1. Source code contains pom.xml file with below required dependencies.
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId> <!-- starter for using Spring MVC -->
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId> <!--Starter for using Spring Framework's caching support-->
    </dependency>
    <dependency>
        <groupId>javax.cache</groupId> <!-- JSR-107 API-->
        <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

Cache configuration xml and cache setup class.

2. ehcache.xml

<config
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

  <service>
    <jsr107:defaults>
      <jsr107:cache name="personCache" template="heap-cache"/>
    </jsr107:defaults>
  </service>

  <cache-template name="heap-cache">
    <listeners>
        <listener>
          <class>com.sample.ehcache.EventLogger</class>
          <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
          <event-ordering-mode>UNORDERED</event-ordering-mode>
          <events-to-fire-on>CREATED</events-to-fire-on>
          <events-to-fire-on>UPDATED</events-to-fire-on>
          <events-to-fire-on>EXPIRED</events-to-fire-on>
          <events-to-fire-on>REMOVED</events-to-fire-on>
          <events-to-fire-on>EVICTED</events-to-fire-on>
        </listener>
    </listeners>
    <resources>
      <heap unit="entries">2000</heap>
      <offheap unit="MB">100</offheap> <!-- unit of measure is case sensitive! -->
    </resources>
  </cache-template>
</config>


Java class to setup cache of duration of 20 seconds to the cache elements.
3. CacheSetup.java

@Component
public class CacheSetup implements JCacheManagerCustomizer {
    @Override
    public void customize(CacheManager cacheManager) {
        cacheManager.createCache("personCache", new MutableConfiguration<>()
                .setExpiryPolicyFactory(TouchedExpiryPolicy.factoryOf(new Duration(SECONDS, 20)))
                .setStoreByValue(false)
                .setStatisticsEnabled(true));
    }
}

4. application.properties - It loads the ehcache.xml

5. Service class which stores the objects to cache
As seen in below service class; cache names "personCache" is annoted to
this service class and getPerson method output is stored in cache 
for 20 seconds as configured in CacheSetup.java
@Component
@CacheDefaults(cacheName = "personCache")
public class PersonService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PersonService.class);

    @CacheResult
    public Person getPerson(int persId)
    {
        LOGGER.info("persId " + persId + " not found in cache. TimeStamp: {}", new Date());

        switch (persId)
        {
            case 12345:
                return new Person(persId, "James", "Bond");
            case 6789:
                return new Person(persId, "Spider", "Man");
            default:
                return new Person(persId,"Bat","Man");
        }
    }


}

Please download below source code which contains working sample code:

https://github.com/waqarsyed23/EhcacheWithSpringBoot


On Demand Linux t2.micro Instance Hour – AWS unexpected charge

I got the unexpected billing for the service “On Demand Linux t2.micro Instance” usage.

I am using the aws cloud under free tier for which you are eligible of 750 hours per month of free usage.

The free tier for Amazon EC2 provides you with 750 hours usage of Linux (any combination oft2.micro and t1.micro instances), plus 750 hours usage of Windows (any combination of t2.micro andt1.micro instances). How you divide this allotment is up to you. For example, you can use one Linux instance continuously for a month, or 10 Linux instances for 75 hours a month

I had only one instance running but got the bill which says – “$0.015 per On Demand Linux t2.micro Instance Hour”

I logged in to my account and find out that I had setup one more instance in another region which I forgot about and hence the bill.

I had setup an instance in Asia Pacific Mumbai and was using it but then there was another instance running in US West Oregon Region

you need to check if by mistake you have launched another instance in another region which you forgot.

Also you need to make sure that auto scaling is not active else your terminated instance will be launched automatically.
You can follow the below link to terminate your unused instaces to avoid unexpected charges

http://docs.aws.amazon.com/getting-started/latest/drupal/clean-up.html