Tuesday, August 27, 2019

Automate: Create Remote Desktop connection

How to connect to remote machine automatically running a bat file in Windows.
This will ease your life.

below is the sample line

cmdkey /generic:"IP Address" /user:"UserName" /pass:"Password"
mstsc /v:"IP Address"
eg:

cmdkey /generic:111.111.111.111 /user:Domain\user.name /pass:password
mstsc /v:111.111.111.111

Wednesday, August 21, 2019

Microservice - Create Eureka Server

In micro service architecture, Discovery server is a key component.
As we don't have to build everything from the scratch, we have Eureka server which can use very easily with very much less code.

1. Create java project

Create the project using starter io , https://start.spring.io/
Make sure you do this as a habit, Do not create project manually with creating pom file etc. That was old fashion and get use to use the available resources.

Here you can give

  1. Project type -  Maven , Gradle 
  2. Language =Java, Groovy, Kotlin
  3. Spring Boot version = 2.2. M5 , 2.17 etc
  4. Project meta data  = which used give in creating pom file
    1. group  - com.test.micro
    2. artifact  - eurekaServer
    3. Description - Demo project for Eureka Server
    4. package name - com.test.micro.eurekaServer
    5. packaging - Jar | War
    6. java version - 12, 11, 8
  5. dependencies = Eureka server , Actuator, devtools

2. download the project and open with eclipse and run

This will give some errors
It will try to behave as a Eureka Client
use "@EnableEurekaServer" to make this a Eureka server

package com.saap.micro.eurekaServer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

}


As we have not given any properties to configure, This will start with default configs

taking port 8080 as default port
you can acess the eureka server via below url

http://localhost:8080/

As we have no any running clients, we will have an empty dashboard.







Now let's add an yml file and configure the Discovery server as we want.

Create "application.yml" file inside "resources"  folder  (  eurekaServer\src\main\resources)



eureka:
  instance:
    hostname: localhost
  client:  # Not a client, don't register with yourself
    registerWithEureka: false
    fetchRegistry: false

server:
  port: 1111   # HTTP (Tomcat) port



you will get the console out as below - see 1111 newly created port





you can see the port in the console out put also

================================================================

INFO 18152 --- [      Thread-16] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
INFO 18152 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 1111 (http) with context path ''
INFO 18152 --- [  restartedMain] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 1111
INFO 18152 --- [  restartedMain] c.s.m.e.EurekaServerApplication          : Started EurekaServerApplication in 11.818 seconds (JVM running for 12.9)
INFO 18152 --- [io-1111-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 18152 --- [io-1111-exec-10] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
INFO 18152 --- [io-1111-exec-10] o.s.web.servlet.DispatcherServlet        : Completed initialization in 17 ms


package com.saap.micro.eurekaServer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

}

Tuesday, June 18, 2019

Write a method with any number of arguments

Java we can write a method with any number of arguments using elispe as below

protected boolean areAllStringsSet(String... theStrings){

}

When we write amethod loke this it is always better to validate whether all the arguments are valid, NOT NULL

below is a method to check and validate whether those are NULL.
you can use for any check and modify as you need

/**
* If any of the supplied strings are empty then return false;
*/
protected boolean areAllStringsSet(String... theStrings){
boolean retVal = true;
if(theStrings != null){
for(int i=0;i String str = theStrings[i];
if(str != null){
if(str.trim().length() < 0){
retVal = false;
break;
}
}else{
retVal = false;
break;
}
}
}

return retVal;
}

Thursday, June 13, 2019

Java :: Compare Two dates

If you have tried to compare dates in java , you would have experience trouble checking "equal".
This is because, date include a time component. There is a high chance that time component can be different.
But if we need to compare two dates, only looking at the "Year","Month","Day"
Then Time must be removed from the date.
Below example shows how to do that.

package com.date.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateConverter {

public static void main(String[] args) {
Date curDate = new Date();
System.out.println(curDate);
System.out.println(getDateWithoutTime(curDate));
}

/**
* Check whether First date is after or equal to Second date. When
* comparing the dates, the time element is removed before compare, else always
* not equal due to time component.
* Second Date | First Date
*
* @param firstDate
*            First date to be compared.
* @param secondDate
*            Second date to be compared.
* @return True when First date is after or equal Second date and False
*         vice versa.
*/
public final static boolean isFirstDateAfterOrEqualToSecondDate(Date firstDate, Date secondDate) {
if (firstDate != null && secondDate != null) {
Date firstDateWithoutTime = getDateWithoutTime(firstDate);
Date secondDateWithoutTime = getDateWithoutTime(secondDate);
return ((firstDateWithoutTime.after(secondDateWithoutTime))
|| (firstDateWithoutTime.equals(secondDateWithoutTime)));
}
return false;
}

/**
* Check whether First date is after Second date. When comparing the
* dates, the time element is removed before compare.
* Second Date | First Date
*
* @param firstDate
*            First date to be compared.
* @param secondDate
*            Second date to be compared.
* @return True when First date is after Second date and False vice
*         versa.
*/
public final static boolean isFirstDateAfterSecondDate(Date firstDate, Date secondDate) {
if (firstDate != null && secondDate != null) {
return (getDateWithoutTime(firstDate)).after(getDateWithoutTime(secondDate));
}
return false;
}

/**
* Check whether First date is before or equal to Second date. When
* comparing the dates, the time element is removed before compare, else always
* not equal due to time component.
* First Date | Second Date
*
* @param firstDate
*            First date to be compared.
* @param secondDate
*            Second date to be compared.
* @return True when First date is before or equal Second date and False
*         vice versa.
*/
public final static boolean isFirstDateBeforeOrEqualToSecondDate(Date firstDate, Date secondDate) {
if (firstDate != null && secondDate != null) {
Date firstDateWithoutTime = getDateWithoutTime(firstDate);
Date secondDateWithoutTime = getDateWithoutTime(secondDate);
return ((firstDateWithoutTime.before(secondDateWithoutTime))
|| (firstDateWithoutTime.equals(secondDateWithoutTime)));
}
return false;
}

/**
* Check whether First date is before to Second date. When comparing the
* dates, the time element is removed before compare, else always not equal due
* to time component.
* First Date | Second Date
*
* @param firstDate
*            First date to be compared.
* @param secondDate
*            Second date to be compared.
* @return True when First date is before Second date and False vice
*         versa.
*/
public final static boolean isFirstDateBeforeSecondDate(Date firstDate, Date secondDate) {
if (firstDate != null && secondDate != null) {
return (getDateWithoutTime(firstDate)).before(getDateWithoutTime(secondDate));
}
return false;
}

/**
* Check whether date has a time component.
*
* @param aDate
*            valid date object.
* @return True when there is not time value for date and False vice versa.
*/
public final static boolean isTimeEqualToZero(Date aDate) {
if (aDate != null) {
Calendar aCalendarDate = new GregorianCalendar();
aCalendarDate.setTime(aDate);

int theHour = aCalendarDate.get(Calendar.HOUR_OF_DAY);
int theMinute = aCalendarDate.get(Calendar.MINUTE);

return (theHour == 0 && theMinute == 0);
}

return false;
}

/**
* Get the Date without Time. In Other words,get only Year,Month,day component.
*
* @param aDate
*            Valid date object.
* @return Date without Time.
*/
public static final Date getDateWithoutTime(Date aDate) {
Date rtnDate = null;
if (aDate != null) {
Calendar aCalendarDate = new GregorianCalendar();

aCalendarDate.setTime(aDate);
aCalendarDate.set(GregorianCalendar.HOUR, 0);
aCalendarDate.set(GregorianCalendar.MINUTE, 0);
aCalendarDate.set(GregorianCalendar.SECOND, 0);
aCalendarDate.set(GregorianCalendar.MILLISECOND, 0);
aCalendarDate.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
rtnDate = aCalendarDate.getTime();
}
return rtnDate;
}
}

Wednesday, June 5, 2019

Important Online Payment Links


To Pay Water Bill
National Water Supply & Drainage Board
https://payments.waterboard.lk/payment/index

Telephone Bill Payments - NTB card accessible
Mobitel - go to site - click payment link in top right corner (Pay Bill)

https://online.mobitel.lk/onlinepay/

Dilog also same as Mobitel




Thursday, May 16, 2019

Set JSON response to servlet



<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${javax.servlet.version}</version>
</dependency>
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>${gson.version}</version>
</dependency>


=======================================================
public class Employee {
     
    private int id;
     
    private String name;
     
    private String department;
    
    private long salary;
 
    // constructors
    // standard getters and setters.
}

=================================================================
String employeeJsonString = new Gson().toJson(employee);


========= setting for response ==================================
PrintWriter out = response.getWriter();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(employeeJsonString);
out.flush();


============================================================


If you use Jackson , then code will be as follows

private void writeResponse(HttpServletResponse aResponse, String errorCode, String errorMessage) {
  try {
   aResponse.setHeader("SAP-Exception", errorMessage);
   aResponse.setHeader("SAP-NFA-Exception-Code", errorCode);
   aResponse.setHeader("Content-Type", "application/json");
   ObjectMapper objectMapper = new ObjectMapper();
   NFAErrorResponse errorResponse = new NFAErrorResponse();
   errorResponse.setCode(errorCode);
   errorResponse.setMessage(errorMessage);
   String errorJsonString =objectMapper.writeValueAsString(errorResponse);
   PrintWriter out = aResponse.getWriter();
   out.print(errorJsonString);
   out.flush();
  } catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }


for further info
https://www.baeldung.com/servlet-json-response






javax.servlet.http.HttpServletResponse.setHeader()

@Override
public void forwardToUrl(SectionInfo info, String link, int code)
{
 info.setRendered();
 try
 {
  HttpServletResponse response = info.getResponse();
  if( response == null )
  {
   throw new Error("info not bound to a request/response");
  }
  response.setStatus(code);
  response.setHeader("Location", link);
  response.flushBuffer();
 }
 catch( Exception e )
 {
  throw Throwables.propagate(e);
 }
}
 

============================================
Example 2

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String filename = request.getParameter("file");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    ViewerHtmlHandler handler = Utils.createViewerHtmlHandler();
    InputStream original = null;
    try {
        original = handler.getFile(filename).getStream();
    } catch (Exception x) {
        throw new RuntimeException(x);
    }

    Utils.writeToResponse(original, response);
}

====================================================================
Example 3
public void exportProjectBackupFile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
 String path=req.getParameter("path");
 String projectPath=Utils.decodeURL(path);
 if(StringUtils.isEmpty(projectPath)){
  throw new RuleException("Export project not be null.");
 }
 SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
 String projectName=projectPath.substring(1,projectPath.length());
 String filename=projectName+"-urule-repo-"+sd.format(new Date())+".bak";
 resp.setContentType("application/octet-stream");
 resp.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("utf-8"),"iso-8859-1") + "\"");
 resp.setHeader("content-type", "application/octet-stream");
 OutputStream outputStream=resp.getOutputStream();
 repositoryService.exportXml(projectPath,outputStream);
 outputStream.flush();
 outputStream.close();
}
=========================================================================

Example 4

private void downloadWorkflowDescription(HttpServletResponse response, String workflowName) throws ServletException {
 
    try {

        String xml = injector.getInstance(WfDefinitionService.class).fetchWfDefinition(workflowName);
        
        PrintWriter writer = response.getWriter();
        response.setContentType("application/force-download");
        response.setContentLength(xml.length());
        response.setHeader("Content-Transfer-Encoding", "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + workflowName + ".oswf.xml\"");
    
        BufferedReader reader = new BufferedReader(new StringReader(xml)); 
        String line;
        while((line = reader.readLine()) != null) {
            writer.print(line);
            writer.print("\n");
        }
        
    } catch (Exception exception) {
        throw new ServletException(exception);
    }
    
}
============================================================================
Example 5
@SuppressWarnings("unchecked")
private void writeJson(HttpServletResponse response, Map<String, Object> sessionParams) throws ServletException {
 try {
  JSONObject json = new JSONObject();
  json.putAll(sessionParams);
  response.setContentType("application/json");
  response.setHeader("Cache-Control", "no-cache");

  if (log.isTraceEnabled()) {
   log.trace("Responding with: " + json.toJSONString());
  }

  response.getWriter().write(json.toJSONString());
 } catch (IOException e) {
  throw new ServletException("Could not create json.", e);
 }
}
 
===========================================================================
Example 6
 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 String idStr = request.getParameter("id");
 if (idStr != null) {
  Long id = Long.valueOf(idStr);
  LocationPicture picture = null;
  if (id >= 0) {
   picture = LocationPictureDAO.getInstance().get(id);
  } else {
   Map<Long, LocationPicture> temp = (Map<Long, LocationPicture>)request.getSession().getAttribute(TEMP_ROOM_PICTURES);
   if (temp != null)
    picture = temp.get(id);
  }
  if (picture != null) {
   response.setContentType(picture.getContentType());
   response.setHeader( "Content-Disposition", "attachment; filename=\"" + picture.getFileName() + "\"" );
   OutputStream out = response.getOutputStream(); 
   out.write(picture.getDataFile());
   out.flush();
  } else {
   new ServletException("Room picture of the given id does not exist.");
  }
 }
 new ServletException("No room picture id provided.");
}
 

===========================================================================
example 7
**
 * Enables CORS (Cross-origin resource sharing) for the servlet;
 * 
 * @param response
 */
private void setCors(HttpServletResponse response) {
 response.setHeader("Access-Control-Allow-Origin", "*");
 response.setHeader("Access-Control-Max-Age", "3600");
 response.setHeader("Access-Control-Allow-Credentials", "true");
 response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization");
}
========================================================================
for more info