Java Enum example

The enum type in java is a special data type that enables a variable to be set to one of a predefined set of values.

An enum can be in its own file (example: Directions.java) or included in an other class.

Example of a simple enum

enum Directions {
   NORTH, SOUTH, EAST, WEST 
}

A more elaborated example

enum Directions{
     NORTH("N"),
     SOUTH("S"),
     EAST("E"),
     WEST("W");
     // the ; after the fields is needed
     
     private final String symbol;
     
     Directions(String symbol){
      this.symbol=symbol;
     }
     
     public String symbol(){
      return this.symbol;
     }
}

 The use of an enum

Directions direction = Directions.EAST;

//...

switch(direction){
  case EAST:
   System.out.println("EAST");
   break;
  case SOUTH:
   System.out.println("SOUTH");
   break;
  case NORTH:
   System.out.println("NORTH");
   break;
  case WEST:
   System.out.println("WEST");
   break;
   
   default:
}

The above code will print the following:

EAST

 

log4j.properties example

The following example will show how redirect log outpout to Console, a file and both.

This configuration should be writen in log4j.properties file.

 

write the log in the console

# Logger options
log4j.rootLogger=INFO, stdout

# Write the log to the standard output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 

write the log in a file

# Logger options
log4j.rootLogger=INFO, file
log4j.appender.file=org.apache.log4j.RollingFileAppender

# Write the log to a file
log4j.appender.file.File=/var/logs/log.log
log4j.appender.file.MaxFileSize=50MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 

write the log in both console and a file

# Logger options
log4j.rootLogger=INFO, file, stdout
log4j.appender.file=org.apache.log4j.RollingFileAppender

# Write the log to the standard output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Write the log to a file
log4j.appender.file.File=/var/logs/log.log
log4j.appender.file.MaxFileSize=50MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

 

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();

 

How to read and write Properties file in java 8

In Java, properties files are used to store data and configuration. This tutorial will show you how to store and read properties files in Java 8.

Using InputStream

Write to properties file

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class PropertiesFileSample {
 
 final private static String PROPERTIES_FILE_PATH="config.properties";

 public static void main(String[] args) {
  
  Properties properties = new Properties();
  
  // using java 8 try-with-resources structure,
  // so the output stream will be closed automatically
  try(OutputStream outputStream = new FileOutputStream(PROPERTIES_FILE_PATH)){
   
   // set some values
   properties.setProperty("username", "sampleusername");
   properties.setProperty("url", "tutoref.com");
   
   // store the values
   properties.store(outputStream, null);
   
  } catch (IOException e) {
   e.printStackTrace();
  } 
 }

}

The result will look like this :

#Sat Jul 08 23:55:53 EDT 2017
url=tutoref.com
username=sampleusername

 

Read from a properties file

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesFileSample {
 
 final private static String PROPERTIES_FILE_PATH="config.properties";

 public static void main(String[] args) {
 
  Properties properties = new Properties();
 
  // using java 8 try-with-resources structure
  // so the input stream will be closed automatically
  try(InputStream inputStream = new FileInputStream(PROPERTIES_FILE_PATH)){
 
  // read a value
  String url = properties.getProperty("url");
 
  // display the value
  System.out.println(url);
 
 } catch (IOException e) {
  e.printStackTrace();
 } 
 }

}

 

Load properties from classpath

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesFileSample {
 
 final private static String PROPERTIES_FILE_PATH="config.properties";

 public static void main(String[] args) {
  
  Properties properties = new Properties();
  
  // using java 8 try-with-resources structure
  // so the input stream will be closed automatically
  try(
    InputStream inputStream=
    PropertiesFileSample.class.getResourceAsStream(PROPERTIES_FILE_PATH)
    ){
   
   // load the properties
   properties.load(inputStream);
   
   // read a value
   String url = properties.getProperty("url");
   
   // display the value
   System.out.println(url);
   
  } catch (IOException e) {
   e.printStackTrace();
  } 
 }

}

 

If you want to load the properties file from a non-static method, you should use the following:

InputStream is = getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE_PATH);

 

 

How to connect to an HTTPS page in java using HttpsURLConnection

The folllowing code will connect to a https page (using SSL), get the response code and content.

 

If you have timeout or networking issues, check if you don’t have to modify the firewall configuration or install a SSL certificate on your JVM.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class SampleHttpsClient {
 
 public static void main(String[] args) {
  
  String host = "https://www.google.com";
  try {
   
   URL url = new URL(host);
   HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
   
   // get response code, 200 = Success
   int responseCode = httpsURLConnection.getResponseCode();
   System.out.println(responseCode);
   
   // if response == 200, display the content
   if(responseCode==200){
    System.out.println(httpsURLConnection.getContent().toString());
    BufferedReader br = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
    String line=null;
    while((line = br.readLine())!= null){
     System.out.println(line);
    }
   }
   
  } catch (IOException e) {
   e.printStackTrace();
  } 
  
 }
 
}

 

Java httpURLConnection example

This code will connect to a given URL and gets the content if the response is a success.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
  
  private static final String USER_AGENT = "Mozilla/5.0";
  
  public static void main(String[] args) {
    
    String host = "http://tutoref.com";
    try {
      
      URL url = new URL(host);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      
      // specify request header
      httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
      
      // get response code, 200 = Success
      int responseCode = httpURLConnection.getResponseCode();
      System.out.println(responseCode);
      
      // if response == 200, display the content
      if(responseCode==200){
        System.out.println(httpURLConnection.getContent().toString());
        BufferedReader br = 
           new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream())
           );
        String line=null;
        while((line = br.readLine())!= null){
          System.out.println(line);
        }
      }
      
      
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}

 

 

How to send url to Intent in Android

This code will open the link in your Android browser. We suppose you have an Activity and you did the correct imports :

 

String url = "http://www.tutoref.com";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);

 

The necessary imports are:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

 

PHP MySQL example

This example shows how to connect to a MySQL database and browse data using PHP:

<?php
$host= "localhost";
$username = "user";
$password = "pwd";
$dbname = "dbName";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM users";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

 

What is new in Java 8

Java 8 is a major release of the java programming language. It introduces new features and enhancements. The most significant ones are the following.

Lambda expressions

New Date and Time API

Method references

Default methods

Repeating annotations

Type annotations

Stream API

Optional

Narshon

new tools and utilities