Selasa, 24 Oktober 2017

Convert Excel Exponential number in java

When we write the number in excel, it automatically converts in the exponential format and then try to get the values in Java using Apache POI API, it comes in the exponential format only. So to get the actual, we have to convert the cell into number format and get the value.

Let's take an example and see how to get the actual value that is in exponential format.

Suppose we have the below excel that need to parse

Actual values are:
  • 90153856767
  • 90176554678

Below is the program to parse the excel file and get the actual values. The section that is marked in red is used to convert the exponential number into actual values.

package com.test.ankur;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ParseExponential {

public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:/Ankur/ExponentialNumber.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
Iterator cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
switch (columnIndex) {
case 0:
nextCell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
Double doubleValue = nextCell.getNumericCellValue();
BigDecimal bd = new BigDecimal(doubleValue.toString());
long lonVal = bd.longValue();
String phoneNumber = Long.toString(lonVal).trim();

System.out.print("PhoneNumber " + phoneNumber);
break;
case 1:
nextCell.setCellType(XSSFCell.CELL_TYPE_STRING);
String firstName = nextCell.getStringCellValue();
System.out.print(" FirstName " + firstName);
break;
}

}
System.out.println();

}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


Output would be:

How to Read Excel Files in Java using Apache POI

In this blog, we will show you how to read excel file using Apache POI (Poor Obfuscation Implementation) library which is very popular amongst the available library.

Apache POI library

Apache POI is the pure Java API for reading and writing Excel files in both formats XLS (Excel 2003 and earlier) and XLSX (Excel 2007 and later).

To use Apache POI in Java project:

For non-Maven projects:

Download the latest library from here: Apache POI - Download Release Artifacts
Extract the zip file and add the appropriate JAR files to the  project’s classpath:

  • If reading and writing only Excel 2003 format, only the file poi-VERSION.jar is enough.
  • If reading and writing Excel 2007 format, we have to include the following files:
    • poi-ooxml-VERSION.jar
    • poi-ooxml-schemas-VERSION.jar
    • xmlbeans-VERSION.jar  
For Maven projects:

Add the following dependency to the project’s pom.xml file:

  • For Excel 2003 format only(XLS)
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>VERSION</version>
</dependency

  • For Excel 2007 format(XLSX)
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>VERSION</version>
</dependency


Note: VERSION need to replace with the POI version that you are using(for example: 3.9)

The Apache API Basics

There are two main prefixes which we will encounter while working with Apache POI APIs:

HSSF: denotes the API is for working with Excel 2003 and earlier.
XSSF: denotes the API is for working with Excel 2007 and later.

To get started the Apache POI API, we just need to understand and use the following 4 interfaces:
  • Workbook: high-level representation of an Excel workbook. Implementation classes are: 
    • HSSFWorkbook
    • XSSFWorkbook.
  • Sheet: high-level representation of an Excel worksheet. Implementation classes are:
    • HSSFSheet 
    • XSSFSheet
  • Row: high-level representation of a row in a spreadsheet. Implementation classes are:
    • HSSFRow 
    • XSSFRow
  • Cell: high-level representation of a cell in a row. Implementation classes are:
    • HSSFCell 
    • XSSFCell

    Let's see the example how to read excel(xlsx) file using the Apache POI library. Below is the sample of excel file that wants to read


    Download the sample file from here
    Download the project from here

    Below is the code to read the file:

    package com.test.ankur;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Iterator;

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    public class ReadExcel {
          
           public static void main(String[] args) throws IOException {
            String excelFilePath = "C:/Ankur/ReadFile.xlsx";
            FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            
            while (rowIterator.hasNext()) {
                Row nextRow = rowIterator.next();
                Iterator<Cell> cellIterator = nextRow.cellIterator();
                
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    
                    switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue());
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.print(cell.getBooleanCellValue());
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue());
                            break;
                    }
                    System.out.print(" | ");
                }
                System.out.println();
            }
                    
            inputStream.close();
        }
    }


    Run the program and see the output as below:




    Senin, 23 Oktober 2017

    Move Oracle ICS integration from one instance to another

    This is very important and useful blog for those who wants to move integration from one ICS instance to another ICS instance.

    Following are the typical use cases when it is required to move integration from one instance to another:
    1. Completed the development and move the changes to the Test instance 
    2. Got UAT approval and move the integration to the production instance.

    The purpose of this blog is to guide you, how to move Oracle Integration Cloud Service (ICS) integrations between different ICS environments.

    Oracle ICS provides export and import utilities to move the integration between different ICS environments.

    Usually, the Connection endpoints used by the integrations will be different in different environments. So we have to update the connection details manually.

    Below are the steps to move integration from one instance to another:
    1. Export an integration from one ICS instance
    2. Import the integration on second ICS instance
    3. Update Connection details
    4. Activate the integration on the second ICS Environment in which integration has been imported
    Export an integration from one ICS instance

    Please look the blog to see how to export the integration

    Import the integration on second ICS instance

    Please look the blog to see how to export the integration. 

    Since connection properties and security credentials are not part of the exported integration, the imported integration is typically not ready for activation. 

    An attempt to activate will error out and the error message indicates the connection(s) with missing information. So let's follow the next step to activate the integration successfully.

    Update Connection details

    The connections being used in the integration will be created automatically upon integration import. We just need to update the connection details. Just open the connection and edit the connection details. Once the connection details are updated test the connection and close.

    Activate the integration on the second ICS Environment in which integration has been imported

    Activate the integration on which integration has been imported. This time we will be able to successfully activate the integration.




    Uploading SSL certificate in Oracle Integration Cloud Serive

    Certificates are used to validate outbound SSL connections. If we make an SSL connection in which the root certificate does not exist in Oracle Integration Cloud Service, an exception is thrown. In such cases, we must upload the appropriate certificate.

    A certificate enables Oracle Integration Cloud Service to connect with external services. If the external endpoint requires a specific certificate, request the certificate and then upload it into Oracle Integration Cloud Service.

    Below is the process to upload the certificate in Oracle ICS
    • Login into ICS console
    • From home page, click the menu in the upper left corner
    • Click Settings - > Certificates

    All certificates currently uploaded to the trust store are displayed in the Certificates dialog. 
    • Click Upload button from the upper right corner
    • In the Upload Certificate dialog box, select the certificate type. Each certificate type enables Oracle Integration Cloud Service to connect with external services.
    • Trust Certificate: Use this option to upload a trusted certificate
      • Enter a unique alias for the certificate
      • Click Browse, then select the trust file (for example, .cer or .crt) to upload
    • Message Protection Certificate: Use this option to upload a keystore certificate with SAML token support. Create, read, update, and delete (CRUD) operations are supported on this type of certificate
      • Enter a unique alias for the certificate
      • Click Browse, then select the certificate file (.cer or .crt) to upload
    • Identity Certificate: Use this option to upload a certificate for two-way SSL communication.
      • Click Browse, then select the keystore file (.jks) to upload.
      • Enter the password of the keystore being imported.
      • Enter the comma-separated list of aliases from the keystore being imported.
      • Enter the comma-separated list of passwords corresponding to key aliases.
    Select Show Key Password(s) to ensure that the password we entered is correctly entering a list of keystore passwords.

    Jumat, 20 Oktober 2017

    Last Run Date and Time in Oracle ICS (Integration Cloud Service)

    Sometimes it is required to get last run date and time of the scheduled integration to avoid the duplicate processing of data.

    This is possible in the Scheduled Integration type. This can be achieved using creating parameters in Scheduled Integration.

    We can create and update scalar type parameters in scheduled integrations that determine how to batch and read data received from a source location. We then use these parameter values downstream in the integration. We create and assign values to these parameters in the Schedule Parameters page that is available in scheduled orchestrated integrations. We can also assign values to these parameters in assign actions. Up to five parameters are supported in the Schedule Parameters page.

    Let's see how to get last run date and time.
    • Login into ICS console
    • Click on Integrations tile from home page
    • Click on Create button from upper right side corner
    • Select the Orchestration pattern
    • For the What triggers this integration option, select Schedule and click Create button
    • Click on Scheduled icon, then select Edit
    • In the Parameter Name column, click the plus icon
    • Enter a name(LastRun), an optional description, and a default value in the Value column
    • Click Close to save the changes and exit the page. A red warning icon is displayed on the Schedule icon. If we place the cursor over the icon, a message indicates that one or more parameters are missing a value
    • From the Actions section, drag an Assign activity into the integration, enter a name, and then click OK.
    • In the Name column, click the plus icon, then select the parameter from the dropdown list that we created in the Schedule Parameters page
    • Click the Edit icon to invoke the Expression Builder and drag the startTime into the Expression box, then close button
    • Drop Logger action between Scheduled and Assign Activity. Give Name and optionally Description, then Create
    • Select Always Radio button, click on Edit Expression icon, and add the below expression:
    concat('Previous date and time ' ,$LastRun)

    • To complete the integration, add any Invoke activity as the mandatory step.
    Let's Activate the integration and Submit the integration. Open the Monitoring Dashboard and see the instance Activity Stream


    Note: First time the last run date will come null. 

    Let's submit the integration again and see what previous date & time comes


    See the previous date & time is 2017-10-20T09:46:56.238+00:00. This is the time of the previous run itself.



    Senin, 09 Oktober 2017

    Exception handling(Global Fault Handler) in Oracle ICS

    Oracle Integration Cloud Service provides "Global Fault Handler" to catch faults in orchestrated integration and perform actions.

    We can add global fault handling to orchestrated integrations. This functionality enables us to direct business faults back to the caller or apply business logic before sending faults to the error handling framework. We can add fault handling to any integration type (for example, asynchronous, synchronous, or scheduled fire-and-forget (no response expected)).

    So let's see how to enable "Global Fault Handler" in the orchestrated integration.

    I'm using you already have developed one orchestrated integration, if not, please follow the blog

    • Click on Orchestration and select Global Fault
    • Global Fault handler canvas will get open. We can apply any business rule, invoke external service, send email notification etc.
    • Let's add notification activity to send an email once an exception occurs in the integration.
    • Drop the Notification activity from the Actions
    • Complete the Notification activity. If you don't know how to configure it, please follow the blog
    • Save and close the "Global Fault Handler"
    As soon as an exception will occur in the integration, Global Fault Handler will get execute and exit the integration. 



    Minggu, 08 Oktober 2017

    Java Regular Expression

    Some useful java function that may help me in the java project
    • Convert List of integer into any literal separated string
    • public static String joinList(List<Integer> list, String literal) {
      return list.toString().replaceAll(",", literal).replaceAll("[\\[.\\].\\s+]", "");
      }
    • Generate random number of 10 digits
    • public static String randomNumber(){
      Long randomNumber = (long) Math.floor(Math.random() * 9000000000L) + 1000000000L;
      String number = Long.toString(randomNumber);
      return number;
      }
    • Get Current date into the specified format
    • public static String currentDate(String dateFormat){
      SimpleDateFormat s = new SimpleDateFormat(dateFormat);
      Calendar cal = Calendar.getInstance();
      return s.format(new Date(cal.getTimeInMillis()));
      }
    • Check given input string is numeric or not
    • public static boolean isNumeric(String inputString) {
      return inputString.matches("[-+]?\\d*\\.?\\d+");
      }
    • Check given input string is alphabetic or not
    • public static boolean isAlphabetic(String inputString) {
      return inputString.matches("[a-zA-Z]+");
      }
    • Regular expression to validate email address
    • public static boolean isEmailFormat(String inputString) {
      return inputString.matches("^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$");
      }
    • Regular expression to validate alphanumeric string
    • public static boolean isAlphaNumeric(String inputString) {
      return inputString.matches("^[a-zA-Z0-9\\s]*$");
      }