Wednesday, December 11, 2019

Kotlin SpringBoot 2 Spring Data JPA RESTful Web Service

Hi everyone.

I share example how to integration Kotlin - Spring Boot2 - Spring Data JPA-RESTful Web Service and CRUD example.


Technologies used:

1. Spring Boot 2.2.2.RELEASE
2. Gradle 2.x
3. Java 8
4. Eclipse: Oxygen.1.a Release (4.7.1a) or  IntelliJ Community
5. Spring Tools Suite (STS) 4
6. Postman
7. MySql

Code on GitHub:

https://github.com/HenryXiloj/Kotlin-SpringBoot2-RESTful


Steps:

Step 1:

Execute next script on MySql

CREATE TABLE users 
             ( 
                          id       INT(11) NOT NULL auto_increment, 
                          username VARCHAR(255) NOT NULL, 
                          password VARCHAR(255) NOT NULL, 
                          created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP() on 
             UPDATE CURRENT_TIMESTAMP(), 
                    PRIMARY KEY (id) 
             )

Step 2: Import project on Eclipse or IntelliJ


Eclipse:


IntelliJ:  File -> open --> choose folder backend




Righ click on project  Gradle -> Refresh Gracle project (Eclipse)



IntelliJ:

View -> Tool Windows -> Gradle -> Righ click on project -> Refresh Gradle dependencies



Step 3.

Run project from directory on console next command:

./gradlew bootRun



Run project from IntelliJ :

View -> Tool Windows -> Gradle -> Execute Gradle Task -> gradle bootRun




Step 4: Test.


GET  (by default)
GET all users

http://localhost:8080/ws/users





GET user by id.

http://localhost:8080/ws/users/1




POST user (save)

http://localhost:8080/ws/users





PUT user (update user)

http://localhost:8080/ws/users/1




DELETE user.

http://localhost:8080/ws/users/1



Great :).















References:








































Wednesday, June 12, 2019

Stop and Start JAR file in background CMD on Windows using bat file

I share example how to execute JAR file in background or if you want execute command line in background on Windows.

Steps:

1. Create file start.bat and add next code.

@echo OFF
cd C:\path_your_jar
start javaw -jar your_jar.jar


2. Create file stop.bat and add next code. for example if you application up in the port 9000 then you find the port and PID and kill.

@ECHO OFF                                                                           
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr "9000" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                 
:SkipLine                                                                           
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%

or

if you want to find jar and to change the next line.

@ECHO OFF                                                                           
FOR /F "tokens=1" %%T IN ('jps -m ^| find "jar" ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                 
:SkipLine                                                                           
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%

That is it.




Tuesday, May 28, 2019

Docker command line

Docker compose up

docker-compose -f my_docker-compose.yml up

Removing All Unused Objects

docker system prune

Stop a particular container

docker container stop <<container_id>>

Removing Docker Containers

docker container ls -a
docker container rm id_container id_container

Remove all stopped containers

docker container ls -a --filter status=exited --filter status=created
docker container prune

Removing Docker Images

docker image ls
docker image rm id_image id_image

Remove dangling and unused images

docker image prune

Create your first docker container from repository (Docker hub)

docker search ubuntu (images name)
docker pull name_image
docker images
docker run -i -t image_id /bin/bash
exit
docker ps -a
docker start container_id
docker attach container_id (optional)
docker commit container_id your_name_image (optional)

Build an image with the Dockerfile

(I use “.” because you need to have Dockerfile in current directory).
docker build -t name_image .

Launching a container

docker run -ti my_image /bin/bash

Rename docker image

docker tag <old_name> <new_name>
docker rmi <old_name>

Push image on dockerhub or docker registry

docker tag id_image id_docker/your_name_image:your_version
docker push id_docker/your_name_image:your_version

Add your username to the docker group

sudo usermod -aG docker YOUR_USER

To apply the new group membership

su - YOUR_USER

Check if you user is added.

id -nG

Login to docker registry

docker login your_ip:your_port
usermame: your_username_docker_registry
password: your_pass_docker_registry

Running image detach mode

docker run -d --rm -p 9000:8080 your_image:version

Copy file in container.

docker cp path_local_file your_container_name:/path_file_your_replace

MariaDB


docker network create some-network 
docker run --detach --network some-network --name some-mariadb --env MARIADB_USER=<<YOUR_USER>> --env MARIADB_PASSWORD=<<YOUR_PASSWORD>> --env MARIADB_ROOT_PASSWORD=<<YOUR_PASSWORD>>  mariadb:latest
docker run -it --network some-network --rm mariadb mysql -hsome-mariadb -u <<YOUR_USER>> -p




Thursday, May 23, 2019

Running Oracle database XE 11G using Docker

I share example how to install Oracle 11g on Docker.

Steps:

1. I get image from https://hub.docker.com/r/pengbai/docker-oracle-xe-11g-r2/

2. this commands is optional, if you want to use docker without sudo then add your current user on docker.

Add your username to the docker group

sudo usermod -aG docker YOUR_USER

To apply the new group membership

su - YOUR_USER

Check if you user is added.

id -nG



3.  Pull image

docker pull pengbai/docker-oracle-xe-11g-r2



Run with 8080 and 1521 ports opened:

docker run -d --shm-size=1g -p 1521:1521 -p 8080:8080 pengbai/docker-oracle-xe-11g-r2

Note: It's important to run Oracle XE with >1GB shared memory.


check container
docker ps


Wait one moment for start up oracle

Check  docker logs 

docker logs -f YOUR_ID_CONTAINER










4. Connect database with following setting:

Go to. http://localhost:8080/apex

Connect to Oracle Application Express web management console with following settings:
url: http://localhost:8080/apex
workspace: internal
user: admin
password: oracle














Change password and press return button












Login again. if login is correct display this.
















Try to connect Sql Developer or by console use this.
hostname: localhost
port: 1521
sid: xe
username: system
password: oracle

I recommend change the password of user system, with next commands.
alter user system identified by newpa$$word;
alter user system account unlock ;
And check status users:
select username, account_status, EXPIRY_DATE from dba_users




References:











Install SQLPlus client on Ubuntu 20.04 or CentOS 8

I share example how  to install SQLPlus client on Ubuntu or Centos

UBUNTU

Steps:

1.   you need to install alien package.

sudo apt-get install alien



2. You need to download Instant Client Downloads ,  you choose the current version on page (basic*.rpm,  sqlplus.rpm and devel*.rmp).  you run command with your version.





sudo alien -i oracle-instantclient*-basic*.rpm
sudo alien -i oracle-instantclient*-sqlplus*.rpm
sudo alien -i oracle-instantclient*-devel*.rpm





3. Create Oracle configuration file:

sudo sensible-editor /etc/ld.so.conf.d/oracle.conf






4. Add the next line,  depends if your machine 32 or 64 bit.

#for 32 bits
/usr/lib/oracle/<your version>/client/lib/ 

#for 64 bits
/usr/lib/oracle/<your version>/client64/lib/



 

5. Update the configuration

sudo ldconfig




6. Try to connect using:

# if you have 32 bits
sqlplus username/password@//dbhost:1521/SID

# if you have 64 bits
sqlplus64 username/password@//dbhost:1521/SID



CENTOS 8

Steps:

1. You need to download Instant Client Downloads ,  you choose the current version on page (basic*.rpm,  sqlplus.rpm and devel*.rmp).  you run command with your version.

sudo yum localinstall oracle-instantclient*-basic*.rpm
sudo yum localinstall oracle-instantclient*-sqlplus*.rpm
sudo yum localinstall oracle-instantclient*-devel*.rpm

2.  Run the next command

sudo yum install libnsl 

3. Create Oracle configuration file:

sudo nano /etc/ld.so.conf.d/oracle.conf

4. Add the next line,  depends if your machine 32 or 64 bit.

#for 32 bits
/usr/lib/oracle/32/client/lib/ 

#for 64 bits
/usr/lib/oracle/64/client64/lib/ 

5. Update the configuration

sudo ldconfig

6. Try to connect using:

# if you have 32 bits
sqlplus username/password@//dbhost:1521/SID

# if you have 64 bits
sqlplus64 username/password@//dbhost:1521/SID

That is it.




References: https://askubuntu.com/questions/159939/how-to-install-sqlplus/207145




How to Install Docker on Linux Ubuntu 18.04

I share example how to install docker on ubuntu using default repositories:

Steps:

1. Update Software repositories on terminal

sudo apt-get update

2. If you have old version uninstall.

sudo apt-get remove docker docker-engine docker.io

3. Install Docker.

sudo apt install docker.io

4. Start and Automate Docker.

sudo systemctl start docker

 sudo systemctl enable docker

5. Check version.

docker --version

That is it.







References: https://phoenixnap.com/kb/how-to-install-docker-on-ubuntu-18-04

Friday, May 3, 2019

Spring Boot profile with maven

I share example how to add profile in spring boot with maven.

For example :

1. I add 3 profiles on pom.xml by default profile prod is active.

-local
-dev
-prod




2. Also add on pom.xml on section <build></build>



3. Add 3 file on Spring boot project src/main/resources, each file is one profile.





4. Add into application.properties



5. if you want change profile create file application.yml and write:



In the image the local is the profile active if you change, change the position the profile. the concepts is similar a pile. if you don't want to create file application.yml then into the application.properties (spring.profiles.active=prod).

that is it.












Thursday, April 11, 2019

LocalStorage, SessionStorage or Native Session (Angular 7 or greater)

I share example how to integrate LocalStorage, SessionStorage or Native session storage, Native local storage.

LocalStorage: If you create  local storage value, the value exist on the browser.
SessionStorage: If you create session storage value, the value exist just current tab browser, if you open new tab the value doesn't exist.

Native session is similar concepts, but you don´t need to install anything. check in the end the blog. I recommed use native session or native local storage.

Use ngx-webstorage


1. Install on project angular.

npm install --save ngx-webstorage

2. Add app.module.ts

imports: [
NgxWebstorageModule.forRoot(),
]

3.  Import on your component

import {LocalStorageService, SessionStorageService} from 'ngx-webstorage';

4. Add on your constructor

constructor(private localSt:LocalStorageService,
private sessionSt:SessionStorageService) {}


5. Examples

/*Set*/

this.localSt.store("keyLocal", "value");
this.sessionSt.store("keySession", "2");

/*Get*/

this.localSt.retrieve("keyLocal");
this.sessionSt.retrieve("keySession");


/*remove*/
this.localSt.clear("keyLocal");
this.sessionSt.clear("keySession");


Native session or local storage javascript


*add*
sessionStorage.setItem("YOUR_KEY", YOUR_VALUE)

*Get*
sessionStorage.getItem("YOUR_KEY")

*Remove*
sessionStorage.removeItem("YOUR_KEY")


*add*
localStorage.setItem("YOUR_KEY", YOUR_VALUE)

*Get*
localStorage.getItem("YOUR_KEY")

*Remove*
localStorage.removeItem("YOUR_KEY")












Friday, March 22, 2019

XML Java Transformer outputs instead of <>

I share example how java Transformer outputs &lt; and &gt; instead of <> on XML.

/**
Example
*/

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class Test {

    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
            "&lt;company&gt;" +
            "&lt;staff id=\"1001\"&gt;" +
            "&lt;firstname&gt;henry&lt;/firstname&gt;" +
            "&lt;/staff&gt;" +
            "&lt;/company&gt;";



        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader(StringEscapeUtils.unescapeXml(xml.toString()))));

        System.out.println("final xml " + xmlTransformerInput(doc).toString());

    }


    public static String xmlTransformerInput(Document fDoc) {

        try {

            fDoc.setXmlStandalone(true);
            DOMSource docSource = new DOMSource(fDoc);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter sw = new StringWriter();
            transformer.transform(docSource, new StreamResult(sw));

            return sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}

Wednesday, March 13, 2019

Create new Database from command line Oracle 11g Express


I share example how to create new user from command line, you need SQL*Plus or JDeveloper and super user, I'm using Oracle 11g Express for that use the user SYSTEM.

Steps:

Step 1:

connect SYSTEM/password; 

Step 2:

CREATE USER your_schema IDENTIFIED BY your_password; 

Step 3:

ALTER USER your_schema QUOTA UNLIMITED ON SYSTEM; 

Step 4:

GRANT CREATE SESSION, CONNECT, RESOURCE, DBA TO your_schema; 

Step 5:

GRANT ALL PRIVILEGES TO your_schema; 

You try connect with the new user.

That's it. 

Creating REST APIs with OpenAPI, Spring Boot 3.3.3, Java 21, and Jakarta

 Introduction In today's software landscape, designing robust and scalable REST APIs is a crucial aspect of application development. Wit...