How to add bootstrap to angular project

To add and use twitter bootstrap framework into your angular projet follow the next instructions.

Create a new angular project

ng create my-project

 

Install bootstrap dependencies into angular project

npm install bootstrap --save
npm install jquery --save
npm install popper --save #optional

The –save parameter will automatically add the new dependencies into package.json file.

The popper dependency is optional, it helps positioning tool-tips and popovers.

Import css and js files into angular.json file

Inside the file angular.json, locate the styles and scripts lines and make sure you have the following lines :

"styles": [
    "node_modules/bootstrap/dist/css/bootstrap.min.css",
    "src/styles.css"
    ],
"scripts": [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js"
]

Now you can use bootstrap in your angular project.

 

How to add public ssh Key to Remote Server

Adding a public ssh key to a remote server will allow you to access that server without being prompted for the password everytime time.

Here are the steps you should follow.

1- Generate the keys

ssh-keygen -t rsa

2- Push the key to the remote server

cat ~/.ssh/id_rsa.pub | ssh user@hostname 'cat >> .ssh/authorized_keys'

Rename local and remote branch in git

Sometimes you need to change a branch name that you already pushed to the remote server. To rename a remote branch follow these steps.

1- checkout your branch

git checkout old-branch-name

2- rename the branch locally

git branch -m new-branch-name

3- Delete the old-branch-name branch and poush the new-branch-name branch

git push origin :old-branch-name new-branch-name

4- Change the upsdtream branch to new-branch-name

git push origin -u new-branch-name

 

How to create a SOAP client using java, maven and eclipse

 

In this tutorial we will see how to create a java soap client using maven and eclipse. You can adapt with your configuration if you are using other tools.

For the example, we will use the AWSECommerceService SOAP service from Amazon. you may need additional keys generated from Amazon’s website to make the example work. The WSDL is available at :

http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl

1- Create a new project

Create a new maven project using the maven-archetype-quickstart.

eclipse-maven-new-project

2 – Download the WSDL

Download and put the the wsdl file in src/main/resources . You may have to create the folder if it does not exist.

project structure

3- Add maven dependencies and plugins

Open the pom.xml file and add the maven-compiler-plugin and the cxf-codegen-plugin as follows:

<properties>
 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 <cxf.version>3.3.0</cxf.version>
</properties>
<build>
 <plugins>
  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.2</version>
   <configuration>
    <source>1.8</source>
    <target>1.8</target>
   </configuration>
  </plugin>
  <plugin>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-codegen-plugin</artifactId>
   <version>${cxf.version}</version>
   <executions>
    <execution>
     <id>generate-sources</id>
     <phase>generate-sources</phase>
     <configuration>
      <sourceRoot>${basedir}/src/generated</sourceRoot>
      <wsdlOptions>
       <wsdlOption>
        <wsdl>${basedir}/src/main/resources/AWSECommerceService.wsdl
        </wsdl>
       </wsdlOption>
      </wsdlOptions>
     </configuration>
     <goals>
      <goal>wsdl2java</goal>
     </goals>
    </execution>
   </executions>
  </plugin>
 </plugins>
 <finalName>soapclient</finalName>
</build>

In the dependencies section add the following dependencies :

<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-rt-frontend-jaxws</artifactId>
 <version>${cxf.version}</version>
</dependency>
<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-rt-transports-http</artifactId>
 <version>${cxf.version}</version>
</dependency>

4- Generate the classes using CXF codegen plugin

To generate the classes using eclipse Do a right click on the project then click on  Run as > Maven generate resources. This will be generate the required classes under src/generated. You may have to add the new generated folder into eclipse build path, but it’s not necessary to execute the maven build.

5- Consume the SOAP service

Final step is to use the generated classes in order to consume the service like in the following example :

package com.tutoref.soapclient;

import java.net.MalformedURLException;
import java.net.URL;

import com.amazon.webservices.awsecommerceservice._2011_08_01.AWSECommerceService;
import com.amazon.webservices.awsecommerceservice._2011_08_01.AWSECommerceServicePortType;
import com.amazon.webservices.awsecommerceservice._2011_08_01.ItemSearch;
import com.amazon.webservices.awsecommerceservice._2011_08_01.ItemSearchResponse;

public class App{
 
 public static void main( String[] args ){
  try {
   // instantiate the client !! 
   // this is only an example, to make the code work you may need to generate keys
   // Documentation is available on Amazon's website
   URL url = new URL("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl");
   AWSECommerceService service = new AWSECommerceService(url);
   AWSECommerceServicePortType port = service.getAWSECommerceServicePortCA();

   // prepare the search criteria
   ItemSearch itemSearch = new ItemSearch();
   itemSearch.setAssociateTag("eBook");

   // invoke the search action
   ItemSearchResponse itemSearchResponse = port.itemSearch(itemSearch);

   // .. Do whatever what you do with the response ...

  } catch (MalformedURLException e) {
   e.printStackTrace();
  }
 }
    
}

 

How to get the root exception of any exception

Sometimes, the root exception causing your code to fail is hidden behind an other exception or a set of nested exceptions.

Nested Exceptions

Nested Exceptions

 

The following code (function) searches for the root exception of any exception and returns it :

public static Throwable getRootException(Throwable exception){
 Throwable rootException=exception;
 while(rootException.getCause()!=null){
  rootException = rootException.getCause();
 }
 return rootException;
}

Example of usage :

catch(MyException e){
  System.out.println(getRootException(e).getLocalizedMessage());
}

 

 

How to create automated backups for your web server?

If you have a web server running one or many websites or applications and hosting a database server it may be a good idea to have an automated backup process.

Most (or all) Web Hosting providers will charge you for such service, but the good news is that you can create your own automated backup process. Do not wait until you wake up a morning and discover that your homepage has changed into this :

You have boon hacked

The following tutorial has been written and tested with the following configuration:

  • Operating System : Ubuntu Linux 14.04.4 with root access
  • Web Server : Apache2
  • Database Server : Mysql 5.5.49
  • Scripting tool : Unix Shell

You can adapt the script or paths to meet your configuration’s needs. I will not cover any  external file transfer process, the files will be stored on the same server, but it’s not a big deal to automate the transfer of files to an other server.

Before we start, I will summarize the backup strategy .

  1. Create folder structures that will contain the backup files;
  2. The backup program consists of a shell script (.sh) that runs everyday at a fixed hour using a CRON task. The logic of that script will be the following :
    • Rename the existing (yesterday’s files) backup files by prefixing them with the the current date;
    • Delete backups older than X days (in our case it will be 5 days);
    • Take backupa of databases and compress the files;
    • Take backup of the Apache www folder and compress it.
  3. And finally, create the CRON task and set the appropriate permissions.

 

Folder Structure

We will create two folders:

  • /bkp : will be used to store the backup files ;
  • /opt/backup/ : will contain the backup script (backup.sh) .

To create the two folder execute the following commands :

mkdir /bkp
mkdir /opt/backup

 

Backup Script

We start by creating the script and give it the right permissions. On the command line execute the following commands:

# create the script file
touch /opt/backup/backup.sh

# make the file executable
chmod +x /opt/backup/backup.sh

Then we will start editing the script using VI editor (or your preferred text editor):

vi /opt/backup/backup.sh

Since it’s a shell script, it must start with the following line :

#!/bin/sh

The following sections will cover content that will be added to the backup.sh shell script.

Rename the old backup files

The next steps of the script will consist of creating new backup files. We don’t want our backup files to be replaced by the new ones. We will prefix the last created backup files with the current day’s date.

Add these lines to the script:

# rename existing backup files

## Switch to the backups folder
cd /bkp

## get the current date
current_date=$(date +"%Y-%m-%d")
shopt -s extglob

## Rename the files not starting with a date
for file in !([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*.gz); do
  mv "$file" "${current_date}_$file"
done

 

Delete backups older than X days

Your server space may be limited. We have to make a decision about the number of days we want to keep. For this tutorial we will choose 5 days.

# delete backups older than 5 days under /bkp folder
find /bkp -type f -name '*' -mtime +5 -exec rm {} \;

 

Take database backups

We will use the mysqldump command to create backups of the databases. Lets say we have 3 mysql databases : db1, db2 and db3. The backups will consist of what we call mysql dumps .

In addition, we will compress these mysql dumps (or backup files) in order to save space on the server.

Add the following lines to the script (replace database names, usernames and passwords with you own values):

# take compressed backups of databases
mysqldump -u root yourPassword db1| gzip -9 > /bkp/db1.sql.gz
mysqldump -u root yourPassword db2| gzip -9 > /bkp/db2.sql.gz
mysqldump -u root yourPassword db3| gzip -9 > /bkp/db3.sql.gz

 

Take folders backup

Now we will add the commands to backup our website’s files and folders. For Apache web server, website files or commonly stored in /var/www, but it’s not a rule, configuration my change. For this tutorial we suppose that our files are located in /var/www folder .

To take a backup, we will simply use the tar command to create a compressed archive for the whole www folder.

Add the following lines to the script (Replace the paths with you own values) :

# take compressed backup of important folders
tar -zcf /bkp/www.tar.gz /var/www/

Note: you can also use the same command to take a backup of any important folders located on your server.

Save the backup.sh file. Here is the final structure of the script :

#!/bin/sh

# rename existing backup files

# Switch to the backups folder
cd /bkp

# get the current date
current_date=$(date +"%Y-%m-%d")
shopt -s extglob

# Rename the files not starting with a date
for file in !([0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]*.gz); do
  mv "$file" "${current_date}_$file"
done

# delete backups older than 5 days under /bkp folder
find /bkp -type f -name '*' -mtime +5 -exec rm {} \;

# take compressed backups of databases
mysqldump -u root yourPassword db1| gzip -9 > /bkp/db1.sql.gz
mysqldump -u root yourPassword db2| gzip -9 > /bkp/db2.sql.gz
mysqldump -u root yourPassword db3| gzip -9 > /bkp/db3.sql.gz

# take compressed backup of important folders
tar -zcf /bkp/www.tar.gz /var/www/

 

Create the CRON task

Now that our script is ready, you can test the process by executing it and make sure it has the behavior you wanted. When satisfied with the results, you can automate the process using the CRON tasks.

For this tutotrial, we want our script be executed every day at 00:01 AM. On a shell command line execute the following command to start editing the crontab :

sudo crontab -e

Then add the following line and save the file :

01 0 * * * /opt/backup/backup.sh

At this point everything must be OK, you have to wait until 00:01 AM to see the results.

Restoring the files

If you need to use the saved backup files simply do the following:

MySQL dumps

  1. Uncompress the files usinng gunzip command ( ex: gunzip db1.gz)
  2. This will produce an SQL file.
  3. Import the SQL file using any importing tool (phpmyadmin, MySQL Workbench, MySQL Administrator, etc)
  4. Sometimes you will experience some problems with file encoding, in most cases you have to remove or change some parameters.

tar archives

  1. Just uncompress the tar archive and copy the files in their appropriate location which is /var/ww for this tutorial. (Example : tar xzvf www.tar.gz)

 

 

How to create directories in Java

In java you can create a directory (or directories) using the standard IO package or using the java NIO package.

Create directories using the java IO package

// create a single directory
new File("c:\\myDir").mkdir();

// create a directory and all its sub-directories
new File("c:\\myRootDir\\Subdir1\\SubDir2").mkdirs();

 

Create directories using the java NIO package

This will work only on Java 7 and above.

Path path = Paths.get("C:\\Mydir");
Files.createDirectories(path);

You have to import the classes java.nio.file.Paths and java.nio.file.Files .

 

 

 

How to access to class private members in Java

It is possible to use to access class private instance variables and methods using Reflexion.

Access to private instance variables

MyClass myClass = new MyClass();
Field field = MyClass.class.getDeclaredField("myField");
field.setAccessible(true);
Object value = field.get(myClass);
System.out.println(value);

 

Access to private methods

MyClass myClass = new MyClass();
Method method = myClass.getClass().getDeclaredMethod("myMethodName");
method.setAccessible(true);
Object o = method.invoke(object);

 

How to connect to a database using JDBC

This example shows how to connect to a database using JDBC. (In this example we will connect to Oracle database) .

You will need to add the odbc{x}.jar library to your classpath, downloadable from Oracle’s website.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcExample {

 public static void main(String[] args) {
  
  try{
  	// register the driver
  	Class.forName("oracle.jdbc.driver.OracleDriver");
  	// create the connexion
  	Connection connection
            =DriverManager.getConnection(
               "jdbc:oracle:thin:@localhost:1521:xe", "system", "pwd"
                );
  } catch (ClassNotFoundException e) {
    // the driver was not found
    e.printStackTrace();
  } catch (SQLException e) {
    // Error when connecting to database
    e.printStackTrace();
  }
 }

}

 

How to disable SSL certificat validation in Java

This fix will disable the SSL certificate validation. It is not recommanded in a production environment. A recommanded approach is to install the needed certificates on the JVM.

Create the following class:

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;


public class SSLFix {
 
 public static void execute(){
  TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return null;
          }
          @Override
          public void checkClientTrusted(X509Certificate[] arg0, String arg1)
           throws CertificateException {}
 
          @Override
          public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {}

          }
     };

  SSLContext sc=null;
  try {
   sc = SSLContext.getInstance("SSL");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  try {
   sc.init(null, trustAllCerts, new java.security.SecureRandom());
  } catch (KeyManagementException e) {
   e.printStackTrace();
  }
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

  // Create all-trusting host name verifier
  HostnameVerifier validHosts = new HostnameVerifier() {
  @Override
  public boolean verify(String arg0, SSLSession arg1) {
   return true;
  }
  };
  // All hosts will be valid
  HttpsURLConnection.setDefaultHostnameVerifier(validHosts);
 }

}

 

Now whenever you want to create a SSL connection, add the following line just before the connection:

SSLFix.execute();