Monday, September 14, 2020

Connect Oracle Database From Shell Script

There are two ways to connect Oracle from shell script.

1. You need to install SQL Plus Client on your server

2. You'll have install ORACLE on your server.

I share example for both.

Create file Oracle-ShellScript.sh

sudo nano Oracle-ShellScript.sh




Example with $ORACLE_HOME, add next lines into file. Check your path ORACLE_HOME

#!/bin/sh

#parameters DB
DATABASE_USER=$1
DATABASE_PASS=$2
IP=$3
SID=$4


DATE=`date +"%d%m%y"`
u="$USER"
echo "User name $u"

cd /home/$u

LOCATION=$PWD
echo "path ${LOCATION}"


ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe
export ORACLE_HOME
echo $ORACLE_HOME

dbConexion() {
$ORACLE_HOME/bin/sqlplus -s <<EOF> ${LOCATION}/log${DATE}.out
$DATABASE_USER/$DATABASE_PASS@//$IP:1521/$SID
select sysdate from dual;

EOF

}

dbValidate() {
p=`cat ${LOCATION}/log${DATE}.out | grep SYSDATE`
if [ -n "$p" ]
then
echo "Ok conexion"
rm ${LOCATION}/log${DATE}.out
else
echo "Bad conexion."
exit
fi
}

echo "Start process"
dbConexion
echo "Check conexion on DB"
dbValidate
echo "End process"



Example with SQL Plus client add next lines into file:

#!/bin/sh

#parameters DB
DATABASE_USER=$1
DATABASE_PASS=$2
IP=$3
SID=$4


DATE=`date +"%d%m%y"`
u="$USER"
echo "User name $u"

cd /home/$u

LOCATION=$PWD
echo "path ${LOCATION}"

dbConexion() {
sqlplus64 -s <<EOF> ${LOCATION}/log${DATE}.out
$DATABASE_USER/$DATABASE_PASS@//$IP:1521/$SID
select sysdate from dual;

EOF

}

dbValidate() {
p=`cat ${LOCATION}/log${DATE}.out | grep SYSDATE`
if [ -n "$p" ]
then
echo "Ok conexion"
rm ${LOCATION}/log${DATE}.out
else
echo "Bad conexion."
exit
fi
}

echo "Start process"
dbConexion
echo "Check conexion on DB"
dbValidate
echo "End process"

Test: Send the next argument to shell script user_db, password_db, ip and sid

sh Oracle-ShellScript.sh YOUR_USER_DB YOUR_PASSWORD_DB YOUR_IP YOUR_SID












Friday, September 11, 2020

How to Install Apache2 + PHP 7.2 + Joomla on Ubuntu 20.04

In this post, you will learn how to install Apache2 + PHP 7.2 + Joomla 3.9.21, for write this post i get two references, you checks links in the end post. let's start. 

1. Update and upgrade system packages

 sudo apt-get update && sudo apt-get upgrade

2. Install apache 

sudo apt install apache2

The comands below, you need to stop, start, status, reload and enable apache2 service.

sudo systemctl start apache2.service

sudo systemctl enable apache2.service


3. Install PHP 7.2 is not be avaible in ubuntu default repositories, for that run next commands.

sudo apt-get install software-properties-common

sudo add-apt-repository ppa:ondrej/php

sudo apt-get update && sudo apt-get upgrade

sudo apt install libapache2-mod-php7.2 openssl php-imagick php7.2-common php7.2-curl php7.2-gd php7.2-imap php7.2-intl php7.2-json php7.2-ldap php7.2-mbstring php7.2-mysql php7.2-pgsql php-smbclient php-ssh2 php7.2-sqlite3 php7.2-xml php7.2-zip

sudo systemctl start apache2.service

sudo systemctl enable apache2.service


4. Check version PHP 

php -v

Go to browser type this (localhost or your_ip)

http://localhost/
















5. Install MariaDB

sudo apt install mariadb-server

In this command, Set the password for the root and you choose the other options that it will ask you according to what you need.

sudo mysql_secure_installation

6. Create Database for joomla

sudo mysql -u root -p


CREATE DATABASE YOUR_DATABASE_NAME;

GRANT ALL ON YOUR_DATABASE_NAME.* TO 'YOUR_USER'@'localhost' IDENTIFIED BY 'YOUR_PASSWORD';

FLUSH PRIVILEGES;

EXIT;

7.  Download Joomla 3-9-21

sudo wget https://downloads.joomla.org/cms/joomla3/3-9-21/Joomla_3-9-21-Stable-Full_Package.zip

sudo mkdir /var/www/html/joomla

sudo unzip Joomla_3-9-21-Stable-Full_Package.zip -d /var/www/html/joomla

Change the permissions

sudo chown -R www-data:www-data /var/www/html/joomla

sudo chmod -R 755 /var/www/html/joomla

8. Restar apache2

sudo systemctl restart apache2

9. Configure apache for joomla

sudo nano /etc/apache2/sites-available/joomla.conf


Copy the lines into file and then crtl + o and ctrl + x.

<VirtualHost *:80>
     ServerAdmin admin@example.com
     DocumentRoot /var/www/html/joomla/
     ServerName example.com
     ServerAlias www.example.com

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /var/www/html/joomla/>
            Options FollowSymlinks
            AllowOverride All
            Require all granted
     </Directory>
</VirtualHost>

10. Enable Virtual host

sudo a2ensite joomla.conf

sudo a2enmod rewrite

sudo systemctl restart apache2


11. Great the joomla stand up on Ubuntu 20, check

http://YOUR_IP/joomla

First configuration general add your Site Name, Description, email, username i recomend wrote the same and the last add password



















Second Database configuration, choose MySQLI, Hostname: localhost, username: YOUR_USER, password: YOUR_PASSWORD, Database Name: YOUR_DATABASE_NAME 



















And in the end, only check your configuration, and then click 'install' 

































12. If the installation is success then you will get notification.
















13. Click Remove installation folder, is mandatory. 
























14. Click on button 'Administrator'















Open the login, write your username and your passoword.













Great, you install joomla on ubuntu 20.
























References: 
https://www.tecmint.com/install-joomla-on-ubuntu/
https://websiteforstudents.com/apache2-with-php-7-1-support-on-ubuntu-18-04-lts-beta-server/
                    




Monday, September 7, 2020

Basic Login ReactJs - OAuth2 - Axios

React - OAuth2 - Axios

I share basic example how to integrate React, OAuth2 and Axios, in this example i just share code how to implement on  front end of course you need to add css  if you want customize , if you want to know how to implement on backend, you can get example on my github, i used Kotlin or Java for backend. check in the end the post.

Create proyect react:

npx create-react-app login-react-oauth2-axios







Install Axios:

cd login-react-oauth2-axios

npm i axios




Create next folder and files, below of struct and check image

- components
        -login
             Files:
                    Login.js
        -menu
             Files:
                    Menu.js
-services 
        -auth
             Files:
                AuthService.js
        -util
             Files:
                Util.js

















I used class but you prefered, you can use Hooks .

Util.js: Is most import because when you sent request POST, GET, DELETE or something like that add on header your token, for open your web service on backend.

Add next code. (change the url)

For example in my code, my context of my backend is services, i created two const because the first const restApi i used for call all my web services, when i call web service automatically inject header authorization with interceptors, and second const authUrl i used for get my first token from backend.


import axios from "axios";

const restApi = axios.create({
    baseURL: 'http://localhost:9000/services'
})

const authUrl  = 'http://localhost:9000/services/oauth/token';

restApi.interceptors.request.use(function(config){
    console.log("request send");
    let token = sessionStorage.getItem('token');
    config.headers.Authorization = `Bearer ${token}`;
    return config;
})
export {restApiauthUrl}


AuthService.js: I save first token, you have to add YOUR_CLIENT and YOUR SECRET of your backend on btoa.

import { Component } from "react";
import axios from "axios";
import { authUrl } from "../util/Util";

class AuthService extends Component {
  login(json) {
    const headers = {
      Authorization: "Basic " + btoa("YOUR_CLIENT:YOUR_SECRET"),
      "Content-type": "application/x-www-form-urlencoded",
    };

    return axios({
      method: "POST",
      url: authUrl,
      params: {
        username: json.username,
        password: json.password,
        grant_type: "password",
      },
      headers: headers,
    });
  }

  user(accessToken) {
    const payload = this.getDataToken(accessToken);
    return payload.username;
  }

  saveToken(accessToken) {
    sessionStorage.setItem("token"accessToken);
  }

  getDataToken(accessToken) {
    if (accessToken) {
      console.log(JSON.parse(atob(accessToken.split(".")[1])));
      return JSON.parse(atob(accessToken.split(".")[1]));
    }
    return null;
  }

  isAuthenticated() {
    let token = sessionStorage.getItem("token");
    const payload = this.getDataToken(token);
    if (payload != null && payload.username && payload.username.length > 0) {
      return true;
    }
    return false;
  }
}

const authService = new AuthService();

export default authService;



Menu.js: If you login with credetencial correct and display your username.

import React, { Component } from "react";
import authService from "../../services/auth/AuthService";

class Menu extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
    };
  }

  componentWillMount() {
    let token = sessionStorage.getItem("token");
    let username = authService.user(token);
    this.setState({
      username: username,
    });
  }
  render() {
    return <div>Welcome {this.state.username}</div>;
  }
}

export default Menu;


Login.js: add next code on login.

import React, { Component } from "react";

import Menu from "../menu/Menu";

import authService from "../../services/auth/AuthService";

class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: "",
      authenticated: false,
    };
  }

  changeHandler = (event=> {
    this.setState({ [event.target.name]: event.target.value });
  };

  submitHandler = (e=> {
    e.preventDefault();

    authService
      .login(this.state)
      .then((response=> {
        authService.saveToken(response.data.access_token);
        this.setState({
          authenticated: true,
        });
      })
      .catch((error=> {
        console.log(error);
      });
  };

  render() {
    if (this.state.authenticated) {
      return (
        <div>
          <Menu></Menu>
        </div>
      );
    } else {
      const { usernamepassword } = this.state;
      return (
        <div>
          <form onSubmit={this.submitHandler}>
            <div>
              <input
                type="text"
                name="username"
                value={username}
                onChange={this.changeHandler}
              ></input>
            </div>
            <div>
              <input
                type="password"
                name="password"
                value={password}
                onChange={this.changeHandler}
              ></input>
            </div>
            <button type="submit">Login</button>
          </form>
        </div>
      );
    }
  }
}

export default Login;


And the last

App.js:  Add the next code.

import React, { Component } from "react";
import Login from "./components/login/Login";
import Menu from "./components/menu/Menu";
import authService from "./services/auth/AuthService";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      authenticated: false,
    };
  }

  componentWillMount() {
    let isAuth = authService.isAuthenticated();
    console.log(isAuth);

    this.setState({
      authenticated: isAuth,
    });
  }

  render() {
    if (this.state.authenticated) {
      return (
        <div>
          <Menu></Menu>
        </div>
      );
    } else {
      return (
        <div>
          <Login></Login>
        </div>
      );
    }
  }
}

export default App;


Test:

npm start








Code on GitHub:















Multiple Data Sources in Spring Boot 3 with Java 21

  In this blog post, we'll explore the configuration and setup for a Spring Boot 3 application with Java 21 that uses multiple data sour...