Created

Jan 28, 2013

Create a custom adapter

Posted by Vianney Baron

Although out of the box CQ offers a number of versatile object types and their associated APIs, it can sometimes be helpful to define your own Java value objects. However the actual data is stored in CRX, so I need an easy way to map my product node in CRX to my Product class in Java. This is where the AdapterFactory comes in.

Most CQ developers are familiar with the concept of the adaptTo(), allowing them to adapt a few basic CQ objects to a number of more complex and more structured classes, as described here.

Well the AdapterFactory actually lets us create our own adapters, so we can then adaptTo() from/to any class we want! And it’s really easy to do too, as you'll soon find out.

For example if I am building an eCommerce website I might want to create a Product class, containing all the properties for my product, and their associated getters and setters, as such:

public class Product {

	public static final String PROP_SERIAL = "serial";
	public static final String PROP_PRICE = "price";
	public static final String PROP_CATEGORY = "category";
	public static final String PROP_IMG_URL = "imgURL";

	private String path;
	private String serial;
	private Double price;
	private String category;
	private String imgURL;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getSerial() {
		return serial;
	}

	public void setSerial(String serial) {
		this.serial = serial;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}
	
	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getImgURL() {
		return imgURL;
	}

	public void setImgURL(String imgURL) {
		this.imgURL = imgURL;
	}

}

This is a simple POJO, a typed object that will allow me to manipulate my products easily. But to ease the manipulation of this object and its associated data in CRX we'll create a custom adapter for it. For instance if our products are stored as pages here’s the code to adapt a Page object to our Product object:

@Component(metatype = true, immediate = true)
@Service
public class ProductAdapter implements AdapterFactory {

	private static final Logger LOG = LoggerFactory
			.getLogger(ProductAdapter.class);

	private static final Class<ProductVO> PRODUCT_CLASS = Product.class;
	private static final Class<Page> PAGE_CLASS = Page.class;

	@Property(name = "adapters")
	protected static final String[] ADAPTER_CLASSES = { PRODUCT_CLASS
			.getName() };

	@Property(name = "adaptables")
	protected static final String[] ADAPTABLE_CLASSES = { PAGE_CLASS.getName() };

	@Override
	public  <AdapterType> AdapterType getAdapter(Object adaptable,
			Class<AdapterType> type) {
		if (adaptable instanceof Page) {
			return this.adaptFromPage((Page) adaptable, type);
		}
		return null;
	}

	private  <AdapterType> AdapterType adaptFromPage(Page page,
			Class<AdapterType> type) {
		if ((page != null) && (page.getContentResource() != null)) {
			return adaptFromResource(page.getContentResource(), type);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private  <AdapterType> AdapterType adaptFromResource(Resource resource,
			Class<AdapterType> type) {
		Product product = new Product();
		try {
			Node productNode = resource.adaptTo(Node.class);
			product.setPath(productNode.getParent().getPath());

			// Set serial
			if (productNode.hasProperty(Product.PROP_SERIAL))
				product.setSerial(productNode.getProperty(Product.PROP_SERIAL)
						.getString());

			// Set category
			if (productNode.hasProperty(Product.PROP_CATEGORY))
				product.setCategory(productNode.getProperty(
						Product.PROP_CATEGORY).getString());

			// Set price
			if (productNode.hasProperty(Product.PROP_PRICE))
				product.setPrice(productNode
						.getProperty(Product.PROP_PRICE).getDouble());

			// Set image url
			if (productNode.hasProperty(Product.PROP_IMG_URL))
				product.setImgURL(productNode.getProperty(
						Product.PROP_IMG_URL).getString());

		} catch (RepositoryException repositoryException) {
			LOG.error("RepositoryException ------ > ", repositoryException);
		}
		return (AdapterType) product;
	}

}

A few things to point out here: we are simply declaring a new service implementing the AdapterFactory class, and then we configure it by declaring a list of “adaptables” which are the classes we can adapt from, and a list of “adapters” which are the classes we’re adapting to. We then override the getAdapter() method and insert the logic in there.

Now whenever I need to manipulate a product I can simply use:

Product currentProduct = currentPage.adaptTo(Product.class);

COMMENTS

  • By APK - 10:29 AM on May 31, 2014   Reply
    Many Thanks.
  • By tidung.net - 5:03 AM on Jun 02, 2014   Reply
    Thanks.
    • By apk - 11:19 AM on Jun 06, 2014   Reply
      Thanks.
      • By Jasa SEO - 11:33 AM on Jun 08, 2014   Reply
        Many Thanks.
        • By Tattoos - 4:40 PM on Jun 08, 2014   Reply
          Many Thanks.
          • By step up height - 7:07 AM on Jun 09, 2014   Reply
            It has increased my height and is definitely one of the great products I have ever used.
            • By help with outlook - 11:59 AM on Jun 11, 2014   Reply
              We all know that the CQ offers a number of various types of objects.this one read proves to be very useful to us.this is very informative article and i am personally very much thankful to the writer for giving me what i was exactly looking for
              • By foto Wedding - 3:51 PM on Jun 11, 2014   Reply
                i really to say nice tools from adobe. i like it.
                • By decor - 12:03 PM on Jun 12, 2014   Reply
                  Shows deal with all segments of the industry (like AHR Expo) or concentrate on particular segments.
                  • By Trainer terbaik indonesia - 9:19 PM on Jun 12, 2014   Reply
                    i really to say nice tools from adobe. i like it.
                    • By Jasa SEO Lampung - 9:20 PM on Jun 12, 2014   Reply
                      i like this content
                      • By pusat grosir tas - 9:33 PM on Jun 12, 2014   Reply
                        Many Thanks.
                        • By Obat Keputihan - 9:35 AM on Jun 22, 2014   Reply
                          Many Thanks.
                          • By Agen Judi Online - 9:29 AM on Jun 25, 2014   Reply
                            As we age this careful system changes. Moreover to monitoring moment-to-moment threats such as an beginning car or a decrease banister, our threat verifying starts to intuit a distant but progressively approaching dark thinking — the approaching end, the biggest boundary.
                            • By official sites - 7:34 AM on Jun 28, 2014   Reply
                              Show supervisors need to accept on the internet promotion, social networking and other promotion communications methods of gaining participants and participants – especially the younger years.
                              • By official sites - 7:35 AM on Jun 28, 2014   Reply
                                Show supervisors need to accept on the internet promotion, social networking and other promotion communications methods of gaining participants and participants – especially the younger years.
                                • By bisnis gratis libertagia $3 tiap hari - 1:58 PM on Jul 02, 2014   Reply
                                  Appreciate the recommendation. Let me try it out. Also visit my page free Psn codes
                                  • By Khaito - 8:00 AM on Jul 04, 2014   Reply
                                    I would like to thank the author for this marvelous efforts .I appreciate your efforts in preparing create custom adapter post. I really like your blog articles.
                                    • By airul - 10:53 AM on Jul 06, 2014   Reply
                                      Thanks.
                                      • By natural carpet cleaning rowlett - 8:05 AM on Jul 07, 2014   Reply
                                        It turned out much more practical than I thought! Aside from just letting him chew on the links, I also used a chain of them to hook up toys to the stroller bars, so he could freely play with them but they won't drop to the floor.
                                        • By stumbleupon - 8:03 AM on Jul 08, 2014   Reply
                                          Buddhism understands of that from the perspective of ego the opportunities of lack of way of life is generally difficult.
                                          • You're so cool! I do not believe I've read through something like that before. So nice to find somebody with a few unique thoughts on this issue. Really.. thank you for starting this up. This site is something that is required on the web, someone with some originality!
                                            • By clash of clans cheats - 9:09 AM on Jul 11, 2014   Reply
                                              As we age this careful system changes. Moreover to monitoring moment-to-moment threats such as an beginning car or a decrease banister, our threat verifying starts to intuit a distant but progressively approaching dark thinking — the approaching end, the biggest boundary
                                              • By model baju lebaran - 4:26 PM on Jul 12, 2014   Reply
                                                i really to say nice tools from adobe. i like it.
                                                • By venus factor reviews - 8:32 AM on Jul 15, 2014   Reply
                                                  We also used a tube threads machine, so we could comprehend the different procedures available, and how long engaged when a specialist is on a job, threads tube.
                                                  • By Abus Secvest - 1:11 PM on Jul 15, 2014   Reply
                                                    turned out much more practical than I thought! Aside from just letting him chew on the links, I also used a chain of them to hook up toys to the stroller bars, so he could freely play with them but they won't drop to the floor.
                                                    • By url opener - 6:15 PM on Jul 15, 2014   Reply
                                                      Actually get pleasure from this fantastic submit that you've got provided for people like us. Fantastic web page along with a wonderful topic also i really find amazed to learn to read this. Its fantastic
                                                      • By High School Diploma Online - 11:14 AM on Jul 18, 2014   Reply
                                                        What a great code you have shared here really like your work
                                                        Thanks
                                                        • By barcelona chair - 12:17 PM on Jul 18, 2014   Reply
                                                          There is no fiduciary responsibility. And instead of having a regulating power, you designate a company to immediate the conversation.
                                                          • By duplichecker - 7:38 PM on Jul 18, 2014   Reply
                                                            Very nice post even i would say that whole blog is awesome. I keep learning new things every day from post like these. Good stuff!
                                                            • By Crystal X Asli - 7:56 PM on Jul 22, 2014   Reply
                                                              i really to say nice tools from adobe. i like it.
                                                              • By Crystal X Asli - 7:56 PM on Jul 22, 2014   Reply
                                                                i really to say nice tools from adobe. i like it.

                                                                ADD A COMMENT