Monday, July 30, 2018

Creating First SpringBoot Application

1. created maven project

mvn archetype:generate -DgroupId=com.test -DartifactId=SpringBootTest -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2. To make this is a springboot application, we need to add the dependencies related to Springboot.

https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started-first-application.html

 add "spring-boot-starter-parent" in "parent"  section.

 This is special starter
   a.) Provides useful maven defaults
   b.) Provides a dependancy management section - this helps you to ommit the "version" tags for "blessed" dependancies

 
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>

3. Add other "Starters" which need to build a specific type of application.
  Let's say , we are going to build web, we add "spring-boot-starter-web" as dependency
 
Before adding the "spring-boot-starter-web" as dependency , we can check what we have with us currently with "mvn dependency:tree" command
This will give us an output as below.

[INFO] com.test:SpringBootTest:jar:1.0-SNAPSHOT
[INFO] \- junit:junit:jar:3.8.1:test
[INFO] ------------------------------------------------------------------------


"mvn dependency:tree" command prints the tree version of the dependancies in your project.

Important : "spring-boot-starter-parent" does not provides any dependancy itself. Not in the list.

So let's add neccessary dependancies and check the tree. As we are going to make web app, let's add the dependancy.

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

If you run "mvn dependency:tree" again ,  you will see the number of dependancies including springboot

[INFO] com.test:SpringBootTest:jar:1.0-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.0.3.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:2.0.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:2.0.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.0.3.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.0.3.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  |  |  |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] |  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.10.0:compile
[INFO] |  |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.10.0:compile
[INFO] |  |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
[INFO] |  |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  |  +- org.springframework:spring-core:jar:5.0.7.RELEASE:compile
[INFO] |  |  |  \- org.springframework:spring-jcl:jar:5.0.7.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.19:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.0.3.RELEASE:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.6:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] |  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.9.6:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.6:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.6:compile
[INFO] |  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.6:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.0.3.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.31:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.31:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.31:compile
[INFO] |  +- org.hibernate.validator:hibernate-validator:jar:6.0.10.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:2.0.1.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.2.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.3.4:compile
[INFO] |  +- org.springframework:spring-web:jar:5.0.7.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.0.7.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:5.0.7.RELEASE:compile
[INFO] |     +- org.springframework:spring-aop:jar:5.0.7.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:5.0.7.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:5.0.7.RELEASE:compile
[INFO] \- junit:junit:jar:3.8.1:test
[INFO] ------------------------------------------------------------------------



4. writting code.

Let's create a class with name "Example" and put inside "src/main/java".
Imporatnt: By default, maven compiles sources from "src/main/java".

So the file name will be "src/main/java/Example.java"

-------------------------------------------------------------------------------

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

@RequestMapping("/")
String home() {
return "Hello World!";
}

public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}

}

------------------------------------------------------------------------------

5. Run application.
 Simply run the main class. This will deploy your main class in tomcat server and you can view the output by simply calling "http://localhost:8080/" from your web browser.

 This will give the output

 ---------------
 Hello World

 ---------------

 6. Creating an executable jar

 We can create an executable jar using "spring-boot-maven-plugin" in "pom.xml". Add the below, just below the "dependencies"

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>


but if you have more than one class with main method, then better to sepcify the class you need to run

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>

<configuration>
<mainClass>Example.class</mainClass>
<layout>ZIP</layout>
</configuration>
</plugin>
</plugins>
</build>



Important :
"spring-boot-starter-parent" POM includes configuration to bind the "repackage" goal. In simple, If you do not use the parent POM, you have to declare this configuration of your own.



Below is the final POM file.

--------------------------------------------------------------------

<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>SpringBootTest</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringBootTest</name>
<url>http://maven.apache.org</url>

<!-- spring boot parent starter -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>

<dependencies>

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

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>

<configuration>
<mainClass>Example.class</mainClass>
<layout>ZIP</layout>
</configuration>
</plugin>
</plugins>
</build>
</project>





  Understanding annotations

 @RestController -> know as a stereotype annotation, provides a hint for the people reading the code and for the Spring , that class plays a specific role.
 So in this case, our class is a web @Controller.

 @RequestMapping --> provides  “routing” information.
 tells Spring that any HTTP request with the "/" path should be mapped to the "home " method.

 @RestController --> Spring to render the resulting string directly back to the caller.

 @RestController and @RequestMapping annotations are Spring MVC annotations. (They are not specific to Spring Boot.)

 @EnableAutoConfiguration -->
 tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. As we have added "spring-boot-starter-web" Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.


Our main method delegates to Spring Boot’s SpringApplication class by calling run. SpringApplication bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to pass Example.class as an argument to the run method to tell SpringApplication which is the primary Spring component. The args array is also passed through to expose any command-line arguments.

SpringBoot Application error

Below is the Exception comes when you execute : mvn package

Issue: You have more than one class inside the application with 'main" method

solution : Find the other main method and delete or comment that. Or specify the class you need to refer the main method.
Hint : If you create a project using a maven template, most probably it will create a App.java class with main method. So look for that.

You can easily solve by stating the main class. eg: main class is Example.java


<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>

<configuration>
<mainClass>Example.class</mainClass>
<layout>ZIP</layout>
</configuration>
</plugin>
</plugins>
</build>

for more information refer

https://docs.spring.io/spring-boot/docs/current/maven-plugin/usage.html
----------------------------------------------------------------------------------------------------------------

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.3.RELEASE:repackage (default) on project SpringBootTest: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.3.RELEASE:repackage failed: Unable to find main class -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.3.RELEASE:repackage (default) on project SpringBootTest: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.3.RELEASE:repackage failed: Unable to find main class
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:225)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.3.RELEASE:repackage failed: Unable to find main class
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:110)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
        ... 19 more
Caused by: java.lang.IllegalStateException: Unable to find main class
        at org.springframework.boot.loader.tools.Repackager.buildManifest(Repackager.java:300)
        at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:238)
        at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:195)
        at org.springframework.boot.maven.RepackageMojo.repackage(RepackageMojo.java:220)
        at org.springframework.boot.maven.RepackageMojo.execute(RepackageMojo.java:207)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
        ... 20 more
[ERROR]
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

Monday, July 23, 2018

Programming Problem Terminology for Problem Designers

Programming Problem Terminology for Problem Designers
What problems will work?
1. Read input from stdin and output to stdout.
2. Name the class as Main in Java.
3. Program must contain a main() method.
4. Evaluate programs based on the test cases which include input and the corresponding output.
5. For each programming problem, all the test cases corresponding to that problem will be run.
Score = (number of successes/ total number of test cases) *100%
6. Each test case would be run against a fixed time out (which is 8 sec for now and have to be determined). The size of the input and output is not limited.

Exam Instructions for Examinee:
In Programming section if you use Java,
Name the class as Main. Your program must contain a public static void main(string[] args)  method which reads input from stdin and output to stdout
If you use C# your class must contain public static void Main(string[] args) which reads input from stdin and output to stdout

Sample Problem:
You have got a range of numbers between 1 to N, where one of the numbers is repeated. You need to write a program to find out the duplicate number.


Sample Test cases:
Data Set Input Output
1 0 3 2 7 9 9 4    9
2 80 3 2 9 99 7 0 1 7 79 44 33 56 67 89 88 78 63 34 32 38 47 8 4 27965  43752  15488  18410  41356  37480  8678  13635  31532  29352  40413  23158  4347  29432  46659  45783  32156  7
3 22477  16608  14208  3579  38156  41  49523  8884  31114  38254  6133  6032  6838  42650  42457  11380  30785  30295  35461  17199  8311  2266  43719  8851  43966  27635  12256  45083  38490  17856  26463  5246  39137  42821  10349  46336  29396  3131  44969  8708  9429  37687  41780  44158  36055  31252  19186  23944  21798  6550  27276  49463  29064  39584  5060  5086  19460  35477  20883  44276  41113  11393  17411  41193  3786  23743  37030  28463  457  44770  19311  14069  17036  32872  11035  26694  13583  2496  41488  44868  29165  28540  6325  16504  13702  10539  23515  20496  8814  4372  35492  31559  23388  12119  34484  22477  8220  29380  49738  48480  29071  14781  26890  47515  23151  30856  30108  19888  13464  11831  25887  27965  43752  15488  18410  41356  37480  8678  13635  31532  29352  40413  23158  4347  29432  46659  45783  32156  28270  21977  19995  12963  16438  16610  27607  35385  36271  10223  44212  31022  11220  13888  10717  21864  15745  10489  3966  5303  42395  21729  6987  15560  18631  34321  49745  39271  30996  35842  24049  36385  12182  45227  23355  2517  34566  6434  11775  42280  4473  21119  43460  24103  28334  40792  23764  37701  46719  35502  10661  46243  28658  22477




Sample Answer:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;

public class Main {
   public static void findDuplicateNumber(int[] ar) {
        Arrays.sort(ar);

        for (int i = 1; i < ar.length; i++) {
            if (ar[i] == ar[i - 1]) {
                System.out.println(ar[i]);
                break;
            }
        }      
    }  
    public static void main(String a[]){
        Scanner scan = new Scanner(System.in);
        List numbers = new ArrayList();
        while (scan.hasNextInt()) {
            numbers.add(scan.nextInt());
                }
       
        int[] arr=new int[numbers.size()];
       
        for(int x=0;x
               arr[x]=numbers.get(x);        
        }
       findDuplicateNumber(arr);
            }
}







Sample Answer 2

import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import   java.lang.Math.*;

public class Main {

  public static void smallestDistance(int ints[]) {

                        int index = 0;

                        for (int i = 1; i < ints.length - 1; i++) {
                                    if (Math.abs(ints[index] - ints[index + 1]) > Math.abs(ints[i]
                                                            - ints[i + 1])) {
                                                index = i;
                                    }
                        }
                        System.out.println(index);
            }
           
    public static void main(String a[]){
        Scanner scan = new Scanner(System.in);
        List numbers = new ArrayList();
        while (scan.hasNextInt()) {
            numbers.add(scan.nextInt());
                }
       
        int[] arr=new int[numbers.size()];
       
        for(int x=0;x
               arr[x]=numbers.get(x);        
        }
        smallestDistance(arr);
            }
}

Restart windows server at specific time

I day today activities, you may need to restart your servers daily, weekly etc. when you have so many servers, it may be a vert cumbersome task.
1. Restart server - create a script
2. run task at specific time  -create task schedular


1. below is the script
---------------------------------------
shutdown /r /f
----------------------------------------


2. create task

a.) General tab , tick "Run whether user log or not" and "Run with highest privileges"
b.) Trigger give time you need to execute the script

refer previous article to set up command
   https://cgenit.blogspot.com/2018/07/stop-iis-with-task-schedular.html

Stop IIS with Task Schedular


1. create a powershell with needed commands
2. create basic task with executing the powershell script with highest privileges and with whether user log or not.


Below is the powershell script

----------------------------------
# Start-Process powershell -Verb runAs

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))


$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}

# Do your adminy thing here...

iisreset /stop




2. Create Basic task

a.) General tab , tick "Run whether user log or not" and "Run with highest privileges"
b.) Trigger give time you need to execute the script
c.) Actions
     program script  = powershell.exe
    Arguments = -ExecutionPolicy Bypass  C:\Project\stopIIS.ps1








Tuesday, July 17, 2018

Windows task Schedulars

It was pretty hard to find a command to enable and disable the windows task schedulers.
Only way to do that was to rename the job files. Job files basically resides in "Task" folder.

This folder my have below paths
C:\Windows\Tasks
or
C:\Windows\System32\Tasks\


I renamed task files. Better to backup those files before doing this.

let's take a task scheduler created inside "Test" folder and name of the task as "TestPS"

the of the file would look like
C:\Windows\System32\Tasks\Test\TestPS


Disable  - rename as .bak
---------
move "C:\Windows\System32\Tasks\Test\TestPS" "C:\Windows\System32\Tasks\Test\TestPS.bak"

Enable  - rename as original file
------------------------------
move "C:\Windows\System32\Tasks\Test\TestPS.bak" "C:\Windows\System32\Tasks\Test\TestPS" 

Tuesday, July 3, 2018

Defrag and reindex datazen raven db

Below are the steps to run command line with admin privileges.

---------------------------------------------------------------------------------------------------------

net stop datazenrenderingservice
net stop datazendata
net stop datazen

cd C:\Program Files\Datazen Enterprise Server\service


esentutl /d Data\Data

Datazen.Server.Service.exe /console /resetindexes /shutdown

net start datazen
net start datazendata
net start datazenrenderingservice


---------------------------------------------------------------------------------------------------------

Restore datazen with a backup

Below are the command list to restore backup file in the datazen. You need to perform these command using command prompt with administrator privileges.

-------------------------------------------------------------------------------------------------------------

net stop datazenrenderingservice
net stop datazendata
net stop datazen

cd C:\Program Files\Datazen Enterprise Server\service


rmdir /S /Q Data

mkdir Data

Raven.Server.exe -restore -src D:\Datazen\Backups\datazen-2018061544243-eaaa -dest Data


esentutl /d Data\Data

Datazen.Server.Service.exe /console /resetindexes /shutdown

net start datazen
net start datazendata
net start datazenrenderingservice

-------------------------------------------------------------------------------------------------------------