Featured FREE Whitepapers

What's New Here?

java-interview-questions-answers

4 Foolproof Tips Get You Started With JBoss BRMS 6.0.3

Last week Red Hat released the next version of JBoss BRMS, labeled 6.0.3 and it is available in their Customer Portal for those with a subscription. If you are curious as to what is new in this release, see the release notes and the rest of the documentation online in the Customer Portal.   What we are looking for are some easy ways to get started with this new release and this article has just the things you are looking for. We will give you a foolproof installation to get you started, then show you a complete online web shop project you can experiment with, provide a completed Cool Store project for your evaluation needs and finally provide you with an advanced integration example that ties together JBoss BRMS with  JBoss Data Virtualization. Tip #1This is the first step in your journey, getting up and running without a lot of hassle or wasted time. This starts with the JBoss BRMS Install Demo which gets you started with a clean installation, a user to get started, and the product open in your browser for you to get started designing your rules, events and rule flows.     Tip #2 Now you have an installation, you are looking at the product, but what should you do next? No worries, we have a very nice hands on tutorial for you that shows you how to take your installation from zero to a full blown online web shopping cart application. You will build the rules, event and rule flow that is needed to realize this application. Check this online workshop here:  Tip #3 Maybe you are just looking to evaluate or just play with the product we also have a fully finished Cool Store retail example for you to enjoy.This is the fully completed online web shopping cart application with rules, decision table, event and rule flow that you can also put together yourself (see Tip #2). This project also has links to more information and details around what it is made of and also provides a video walk through. Give it a go and install the Cool Store Demo project to evaluate JBoss BRMS today.   Tip #4 The final step is to examine more advanced use cases like integration cases using JBoss Data Virtualization.It just so happens we have an interesting project, JBoss BRMS & JBoss DV Integration Demo, that is just as easy to install as the previous ones and it demonstrates the value of decision logic being used with diverse data sources in an enterprise. Also be sure to enjoy the extensive video collection that is presented in the projects documentation, they walk you through all the details. We hope these foolproof tips are all you need to get started with JBoss BRMS and the new 6.0.3 release.Reference: 4 Foolproof Tips Get You Started With JBoss BRMS 6.0.3 from our JCG partner Eric Schabell at the Eric Schabell’s blog blog....
apache-maven-logo

Maven excludes all transitive dependencies

“Transitive dependencies are a new feature in Maven 2.0. This allows you to avoid needing to discover and specify the libraries that your own dependencies require, and including them automatically.” I had a problem, where some dependencies were available in the run time, but they weren’t available in the public nexus repositories. For an example, Hibernate depends on the Sun JTA API JAR and it is not available in the central Maven repository because it cannot be freely redistributed. So when building the project, it was trying to download transitive dependencies and got failed. So I looked  a way to ignore all the transitive dependencies, and found that we can ignore all the associated dependencies of a given dependency. There we can exclude all transitive dependencies without specifying groupId and artifactId of the dependencies. So need to use astric(*) character as groupid and artifactid of the dependency. <dependency> <groupId>sample.ProjectA</groupId> <artifactId>Project-A</artifactId> <version>1.0</version> <scope>compile</scope> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency> This wildcard transitive dependencies ignoring is available with maven 3.2.1 release. So it’s worth to upgrade into latest maven version.Reference: Maven excludes all transitive dependencies from our JCG partner Chandana Napagoda at the Chandana Napagoda blog blog....
software-development-2-logo

Diction in Software Development (i.e. Don’t be a d1ck!)

Over the years, I’ve come to realize how important diction is in software development (and life in general). It may mean the difference between a 15 minute meeting where everyone nods their heads, and a day long battle of egos (especially when you have a room full of passionate people). Here are a couple key words and phrases, I’ve incorporated into my vernacular. Hopefully, these will help out next time you are in an architecture/design session (or a conversation with your significant other).     “I appreciate X”: Always use the phrase, “I appreciate that…” in response to a point. But more importantly, *mean* it. It is an age-old adage, but when talking, it is best to listen. Once you’ve heard the other party, try to understand and appreciate what they are saying. Then, let them know that you appreciate their point, before adding additional information to the conversation (tnx to +Jeff Klein for this one). “I am not passionate about X” To drive consensus, I try to hold focused design discussions. During those discussions, I’d try to squash tangential topics. I used to say, “I don’t care about that, do whatever, we’re focused on X”. Obviously, that would aggravate the people that did care about X. These days, I use the phrase, “I am not passionate about that…”. People have different value-systems. Those value systems drive different priorities. It is important to acknowledge that, while also keeping discussions focused (tnx to +Bob Binion for this one). “What is the motivation / thought process behind X?” People enter meetings with different intentions. Those intentions often drive their positions.  It is tremendously important to understand those motivations, especially in larger companies or B2B interactions where organizational dynamics come into play. In those contexts, success is often gauged by the size of one’s department. Thus, suggesting an approach that eliminates departments of people is a difficult conversation. Sometimes you don’t have the right people in the room for that conversation.  I’ve found that it is often useful to tease out motivations and the thought processes behind positions. Then you can address them directly, or at least “appreciate” that motivations are in conflict. Eliminate the “But’s” This is a simple change, but a monumental difference in both diction and philosophy. If you listen to *yourself*, you’ll likely make statements like, “X is great, but consider Y”. You’ll be surprised how many of these can actually be changed to, “X is great, *and* consider Y”. Believe me, this changes the whole dynamic of the conversation. AND, this actually begins to change the way you think… When you view the world as a set of boolean tradeoffs, “either you can have X or you can have Y”, you never consider the potential of having X *and* Y. Considering that possibility is at the root of many innovations (e.g. I want multi-dimensional analytics AND I want them in real-time!). F. Scott Fitzgerald said, “The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function.” These days, this is how I try to live my life, embracing the “what if?” and then delivering on it. (tnx to +Jim Stogdill and +William Loftus for this perspective)Reference: Diction in Software Development (i.e. Don’t be a d1ck!) from our JCG partner Brian ONeill at the Brian ONeill’s Blog blog....
software-development-2-logo

Stop Chatting, Start Coding

The first principle of eXtremely Distributed Software Development (XDSD) states that “everyone gets paid for verified deliverables”. This literally means that, in order to get paid, every programmer has to write the code, commit it to the repository, pass a code review and make sure the code is merged into the destination branch. Only then, is his result appreciated and paid for.          For most of my clients this already sounds extreme. They are used to a traditional scheme of paying per hour or per month. They immediately realize the benefits of XDSD, though, because for them this approach means that project funds are not wasted on activities that don’t produce results. But that’s not all. This principle also means that nobody is paid for anything except tasks explicitly assigned to him/her. Thus, when a programmer has a question about current design, specification, configuration, etc. — nobody will be interested in answering it. Why not? Because there is no payment attached to this. Answering questions in Skype or Hipchat or by email is something that is not appreciated in XDSD in any way. The project simply doesn’t pay for this activity. That’s why none of our programmers do this. We don’t use any (I mean it!) informal communication channels in XDSD projects. We don’t do meetings or conference calls. We never discuss any technical issues on Skype or by phone. So, how do we resolve problems and share information? We use task tracking systems for that. When a developer has a question, he submits it as a new “ticket”. The project manager then picks it up and assigns it to another developer, who is able to answer it. Then, the answer goes back through the tracking system or directly into the source code. The “question ticket” gets closed when its author is satisfied with the answer. When the ticket is closed, those who answered it get paid. Using this model, we significantly improve project communications, by making them clean and transparent. We also save a lot of project funds, since every hour spent by a team member is traceable to the line of code he produced. You can see how this happens in action, for example, in this ticket (the project is open source; that’s why all communications are open): jcabi/jcabi-github#731. One Java developer is having a problem with his Git repository. Apparently he did something wrong and couldn’t solve the problem by himself. He asked for help by submitting a new bug to the project. He was paid for the bug report. Then, another team member was assigned to help him. He did, through a number of suggestions and instructions. In the end, the problem was solved, and he was also paid for the solution. In total, the project spent 45 minutes, and the problem was solved. Related Posts You may also find these posts interesting:Incremental Requirements With Requs How Hourly Rate Is Calculated How XDSD Is Different Github Guidelines Definition Of DoneReference: Stop Chatting, Start Coding from our JCG partner Yegor Bugayenko at the About Programming blog....
software-development-2-logo

Single Sign-On with the Delegated Access Control Pattern

Suppose a medium-scale enterprise has a limited number of RESTful APIs. Company employees are allowed to access these APIs via web applications while they’re behind the company firewall. All user data is stored in a Microsoft Active Directory, and all the web applications are connected to a Security Assertion Markup Language (SAML) 2.0 identity provider to authenticate users. The web applications need to access back-end APIs on behalf of the logged-in user.          The catch here is this last statement: “The web applications need to access back-end APIs on behalf of the logged-in user.” This suggests the need for an access-delegation protocol: OAuth. However, users don’t present their credentials directly to the web application—they authenticate through a SAML 2.0 identity provider. In this case, you need to find a way to exchange the SAML token received in the SAML 2.0 Web SSO protocol for an OAuth access token, which is defined in the SAML grant type for the OAuth 2.0 specification. Once the web application receives the SAML token, as shown in step 3 of the above figure, it has to exchange it with an access token by talking to the OAuth authorization server. The authorization server must trust the SAML 2.0 identity provider. Once the web application gets the access token, it can use it to access back-end APIs. The SAML grant type for OAuth doesn’t provide a refresh token. The lifetime of the access token issued by the OAuth authorization must match the lifetime of the SAML token used in the authorization grant. After the user logs in to the web application with a valid SAML token, the web app creates a session for the user from there onward, and it doesn’t worry about the lifetime of the SAML token. This can lead to some issues. Say the SAML token expires, but the user still has a valid browser session in the web application. Because the SAML token has expired, you can expect that the corresponding OAuth access token obtained at the time of user login has expired as well. Now, if the web application tries to access a back-end API, the request will be rejected because the access token is expired. In such a scenario, the web application has to redirect the user back to the SAML 2.0 identity provider, get a new SAML token, and exchange that token for a new access token. If the session at the SAML 2.0 identity provider is still live, then this redirection can be made transparent to the end user. This is one of the ten API security patterns covered in my book Advanced API Security. You can find more details about this from the book.Reference: Single Sign-On with the Delegated Access Control Pattern from our JCG partner Prabath Siriwardena at the Facile Login blog....
software-development-2-logo

Legacy Code To Testable Code #1: Renaming

This post is part of the “Legacy Code to Testable Code” series. In the series we’ll talk about making refactoring steps before writing tests for legacy code, and how they make our life easier. Renaming is easy and is usually safe. Most IDEs have the functionality, and most languages (I’m not talking about you, C++) lend themselves to safe renaming. Why start at renaming? It helps make the code more understandable. When we can understand the code better, the tests we write will be more effective. In other words: don’t write tests for code you don’t understand. Renaming is an easy win on the way there. Naming things is maybe the hardest thing in programming. Lots of code grows complex because we slap “Manager” as a class suffix. It’s like giving ourselves permission to make room for code we don’t know where to put. It doesn’t end with one class, though. Once there’s an AccountManager class, soon BankManager and CustomerManager will appear. The same goes for a getValidCustomer method that should really be a void method, but instead returning a success code. When we’re sloppy, we allow for generalized, confusing names to flourish in the code. When names are vague, all kinds of implementation pours in. It doesn’t matter if I wrote the code, or somebody who doesn’t work here anymore did. Legacy code can always do with improvement. One of our main goals in writing tests is to improve code. But improving code safely without effort is a bonus. Risk is key here. If the IDE can do the renaming safely, we are more likely to do it. If, on the other hand, we need to rely on manual changes, chances are we won’t. Mostly, when we’re doing pre-test renaming, we’ll concentrate more on method names, and maybe variables in the code. These are usually small enough for picking good names (and if not enough, can be extracted). Renaming classes is usually harder, because they generally cover more ground (remember how that happened, kids?). Renaming is a part of our familiarization with the code, before testing it. Even if I don’t know what to test, making the code readable helps me not only understand what it does, but also how to test it. Renaming variables We usually name by scope, if at all. Making the distinction helps in making sense. If there’s already a convention in the code (like m_ prefix for fields), make sure that the convention is followed in the code you’re observing. If there isn’t a convention, start one. Compare the type of the variable to the method and to their type. If it can be improved, rename it. For example: Acct a = BankManager.getAccount(); We can rename a to account, and the we wouldn’t need to remember what a is in the next 500 lines of our method. If the method returning the value seems confusing, its type can help you rename it. Don’t skimp on vowels! It’s starts as a clever way to save screen space, but after the vowels go, we think about other options, and soon we’re left with: acct. Not only less readable, but also annoying. Make the code readable. Apart from renaming, if you can tidy up the code, put the declarations into one area, the beginning of class or methods. If you find declaration spread around, clean it up. Renaming methods Method are harder to rename because they tend to do more, because of the aforementioned sloppiness. We usually start with a simple name, and then find the method the best place to do a couple things more . We soon have a big method, with a name reminding us of what the method was back then. This is confusing to the reader, and of course makes it harder to test. But we’re not there yet. For now, make the renaming simple: If the method returns something prefix it with get. If it does something, make sure it start with a verb like set or make or call. Check out the last lines of the method, or the exit points. Usually (not always), from the structure you’ll see what is the purpose of the function. Try to make the name fit the purpose. It may not be always the case though, so be careful. Don’t skimp on vowels! And don’t worry about the screen space. Make method names convey their purpose, and use the entire alphabet for it. Renaming classes These are the hard ones to rename, and I usually recommend not to (at least not until you cut them down to size). We only see the types at declaration or creation time, so renaming them won’t bring us much benefit in terms of understanding. It might be beneficial to identify a base or derived class in its name. Mostly it won’t, and lends itself to get nasty later, when adding a third hierarchy layer, for example.  I still like an I prefix to an interface, although it may get me killed in some communities. And always remember kids: Don’t skimp on vowels! Applies to classes too. Now that we’re done with renaming, it’s extraction time. Up next.Reference: Legacy Code To Testable Code #1: Renaming from our JCG partner Gil Zilberfeld at the Geek Out of Water blog....
coderpower-logo

Show your dev skills and win with CoderPower

CoderPower and Salesforce1 launch a series of coding challenges in the USA and in Europe. CoderPower is a platform where developers from all around the globe compete to get points and win prizes. After a summer competition with Salesforce1 and a constest with IBM in September, Salesforce1 launches a new series of challenges. The aim is simple: try to be the best developer at every coding challenge to win prizes. Each challenge has a time limit and the faster you solve the challenge, the more points you will get. At the end, Salesforce1 rewards the winner of each challenge and the overall best developer with cool prizes. A nice prizepool will reward the winners at the end of the challenge. In Europe, the overall winner will get a 3D Printer while people ranking 2nd and 3rd will receive a Samsung Gear 2. Also, the highest scorer of each challenge will get a Sphero.In the USA, the grand prize is an Xbox One with Kinect, while winners of challenges can win Quadcopter Drones, FitBits bracelets and Jambox Bluetooth Speakers. If you live in Europe, you may access the #Salesforce1Challenge at the following address: http://salesforcedevs.coderpower.com. Sign up before October 21st. If you live in the USA, login to salesforce.coderpower.com to try to win the challenges. The USA challenge will come to an end on November 10th. And finally, add the “JavaCodeGeeks” tag when you complete your profile on CoderPower. You will have a dedicated Leaderboard for JavaCodeGeeks readers, and the best developer will get a special prize: 1 Google Cardboard (see the JavaCodeGeeks leaderboard) ...
jboss-jbpm-logo

5 Handy Tips From JBoss BPM Suite For Release 6.0.3

Last week Red Hat released the next version of JBoss BPM Suite, labeled 6.0.3 and it is available in their Customer Portal for those with a subscription. If you are curious as to what is new in this release, see the release notes and the rest of the documentation online in the Customer Portal. What we are looking for are some easy ways to get started with this new release and this article has just the things you are looking for. We will give you a foolproof installation to get you started, then show you a complete HR employee rewards project you can experiment with, provide a completed HR employee rewards project for your evaluation needs, give you a list of more demo projects you might like to explore and finally provide you with an advanced integration example that ties together JBoss BPM Suite with JBoss Fuse.Tip #1 This is the first step in your journey, getting up and running without a lot of hassle or wasted time. This starts with the JBoss BPM Suite Install Demo which gets you started with a clean installation, a user to get started, and the product open in your browser for you to get started designing your rules, events and BPM projects. Tip #2 Now you have an installation, you are looking at the product, but what should you do next? No worries, we have a very nice hands on tutorial for you that shows you how to take your installation from zero to a full blown online HR Employee Rewards process project. You will work with the domain modeler, the form modeler and the process designer to realize this application. Check this online workshop here:Tip #3 Maybe you are just looking to evaluate or just play with the product we also have a fully finished HR employee rewards example for you to enjoy.This is the fully completed HR application with a domain model, human task forms and BPM process that you can also put together yourself (see Tip #2). This project also has links to more information and details around what it is made of and also provides a video walk through. Give it a go and install the HR Employee Rewards Demo project to evaluate JBoss BPM Suite today. Tip #4 There are many more demo projects you can look at to dig deeper into various aspects of the product, here is a list for your explorations:JBoss BPM Suite Mortgage demo (financial / web service ) JBoss BPM Suite Document Integration demo ( telco / ECM / CMIS) JBoss BPM Suite Governance demo (DTGov / S-RAMP) JBoss BPM Suite Generic Loan demo (financial / signals) JBoss BPM Suite Customer Evaluation demo (rules) JBoss BPM Suite & JBoss FSW Integration demoThese should keep you busy and let you dig into the various aspects of this product. Tip #5 The final step is to examine more advanced use cases like integration cases using JBoss Fuse.It just so happens we have an interesting project, JBoss BPM Suite & JBoss Fuse Integration Demo, that is just as easy to install as the previous ones and it demonstrates the integration of a Camel route with a BPM process. Also be sure to watch the video in the project documentation that walks you through all the details. We hope these handy tips are all you need to get started with JBoss BPM Suite’s new 6.0.3 release.Reference: 5 Handy Tips From JBoss BPM Suite For Release 6.0.3 from our JCG partner Eric Schabell at the Eric Schabell’s blog blog....
software-development-2-logo

WSO2 Identity Server 5.0.0 Authentication Framework

The WSO2 Identity Server 5.0.0 takes the identity management into a new direction. No more there will be federation silos or spaghetti identity anti-patterns. The authentication framework we introduced in IS 5.0.0 powers this all. The objective of this blog post is to introduce high-level concepts associated with the authentication framework. Inbound Authenticators The responsibility of inbound authenticators is to identify and parse all the incoming authentication requests and then build the corresponding response.  A given inbound authenticator has two parts.Request Processor Response BuilderFor each protocol supported by WSO2 IS – there should be an inbound authenticator. Out-of-the-box it comes with inbound authenticators for SAML 2.0, OpenID, OpenID Connect, OAuth 2.0, and WS-Federation (passive). In other words, the responsibility of the SAML 2.0 request processor is to accept a SAML request from a service provider, validate the SAML request and then build a common object model understood by the authentication framework and handover the request to it. The responsibility of the SAML response builder is to accept a common object model from the authentication framework and build a SAML response out of it. Both the request processors and the response builders are protocol aware while the authentication framework is not coupled to any protocol. Local Authenticators The responsibility of the local authenticators is to authenticate the user with locally available credentials. This can be either username / password or even IWA (Integrated Windows Authentication). Local authenticators are decoupled from the Inbound Authenticators. Once the initial request is handed over to the authentication framework from an inbound authenticator, the authentication framework talks to the service provider configuration component to find the set of local authenticators registered with the service provider corresponding to the current authentication request. Once the local authentication is successfully completed, the local authenticator will notify the framework. The framework will now decide no more authentication is needed and hand over the control to the corresponding response builder of the inbound authenticator. You can develop your own local authenticators and plug them into the Identity Server. Outbound / Federated Authenticators The responsibility of the federated authenticators is to authenticate the user with an external system. This can be with Facebook, Google, Yahoo, LinkedIn, Twitter, Salesforce or any other identity provider. Federated authenticators are decoupled from the Inbound Authenticators. Once the initial request is handed over to the authentication framework from an inbound authenticator, the authentication framework talks to the service provider configuration component to find the set of federated authenticators registered with the service provider corresponding to the current authentication request. A federated authenticator has no value unless its associated with an identity provider. For example IS 5.0.0 out-of-the-box supports SAML 2.0, OpenID, OpenID Connect, OAuth 2.0 and WS-Federation (passive). The SAML 2 .0 federated authenticator itself has no value. It has to be associated with an Identity Provider. Google Apps can be an identity provider – with the SAML 2.0 federated authenticator. This federated authenticator knows how to generate a SAML request to the Google Apps and process a SAML response from it. There are two parts in a federated authenticator.Request Builder Response ProcessorOnce the federation authentication is successfully completed, the federated authenticator will notify the authentication framework. The framework will now decide no more authentication is needed and hand over the control to the corresponding response builder of the inbound authenticator. Both the request builder and the response processor are protocol aware while the authentication framework is not coupled to any protocol. You can develop your own federated authenticators and plug them into the Identity Server. Request-path Authenticators This is a special type of authenticator. Request-path authenticator is always a local authenticator. Once the initial request is handed over to the authentication framework from an inbound authenticator, the authentication framework talks to the service provider configuration component to find the set of request-path  authenticators registered with the service provider corresponding to the current authentication request. Then the framework will check whether there is any request-path authenticator applicable for the initial authentication request. In other words, a request path authenticator will get executed only if the initial authentication request brings the applicable set of credentials with it. The request-path authenticators always require the user credentials to be present in the initial authentication request itself. This does not need any end-user interactions with the Identity Server. Once the request-path authentication is successfully completed, the request-path authenticator will notify the authentication framework. The framework will now decide no more authentication is needed and hand over the control to the corresponding response builder of the inbound authenticator. Identity Provider Configuration The responsibility of the Identity Provider configuration in IS 5.0.0 is to represent external Identity Providers. These external identity providers can be Facebook, Yahoo, Google, Salesforce, Microsoft Windows Live or whoever. If we want to authenticate users against these identity providers, then we must associate one or more Federated Authenticators. For example, if we want to authenticate users against Google Apps, then we need to associate SAML 2.0 authenticator with Salesforce identity provider. If we want to authenticate users against Yahoo – then we need to associate OpenID authenticator with it. To make this process much easier Identity Server also comes with a set of more specific federated authenticators as well. For example, if you want authenticate against Facebook, you do not need to configure OAuth 2.0 authenticator – instead you can directly use the Facebook federated authenticator.Each identity provider configuration can also maintain a claim mapping. This is to map its own set of claims to the identity server’s claims. When the response from an external identity provider is received by the response processor component of the federated authenticator – before it hands over the control to the authentication framework, the response processor will create a name/value pair of user claims received in the response from the identity provider. These claims are specific to the external identity provider. Then its the responsibility of the authentication framework to read the claim mapping configuration from the identity provider component and do the conversion. So, while inside the framework, all the user claim values will be in a common format.Service Provider Configuration The responsibility of the Service Provider configuration is to represent external service providers. These external service providers can be a web application, a mobile application, a liferay portal, Salesforce (Salesforce can be both a service provider and an identity provider), Google Apps (Google Apps can be both a service provider and an identity provider) and many more. In the service provider configuration you define how the service provider talks to the identity server – this is via inbound authenticators. When you register a service provider you need to associate one or more inbound authenticators with it.The service provider configuration also defines how to authenticate users. This can be via a local authenticator, request-path authenticator or federated authenticator. Based on this configuration, Identity Server knows when it receives an authentication request (via an inbound authenticator) how to authenticate the user based on the service provider who initiates it.Each service provider configuration can also maintain a claim mapping. This is to map its own set of claims to the identity server’s claims. When the authentication framework hands-over a set of claims (which it gets from the local user store or from an external identity provider) to the response builder of the inbound authenticator, the framework will talk to the service provider configuration component, find the claim mapping and do the claim conversion. Now the response builder will receive the claims in a manner understood by the corresponding service provider.Multi-option Authentication The service provider can define how to authenticate users at the Identity Server, for authentication requests initiated by it. While doing that, each service provider can pick more than one authenticators – so, the end user will get multiple login options. This can be a combination of local authenticators and federated authenticators. Multi-level (multi-factor) Authentication The service provider can define how to authenticate users at the Identity Server, for authentication requests initiated by it. While doing that, each service provider can define multiple steps and for each step it can pick more than one authenticators.The authentication framework will track all the authenticators in each step and will proceed to the next step only if the user authenticates successfully in the current step. Its an AND between steps while its an OR between the authenticators in a given step.Reference: WSO2 Identity Server 5.0.0 Authentication Framework from our JCG partner Prabath Siriwardena at the Facile Login blog....
akka-logo

Akka Notes – Actor Messaging – Request and Response – 3

Last time when we saw Actor messaging, we saw how fire-n-forget messages are sent (Meaning, we just send a message to the Actor but don’t expect a response from the Actor). Technically, we fire messages to Actors for its side-effects ALL THE TIME. It is by design. Other than not responding, the target Actor could ALSO do the following with that message:        Send a response back to the sender (in our case, the TeacherActor would respond with a quote back to the StudentActor OR Forward a response back to some other Actor who might be the intended audience which in turn might respond/forward/have a side-effect. Routers and Supervisors are examples of those cases (we’ll look at them very soon).Request & Response In this write-up, we’ll be focussing only on Point 1 – the request-response cycle.The picture conveys what we are trying to achieve this time. For sake of brevity, I didn’t represent the ActorSystem, Dispatcher or Mailboxes in the picture.The DriverApp sends an InitSignal message to the StudentActor. The StudentActor reacts to the InitSignal message and sends a QuoteRequest message to the TeacherActor. The TeacherActor, like we saw in the first discussion, responds with a QuoteResponse. The StudentActor just logs the QuoteResponse to the console/logger.We’ll also cook up a testcase to verify it. Let’s look at these 4 points in detail now : 1. The DriverApp sends an InitSignal message to the StudentActorBy now, you would have guessed what would the DriverApp do. Just 4 things :Initialize the ActorSystem //Initialize the ActorSystem val system = ActorSystem("UniversityMessageSystem") Create the TeacherActor //create the teacher actor val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor") Create the StudentActor //create the Student Actor - pass the teacher actorref as a constructor parameter to StudentActor val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor") You’ll notice that I am passing in the ActorRef of the TeacherActor to the constructor of the StudentActor so that the StudentActor could use the ActorRef for sending messages to the TeacherActor. There are other ways to achieve this (like passing in the Props) but this method would come in handy when we look at Supervisors and Routers in the following write-ups. We’ll also be looking at child actors pretty soon but that wouldn’t semantically be the right approach here – Student creating Teacher doesn’t sound nice. Does it? Lastly, The DriverApp would then send an InitSignal to the StudentActor, so that the StudentActor could start sending the QuoteRequest message to the TeacherActor.//send a message to the Student Actor studentRef ! InitSignal That’s pretty much the DriverClass. The Thread.sleep and the ActorSystem.shutdown are just to wait for a couple of seconds for the message sending to finish before we finally shut down the ActorSystem. DriverApp.scala package me.rerun.akkanotes.messaging.requestresponseimport akka.actor.ActorSystem import akka.actor.Props import me.rerun.akkanotes.messaging.protocols.StudentProtocol._ import akka.actor.ActorRefobject DriverApp extends App {//Initialize the ActorSystem val system = ActorSystem("UniversityMessageSystem")//construct the teacher actor val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor")//construct the Student Actor - pass the teacher actorref as a constructor parameter to StudentActor val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")//send a message to the Student Actor studentRef ! InitSignal//Let's wait for a couple of seconds before we shut down the system Thread.sleep(2000)//Shut down the ActorSystem. system.shutdown()} 2. The StudentActor reacts to the InitSignal message and sends a QuoteRequest message to the TeacherActor AND 4. The StudentActor receives the QuoteResponse from TeacherActor and just logs to the console/logger Why did I combine Points 2 and 4? Because it is so simple you’ll hate me if I separate them.So, Point 2 – the StudentActor receives the InitSignal message from the DriverApp and sends QuoteRequest to the TeacherActor. def receive = { case InitSignal=> { teacherActorRef!QuoteRequest } ... ... That’s it !!! Point 4 – The StudentActor logs the message that it receives from the TeacherActor.Just, as promised : case QuoteResponse(quoteString) => { log.info ("Received QuoteResponse from Teacher") log.info(s"Printing from Student Actor $quoteString") } I am sure you’d agree that it almost looks like pseudocode now. So, the entire StudentActor class looks like : StudentActor.scala package me.rerun.akkanotes.messaging.requestresponseimport akka.actor.Actor import akka.actor.ActorLogging import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._ import me.rerun.akkanotes.messaging.protocols.StudentProtocol._ import akka.actor.Props import akka.actor.ActorRefclass StudentActor (teacherActorRef:ActorRef) extends Actor with ActorLogging {def receive = { case InitSignal=> { teacherActorRef!QuoteRequest }case QuoteResponse(quoteString) => { log.info ("Received QuoteResponse from Teacher") log.info(s"Printing from Student Actor $quoteString") } } } 3. The TeacherActor responds with a QuoteResponse. This is the exact same code as we saw in the fire-n-forget write-up. The TeacherActor receives a QuoteRequest message and sends QuoteResponse back. TeacherActor.scala package me.rerun.akkanotes.messaging.requestresponseimport scala.util.Randomimport akka.actor.Actor import akka.actor.ActorLogging import akka.actor.actorRef2Scala import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._class TeacherActor extends Actor with ActorLogging {val quotes = List( "Moderation is for cowards", "Anything worth doing is worth overdoing", "The trouble is you think you have time", "You never gonna know if you never even try")def receive = {case QuoteRequest => {import util.Random//Get a random Quote from the list and construct a response val quoteResponse = QuoteResponse(quotes(Random.nextInt(quotes.size)))//respond back to the Student who is the original sender of QuoteRequest sender ! quoteResponse} } } Testcases Now, our testcase would simulate the DriverApp. Since, the StudentActor just logs the message and we won’t be able to assert on the QuoteResponse itself, we’ll just assert the presence of the log message in the EventStream (just like we talked last time). So, our testcase looks like : "A student" must {"log a QuoteResponse eventually when an InitSignal is sent to it" in {import me.rerun.akkanotes.messaging.protocols.StudentProtocol._val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor") val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")EventFilter.info (start="Printing from Student Actor", occurrences=1).intercept{ studentRef!InitSignal } } } Code The entire project could be downloaded from github here. Next up, we’ll see how to use schedulers in Akka and monitoring your Akka app using Kamon.Reference: Akka Notes – Actor Messaging – Request and Response – 3 from our JCG partner Arun Manivannan at the Rerun.me blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close