Import Data from RDBMS/Oracle into Hive using Spark/Scala

In this blog, I would explain how to import data from RDBMS into hive using Spark/Scala.

package com
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.spark.sql.hive
import org.apache.spark.io.SnappyCompressionCodec
import java.util.Properties
import java.util.Properties
import java.sql.DriverManager
import java.sql.Connection
object importExadata {
def main(args: Array[String]){
val sc=new SparkContext(args(0),”importExadata”)
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
hiveContext.sql(“SET hive.exec.dynamic.partition = true”)
hiveContext.sql(“SET hive.exec.dynamic.partition.mode = nonstrict “)
hiveContext.sql(“SET hive.exec.max.dynamic.partitions.pernode = 400”)
hiveContext.sql(“set hive.execution.engine=spark”)
val url=”jdbc:oracle:thin:@<hostname>:<port>:<sid>”
val prop = new java.util.Properties
prop.setProperty(“user”,”<user_name>”)
prop.setProperty(“password”,”<password>”)
prop.setProperty(“driver”,”oracle.jdbc.OracleDriver”)

//Spark 1.6
val df1 = hiveContext.read.format(“jdbc”).option(“url”, “jdbc:oracle:<hostname>:<port>:<sid>”).option(“dbtable”, “<dbname>.tablename>”).option(“user”, “<user_name>”).option(“password”, “<password>”).option(“dbtable”, s”(select cast(col_name> as string) from <dbname>.<tablename>)”).option(“lowerBound”,”1″).option(“upperBound”,”10000″).option(“numPartitions”,”1″).option(“fetchSize”, “1000”).load()

//Spark 2.0 (dbname and tablename in rdbms database)

val df2=hiveContext.read.jdbc(url, “<dbname>.<table_name>”, prop)

(dbname and tablename in hive database)
df2.write.option(“mode”,”append”).format(“orc”).insertInto(“<dbname>.<table_name>”)
}
}

Convert Sequence File to Parquet using Spark/Scala

In this blog, I will detail the code for converting sequence file to parquet using spark/scala. Suppose your existing hive table is in sequential format and partitioned by year and month. Read the database name,table name, partition dates, output path from the file. These are separted by ~ in the input file. Once the data is converted to parquet format, create an external table having similar structure as that of sequential table but in parquet format and pointing to the output path. The below code is 10 times faster than Spark SQL.

package com

import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.spark.sql.hive
import org.apache.spark.io.SnappyCompressionCodec
import scala.io.Source
object sequencetoorc {
def main(args: Array[String])
{
val sc=new SparkContext(args(0),”SeqtoOrc”)
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
val lines = Source.fromFile(args(1)).getLines.toList
for(tables <- lines)
{
var dbname=tables.mkString.split(“~”)(0)
var tab=tables.mkString.split(“~”)(1)
var newyear=tables.mkString.split(“~”)(2)
var year=tables.mkString.split(“~”)(3)
var outputpath=tables.mkString.split(“~”)(4)
val rdd1=hiveContext.sql(s”select * from $dbname.$tab where year between ‘$newyear’ and ‘$year'”)
rdd1.registerTempTable(“orctable”)
val results=hiveContext.sql(“select * from orctable”)
results.write.partitionBy(“year”,”month”).format(“parquet”).option(“compression”, “snappy”).mode(“append”).save(s”$outputpath”)
}
}
}

Convert ORC to Sequence File using Spark/Scala

In my previous blog, https://wordpress.com/post/aikanshbigdatablogs.wordpress.com/450 I explained how to convert Sequence File to ORC. In this, I will detail the code on how to do the reverse (convert orc to sequential format). In below code, I read the orc file and convert it into sequential format with fields separated by “|”. After successful conversion, create a hive table in sequential format with fields separated by “|” pointing to output path.

package com

import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.hive.ql.io.orc.OrcInputFormat
import org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat
import scala.io.Source
import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
object orctoseq1{
def main(args: Array[String])
{
val sc=new SparkContext(args(0),”orctoseq”)

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val fs = org.apache.hadoop.fs.FileSystem.get(hadoopConf)

val exists = fs.exists(new org.apache.hadoop.fs.Path(s”$inputpath/”))
if (exists){
val orcfile = s(“$inputpath/*”,classOf[OrcInputFormat], classOf[OrcOutputFormat])
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
val df = sqlContext.read.format(“orc”).load(orcfile)
val rddout = df.rdd.repartition(10).map(f => (new BytesWritable(), new Text(f.toSeq.mkString(“|”)))).saveAsSequenceFile(s”$inputpath”+s”_temp/”,
Some(classOf[BZip2Codec]))
val tempexists = fs.exists(new org.apache.hadoop.fs.Path(s”$inputpath”+s”_temp/_SUCCESS”))
if (tempexists){
fs.delete(new org.apache.hadoop.fs.Path(s”$inputpath/”),true)
fs.rename(new org.apache.hadoop.fs.Path(s”$inputpath”+s”_temp/”), new org.apache.hadoop.fs.Path(s”$inputpath/”))
fs.delete(new org.apache.hadoop.fs.Path(s”$inputpath/_SUCCESS”))
}
}
}
}

Export data to Oracle Exadata (RDBMS) from Hive using Spark/Scala

Suppose, you  have employee table in hive having name,age and gender columns. You need to export it to Oracle Exadata using Spark Scala.

Create the similar structure table in exadata (eg. employee having same column names and corresponding datatypes in Exadata) and follow the below code.

 

package com
import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.spark.sql.hive
import org.apache.spark.io.SnappyCompressionCodec
import java.util.Properties
import java.util.Properties
import java.sql.DriverManager
import java.sql.Connection
object exportToExadata {
def main(args: Array[String])
{

//provide ip of host, port number and its sid in url below

val url=”jdbc:oracle:thin:@ip_of_host:port:sid”
val prop = new java.util.Properties

//provide username and password
prop.setProperty(“user”,”username”)
prop.setProperty(“password”,”password”)
prop.setProperty(“driver”,”oracle.jdbc.OracleDriver”)
val sc=new SparkContext(args(0),”exadata”)
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
hiveContext.sql(“SET hive.exec.dynamic.partition = true”)
hiveContext.sql(“SET hive.exec.dynamic.partition.mode = nonstrict “)
hiveContext.sql(“SET hive.exec.max.dynamic.partitions.pernode = 400”)
hiveContext.sql(“set hive.execution.engine=spark”)

val rdd1=hiveContext.sql(s”select name,age,gender from employee”)
if(rdd1.count()>1)
{
rdd1.write.mode(“append”).jdbc(url,”employee”,prop)
}
}
sc.stop()
}

Convert Sequence File to ORC using Spark/Scala

In this blog, I will detail the code for converting sequence file to orc using spark/scala. Suppose your existing hive table is in sequential format and partitioned by year and month. Read the database name,table name, partition dates, output path from the file. These are separted by ~ in the input file. Once the data is converted to ORC format, create an external table having similar structure as that of sequential table but in ORC format and pointing to the output path. The below code is 10 times faster than Spark SQL. I

package com

import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.spark.sql.hive
import org.apache.spark.io.SnappyCompressionCodec
import scala.io.Source
object sequencetoorc {
def main(args: Array[String])
{
val sc=new SparkContext(args(0),”SeqtoOrc”)
val hiveContext = new org.apache.spark.sql.hive.HiveContext(sc)
val lines = Source.fromFile(args(1)).getLines.toList
for(tables <- lines)
{
var dbname=tables.mkString.split(“~”)(0)
var tab=tables.mkString.split(“~”)(1)
var newyear=tables.mkString.split(“~”)(2)
var year=tables.mkString.split(“~”)(3)
var outputpath=tables.mkString.split(“~”)(4)
val rdd1=hiveContext.sql(s”select * from $dbname.$tab where year between ‘$newyear’ and ‘$year'”)
rdd1.registerTempTable(“orctable”)
val results=hiveContext.sql(“select * from orctable”)
results.write.partitionBy(“year”,”month”).format(“orc”).option(“compression”, “snappy”).mode(“append”).save(s”$outputpath”)
}
}
}

Merge Sequence File using Spark-Scala

package com
import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
import org.apache.spark.SparkContext
import org.apache.spark._
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import org.apache.hadoop.io.compress.BZip2Codec
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.BytesWritable
import scala.io.Source
import java.util.Calendar
import java.text.SimpleDateFormat
import java.util.Date
object mergemwch {
def main(args: Array[String])
{
val sc=new SparkContext(args(0),”merge”)

val hadoopConf = new org.apache.hadoop.conf.Configuration()
val fs = org.apache.hadoop.fs.FileSystem.get(hadoopConf)

//put your hdfs input path
var inputpath=”hdfs://<path_goes_here>”

val exists = fs.exists(new org.apache.hadoop.fs.Path(s”$inputpath”))
if (exists){
val rddinput = sc.sequenceFile(s”$inputpath/*”,classOf[BytesWritable], classOf[Text],15)
val summary = fs.getContentSummary(new org.apache.hadoop.fs.Path(s”$inputpath”))
val length = summary.getLength
val numFiles = length/(1024*1024*100) //making every file around 100 MB
val rddout = rddinput.repartition(numFiles.toInt).saveAsSequenceFile(s”$inputpath”+s”_temp/”,
Some(classOf[BZip2Codec]))
val tempexists = fs.exists(new org.apache.hadoop.fs.Path(s”$inputpath”+s”_temp/_SUCCESS”))
if (tempexists){
fs.delete(new org.apache.hadoop.fs.Path(s”$inputpath/”),true)
fs.rename(new org.apache.hadoop.fs.Path(s”$inputpath”+s”_temp/”), new org.apache.hadoop.fs.Path(s”$inputpath”))
fs.delete(new org.apache.hadoop.fs.Path(s”$inputpath/_SUCCESS”))
}
}
}
}

Read and Write Parquet file using Spark/Scala

package com

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object Parquet extends App{
System.setProperty(“hadoop.home.dir”, “c://winutil//”)
val conf=new SparkConf().setMaster(“local[2]”).setAppName(“auction”)
val sc = new SparkContext(conf)
val data = Array(1, 2, 3, 4, 5) // create Array of Integers
val dataRDD = sc.parallelize(data) // create an RDD

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._;
val dataDF = dataRDD.toDF() // convert RDD to DataFrame
dataDF.write.parquet(“data.parquet”) // write to parquet

val newDataDF = sqlContext.read.parquet(“data.parquet”) // read back parquet to DF // show contents
println(newDataDF)
}

Convert CSV to Parquet using MapReduce

In this blog, I will share the code to convert CSV file to Parquet using Map Reduce.

  1. ConvertUtils.java
  2. Utils.java
  3. CsvParquetWriter.java
  4. CsvWriteSupport.java

Please use following csv and schema file as an example:

name.csv:

aikansh|31
harit|27
firoz|30
gaurav|22

name.schema:

message m {optional binary name;optional int64 age;}

ConvertUtils.java

package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;

import parquet.Log;
import parquet.Preconditions;
import parquet.column.page.PageReadStore;
import parquet.example.data.Group;
import parquet.example.data.simple.convert.GroupRecordConverter;
import parquet.hadoop.ParquetFileReader;
import parquet.hadoop.ParquetReader;
import parquet.hadoop.example.GroupReadSupport;
import parquet.hadoop.metadata.ParquetMetadata;
import parquet.io.ColumnIOFactory;
import parquet.io.MessageColumnIO;
import parquet.io.RecordReader;
import parquet.schema.MessageType;
import parquet.schema.MessageTypeParser;

public class ConvertUtils {

private static final Log LOG = Log.getLog(ConvertUtils.class);

public static final String CSV_DELIMITER= “|”;

private static String readFile(String path) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(path));
StringBuilder stringBuilder = new StringBuilder();

try {
String line = null;
String ls = System.getProperty(“line.separator”);

while ((line = reader.readLine()) != null ) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
} finally {
Utils.closeQuietly(reader);
}

return stringBuilder.toString();
}

public static String getSchema(File csvFile) throws IOException {
String fileName = csvFile.getName().substring(
0, csvFile.getName().length() – “.csv”.length()) + “.schema”;
File schemaFile = new File(csvFile.getParentFile(), fileName);
return readFile(schemaFile.getAbsolutePath());
}

public static void convertCsvToParquet(File csvFile, File outputParquetFile) throws IOException {
convertCsvToParquet(csvFile, outputParquetFile, false);
}

public static void convertCsvToParquet(File csvFile, File outputParquetFile, boolean enableDictionary) throws IOException {
LOG.info(“Converting ” + csvFile.getName() + ” to ” + outputParquetFile.getName());
String rawSchema = getSchema(csvFile);
if(outputParquetFile.exists()) {
throw new IOException(“Output file ” + outputParquetFile.getAbsolutePath() +
” already exists”);
}

Path path = new Path(outputParquetFile.toURI());

MessageType schema = MessageTypeParser.parseMessageType(rawSchema);
CsvParquetWriter writer = new CsvParquetWriter(path, schema, enableDictionary);

BufferedReader br = new BufferedReader(new FileReader(csvFile));
String line;
int lineNumber = 0;
try {
while ((line = br.readLine()) != null) {
String[] fields = line.split(Pattern.quote(CSV_DELIMITER));
writer.write(Arrays.asList(fields));
++lineNumber;
}

writer.close();
} finally {
LOG.info(“Number of lines: ” + lineNumber);
Utils.closeQuietly(br);
}
}

public static void convertParquetToCSV(File parquetFile, File csvOutputFile) throws IOException {
Preconditions.checkArgument(parquetFile.getName().endsWith(“.parquet”),
“parquet file should have .parquet extension”);
Preconditions.checkArgument(csvOutputFile.getName().endsWith(“.csv”),
“csv file should have .csv extension”);
Preconditions.checkArgument(!csvOutputFile.exists(),
“Output file ” + csvOutputFile.getAbsolutePath() + ” already exists”);

LOG.info(“Converting ” + parquetFile.getName() + ” to ” + csvOutputFile.getName());
Path parquetFilePath = new Path(parquetFile.toURI());

Configuration configuration = new Configuration(true);

GroupReadSupport readSupport = new GroupReadSupport();
ParquetMetadata readFooter = ParquetFileReader.readFooter(configuration, parquetFilePath);
MessageType schema = readFooter.getFileMetaData().getSchema();

readSupport.init(configuration, null, schema);
BufferedWriter w = new BufferedWriter(new FileWriter(csvOutputFile));
ParquetReader<Group> reader = new ParquetReader<Group>(parquetFilePath, readSupport);
try{
Group g = null;
while( (g = reader.read())!= null) {
writeGroup(w, g, schema);
}
reader.close();
}
finally {
Utils.closeQuietly(w);
}
}

private static void writeGroup(BufferedWriter w, Group g, MessageType schema)
throws IOException{
for (int j = 0; j < schema.getFieldCount(); j++) {
if (j > 0) {
w.write(CSV_DELIMITER);
}
String valueToString = g.getValueToString(j, 0);
w.write(valueToString);
}
w.write(‘\n’);
}

@Deprecated
public static void convertParquetToCSVEx(File parquetFile, File csvOutputFile) throws IOException {
Preconditions.checkArgument(parquetFile.getName().endsWith(“.parquet”),
“parquet file should have .parquet extension”);
Preconditions.checkArgument(csvOutputFile.getName().endsWith(“.csv”),
“csv file should have .csv extension”);
Preconditions.checkArgument(!csvOutputFile.exists(),
“Output file ” + csvOutputFile.getAbsolutePath() + ” already exists”);

LOG.info(“Converting ” + parquetFile.getName() + ” to ” + csvOutputFile.getName());

Path parquetFilePath = new Path(parquetFile.toURI());

Configuration configuration = new Configuration(true);

// TODO Following can be changed by using ParquetReader instead of ParquetFileReader
ParquetMetadata readFooter = ParquetFileReader.readFooter(configuration, parquetFilePath);
MessageType schema = readFooter.getFileMetaData().getSchema();
ParquetFileReader parquetFileReader = new ParquetFileReader(
configuration, parquetFilePath, readFooter.getBlocks(), schema.getColumns());
BufferedWriter w = new BufferedWriter(new FileWriter(csvOutputFile));
PageReadStore pages = null;
try {
while (null != (pages = parquetFileReader.readNextRowGroup())) {
final long rows = pages.getRowCount();
LOG.info(“Number of rows: ” + rows);

final MessageColumnIO columnIO = new ColumnIOFactory().getColumnIO(schema);
final RecordReader<Group> recordReader = columnIO.getRecordReader(pages, new GroupRecordConverter(schema));
for (int i = 0; i < rows; i++) {
final Group g = recordReader.read();
writeGroup(w, g, schema);
}
}
} finally {
Utils.closeQuietly(parquetFileReader);
Utils.closeQuietly(w);
}
}

public static void main(String[] args) {
try {
convertCsvToParquet(new File(args[0]),new File(args[1]));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

Utils.java

package com;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.io.file.tfile.Utils.Version;

import parquet.Log;

public class Utils {

private static final Log LOG = Log.getLog(Utils.class);

public static void closeQuietly(Closeable res) {
try {
if(res != null) {
res.close();
}
} catch (IOException ioe) {
LOG.warn(“Exception closing reader ” + res + “: ” + ioe.getMessage());
}
}

public static void writePerfResult(String module, long millis) throws IOException{
PrintWriter writer = null;
try {
File outputFile = new File(“target/test/perftime.” + module + “.txt”);
outputFile.delete();
writer = new PrintWriter(outputFile);
writer.write(String.valueOf(millis));
} finally {
closeQuietly(writer);
}
}

public static long readPerfResult(String version, String module) throws IOException {
BufferedReader reader = null;
try {
File inFile = new File(“../” + version + “/target/test/perftime.” + module + “.txt”);
reader = new BufferedReader(new FileReader(inFile));
return Long.parseLong(reader.readLine());
} finally {
closeQuietly(reader);
}
}

public static File createTestFile(long largerThanMB) throws IOException {
File outputFile = new File(“target/test/csv/perftest.csv”);
if(outputFile.exists()) {
return outputFile;
}
File toCopy = new File(“../parquet-testdata/tpch/customer.csv”);
FileUtils.copyFile(new File(“../parquet-testdata/tpch/customer.schema”), new File(“target/test/csv/perftest.schema”));

OutputStream output = null;
InputStream input = null;

try {
output = new BufferedOutputStream(new FileOutputStream(outputFile, true));
input = new BufferedInputStream(new FileInputStream(toCopy));
input.mark(Integer.MAX_VALUE);
while(outputFile.length() <= largerThanMB * 1024 * 1024) {
//appendFile(output, toCopy);
IOUtils.copy(input, output);
input.reset();
}
} finally {
closeQuietly(input);
closeQuietly(output);
}

return outputFile;
}

public static File[] getAllOriginalCSVFiles() {
File baseDir = new File(“../parquet-testdata/tpch”);
final File[] csvFiles = baseDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(“.csv”);
}
});
return csvFiles;
}

public static String[] getAllPreviousVersionDirs() throws IOException {
File baseDir = new File(“..”);
final String currentVersion = getCurrentVersion();
final String[] versions = baseDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(“parquet-compat-“)
&& new Version(name.replace(“parquet-compat-“, “”)).compareTo(new Version(currentVersion)) < 0;
}
});
return versions;
}

static class Version implements Comparable<Version> {
int major;
int minor;
int minorminor;
String tag;

Version(String versionStr) {
String[] versions = versionStr.split(“\\.”);
int size = versions.length;
if (size > 0) {
this.major = Integer.parseInt(versions[0]);
}
if (size > 1) {
this.minor = Integer.parseInt(versions[1]);
}
if (size > 2) {
if(versions[2].contains(“-“)) {
String[] minorMin = versions[2].split(“-“);
this.minorminor = Integer.parseInt(minorMin[0]);
this.tag = minorMin[1];
} else {
this.minorminor = Integer.parseInt(versions[2]);
}
}
if(size == 4) {
this.tag = versions[3];
}
if (size > 4) {
throw new RuntimeException(“Illegal version number ” + versionStr);
}
}

public int compareMajorMinor(Version o) {
return ComparisonChain.
start().
compare(major, o.major).
compare(minor, o.minor).
result();
}

@Override
public int compareTo(Version o) {
return ComparisonChain.
start().
compare(major, o.major).
compare(minor, o.minor).
compare(minorminor, o.minorminor).
compare(tag, o.tag).
result();
}

// Very basic implementation of comparisonchain
private static class ComparisonChain {
int result = 0;
private ComparisonChain(int result) {
this.result = result;
}
static ComparisonChain start() {
return new ComparisonChain(0);
}
ComparisonChain compare(String a, String b) {
if (result != 0) {
return this;
}
if(b == null) {
if (a!= null) result=1;
else result= 0;
} else if (a == null) {
result=1;
} else if (result == 0) {
result = a.compareTo(b);
}
return this;
}
ComparisonChain compare(int a, int b) {
if (result == 0) {
result = Integer.compare(a, b);
}
return this;
}
int result() {
return result;
}
}
}

public static File getParquetOutputFile(String name, String module, boolean deleteIfExists) {
File outputFile = new File(“target/parquet/”, getParquetFileName(name, module));
outputFile.getParentFile().mkdirs();
if(deleteIfExists) {
outputFile.delete();
}
return outputFile;
}

private static String getParquetFileName (String name, String module) {
return name + (module != null ? “.” + module : “”) + “.parquet”;
}

public static File getParquetFile(String name, String version, String module, boolean failIfNotExist)
throws IOException {
File parquetFile = new File(“../”+version+”/target/parquet/”, getParquetFileName(name, module));
parquetFile.getParentFile().mkdirs();
if(!parquetFile.exists()) {
String msg = “File ” + parquetFile.getAbsolutePath() + ” does not exist”;
if(failIfNotExist) {
throw new IOException(msg);
}
LOG.warn(msg);
}
return parquetFile;
}

private static String getCurrentVersion() throws IOException {
return new File(“.”).getCanonicalFile().getName().replace(“parquet-compat-“, “”);
}

public static String[] getImpalaDirectories() throws IOException {
File baseDir = new File(“../parquet-testdata/impala”);
final String currentVersion = getCurrentVersion();
final String[] impalaVersions = baseDir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith(“.”)) {
return false;
}
if (name.contains(“-“)) {
name = name.split(“-“)[0];
}
return new Version(name).compareMajorMinor(new Version(currentVersion)) == 0;
}
});
return impalaVersions;
}

public static File getParquetImpalaFile(String name, String impalaVersion) throws IOException {
String fileName = name + “.impala.parquet”;
File parquetFile = new File(“../parquet-testdata/impala/” + impalaVersion, fileName);
if(!parquetFile.exists()) {
throw new IOException(“File ” + fileName + ” does not exist”);
}
return parquetFile;
}

public static String getFileNamePrefix(File file) {
return file.getName().substring(0, file.getName().indexOf(“.”));
}

public static File getCsvTestFile(String name, String module, boolean deleteIfExists) {
File outputFile = new File(“target/test/csv/”,
name + (module != null ? “.” + module : “”) + “.csv”);
outputFile.getParentFile().mkdirs();
if(deleteIfExists) {
outputFile.delete();
}
return outputFile;
}

public static File getParquetTestFile(String name, String module, boolean deleteIfExists) {
File outputFile = new File(“target/test/parquet/”,
name + (module != null ? “.” + module : “”) + “.csv”);
outputFile.getParentFile().mkdirs();
if(deleteIfExists) {
outputFile.delete();
}
return outputFile;
}

public static void verify(File expectedCsvFile, File outputCsvFile) throws IOException {
BufferedReader expected = null;
BufferedReader out = null;
try {
expected = new BufferedReader(new FileReader(expectedCsvFile));
out = new BufferedReader(new FileReader(outputCsvFile));
String lineIn;
String lineOut = null;
int lineNumber = 0;
while ((lineIn = expected.readLine()) != null && (lineOut = out.readLine()) != null) {
++ lineNumber;
lineOut = lineOut.substring(lineOut.indexOf(“\t”) + 1);
assertEquals(“line ” + lineNumber, lineIn, lineOut);
}
assertNull(“line ” + lineNumber, lineIn);
assertNull(“line ” + lineNumber, out.readLine());
} finally {
Utils.closeQuietly(expected);
Utils.closeQuietly(out);
}
}

public static void verify(File expectedCsvFile, File outputCsvFile, boolean orderMatters) throws IOException {
if(!orderMatters) {
// sort the files before diff’ing them
expectedCsvFile = sortFile(expectedCsvFile);
outputCsvFile = sortFile(outputCsvFile);
}
verify(expectedCsvFile, outputCsvFile);
}

private static File sortFile(File inFile) throws IOException {
File sortedFile = new File(inFile.getAbsolutePath().concat(“.sorted”));
BufferedReader reader = new BufferedReader(new FileReader(inFile));
PrintWriter out = new PrintWriter(new FileWriter(sortedFile));

try {
String inputLine;
List<String> lineList = new ArrayList<String>();
while ((inputLine = reader.readLine()) != null) {
lineList.add(inputLine);
}
Collections.sort(lineList);

for (String outputLine : lineList) {
out.println(outputLine);
}
out.flush();
} finally {
closeQuietly(reader);
closeQuietly(out);
}
return sortedFile;
}
}

CsvParquetWriter.java

package com;

import java.io.IOException;
import java.util.List;

import org.apache.hadoop.fs.Path;

import parquet.hadoop.ParquetWriter;
import parquet.hadoop.api.WriteSupport;
import parquet.hadoop.metadata.CompressionCodecName;
import parquet.schema.MessageType;

public class CsvParquetWriter extends ParquetWriter<List<String>> {

public CsvParquetWriter(Path file, MessageType schema) throws IOException {
this(file, schema, false);
}

public CsvParquetWriter(Path file, MessageType schema, boolean enableDictionary) throws IOException {
this(file, schema, CompressionCodecName.UNCOMPRESSED, enableDictionary);
}

public CsvParquetWriter(Path file, MessageType schema, CompressionCodecName codecName, boolean enableDictionary) throws IOException {
super(file, (WriteSupport<List<String>>) new CsvWriteSupport(schema), codecName, DEFAULT_BLOCK_SIZE, DEFAULT_PAGE_SIZE, enableDictionary, false);
}
}

CsvWriteSupport.java

package com;

import java.util.HashMap;
import java.util.List;

import org.apache.hadoop.conf.Configuration;

import parquet.column.ColumnDescriptor;
import parquet.hadoop.api.WriteSupport;
import parquet.io.ParquetEncodingException;
import parquet.io.api.Binary;
import parquet.io.api.RecordConsumer;
import parquet.schema.MessageType;

public class CsvWriteSupport extends WriteSupport<List<String>> {
MessageType schema;
RecordConsumer recordConsumer;
List<ColumnDescriptor> cols;

// TODO: support specifying encodings and compression
public CsvWriteSupport(MessageType schema) {
this.schema = schema;
this.cols = schema.getColumns();
}

@Override
public WriteContext init(Configuration config) {
return new WriteContext(schema, new HashMap<String, String>());
}

@Override
public void prepareForWrite(RecordConsumer r) {
recordConsumer = r;
}

@Override
public void write(List<String> values) {
if (values.size() != cols.size()) {
throw new ParquetEncodingException(“Invalid input data. Expecting ” +
cols.size() + ” columns. Input had ” + values.size() + ” columns (” + cols + “) : ” + values);
}

recordConsumer.startMessage();
for (int i = 0; i < cols.size(); ++i) {
String val = values.get(i);
// val.length() == 0 indicates a NULL value.
if (val.length() > 0) {
recordConsumer.startField(cols.get(i).getPath()[0], i);
switch (cols.get(i).getType()) {
case BOOLEAN:
recordConsumer.addBoolean(Boolean.parseBoolean(val));
break;
case FLOAT:
recordConsumer.addFloat(Float.parseFloat(val));
break;
case DOUBLE:
recordConsumer.addDouble(Double.parseDouble(val));
break;
case INT32:
recordConsumer.addInteger(Integer.parseInt(val));
break;
case INT64:
recordConsumer.addLong(Long.parseLong(val));
break;
case BINARY:
recordConsumer.addBinary(stringToBinary(val));
break;
default:
throw new ParquetEncodingException(
“Unsupported column type: ” + cols.get(i).getType());
}
recordConsumer.endField(cols.get(i).getPath()[0], i);
}
}
recordConsumer.endMessage();
}

private Binary stringToBinary(Object value) {
return Binary.fromString(value.toString());
}
}

Read pdf using Scala and pdfbox

In this blog, I will publish the code to read pdf using scala and pdfbox utility.

You will need the pdfbox-app-1.8.7 and commons-io-2.4 jar utility in addition to scala jars.

package com

import java.io._
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.util.PDFTextStripper

object PdfToText extends App{
System.setProperty(“java.awt.headless”, “true”)

override def main(args: Array[String]) {
if (args.length != 3) printUsageAndExit

val startPage = args(0).toInt
val endPage = args(1).toInt
val filename = args(2)

// sanity check
if (startPage > endPage) printUsageAndExit

println(getTextFromPdf(startPage, endPage, filename))
}

def printUsageAndExit {
println(“”)
println(“Usage: pdftotext startPage endPage filename”)
println(” (endPage must be >= startPage)”)
System.exit(1)
}

def getTextFromPdf(startPage: Int, endPage: Int, filename: String): Option[String] = {
try {
val pdf = PDDocument.load(new File(filename))
val stripper = new PDFTextStripper
stripper.setStartPage(startPage)
stripper.setEndPage(endPage)
Some(stripper.getText(pdf))
} catch {
case t: Throwable =>
t.printStackTrace
None
}
}

}

Pass the arguments as 13, 14, D:/SecuringHadoop.pdf (as an example)

If you want to use the save compiled version of scala and read pdf using scala script, use the below code:

#!/bin/sh
exec scala -savecompiled -classpath "lib/pdfbox-app-1.8.7.jar:lib/commons-io-2.4.jar" "$0" "$@"
!#

import java.io._
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.util.PDFTextStripper

object PdfToText {

    System.setProperty("java.awt.headless", "true")

    def main(args: Array[String]) {
        if (args.length != 3) printUsageAndExit

        val startPage = args(0).toInt
        val endPage = args(1).toInt
        val filename = args(2)

        // sanity check
        if (startPage > endPage) printUsageAndExit

        println(getTextFromPdf(startPage, endPage, filename))
    }

    def printUsageAndExit {
        println("")
        println("Usage: pdftotext startPage endPage filename")
        println("       (endPage must be >= startPage)")
        System.exit(1)
    }

    def getTextFromPdf(startPage: Int, endPage: Int, filename: String): Option[String] = {
        try {
            val pdf = PDDocument.load(new File(filename))
            val stripper = new PDFTextStripper
            stripper.setStartPage(startPage)
            stripper.setEndPage(endPage)
            Some(stripper.getText(pdf))
        } catch {
            case t: Throwable =>
                t.printStackTrace
                None
        }
    }

}

PdfToText.main(args)

Pre-compiled Scala scripts

To eliminate lag time in starting up scala script, scala interpreter provides -saveCompiled argument of scala interpreter.

Then run the script once. This will still run slow, but it generates a compiled version of the script. After that, the script runs with a consistently lower real time (wall clock) on all subsequent runs

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

println("Hello, world!")
args foreach println


Create your own website, free on WordPress.com.Create your own website.
Start free