Featured post

Docker setup for Liferay 7 with MySQL

Friday, 7 April 2017

Spring OSGI portlet or bundle with Liferay 7


When you see the blog title, The question arises, is what's new in this post?


Everyone knows how to create Spring MVC Portlets! 
But do we know how to create a portlet which is OSGI enabled and can run parallel with other osgi bundles inside Liferay.

If you have been through these links and many more -

https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/spring-mvc
https://github.com/vernaillen/liferay7-springmvc-portlet

You must have noticed it's the same old way which includes all required jars inside the application's lib because we do not have support of global library now.
Liferay 7 is OSGI way now and by OSGI convention you do not include library into each other, but you share them from same place :)

Basic diagram of OSGI, copied from  -

https://fredhsu.wordpress.com/2013/05/03/opendaylight-and-osgi-basics/


To make it work for spring, we need to do two things

  • We will be using Apache Service Mix Spring Bundles(OSGI bundles for spring)
  • Support of few maven plugins, major one is Maven Bundle Plugin to add require entries to the manifest file and prepare it like a bundle but in a war type.

You can find the source code here - https://github.com/bardiavipin/osgi-spring
Meanwhile, you are checking out source code, I will explain minimal changes in your spring portlets to make them bundles.

Create a basic Spring portlet from your IDE or from command prompt or manually with Maven.

Copy below dependencies to deploy folder

Apache ServiceMix :: Bundles :: spring-beans (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-web (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-core (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-aop (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-expression (4.3.1.RELEASE_1)
com.github.ben-manes.caffeine (2.3.2)
Apache ServiceMix :: Bundles :: spring-context-support (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-context (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: spring-webmvc (4.3.1.RELEASE_1)
Apache ServiceMix :: Bundles :: commons-configuration (1.9.0.2)
Apache ServiceMix :: Bundles :: spring-webmvc-portlet (4.3.1.RELEASE_1)

Note:Caffeine is a required library for one for the spring modules.

You can check the status of bundles from Gogo Shell

Now we will be going through major changes inside Portlet files-


Context file for sample portlet is - spring portlet xml

<!--Not Working--><!--<context:component-scan base-package="com.osgi.spring" />-->

<bean class="com.osgi.spring.PortletViewController"/> <!-- Handler mappings for annotation based controllers --><bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> <bean class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>


As you can see in the context file, component scan is commented as it is not working for this example. I used the workaround to create simple bean and pass the controller class. Spring players can tell me what is the issue here :)

BND Dependency Fix - BNDDependencyFix

@SuppressWarnings("unused")
public class BNDDependencyFix {

    static {
        System.out.println(ModelAndViewResolver.class);


When you deploy the portlet without this class, you get errors like this -
java.lang.ClassNotFoundException: org.springframework.context.config.ContextNamespaceHandler cannot be found.

In this class we are initializing or loading the necessary classes from static method.
If you find more errors with same type, you can add your class name here.

Major Maven Plugins - pom.xml

  • War plugin to exclude all jars from final war
  • Bundle plugin make necessary changes in Manifest file to create it a bundle
  • Shade plugin to make single files from spring.schemas and spring.handlers and transform  them to a single file independently
  • Truezip plugin to move spring.handlers and  spring.schemas  to classes/META-INF

When you are done with building and deploying this portlet, you can see your portlet is interacting to another Liferay bundle - portal-kernel to fetch release information. Each of the library is deployed as OSGI only and shared between applications.

You can include jar as well inside apps lib with little change in configuration, but until and unless it is necessary don't break the architecture :)

You can use Maven Bundle plugin for any of your independent project and convert it to a osgi bundle.


You are just done, Try & Enjoy the function.............:)

30 comments:

  1. HI Vipin,

    Is it possible to create spring mvc portlet using OSGI and gradle as build tool.?

    From where i get Apache ServiceMix :: Bundles :: spring-beans (4.3.1.RELEASE_1) dependency.?

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.

      Delete
  2. Hi Krunal,

    Using OSGI you can create spring modules with Dynamic modules- http://www.javaworld.com/article/2077837/application-development/java-se-hello-osgi-part-1-bundles-for-beginners.html

    Apache service mix bundles are available in maven repo only, to be specific - https://mvnrepository.com/artifact/org.apache.servicemix.bundles

    Hope it helps :)

    ReplyDelete
  3. I stepped into same weird "component-scan" issue. In my case, I'm using annotation config and I have added @ComponentScan to my @Configuration class. But it does not work and there is apparently no reason for that. I'm using spring 4.1.9.RELEASE emdebbed in Liferay. Did anyone find where's the problem?

    ReplyDelete
    Replies
    1. Answer found. Spring's component scan does not work in OSGi environment... https://stackoverflow.com/questions/16795205/spring-component-scan-broken-in-osgi-container

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete
  6. Try playing online gambling on the BGAOC website. great blackjack online Only here are permanent and Bosnian wins.

    ReplyDelete
  7. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Project Centers in Chennai.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Corporate TRaining Spring Framework the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete
  8. Crypto-currency as a modern form of the digital asset has received a worldwide acclaim for easy and faster financial transactions and its awareness among people have allowed them to take more interest in the field thus opening up new and advanced ways of making payments. Crypto.com Referral Code with the growing demand of this global phenomenon more,new traders and business owners are now willing to invest in this currency platform despite its fluctuating prices however it is quite difficult to choose the best one when the market is full. In the list of crypto-currencies bit-coins is one of the oldest and more popular Crypto.com Referral Code for the last few years. It is basically used for trading goods and services and has become the part of the so-called computerized block-chain system allowing anyone to use it thus increasing the craze among the public, Crypto.com Referral Code.

    Common people who are willing to purchase BTC can use an online wallet system for buying them safely in exchange of cash or credit cards and in a comfortable way from the thousands of BTC foundations around the world and keep them as assets for the future. Due to its popularity, many corporate investors are now accepting them as cross-border payments and the rise is unstoppable. With the advent of the internet and mobile devices,information gathering has become quite easy as a result the BTC financial transactions are accessible and its price is set in accordance with people’s choice and preferences thus leading to a profitable investment with Crypto.com Referral Code. Recent surveys have also proved that instability is good for BTC exchange as if there is instability and political unrest in the country due to which banks suffer then investing in BTC can surely be a better option. Again bit-coin transaction fees are pretty cheaper and a more convenient technology for making contracts thus attracting the crowd. The BTC can also be converted into different fiat currencies and is used for trading of securities, for land titles, document stamping, public rewards and vice versa.

    Another advanced block-chain project is Ethereumor the ETH which has served much more than just a digital form of crypto-currency Crypto.com Referral Code and its popularity in the last few decades have allowed billions of people to hold wallets for them. With the ease of the online world,the ETH have allowed the retailers and business organizations to accept them for trading purposes, therefore, can serve as the future of the financial system.

    ReplyDelete
  9. Health Experts have proven that regular exercise coupled with a good diet allow you to live longer and healthier. In this busy day and age, not everyone has the time to go to the gym - resulting to a lot of overweight people that desperately need to exercise. A healthy alternative is for you to Buy Home Gym Equipments that you can store in your own home or even at your office. Here are some tips when buying home gym equipment.

    First, know your fitness goals and keep these goals in mind when you are buying home gym equipment. One of the biggest mistakes that people make is buying the biggest or trendiest fitness machine simply because they like how it looks. More often than not, these end up gathering dust in your storage rooms or garage because you never end up using them. It is important to take note of what particular type of physical activity you want or enjoy doing before you buy your exercise machine. If you are looking to loose a few pounds and you enjoy walking or hiking, a treadmill is the best option for you. If you are looking to tone your lower body while burning calories a stationary bike is your obvious choice. Similarly, Special Equipments for Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

    Second, set aside a budget before Buying Home Gym Equipments. Quality exercise machines do not come cheap. They are constantly exposed to wear and tear when they are used properly. So, pick machines that are built to last and have passed quality certifications to get the most out of your money. If you are operating on a tight budget, think about investing in several weights, We can Provide you High Quality Home Gym Equipments at Very Low Prices for your Complete Uses: Core Strength Exercises, Strength Training Weight Vests, Core Strength & Abdominal Trainers, Home Cardio Training, Strength Training Power Cages, Strength Training Racks & More.

    Its the Right Time to Buy Home Gym Equipments for you at Very Low Prices.

    ReplyDelete
  10. Archie 420 Dispensary is a trusted Cannabis dispensary base in Los Angeles California USA. It is one of the top dispensary in this part of the country. They do deliver Marijuana in the USA and to over 25 countries in the world. Buy White Russian weed online from USA You can always visit their dispensary in Los Angeles using the address on their website. Place your order and get served by the best dispensary in the planet. Have fun.

    ReplyDelete
  11. Crystal online pharmacy is a trusted online drug store with a wide range of products to suit the needs of our clients. Buy Misoprostol online Crystal Pharmacy do strive to offer the best service and ship products world wide. All the products listed on our website are Ava in stock. Expect your order to be processed Immediately when you send us your request. We deal with varieties of drugs for our customers satisfaction. We cross barriers with our products and struggle hard to meet human satisfaction. When shopping with us, Be safe and secured and you will realize how swift we are with our services.

    ReplyDelete
  12. Universal Gun sales is a trusted Firearm company base in Los Angeles California USA. It is one of the top Firearms Company in this part of the country. Buy suppressors online They do offer the best firearms deal in the USA and to over 25 countries in the world. You can always visit their shop in Los Angeles using the address on their website. Place your order and get served by the best Firearm Company in the planet. Have fun.

    ReplyDelete
  13. Online casino gambling is handier than gaming at the land-based casino. However it is also more dangerous. Rather than the usual risks which found while gaming, there's some risk of scams and fraud at web-based casino sites. These scams are really normal. The web is the simple target for all types of dishonest peoples and scammers, and few of them target only those who play on the internet. sweepstakes cafe

    ReplyDelete
  14. Get the inside knowledge. All you need to know about online casino bonuses. The online casino deposit bonus is a staple element of the online casino world. With the extreme growth of the online casinos on the Internet the casinos have come up with bonus programs to attract new players and keep existing players. รีวิวคาสิโน

    ReplyDelete
  15. The game apps are the beautifully designed apps that entertain and enthralls the target audience to the core that users can't resist reopening the app repetitively. The reason may be the intuitive designs, intriguing gameplay or bespoke layout which thrives the gamers. 바카라사이트

    ReplyDelete
  16. The game apps are the beautifully designed apps that entertain and enthralls the target audience to the core that users can't resist reopening the app repetitively. The reason may be the intuitive designs, intriguing gameplay or bespoke layout which thrives the gamers. 바카라사이트

    ReplyDelete
  17. The online casino system has grown tremendously in the last decade or so that it has been in existence - to a point where it is almost surpassing the brick and mortar casino system of the fore. Indeed, though hard statistics are hard to come by, chances are that at this point in time, there are more regular casino players who play on online casinos than there are playing in the traditional brick and mortar casinos. Comparing in terms of playing volumes (amounts of money deposited and winnings earned), online casinos are also likely to win over brick and mortar casinos hands down. 바카라

    ReplyDelete
  18. The game apps are the beautifully designed apps that entertain and enthralls the target audience to the core that users can't resist reopening the app repetitively. The reason may be the intuitive designs, intriguing gameplay or bespoke layout which thrives the gamers. 바카라사이트

    ReplyDelete
  19. A survey by the Consumer Federation of America shows that 27% of Americans believe that their best chance to gain $500,000 in their lifetime is to win a sweepstakes or lottery. Fortunately, building a comfortable retirement nest egg is easier than you think. Here are five steps to help you build a comfortable retirement: 파워볼 알고리즘

    ReplyDelete
  20. The best way to win the lotto is to go into it knowing what you're doing. The lottery is a game of chance where you pick your own numbers and see if you got the right combination when they make the drawing. There is no way to know the exact numbers that will be drawn, but you can figure out what they are "most likely" to be by using mathematics. 오토파워볼

    ReplyDelete
  21. Spiderman is one of the most popular superheroes. And because of that, many games were created under his name. Find out what they are and start enjoying. 라이브파워볼

    ReplyDelete
  22. Casino enthusiasts can nowadays take their passion to the next level by playing various popular casino games on the Internet. Online casinos are the perfect alternative to traditional casinos, as they allow people to enjoy a wide range of popular games from the comfort of their home. 스포츠토토

    ReplyDelete
  23. When visiting blogs, i always look for a very nice content like yours .     먹튀검증사이트

    ReplyDelete
  24. Hello! I recently would want to supply a large thumbs up to the great information you could have here within this post. We are returning to your website for more soon. creative writing

    ReplyDelete
  25. Oferecemos os melhores serviços para seguidores, curtidas, comentários e visualizações no Instagram. Os serviços são entregues de forma rápida, segura e por um preço honesto e barato.
    Todos os serviços são iniciados de forma automática e você pode fazer um teste grátis de seguidores, curtidas e visualizações no Instagram.

    O Go Followers surgiu em 2015 e durante alguns anos foi o melhor e maior site para comprar seguidores, curtidas e comentários no instagram. Com o passar dos anos evoluímos e em 2021 lançamos um novo site simples e intuitivo para aumentar a experiência dos mais de 150.000 clientes atendidos.

    Nossa ferramenta envia seguidores brasileiros reais e ativos em sua grande maioria para qualquer perfil do Instagram. Escolha o melhor pacote para comprar seguidores instagram de alta qualidade. Você poderá escolher alguns pacotes como seguidores com curtidas, seguidores masculinos, seguidores femininos e seguidores automáticos.
    Todos os pedidos são feitos de forma automática e iniciam em poucos minutos após a compra, tá esperando o que?

    ReplyDelete