Adapter Design Pattern in Java

Adapter Design pattern – Structural Patterns

Adapter pattern Convert the existing interfaces to a new interface to achieve compatibility and re usability of the unrelated classes in one application. Also known as Wrapper pattern. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. . When a client specifies its requirements in an interface, you can usually create a new class that implements the interface and subclasses an existing class. This approach creates a class adapter that translates a client’s calls into calls to the existing class’s methods.

The Adapter in the Real World
The concept of an Adapter is as the name suggest. It will do what is expected It adapts one object to that of another. Suppose we have any device which will work on 10 Ampere. But we don’t have plug of 10 ampere, then we need an Adapter to work that device .In similar way this design pattern works.

The Adapter in the Software
Here also it is working as same.. When you want to work or use one class to another class that was not designed to fit together, we need a adapter class.

There are two ways of implementing the Adapter Pattern, either use the Inheritance or use the composition.
Let’s do it with the approach of Inheritance.Lets take an example.

PrintOutput.java

package structural.adapter.inheritance;

public interface PrintOutput {
public String getOutput();
}

SystemVinay.java

package structural.adapter.inheritance;
public class SystemVinay{
private String specification = "Hi ,This is adapter Design Pattern";
public String getInput() {
return specification;
}
}// End of class

Finally, there will be an adapter class. This will inherit the PrintOutput and give output for SystemVinay.

OutPutAdapter.java

package structural.adapter.inheritance;
/**
* OutPutAdapter has is the connector between
* the SystemVinayand PrintOutput so as to make the interface
* of one system to suit the client.
*/
public class OutPutAdapter implements PrintOutput {
/**
* Method coming from the interface
* SystemVinaywhich we have to make to
* fit the client SystemVinay
*
* @return Desired output of “Hi ,This is adapter Design Pattern”
*/
public String getOutput() {
SystemVinaysystem = new SystemVinay();
String output = system.getInput();
return output;
}
}// End of class

This class implements the getOutput() method of SystemVinayand sets it to fit the client output.

In- Summary We can say Adapter design pattern is – A class extends another class, takes in an object, and makes the taken object behave like the extended class.

pimp it

Java send mail in text and html

We posted earlier how send email using java email api.
Here is example of sending email in plain text and html format in same email.

  //get mail session
        Properties props = new Properties();
        props.put("mail.smtp.host", "localhost");
        Session session = session.getDefaultInstance(props);

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage(session);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText("This is plain text message", "UTF-8");
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent("<h1>This is plain HTML message", "text/html;charset=UTF-8");
        messageBody.addBodyPart(htmlTextPart);

        mimeMessage.setReplyTo(new InternetAddress[]{new InternetAddress("[email protected]")});
        mimeMessage.setFrom(new InternetAddress("[email protected]"));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
        mimeMessage.setSentDate(new Date());
        mimeMessage.setSubject("Mixed message");
        Transport.send(mimeMessage);

Storing URL Re-Write rules in a seperate file

When using rewrite maps in IIS URL Rewrite it is very common to have a very large number of entries in a rewrite rules. In order to avoid cluttering the configuration file – web.config – with this configuration data the rewrite rules can be defined in a separate configuration file. That file can then be referenced from the web.config file.

For example below are few of the rules defined in one of my web application:

<system.webServer>
      <rewrite>
            <rules>
                 <rule name="HomeURL" stopProcessing="true">
                    <match url="^Home$" />
                    <conditions logicalGrouping="MatchAll"
                      trackAllCaptures="false" />
                     <action type="Rewrite" url="Pages/HomePage.aspx"
                      appendQueryString="false" logRewrittenUrl="true" />
                  </rule>
                  <rule name="DefaultURL" stopProcessing="true">
                     <match url="default" />
                     <conditions logicalGrouping="MatchAll"
                        trackAllCaptures="false" />
                     <action type="Rewrite" url="Pages/HomePage.aspx"
                        appendQueryString="false" logRewrittenUrl="true" />
                  </rule>
               </rules>            
      </rewrite>
  </system.webServer>

Create a seperate file called myRules.config in the same directory where web.config file is and move the rules to the new file:

		<rules>
                       <rule name="HomeURL" stopProcessing="true">
                             <match url="^Home$" />
                             <conditions logicalGrouping="MatchAll"
                                  trackAllCaptures="false" />
                             <action type="Rewrite" url="Pages/HomePage.aspx"
                                  appendQueryString="false" logRewrittenUrl="true" />
                        </rule>
                        <rule name="DefaultURL" stopProcessing="true">
                             <match url="default" />
                             <conditions logicalGrouping="MatchAll"
                                 trackAllCaptures="false" />
                             <action type="Rewrite" url="Pages/HomePage.aspx"
                                 appendQueryString="false" logRewrittenUrl="true" />
                        </rule>
               </rules>    

Save the new file and now open web.config file in notepad. In web.config file add the following inside the <rewrite> section:   

<system.webServer>
      <rewrite>
         <rules configSource="myRewriteMaps.config" />
      </rewrite>
 </system.webServer>

The configSource attribute tells IIS configuration that the <rewriteMaps> section is defined in a separate file myRules.config. This referenced section can be now uses as if it was defined in the same web.config file. Also, the IIS Manager UI will work well with this referenced file: when you modify or add entries to the rewrite map they will be stored in the myRules.config file.

The same approach can be used for storing rewrite mappings in seperate configuration file. For Ex:

<system.webServer>
      <rewrite>
          <rules configSource="myRewriteMaps.config" />

</rewrite>

</system.webServer>

Hope this helps!!! 🙂