Thursday, August 16, 2018

Some useful SQL Queries

Some Useful SQL commands
-------------------------

-- get database names
SELECT name,* FROM master.dbo.sysdatabases



Job History
-----------


USE msdb ; 
GO 

SELECT j.name JobName,h.step_name StepName,
CONVERT(CHAR(10), CAST(STR(h.run_date,8, 0) AS dateTIME), 111) RunDate,
STUFF(STUFF(RIGHT('000000' + CAST ( h.run_time AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') RunTime,
h.run_duration StepDuration,
case h.run_status when 0 then 'failed'
when 1 then 'Succeded'
when 2 then 'Retry'
when 3 then 'Cancelled'
when 4 then 'In Progress'
end as ExecutionStatus,
h.message MessageGenerated
FROM sysjobhistory h inner join sysjobs j
ON j.job_id = h.job_id
-- name of the job
where j.name='Populate_TTC_Task_Details'
-- only failed jobs
AND h.run_status=0
ORDER BY h.run_date desc

Full Job history
------------------

USE msdb ; 
GO 

EXEC dbo.sp_help_jobhistory 
    @job_name = N'Populate_TTC_Task_Details' ; 
GO

Job names
----------
select s.name,l.name
 from  msdb..sysjobs s
 left join master.sys.syslogins l on s.owner_sid = l.sid
 order by s.name

 -- find guid from backups
use [msdb]
SELECT * FROM log_shipping_primary_databases

"D:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqllogship.exe" -Backup E842CE8C-9F88-4483-B3AE-96BA97F62E25 -server ServerName



Most CPU Intensive Queries
--------------------------

--- https://www.red-gate.com/simple-talk/blogs/how-to-find-cpu-intensive-queries/

SELECT
       -- using statement_start_offset and
       -- statement_end_offset we get the query text
       -- from inside the entire batch
       SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
                           ((CASE qs.statement_end_offset
                                        WHEN -1 THEN DATALENGTH(qt.TEXT)
                                        ELSE qs.statement_end_offset
                           END
                           - qs.statement_start_offset)/2)+1)
                           as [Text],
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
-- converting microseconds to seconds
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
       -- Retrieve the query text
       CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
       -- Retrieve the query plan
       CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC -- CPU time


Longest Running queries
-----------------------
SELECT  st.text,
        qp.query_plan,
total_worker_time,
        qs.*
FROM    (
    SELECT  TOP 50 *
    FROM    sys.dm_exec_query_stats
    ORDER BY total_worker_time DESC
) AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp
WHERE qs.max_worker_time > 300
      OR qs.max_elapsed_time > 300
 
 
Permission
----------
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'



Server Info
-----------

SELECT
            SERVERPROPERTY('MachineName') AS [ServerName],
SERVERPROPERTY('ServerName') AS [ServerInstanceName],
            SERVERPROPERTY('InstanceName') AS [Instance],
            SERVERPROPERTY('Edition') AS [Edition],
            SERVERPROPERTY('ProductVersion') AS [ProductVersion],
Left(@@Version, Charindex('-', @@version) - 2) As VersionName



Change Recovery Model
---------------------
USE [master]
GO
ALTER DATABASE [Mydb] SET RECOVERY SIMPLE WITH NO_WAIT
GO


Get Recovery Info
-----------------
SELECT name, recovery_model_desc 
   FROM sys.databases 
      WHERE name in ('Mydb')
 
 
 
Shrink Files
---------------

USE [Mydb]
GO
DBCC SHRINKFILE (N'mydb_log' , 0, TRUNCATEONLY)
GO


Update Column uppercase
------------------------

update [MyDB].[myTable].[HostNameCountry]
set hostname=upper(hostname)



database Size
--------------


IF OBJECT_ID('tempdb.dbo.#space') IS NOT NULL
    DROP TABLE #space

CREATE TABLE #space (
      database_id INT PRIMARY KEY
    , data_used_size DECIMAL(18,2)
    , log_used_size DECIMAL(18,2)
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #space (database_id, data_used_size, log_used_size)
    SELECT
          DB_ID()
        , SUM(CASE WHEN [type] = 0 THEN space_used END)
        , SUM(CASE WHEN [type] = 1 THEN space_used END)
    FROM (
        SELECT s.[type], space_used = SUM(FILEPROPERTY(s.name, ''SpaceUsed'') * 8. / 1024)
        FROM sys.database_files s
        GROUP BY s.[type]
    ) t;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT
      d.database_id
    , d.name
    , d.state_desc
    , d.recovery_model_desc
    , t.total_size
    , t.data_size
    , s.data_used_size
    , t.log_size
    , s.log_used_size
    , bu.full_last_date
    , bu.full_size
    , bu.log_last_date
    , bu.log_size
FROM (
    SELECT
          database_id
        , log_size = CAST(SUM(CASE WHEN [type] = 1 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , data_size = CAST(SUM(CASE WHEN [type] = 0 THEN size END) * 8. / 1024 AS DECIMAL(18,2))
        , total_size = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
    FROM sys.master_files
    GROUP BY database_id
) t
JOIN sys.databases d ON d.database_id = t.database_id
LEFT JOIN #space s ON d.database_id = s.database_id
LEFT JOIN (
    SELECT
          database_name
        , full_last_date = MAX(CASE WHEN [type] = 'D' THEN backup_finish_date END)
        , full_size = MAX(CASE WHEN [type] = 'D' THEN backup_size END)
        , log_last_date = MAX(CASE WHEN [type] = 'L' THEN backup_finish_date END)
        , log_size = MAX(CASE WHEN [type] = 'L' THEN backup_size END)
    FROM (
        SELECT
              s.database_name
            , s.[type]
            , s.backup_finish_date
            , backup_size =
                        CAST(CASE WHEN s.backup_size = s.compressed_backup_size
                                    THEN s.backup_size
                                    ELSE s.compressed_backup_size
                        END / 1048576.0 AS DECIMAL(18,2))
            , RowNum = ROW_NUMBER() OVER (PARTITION BY s.database_name, s.[type] ORDER BY s.backup_finish_date DESC)
        FROM msdb.dbo.backupset s
        WHERE s.[type] IN ('D', 'L')
    ) f
    WHERE f.RowNum = 1
    GROUP BY f.database_name
) bu ON d.name = bu.database_name
ORDER BY t.total_size DESC


Get size of db from back up file
--------------------------------


-- give the path of backup file
RESTORE FILELISTONLY FROM DISK = N'C:\DB_Backup\Mydb.bak'



Link Server Query
----------------

-- get the details of the linkservers
sp_linkedservers



-- query from link server
-- below is the example
select * from openquery(LInkServerName, 'select * from XXXX.XXV_V')



Session Precheck / any active sessions for DB
---------------------------------------------

BEGIN TRANSACTION
SET NOCOUNT ON
BEGIN
DECLARE @V_COUNT INTEGER

SELECT @V_COUNT = count(*) FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid and P.SPID > 50;

IF (@V_COUNT > 0)
BEGIN
SELECT SPID,hostname FROM MASTER..SYSPROCESSES P, MASTER..SYSDATABASES D
WHERE P.DBID = D.DBID AND D.DBID = DB_ID('#DBNAME#') and P.SPID <> @@spid;
RAISERROR('',16,1)
ROLLBACK TRANSACTION
RETURN
END
END


Add user
---------

USE [master]
GO
CREATE LOGIN [NEXA\username] FROM WINDOWS WITH DEFAULT_DATABASE=[master]
GO
USE [Mydb]
GO
CREATE USER [NEXA\username] FOR LOGIN [NEXA\username]
GO
USE [Mydb]
GO
EXEC sp_addrolemember N'db_owner', N'NEXA\username'
GO


Check Performance and kill running Scripts
------------------------------------------

sp_who2

kill 74


Shrink DB
------------------


USE [MyDB]
GO
/****** Object:  StoredProcedure [mydb].[Nexa_Shrink_MyDBTrasactionLog]    Script Date: 9/27/2016 12:00:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [MyDB].[Nexa_Shrink_MyDBTrasactionLog] 
 
AS 
 
BEGIN 
 -- Declare required variables. 
 DECLARE @vcDBMirroringStatus VARCHAR (100); 
 DECLARE @vcMirroringStatus VARCHAR (100); 
 DECLARE @intDBId INT; 
 
 -- Set the values for variables. 
 
 SET @vcMirroringStatus = 'SYNCHRONIZED' -- This is the syncronized status 
 SET @intDBId = DB_ID();-- This is the digite mirroring DB id. 
 
 -- Get the Digite DB mirroring status 
 SET @vcDBMirroringStatus = (select mirroring_state_desc from sys.database_mirroring where database_id = @intDBId) 
 
 -- If Digite DB mirroring status is 'SYNCHRONIZED' only shrink the DB log 
 IF @vcDBMirroringStatus = @vcMirroringStatus 
 BEGIN 
  CHECKPOINT 
  BACKUP LOG  MyDb to disk = 'C:\ShrinkDBLogs\Mydb1.trn' 
  DBCC SHRINKFILE (Mydb_log, 15360) 
 END 
 
END 




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


SELECT TOP 25
dm_mid.database_id AS DatabaseID,
dm_migs.avg_user_impact*(dm_migs.user_seeks+dm_migs.user_scans) Avg_Estimated_Impact,
dm_migs.last_user_seek AS Last_User_Seek,
OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) AS [TableName],
'CREATE INDEX [IX_' + OBJECT_NAME(dm_mid.OBJECT_ID,dm_mid.database_id) + '_'
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.equality_columns,''),', ','_'),'[',''),']','') +
CASE
WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns IS NOT NULL THEN '_'
ELSE ''
END
+ REPLACE(REPLACE(REPLACE(ISNULL(dm_mid.inequality_columns,''),', ','_'),'[',''),']','')
+ ']'
+ ' ON ' + dm_mid.statement
+ ' (' + ISNULL (dm_mid.equality_columns,'')
+ CASE WHEN dm_mid.equality_columns IS NOT NULL AND dm_mid.inequality_columns IS NOT NULL THEN ',' ELSE
'' END
+ ISNULL (dm_mid.inequality_columns, '')
+ ')'
+ ISNULL (' INCLUDE (' + dm_mid.included_columns + ')', '') AS Create_Statement
FROM sys.dm_db_missing_index_groups dm_mig
INNER JOIN sys.dm_db_missing_index_group_stats dm_migs
ON dm_migs.group_handle = dm_mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details dm_mid
ON dm_mig.index_handle = dm_mid.index_handle
WHERE dm_mid.database_ID = DB_ID()
ORDER BY Avg_Estimated_Impact DESC
GO



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







Some useful java commands

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"


jps –lvm

Saturday, August 11, 2018

Create Simple Microservice project to understand the concepts

I have searched throughout the web and below is the sample code i have found.
https://spring.io/blog/2015/07/14/microservices-with-spring

below are the simplified steps in creating running the project



created pom with all dependencies and build the maven project


1.  create package "io.pivotal.microservices.services.registration"
a.)RegistrationServer.java
b.) registration-server.yml inside "src\main\resources"
c.) run RegistrationServer.java and access http://localhost:1111/
run RegistrationServer with jar created. 

2. Create account services
a.) create package "io.pivotal.microservices.services.accounts" and service class "AccountsServer.java"
This class need "AccountsServer.class" and "AccountRepository.java"
b.) Business logic for Account. create package "io.pivotal.microservices.accounts"
create "Account.java"  pojo
create "AccountRepository.java"
create "AccountsConfiguration.java"
create "AccountsController.java". --> need exceptioon class also for this.
create "HomeController.java"
c.) create exception class for account
create package "io.pivotal.microservices.exceptions" and class "AccountNotFoundException.java"

Now error in the "AccountsServer.java"  will be resolved.

Run "AccountsServer.java" -->

3. Errors
a.)error [db-config.properties] cannot be opened because it does not exist

Added "db-config.properties" to folder "src\main\resources"

b.)Error
class path resource [testdb/schema.sql] cannot be opened because it does not exist
create folder "testdb" inside "resources" and Added "schema.sql" and "data.sql"

4. Now run "http://localhost:1111/" , you can see the account service registered.
for more info gotot "http://localhost:1111/eureka/apps/"

Alternativel go and see "http://localhost:1111/eureka/apps/ACCOUNTS-SERVICE"

5. Configuration options
Registration takes upto 30s cause this is default client refresh time. Can change setting "eureka.instance.leaseRenewalIntervalInSeconds"
Note : Smaller numbers are not recommened in Prod

eureka:
  instance:
    leaseRenewalIntervalInSeconds: 5         # DO NOT DO THIS IN PRODUCTION



6. Acessing microservice web service

a.) create package "io.pivotal.microservices.services.web"
b.) create classes
"Account.java"
HomeController.java
SearchCriteria.java
WebAccountsController.java  --> needs "WebAccountsController"
WebAccountsService.java
WebServer.java

7. Make sure you have yml files for each service
registration-server.yml
accounts-server.yml
web-server.yml

8. Running Three services without building jar
mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.registration.RegistrationServer
mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.accounts.AccountsServer
mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.web.WebServer

9. Building jar file.
As we have 3 main classes we need to specify the main class inside POM file.
In this case we create onc single class with main method "Main.java"  and call other services via that class

inside POM

<properties>
<start-class>io.pivotal.microservices.services.Main</start-class>
</properties>

Then create Main class inside package "io.pivotal.microservices.services"

Call the each service and run as below

java -jar target/microservices-demo-2.0.0.RELEASE.jar registration
java -jar target/microservices-demo-2.0.0.RELEASE.jar accounts
java -jar target/microservices-demo-2.0.0.RELEASE.jar web










Create Micro service Project with many services and running one by one

You may have build the all the microservices in a single project or One project has many micro services.

In that case how to run those services picking up one by one as needed.

Example i have taken  from

https://spring.io/blog/2015/07/14/microservices-with-spring


eg : we have three micro services projects.
1. Registration server - eureka server
2. Account service
3. Web

How to run without building the jar:

we use maven and use spring-boot plugin to specify 'run' and give the main class with "-Dstart-class" tag

below is the three sample commands, run from the sample project directory where the POM file exist.(where you run mvn clean package  command)

mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.registration.RegistrationServer

mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.accounts.AccountsServer

mvn spring-boot:run -Dstart-class=io.pivotal.microservices.services.web.WebServer



How to run with Jar

Since we have few main classes

1. We need to specify the maven what is our main class

<properties>
<start-class>io.pivotal.microservices.services.Main</start-class>
</properties>

2. Create One single class with Main method. 
We call it Main.java
As we can. specify only one main class, we need to create a class with one main method which will guide to / call to other main methods (RegistrationServer.java , AccountsServer.java, WebServer.java)



3. Run jar with calling each service via Main.java
open three command lines and execute below three command, which will up three services

java -jar target/microservices-demo-2.0.0.RELEASE.jar registration
java -jar target/microservices-demo-2.0.0.RELEASE.jar accounts
java -jar target/microservices-demo-2.0.0.RELEASE.jar web


----------------------------------------------------------------below code snipet for Main.java--------------

If you do not create Main.java, still maven will build the project without error, but running this you will get 
Exception in thread "main" java.lang.ClassNotFoundException: io.pivotal.microservices.services.Main


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




package io.pivotal.microservices.services;

import io.pivotal.microservices.services.accounts.AccountsServer;
import io.pivotal.microservices.services.registration.RegistrationServer;
import io.pivotal.microservices.services.web.WebServer;

/**
 * Allow the servers to be invoked from the command-line. The jar is built with
 * this as the Main-Class in the jar's MANIFEST.MF.
 * 
 * @author Paul Chapman
 */
public class Main {

 public static void main(String[] args) {

  String serverName = "NO-VALUE";

  switch (args.length) {
  case 2:
   // Optionally set the HTTP port to listen on, overrides
   // value in the -server.yml file
   System.setProperty("server.port", args[1]);
   // Fall through into ..

  case 1:
   serverName = args[0].toLowerCase();
   break;

  default:
   usage();
   return;
  }

  if (serverName.equals("registration") || serverName.equals("reg")) {
   RegistrationServer.main(args);
  } else if (serverName.equals("accounts")) {
   AccountsServer.main(args);
  } else if (serverName.equals("web")) {
   WebServer.main(args);
  } else {
   System.out.println("Unknown server type: " + serverName);
   usage();
  }
 }

 protected static void usage() {
  System.out.println("Usage: java -jar ...  [server-port]");
  System.out.println(
    "     where server-name is 'reg', 'registration', " + "'accounts' or 'web' and server-port > 1024");
 }
}

Friday, August 10, 2018

Error building micro services app

https://spring.io/blog/2015/07/14/microservices-with-spring

Below shows the error. Solution is adding below snipet , "start-class" for the POM. Try building with "mvn clean package"

Solution :

<properties>
<start-class>io.pivotal.microservices.services.Main</start-class>
</properties>


Then run the jar with specifying which main method needs to be choose.

eg :
java -jar microservices-demo-2.0.0.RELEASE.jar account
java -jar microservices-demo-2.0.0.RELEASE.jar account
java -jar microservices-demo-2.0.0.RELEASE.jar account


------ Error --------------------------------

[INFO] Finished at: 2018-08-10T16:41:48+05:30
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.1.RELEASE:repackage (default) on project EurekaServer1: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.1.RELEASE:repackage failed: Unable to find a single main class from the following candidates
[io.pivotal.microservices.services.registration.RegistrationServer, io.pivotal.microservices.services.web.WebServer] ->
[Help 1]org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:2.0.1.RELEASE:repackage (default) on project EurekaServer1: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.1.RELEASE:repackage failed: Unable to find a single main class from the following candidates
[io.pivotal.microservices.services.registration.RegistrationServer, io.pivotal.microservices.services.web.WebServer] at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) 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:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)Caused by: org.apache.maven.plugin.PluginExecutionException: Execution default of goal org.springframework.boot:spring-boot-maven-plugin:2.0.1.RELEASE:repackage failed: Unable to find a single main class from the following candidates
[io.pivotal.microservices.services.registration.RegistrationServer, io.pivotal.microservices.services.web.WebServer] at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:148) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) 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:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)Caused by: java.lang.IllegalStateException: Unable to find a single main class from the following candidates
[io.pivotal.microservices.services.registration.RegistrationServer, io.pivotal.microservices.services.web.WebServer] at org.springframework.boot.loader.tools.MainClassFinder$SingleMainClassCallback.getMainClassName (MainClassFinder.java:451) at org.springframework.boot.loader.tools.MainClassFinder$SingleMainClassCallback.access$100 (MainClassFinder.java:421) at org.springframework.boot.loader.tools.MainClassFinder.findSingleMainClass (MainClassFinder.java:205) at org.springframework.boot.loader.tools.Repackager.findMainMethod (Repackager.java:333) at org.springframework.boot.loader.tools.Repackager.findMainMethodWithTimeoutWarning (Repackager.java:322) at org.springframework.boot.loader.tools.Repackager.buildManifest (Repackager.java:293) 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:221) at org.springframework.boot.maven.RepackageMojo.execute (RepackageMojo.java:208) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:208) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:154) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:146) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:954) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288) at org.apache.maven.cli.MavenCli.main (MavenCli.java:192) 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:289) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:229) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:415) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:356)
[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/PluginExecutionExceptionC:\BackUp_2016_07_14\NonFilter\Projects\EAG\code\Spring\SpringBoot\EurekaServer1>




Now we have another error running jar with argument specifying the service.

Reason: we have not added the Main.java  class we have specified inside the POM. when we build the jar, earlier we had an issue with too many main methods. As we need to get rid of that we specifies a class which needs to be taken as a main class inside POM.
It build the jar without checking the existence of the class.

Solution :
So we create the Main.java class in the specified package.

Error is below when class in not present.

------------------------
Exception in thread "main" java.lang.ClassNotFoundException: io.pivotal.microservices.services.Main
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:93)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:46)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
        at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
        at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)



Tuesday, August 7, 2018

VB script to read and write file

1. To Read line by line in a given file



Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\listfile.txt",1)
Dim strLine
do while not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     'Do something with the line
loop
objFileToRead.Close
Set objFileToRead = Nothing

This will read "listfile.txt' line by line. 
Inside the loop you can do something you need
Let's say you need to write this output to another file.

Let's break the logic to few lines to understanding purposes.

1. create file object and assign to variable.

Set filesys = CreateObject("Scripting.FileSystemObject")


2. Declare the output file path

strOutputFile1= "C:\out.txt"

3. Open a file in writable format (8) and get an object reference

Set objReport1 = filesys.OpenTextFile(strOutputFile1, 8, True)

4. Inside the loop, write the reader content from other object line by line

objReport1.WriteLine strLine

5. close all open streams and close references

objReport1.Close

set objReport1 = nothing

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

Below is the complete vb script to read content from a file and write to another file

2. Read content from a given file line by line and do something and write back to another file



Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\emailList.txt",1)

' to write
Set filesys = CreateObject("Scripting.FileSystemObject")
strOutputFile1= "C:\out.txt"
Set objReport1 = filesys.OpenTextFile(strOutputFile1, 8, True)

Dim strLine
do while not objFileToRead.AtEndOfStream
     strLine = objFileToRead.ReadLine()
     'Do something with the line
 
'MsgBox strLine
' write
objReport1.WriteLine strLine
loop
objFileToRead.Close
Set objFileToRead = Nothing

'closing all for write
objReport1.Close

set objReport1 = nothing

Thursday, August 2, 2018

Some Useful SQL queries for MSSQL

 1.Check the Recovery model of the databases