DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Big Data
  4. How to Build a Data Pipeline Using Kafka, Spark, and Hive

How to Build a Data Pipeline Using Kafka, Spark, and Hive

In this post, we learn how to make a basic data pipeline using these popular Apache frameworks and the Scala language.

Avi Garg user avatar by
Avi Garg
·
May. 07, 19 · Tutorial
Like (5)
Save
Tweet
Share
29.23K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will look at how to build data pipeline to load input files (XML) from a local file system into HDFS, process it using Spark, and load the data into Hive.

Use Case

We have some XML data files getting generated on a server location at regular intervals daily. Our task is to create a data pipeline which will regularly upload the files to HDFS, then process the file data and load it into Hive using Spark.

Solution

Initial Steps

  • Create Hive tables depending on the input file schema and business requirements.

  • Create a Kafka Topic to put the uploaded HDFS path into.

Step 1

At first we will write Scala code to copy files from he local file system to HDFS. We use the copyFromLocal method as mentioned in the below code (FileUploaderHDFS). The below code copies the file from the path assigned to the  localPathStr variable to the HDFS path assigned to the destPath variable.

Once the file gets loaded into HDFS, then the full HDFS path will gets written into a Kafka Topic using the Kafka Producer API. So our Spark code will load the file and process it.

FileUploaderHDFS:

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.apache.hadoop.fs.FileSystem
import java.io.IOException
import java.io.File
import java.nio.file.{Files, Paths, StandardCopyOption}

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}

object FileUploaderHDFS {

  def main(args: Array[String]): Unit = {

    try {

      println("Inside FileUploaderHDFS")
      val hadoopConf = new Configuration()
      val hdfs = FileSystem.get(hadoopConf)

      val localPathStr = "<local-input-file-path>"

      val fileList = getListOfFiles(localPathStr)
      val destPath = new Path("<hdfs-destination-path>")
      if (!hdfs.exists(destPath))
        hdfs.mkdirs(destPath)
      for (file <- fileList) {


        val localFilePath = new Path("file:" + "//" + file)
        hdfs.copyFromLocalFile(localFilePath, destPath)


        /*Move file to processed folder*/
         Files.move(
          Paths.get(file.toString),
          Paths.get("<Processed-File-Path>"),
          StandardCopyOption.REPLACE_EXISTING)

        produceKafkaMsg(destPath + "/" + file.getName)

        println("File has been uploaded into HDFS " + destPath  )

      }


    }

    catch {
      case ex: IOException => {

        println("Input /Output Exception")

      }
    }
  }


  def getListOfFiles(dir: String): List[File] = {
    val d = new File(dir)
    if (d.exists && d.isDirectory) {
      d.listFiles.filter(_.isFile).toList
    } else {
      List[File]()
    }
  }

// This method writes the uploaded file path into Kafka topic
  def produceKafkaMsg(hdfsFile:String):Unit={

    val kafkaProducerProperty = new Properties();
    kafkaProducerProperty.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
    kafkaProducerProperty.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    kafkaProducerProperty.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")

    val kafkaProducer = new KafkaProducer[Nothing, String](kafkaProducerProperty)

    val kafkaProducerRecord = new ProducerRecord("inputFileLists",hdfsFile)
    println(kafkaProducer.send(kafkaProducerRecord))

    println("File has been uploaded into HDFS " + hdfsFile  )


  }

}

Step 2

Write the code for a Kafka Consumer (GetFileFromKafka) which is running in an infinite loop and regularly pools the Kafka Topic for the input message. Once the HDFS file path is available in the topic, it (ApplicationLauncher) launches the Spark application  (ParseInputFile) which process the file and loads the data into a Hive table. Please see below code for details. 

ApplicationLauncher:

import org.apache.spark.launcher.SparkLauncher
import org.apache.spark.launcher.SparkAppHandle

object ApplicationLauncher {

  def launch(hdfsFilePath:String):Unit={

    val command = new SparkLauncher()
      .setAppResource("<file-path-of -your-application-jar>")
      .setMainClass("ParseInputFile")
      .setVerbose(false)
      .addAppArgs(hdfsFilePath)
      .setMaster("local")
      .addSparkArg("--jars","<file-path>/spark-xml_2.11-0.5.0.jar") //It is required to parse xml file
    val appHandle = command.startApplication()
    appHandle.addListener(new SparkAppHandle.Listener{
      def infoChanged(sparkAppHandle : SparkAppHandle) : Unit = {
        println(sparkAppHandle.getState + "  Custom Print")
      }

      def stateChanged(sparkAppHandle : SparkAppHandle) : Unit = {
        println(sparkAppHandle.getState)
        if ("FINISHED".equals(sparkAppHandle.getState.toString)){
          sparkAppHandle.stop
        }
      }
    })



  }

}

GetFileFromKafka

import java.util.{Collections, Properties}

import org.apache.kafka.clients.consumer.{ConsumerConfig, KafkaConsumer}

import scala.collection.JavaConversions._


object GetFileFromKafka {

  def main(args: Array[String]): Unit = {
    println("Inside GetFileFromKafka")
    val kafkaConsumerProperty = new Properties()
    kafkaConsumerProperty.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
    kafkaConsumerProperty.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer")
    kafkaConsumerProperty.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer")
    kafkaConsumerProperty.put(ConsumerConfig.GROUP_ID_CONFIG, "cg01")
    kafkaConsumerProperty.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")

    val topic = "inputFileLists"
    val kafkaConsumer = new KafkaConsumer[String,String](kafkaConsumerProperty)
    kafkaConsumer.subscribe(Collections.singletonList(topic))
    while(true){
      val fileLists = kafkaConsumer.poll(10000)
      //Read the file paths from kafka topic
      for(filePath <- fileLists)
      {
       //Launch Spark-Application to process File
        try{
          ApplicationLauncher.launch(filePath.value())
        }
        catch{
          case e :Throwable => e.printStackTrace
        }


      }
    }


  }

}

Step 3:

Now, in this final step, we will write a Spark application to parse an XML file and load the data into Hive tables ( ParseInputFile) depending on business requirements.

ParseInputFile:

import com.databricks.spark.xml
import org.apache.spark.SparkConf
import org.apache.spark._
import org.apache.spark.sql.SparkSession


object ParseInputFile {

  def main(args: Array[String]): Unit = {

    val filePath = args(0)
    val sparkSession = SparkSession.builder().appName("Read Raw XML").enableHiveSupport().getOrCreate()
    val webRawData = sparkSession.read.format("com.databricks.spark.xml").option("rootTag","records").option("rowTag","record").load(filePath)
    webRawData.registerTempTable("tempRawData")

    sparkSession.sql("<Your-HiveQL-To process data from tempRawData table>").registerTempTable("webDataEnrich")


  sparkSession.sql("<Insert-HiveQL-to load data into respective hive table>")


  }


}

Final Step:

 1. Make sure the FileUploaderHDFS application is synced with the frequency of input files generation.

 2.  Launch the GetFileFromKafka application and it should be running continuously. 

kafka Data (computing) File system Pipeline (software) Build (game engine) hadoop

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Is JavaScript Slice? Practical Examples and Guide
  • Specification by Example Is Not a Test Framework
  • Testing Level Dynamics: Achieving Confidence From Testing
  • Introduction To OpenSSH

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: