Linux

How to connect to a Cisco VPN in Ubuntu 18.04 LTS

Posted on

Here’s the simple steps for you to connect to a Cisco VPN in Ubuntu 18.04 LTS.

Cisco, an American company is the leading provider and manufacturer of enterprise network devices, telecommunication hardware, networking security and networking software.
According to computer profile as of April 2018, Cisco holds a 73.9% market which makes it the undisputed leader in its industry. Without further ado here
are the steps.

1. Install vpnc and network-manager-vpnc-gnome


sudo apt install vpnc network-manager-vpnc-gnome


2. Enter your password



3. Confirm installation



4. After successfully installing the required software it is time to configure it.



5. Add a new VPN connection



6. From the VPN type options, select Cisco Compatible VPN (vpnc)



7. Enter your VPN credentials and press Add



Linux

Bash string manipulation in program arguments

Posted on

In this code snippet, I would like to run an application with a URL payload based on date and time. This
code will be executed in a specific schedule everyday and I would like to dynamically inject the date and time in
the program argument when the program executes.


./json2csv rules.json "ncp" "http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=$(date --date='yesterday' +\%Y-\%m-\%d)+00:00:00&endtime=$(date --date='yesterday' +\%Y-\%m-\%d)+23:59:00&container=false" > $(echo "nercc_mv_$(date --date='yesterday' +\%Y-\%m-\%d).csv")

The way to do this is using the Bash String Manipulation

Inside a string, the bash will evaluate statement inside “$()” in this example:

$(date --date='yesterday' +\%Y-\%m-\%d)


"http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=$(date --date='yesterday' +\%Y-\%m-\%d)+00:00:00&endtime=$(date --date='yesterday' +\%Y-\%m-\%d)+23:59:00&container=false"

The resulting string after bash string manipulation will be like this

http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=2018-09-27+00:00:00&endtime=2018-09-27+23:59:00&container=false
Code Snippet

Standardizing SQLite in Spring framework Project

Posted on

My approach in standardizing SQLite in a Spring framework project

In a software development world were rapid project delivery is needed. The only way for us, developer having a sense of sanity is to build standardize code for future development. In doing so, it shortens the development time but having tested and functioning code base.

ISqliteObjectAssembler.java

This interface will serve as my IOC to have my own implementation of parsing from resultset to my specific Object

/**
 * Created by mrprintedwall on 11/02/17.
 */

public interface ISqliteObjectAssembler
{
	T assemble(ResultSet resultSet) throws SQLException;
}
ISqliteRepository.java
/**
 * Created by mrprintedwall on 11/02/17.
 */

public interface ISqliteRepository
{
	//region CONNECTION

	Connection getConnection() throws SQLException;

	//endregion

	//region ROW METHODS

	/**
	 * INSERT INTO SQLITE AND RETURNS THE GENERATED PRIMARY ID
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int insert(String sql, Map parameters) throws SQLException;

	/**
	 * UPDATE ROWS IN SQLITE AND RETURN AFFECTED NUMBER OF ROWS
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int update(String sql, Map parameters) throws SQLException;

	/**
	 * DELETE ROWS IN SQLITE AND RETURN DELETED NUMBER OF ROWS
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int delete(String sql, Map parameters) throws SQLException;

	/**
	 * GET SINGLE ITEM FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param sqliteObjectAssembler
	 * @param 
	 * @return
	 * @throws SQLException
	 */
	 T getSingle(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;

	/**
	 * GET LIST OF ITEMS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param sqliteObjectAssembler
	 * @param 
	 * @return
	 * @throws SQLException
	 */
	 List getList(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;
	
	/**
	 * GET SINGLE ITEM USING MAP OF PARAMETERS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param parameters
	 * @param sqliteObjectAssembler
	 * @return
	 * @throws SQLException
	 */
	 T getSingle(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;

	/**
	 * GET LIST OF ITEMS USING MAP OF PARAMETERS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param parameters
	 * @param sqliteObjectAssembler
	 * @return
	 * @throws SQLException
	 */
	 List getList(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;
	//endregion

	//region TABLE METHODS

	void createTable(String sql) throws SQLException;
	void alterTable(String sql) throws SQLException;
	void dropTable(String sql) throws SQLException;

	//endregion

}
SqliteDbRepository.java
/**
 * Created by mrprintedwall on 11/02/17.
 */

@Service
public class SqliteDbRepository implements ISqliteRepository
{
	private static final Logger logger = LoggerFactory.getLogger(SqliteDbRepository.class);

	private AppConfig appConfig;

	@Autowired
	public SqliteDbRepository(AppConfig appConfig)
	{
		this.appConfig = appConfig;
	}

	@Override
	public Connection getConnection() throws SQLException
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			Connection connection = DriverManager.getConnection(appConfig.getSqliteConnectionString());
			PreparedStatement preparedStatement = connection.prepareStatement("PRAGMA foreign_keys=ON");
			preparedStatement.execute();
			return connection;
		}
		catch (ClassNotFoundException classNotFoundException)
		{
			logger.error(classNotFoundException.getMessage());
		}
		return null;
	}

	@Override
	public int insert(String sql, Map parameters) throws SQLException
	{
		try(Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			preparedStatement.executeUpdate();
			return getLastInsertedId(connection);
		}
	}

	@Override
	public int update(String sql, Map parameters) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			return preparedStatement.executeUpdate();
		}
	}

	@Override
	public int delete(String sql, Map parameters) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			return preparedStatement.executeUpdate();
		}
	}

	@Override
	public T getSingle(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				return (T) sqliteObjectAssembler.assemble(resultSet);
			}
		}
		return null;
	}

	@Override
	public List getList(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				List results = new ArrayList<>();
				while (resultSet.next())
				{
					try
					{
						results.add((T) sqliteObjectAssembler.assemble(resultSet));
					}
					catch (Exception exception)
					{
						logger.error(exception.getMessage());
					}
				}
				return results;
			}
		}
		return new ArrayList<>();
	}

	@Override
	public  T getSingle(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler)
			throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				return (T) sqliteObjectAssembler.assemble(resultSet);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public  List getList(String sql, Map parameters,
	                           ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				List results = new ArrayList<>();
				while (resultSet.next())
				{
					try
					{
						results.add((T) sqliteObjectAssembler.assemble(resultSet));
					}
					catch (Exception exception)
					{
						logger.error(exception.getMessage());
					}
				}
				return results;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void createTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	/*

	ALTER TABLE EXAMPLE:

	ALTER TABLE table RENAME TO temp_table;

	 */

	@Override
	public void alterTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	@Override
	public void dropTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	/**
	 * GENERIC TABLE CREATE/ALTER/DROP SQL EXECUTOR/HANDLER
	 *
	 * @param sql
	 * @throws SQLException
	 */
	private void tableSqlExecutor(String sql) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			Statement statement = connection.createStatement();
			statement.execute(sql);
		}
	}

	/**
	 * THIS INJECTS THE HASH MAP INTO THE PREPARED STATEMENT
	 *
	 * @param parameters
	 * @param preparedStatement
	 * @throws SQLException
	 */
	private void injectParameterToPreparedStatement(Map parameters, PreparedStatement preparedStatement) throws SQLException
	{
		if (parameters != null && preparedStatement != null)
		{
			for (Map.Entry entry : parameters.entrySet())
			{
				preparedStatement.setObject((int) entry.getKey(), entry.getValue());
			}
		}
	}

	/**
	 * A LITTLE BIT OF RAINBOW, AND SUGAR STRING SANITATION
	 *
	 * @param sql
	 * @return
	 */
	private String sanitizeSqlString(String sql)
	{
		if (sql != null)
		{
			return sql.trim();
		}
		return "";
	}

	/**
	 * THIS WILL RETRIEVE THE LAST GENERATED ID IN SQLITE
	 *
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	private int getLastInsertedId(Connection connection) throws SQLException
	{
		if (connection != null)
		{
			Statement statement = connection.createStatement();
			ResultSet resultSet = statement.executeQuery("SELECT last_insert_rowid()");
			if (resultSet != null)
			{
				return resultSet.getInt(1);
			}
		}
		return 0;
	}

}
Code Snippet

Golang mgo sort number inside a string

Posted on
// Get List
func (z *DocumentTagService) GetDocumentTags() ([]models.DocumentTag, error) {
	z.DatabaseService.Connect()
	var o []models.DocumentTag
	err := (*z.DatabaseService.Db).C(z.Collection).Find(bson.M{}).Sort("-$natural", "-documentReference").All(&o)
	return o, err
}

Result

[
    {
        "idDocumentTag": "5b1390f29ebea41854dcc0dc",
        "documenReference": "MCTU/2018/16",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390f09ebea41854dcc0db",
        "documenReference": "MCTU/2018/15",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390d19ebea41854dcc0da",
        "documenReference": "MCTU/2018/14",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390d09ebea41854dcc0d9",
        "documenReference": "MCTU/2018/13",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390cf9ebea41854dcc0d8",
        "documenReference": "MCTU/2018/12",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390cd9ebea41854dcc0d7",
        "documenReference": "MCTU/2018/11",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b29ebea41854dcc0d6",
        "documenReference": "MCTU/2018/10",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b19ebea41854dcc0d5",
        "documenReference": "MCTU/2018/9",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b09ebea41854dcc0d4",
        "documenReference": "MCTU/2018/8",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390ae9ebea41854dcc0d3",
        "documenReference": "MCTU/2018/7",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900c9ebea41854dcc0d2",
        "documenReference": "MCTU/2018/6",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900c9ebea41854dcc0d1",
        "documenReference": "MCTU/2018/5",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900b9ebea41854dcc0d0",
        "documenReference": "MCTU/2018/4",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900a9ebea41854dcc0cf",
        "documenReference": "MCTU/2018/3",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b138b449ebea41854dcc0ce",
        "documenReference": "MCTU/2018/2",
        "company": "MCTU"
    }
]

General

Replacing My Macbook Pro 2013 trackpad

Posted on

Background

I would like to share my experience in replacing my broken MacBook Pro late 2013 trackpad. One day, when I started using my MacBook pro I realize that the trackpad doesn’t work and my keyboard acting strange when I am moving my fingers across the trackpad. I tried doing the PRAM and SMC reset but to no avail. Then I when online and did my research. My research concluded in 3 possible scenarios. My keyboard still works fine so the keyboard is out of the equation.

1. Trackpad cable might be damaged
2. Trackpad got damaged
3. Mainboard issue (MAJOR)

I initially purchased the trackpad cable and installed it. Installing it is pretty easy but that didn’t resolve the problem. I then proceed with replacing the trackpad and my MacBook is now back in working condition. Replacing a trackpad requires some effort especially in removing the adhesive that binds the battery into the laptop casing.

Laptop parts from

http://www.laptopspecialist.com.my

Linux

A simple firewall-cmd cheatsheet

Posted on

Get Default Zone
Get Active Zones
List Zone Services
Add a permanent port into a zone
Remove a permanent port from a zone
Firewall-cmd reload

I tested this using CentOS 7 with firewalld service running.

Get Default Zone

To know the default zone, use this command

firewall-cmd --get-default-zone

Get Active Zones

firewall-cmd --get-active-zones

List Zone Services

To check services, ports and settings on a specific zone, use this command

firewall-cmd --zone=public --list-all

Add a permanent port into a zone

Adding a permanent TCP/UDP port in a specific zone. Example: opening MongoDB port

firewall-cmd --permanent --zone=public --add-port=27017/tcp
firewall-cmd --permanent --zone=public --add-port=27017/udp

Remove a permanent port from a zone

firewall-cmd --permanent --zone=public --remove-port=27017/tcp
firewall-cmd --permanent --zone=public --remove-port=27017/udp

Firewall-cmd reload

To reflect your firewall changes. You have to reload the firewall using the following command

firewall-cmd --reload
General

Use Cloudflare as Dynamic DNS

Posted on

I would like to share how I use Cloudflare as Dynamic DNS. I am using Dynamic DNS service from No-IP for three years until a colleague of mine mentioned about Cloudflare’s really fast global DNS. Initially, I thought that Cloudflare was just a CDN and an Internet company that protects websites from Distributed Denial-of-Service (DDoS) attack, upon further investigation I found out that Cloudflare also provides a DNS service with a REST-API for you to update your DNS records.

I migrated most of my domain to CloudFlare DNS and then uses their API to update my domain’s DNS records once my ISP changed the IP address.

To know my router’s IP address I use the service of ipinfo.io. You may use other provider or other technique to know your router’s public IP address.

Source code available at https://github.com/mrprintedwall/cloudflare-as-dynamic-dns

$nano updateip.sh
#!/bin/bash

IP=$(curl -s "https://ipinfo.io/ip")
echo "THIS IS IP $IP"
touch dynip.txt
OLD_IP=$(cat dynip.txt)
echo "OLD IP: $OLD_IP"

curlUpdate(){
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$1/dns_records/$2" \
-H "X-Auth-Email: [email protected]" -H "X-Auth-Key: YOUR_CLOUDFLARE_API_KEY" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$4\",\"content\":\"$3\",\"proxied\":$5}"
}

if [ "$IP" != "$OLD_IP" ]; then
    echo "Changing IP"
    echo $IP > dynip.txt
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "johnpili.com" "true"
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.johnpili.com" "true"
    curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "ssh.johnpili.com" "false"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "domain1.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.domain1.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "domain2.com" "true"
    #curlUpdate "ZONE_ID" "ID_OF_DNS_RECORD" "$IP" "www.domain2.com" "true"
fi

You can then setup your CRON to run the script on a specified interval or schedule.

Disclaimer

Cloudflare’s DNS REST API is owned by Cloudflare and subject to Cloudflare’s terms and conditions.

Tutorials

Configure Tomcat To Run on Linux Startup

Posted on
Auto-start Apache Tomcat on Linux

If you are using the core version of Apache Tomcat and would like auto-start it on Linux here are the simple steps. I assume that you already have a running Apache Tomcat and know how to navigate to the terminal and have necessary system permission to proceed with this tutorial. Depending on the distribution that you are using you may need to find a specific location for the configuration or init.d folder.

1. Start by creating startup script into folder /etc/init.d/ or /etc/rc.d depending on what Linux distribution you are using.

$sudo vi tomcat

2. Enter the following scripts inside tomcat file

#!/bin/bash
# 
# tomcat
#
# chkconfig: 35
# description: Start up the Tomcat servlet engine.
# processname: tomcat

# /etc/init.d/tomcat


RETVAL=$?
CATALINA_HOME="/opt/apache-tomcat-8.5.30"

case "$1" in
 start)
        if [ -f $CATALINA_HOME/bin/startup.sh ];
          then
    echo $"Starting Tomcat"
            $CATALINA_HOME/bin/startup.sh
        fi
;;
 stop)
        if [ -f $CATALINA_HOME/bin/shutdown.sh ];
          then
    echo $"Stopping Tomcat"
            $CATALINA_HOME/bin/shutdown.sh
        fi
;;
 *)
 echo $"Usage: $0 {start|stop}"
exit 1
;;
esac

exit $RETVAL

NOTE
You will need to set the CATALINA_HOME and point it to the location where you deploy your Apache Tomcat.

Example:

CATALINA_HOME="/opt/apache-tomcat-8.5.30"

3. In this tutorial, we will create a symbolic link in Runlevel 3

$cd /etc/init.d/rc5.d/
$sudo ln -s ../init.d/tomcat S01tomcat
$sudo ln -s ../init.d/tomcat K01tomcat

In case you’re wondering, what S or K means: S is to start the application and K stands for to kill or shutdown the application. The number denotes the order. There are a lot of articles already available on the Internet about Linux Runlevel. You can check out Linux Runlevels Explained and Understanding init scripts

Distribution Notes

SLES 11 SP4
In SLES11, once you created the files tomcat1 and tomcat2 inside init.d folder you don’t need to create the symbolic link manually. Instead, execute the following command

$chkconfig --set tomcat1 on
$chkconfig --set tomcat2 on

To verify type the following code

$chkconfig

The output should look like this.

runlevel services via chkconfig