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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • Mastering Advanced Aggregations in Spark SQL
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Thermometer Continuation in Scala

Trending

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  • Agile’s Quarter-Century Crisis
  1. DZone
  2. Coding
  3. Languages
  4. Adapter Design Pattern With Scala

Adapter Design Pattern With Scala

Want to learn more about using design patterns in Scala? Check out this post to learn more about the adapter design pattern in Scala.

By 
Nancy Jain user avatar
Nancy Jain
·
Sep. 09, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
14.0K Views

Join the DZone community and get the full member experience.

Join For Free

In our last blog, we discussed the decorator design pattern with Scala. Today, we will explore the Adapter design pattern. We will also implement this pattern in Scala.

Earlier, in many applications, all the user-specific details, like username, IP addresses, phone number, etc., were logged directly without scrambling it. But, after new data protection law, i.e. EUGDPR, it is now mandatory to scramble any user-specific data.

So, we need to change the logging logic for all such applications. In order to do this, we will add some extra methods to our logging framework. But, wait! We all know that most of our applications are generally flooded with logging statements and replacing all the statements with new method names is not logically and practically possible.

So, what can we do now? We can use the Adapter design pattern!

What Is the Adapter Design Pattern?

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that could not otherwise because of incompatible interfaces. Adapter is also known as wraper.

Solution to our Problem

We will change our existing logger framework to a framework that supports methods like scrambledInfo(), scambledError(), scrambledDebug() , etc.

adapterDesignUml

We will create a LoggerAdapter class, which will adapt or wrap the ScrambledLogger . And, whenever the client calls the info method, it will call thescrambledInfo method and will do the same for the methods debug ,error , etc.

Flow chart- Adapter Design pattern

The Client class is the class that will actually call the logging methods.

The LoggerHelper trait is an existing trait on which all the required logging methods are declared.

Now,ScrambledLogger is the new class that will scramble all logs before logging. It is basically an Adaptee.

LoggerAdapter is the class that will act as an interface between our Clientand our adaptee class ScrambledLogger.

package com.knoldus

import org.apache.log4j.BasicConfigurator

object Client extends App {
BasicConfigurator.configure()
val logger : LoggerHelper = LoggerAdapter.getLogger(this.getClass.getName)
logger.info("Log Contains IP address: 127.0.0.1")
logger.debug("UserName: jainnancy trying to sign in")
logger.error("Password: abxyz is wrong ")
}


package com.knoldus

object LoggerAdapter extends LoggerHelper {
var scrambledLogger : ScrambledLogger = _

override def info(msg : String) = scrambledLogger.scrambledInfo(msg)

override def debug(msg : String) = scrambledLogger.scrambledDebug(msg)

override def error(msg : String) = scrambledLogger.scrambledError(msg)

def getLogger(s : String) : LoggerHelper =
{
scrambledLogger = new ScrambledLogger(s)
LoggerAdapter
}
}


package com.knoldus

import org.apache.log4j.BasicConfigurator

trait LoggerHelper {
def info(msg : String)

def debug(msg : String)

def error(msg : String)
}


package com.knoldus

import org.apache.log4j.Logger

class ScrambledLogger(name : String)
{
    private val regex = "\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"
    private val password = "Password: "
    private val userName = "UserName: "
    private val logger = Logger.getLogger(name)

    def scrambledInfo(message : String) =  logger.info(scramble(message))

    def scrambledDebug(message : String) = logger.debug(scramble(message))

    def scrambledError(message : String) = logger.error(scramble(message))

    private def scramble(message : String) = scrambleUsername(scrambleIp((scramblePassword(message))))

    private def scrambleUsername(message : String) = {
        if(message.contains(userName)) {
            val index = message.indexOf(userName) + userName.length()
            val textStartedPassword = message.substring(index)
            message.substring(0, index) + "X" + textStartedPassword.substring(textStartedPassword.indexOf(" "))
        }
        else {
            message
        }
    }

    private def scrambleIp(message : String) = message.replaceAll(regex, "XXX.XXX.XXX.XXX")

    private def scramblePassword(message : String) = {
        if(message.contains(password)) {
            val index = message.indexOf(password) + password.length()
            val textStartedPassword = message.substring(index)
            message.substring(0, index) + "X" + textStartedPassword.substring(textStartedPassword.indexOf(" "))
        }
        else {
            message
        }
    }
}


Note:

  1. We are using the following dependency for Logger: libraryDependencies += "log4j" % "log4j" % "1.2.17"
  2. ScrambledLoggeris also somehow using the Proxy design pattern, which we will discuss in the upcoming blog post.

Hope you enjoyed!

References

  • https://www.scala-lang.org/old/sites/default/files/FrederikThesis.pdf
  • https://sourcemaking.com/design_patterns/adapter
Design Scala (programming language)

Published at DZone with permission of Nancy Jain, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • Mastering Advanced Aggregations in Spark SQL
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Thermometer Continuation in Scala

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!