Author Archives: yogsma

How to compare Strings in Java and more about Strings

Yes, I will be talking about one of the favorite topics or maybe the most argued topic of strings in programming languages. This post will cover how to use strings in Java.

Question

One of the beginner questions in Java is how to compare Strings in java?

Solution

The short answer is .equals compare the values of two strings and see if they are equal or not. Operator == compare the two string objects and see if they are referring to the same memory address.

Example:

String str1 = new String("test");

String str2 = new String("test");

str1.equals(str2) - This will return true.

str1 == str2 - This will return false.

 

Comment

Despite Java supports operator == for strings, it is not used for string comparison often. Object reference checks happen rarely. Another anomaly to this is if two strings are null.

Example:

String str1 = null;

String str2 = null;

str1 == str2 - this will return true.

str1.equals(str2) - this will throw null pointer exception (NPE).

Java offers another method called compareTo for String comparison. This can be used in following way

Example:

String str1 = "test";

String str2 = "test";

str1.compareTo(str2) == 0 - This will return true.

 

More about Strings

We all have seen StringBuffer, StringBuilder, StringWriter, StringTokenizer or just plain String. What are all these different aspects of String and when to use? Isn’t this too much to know when you just want to use a simple String object. This post will cover some information about all these different classes that Java offers.

StringBuffer

StringBuffers are thread-safe, they are just synchronized version of StringBuilder. StringBuffer offers some helpful methods like append and reverse.

Example:

StringBuffer sb = new StringBuffer();

sb.append("first string");

sb.toString();

 

StringBuilder

StringBuilder is not thread-safe, but they offer better performance than StringBuffer. You can say StringBuffer is thread-safe version of StringBuilder.

StringTokenizer

StringTokenizer is completely different from StringBuffer and StringBuilder as it is mainly used for splitting strings into token at a delimiter. StringBuffer and StringBuilder are used to build strings.

StringWriter

StringWriter is a character stream that collects the output in a string buffer. In short, you can say it uses StringBuffer underneath. This is an IO stream, very similar to File IO, but you can still access StringWriter even after stream has been closed.

Example:

StringWriter sw = new StringWriter();

sw.write("this is first string");

sw.toString();

 

Conclusion

In this article, we showed String comparison and different forms of String building. If you enjoyed this post, subscribe to my blog. If you want to read more about Strings, you can read here.

 

Guidelines to avoid null check statements

If you are tired of seeing NullPointer Exception, you are not alone. In this post, I show some guidelines to avoid null check. Have you ever seen code like below?

Object obj = anotherobj.getObject();
if(obj != null)
{
    // do something with obj
}

Imagine if you have to write such if-statement block for every object or variable you retrieve from different contract objects in your code, it would make the code cumbersome and unreadable. Also, it gives an impression of the naivety of developers in such cases.

I am writing this post based on a heavy discussion happening on StackOverflow Avoiding Null Statements. I am only using this post as a reference and writing my own guidelines based on my own experience. Answers to that post on StackOverflow are worth to checkout.

Guidelines to avoid checking null statements

  1. If callee keeps a contract of never returning a null, then the caller doesn’t have to add any check statement for a null value. But this is the basic premise a developer should follow when writing methods.
  2. Most of the time, the issue is not method returning null, but the logic implemented in these methods is not accurate. If the business logic of a method knows a way to handle errors in cases when it can return the right data, it should return an error instead of returning null.
public String getEmployeeInformation(String empcode)
{
   if (empcode == null)
   {
     // instead of returning null, throw an error
      throw new IllegalArgumentException(" empcode is null ");
   }
}

3.  Java 8 offers a new keyword optional 

public Optional<Employee> getEmployeeInfoWithSSN(String ssn) 
{ 
  .............. 
}

 

So if the employee information with particular SSN is not found, then the caller of this method has to explicitly think about the type system.

4.  Intellij Idea offers Java annotations like `Nullable` and `NotNull` 

5.  Write junit test cases for your classes which check for `assertNotNull()`

6.  Java 7 offers a utility method for Objects , Objects.requireNonNull();

Conclusion

In this post, I showed guidelines to avoid null check. Once you use these strategies, you make your life as a programmer way easier.

References

  1. Avoid null check statements
  2. Optional keyword

 

 

Consuming a SOAP Webservice over HTTPS

In the previous post, we talked about producing and consuming a SOAP web service here. This post will be a sequel to that post since recently I faced a similar issue during my project. In this post, we will talk about how to consume a SOAP Webservice over HTTPS. Since this will be a small post, we will not be posting any code on GitHub.

Problem –

While consuming a SOAP web service which is behind SSL, if you don’t handle SSL certificates, you will run into the following error


sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1351)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:156)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:925)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:860)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:728)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 15 more

 

Solution –

Basically this error is happening if your SOAP web service is on SSL and the client is trying to connect to web service, web service doesn’t recognize the client and throws this error.

To resolve this error, you can download an SSL certificate from the server where you are hosting the SOAP web service and import that certificate on your client machine’s Keystore. In a production environment, you should have a way to access this Keystore when a call is made to the web service.

Let’s assume that our web service from the post is on SSL, like https://localhost:8943/benefits/endpoints/users.wsdl. If you access this URL in the browser, you will be able to see the SSL certificate. Export this SSL certificate in base 64 format file, example sslcertificate.crt. Import this certificate in

keytool -import -alias sslcertificateofserver -keystore truststore.jks -storepass changeit -file sslcertificate.crt

Now, we will change the configuration class we wrote to configure web service components.


package com.betterjavacode.benefits.views;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

@Configuration
public class ClientAppConfig
{
   private Resource getKeyStore()
   {
     Environment.getProperty("betterjavacode.com.keystore");
   }

   private String getKeystorePassword()
   {
     Environment.getProperty("betterjavacode.com.keyStorePassword");
   }

   @Bean
   public Jaxb2Marshaller marshaller()
   {
     Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
     marshaller.setContextPath("com.betterjavacode.benefits.soap");
     return marshaller;
   }

   @Bean
   public UserClient userClient(Jaxb2Marshaller marshaller) 
   {
     // WSDL URL - http://localhost:8080/benefits/endpoints/users.wsdl
     UserClient uc = new UserClient();
     uc.setDefaultUri("http://localhost:8080/benefits/endpoints/users.wsdl");
     uc.setMarshaller(marshaller);
     uc.setUnmarshaller(marshaller);

     FileInputStream fis = new FileInputStream(getKeyStore());
     KeyStore ks = KeyStore.getInstance("JKS");
     ks.load(fis, getKeyStorePassword().toCharArray());

     try 
     {
       fis.close();
     } 
     catch (IOException e) 
     {
     }
     KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
     keyManagerFactory.init(ks, keyStorePassword.toCharArray());

     FileInputStream fisTS = new FileInputStream(getKeyStore());
     KeyStore ts = KeyStore.getInstance("JKS");
     ts.load(fisTS, trustStorePassword.toCharArray());

     try 
     {
       fisTS.close();
     } 
     catch(IOException e) 
     {
     }
     TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     trustManagerFactory.init(ts);

     HttpsUrlConnectionMessageSender messageSender = new HttpsUrlConnectionMessageSender();
     messageSender.setKeyManagers(keyManagerFactory.getKeyManagers());
     messageSender.setTrustManagers(trustManagerFactory.getTrustManagers());

     HostNameVerifier hv = new HostNameVerifier(){
        @Override
        public boolean verify( String hostname, SSLSession session)
        {
          return true;
        }
     }
     messageSender.setHostnameVerifier(hv);
     uc.setMessageSender(messageSender);
     return uc;
  } 
}

This change should fix the error about PKIX path building failed.

Conclusion –

In conclusion, we showed how to consume a SOAP Webservice over HTTPS by adding Keystore and Truststore check during runtime.

References

Notes from the book – Getting Real

Here, I will post the notes from the book Getting Real by 37Signals. You can download the copy on their website Getting Real.

The entire book can be summarized in the fact that you build a simple software and then add features. Do not complicate initial design and release. Get it done and ship it.

Notes

  • When there’s too many people involved, nothing gets done. The leaner you are, the faster – and better – things get done.
  • Getting real is a low-risk, low investment way to test new concepts.
  • Build less
    • Do less than your competitors to beat them. Solve the simple problems and leave hairy, difficult, nasty problems to everyone else. Instead of one-upping, try one-downing. Instead of outdoing, try underdoing.
    • When you solve your own problem, you create a tool that you’re passionate about. And passion is key. Passion means you’ll truly use it and care about it. And that’s the best way to get others to feel passionate about it too.
    • Outside money is plan B. Fund your own innovation and your ideas. Constraints drive innovation. If you’re creating software just to make a quick buck, it will show. Truth is a quick payout is pretty unlikely. So focus on building a quality tool that you and your customers can live with for a long time.
    • Launching something great that’s a little smaller in scope than planned is better than launching something mediocre and full of holes because you had to hit some magical time, budget and scope window.
    • Setting expectation is key.
    • The ability to change is key. Having everything fixed makes it touch to change. Injecting scope flexibility will introduce options based on your real experience building the product. Flexibility is your friend. Scope down. It’s better to make half a product than a half-assed product.
  • One bonus you get from having an enemy is a very clear marketing message. People are stroked by conflict. And they also understand a product by comparing it to others. With a chosen enemy, you’re feeding people a story they want to hear.
  • Your passion – or lack of – will shine through. The less your app is a chore to build, the better it will be. Keep it small and managable so you can actually enjoy the process.
  • When it comes to web technology, change must be easy and cheap. If you can’t change on the fly, you’ll lose ground to someone who can.
  • For first version of your app, start with only three people. That’s the magic number that will give you enough manpower yet allow you to stay streamlined and agile. Start with a developer, a designer and a sweeper.
  • Embrace the constraints, let them guide you. Constraints drive innovation and force focus. Instead of trying to remove them, use them to your advantage.
  • Details reveal themselves as you use what you’re building. You’ll see what needs more attention. You’ll feel what’s missing.
  • Don’t sweat stuff until you actually must. Don’t overbuild. Increase hardware and system software as necessary. If you’re slow for a week or two it’s not the end of the world. Just be honest to your customers, explain them you are experiencing some growing pains.
  • The customer is not always right. The truth is you have to sort out who’s right and who’s wrong for your app. The good news is that the internet makes finding the right people easier than ever.
  • In the beginning, make building a solid core product your priority instead of obsessing over scalability and server farms. Create a great app and then worry about what to do once it’s wildly successful.
  • The best software has a vision. The best software takes sides. When someone uses software, they’re not just looking for features, they are looking for an approach. Decide what your vision is and run with it.
  • What you really want to do is to build half a product that kicks ass.
  • The secret to building half a product instead of a half-ass product is saying no. Each time you are saying yes to a feature, you are adopting a child. The initial response is “not now”. If a request for a feature keeps coming back, that’s when we know it’s time to take a deeper look.
  • Build products and offer services you can manage. It’s easy to make promises. It’s much harder to keep them.
  • Don’t force conventions on people. Instead make your software general so everyone can find their own solution.
  • Just because x number of people request something, doesn’t mean you have to include it. Sometimes it’s better to just say no and maintain your vision for the product.
  • More isn’t the answer. Sometimes the biggest favor you can do for customers is to leave something out.
  • Running software is the best way to build momentum, rally your team, and flush out ideas that don’t work. It should be your number one priority from day one. Real things lead to real reactions. And that’s how you get to the truth.
  • Don’t expect to get it right for first time. Let the app grow and speak to you. Let it morph and evolve. With web-based software there’s no need to ship perfection. Design screens, use them, analyze them, and then start over again.
  • From Idea to implementation
    • Big questions – What does the app need to do? How will we know when it’s useful?  What exactly are we going to make? This is about high level ideas, not pixel-level details.
    • Get your ideas out of your head onto the paper. Sketches are quick, dirty and cheap.
    • Make an HTML version of that feature. Get something real posted, so everyone can see what it looks like on screen.
  • Preferences are evil because they create more software. More options require more code.
  • Decisions are temporary so make the call and move on. Done means you’re building momentum.
  • There’s no substitute for real people using your app in real ways. Get real data. Get real feedback. Then improve based on that info.
  • During alone time, give up IM, phone calls, meetings and emails. This is the time you can get in the zone for real work.
  • Simple rules for a meeting
    • Set a 30 minutes timer. Meeting should get over in 30 minutes. Period.
    • Invite as few people as possible.
    • Never have a meeting without a clear agenda.
  • Quick wins that you can celebrate, are great motivators. Release something today.
  • Too many apps start with a program-first mentality. That’s a bad idea. Programming is the heaviest component of building an app, meaning it’s the most expensive and hardest to change. Instead, start by designing first.
  • For each screen, you need to consider three possible states:
    • Regular
    • Blank
    • Error
  • You need to speak same language as your audience too. Just because you’re writing a web app doesn’t mean you can get away with technical jargon. Good writing is good design.
  • The fewer screens you have to worry about, the better they’ll turn out.
  • Solving 80% of the original problem for 20% of the effort is a major win.
  • Don’t be afraid to say no to feature requests that are hard to do.
  • Your code can guide you to fixes that are cheap and light.
  • Functional specs are useless. You know the least about something when you begin to build it. The more you build it, the more you use it, the more you know it.
  • Write one page story about what the app needs to do. Use plain language and make it quick. If it takes more than one page to explain it, then it’s too complex.
  • Build, don’t write. If you need to explain something, try mocking up and prototyping it rather than writing a long-winded document.  An actual interface or prototype is on its way to becoming a real product.
  • To build a better interface, do as your customers do and you’ll understand them better.
  • Your product has a voice and it is talking to your customer 24 hours a day.
  • Make signup and cancellation a painless process. Make sure people can get their data out if they decide to leave.
  • Hollywood Launch
    • Teaser
    • Preview
    • Launch
  • Start off by creating a blog that not only touts your product but offers helpful advice, tips, tricks, links etc.
  • Get advance buzz and signups going asap.
  • Promote through education
    • When the subject you are teaching is your app, it serves dual purpose. You can give something back to the community that supports you and score some nice promotional exposure at the same time.
    • Update your blog regularly and post tips & tricks, articles that help your customer and community
  • If the comments you are receiving for your app, are negative, pay attention. Show you’re listening. Respond to critiques thoughtfully.
  • Listening to customers is the best way to get in tune with your product’s strengths and weaknesses.
  • Strive to build a tool that requires zero training. The less complex is your app, the less you’ll need to help people out.
  • Be as open, honest and transparent as possible. Don’t keep secrets or hide behind spin. An informed customer is your best customer.
  • Go with the flow – be open to new paths and changes in direction. Part of the beauty of web app is its fluidity.

If you enjoyed these notes from the book Getting Real, subscribe to my blog here.

 

How To – Concepts of Websphere

In the enterprise Java application world, Websphere is the most used application server. IBM has created WebSphere as its product for a long time now. Other alternatives have been JBoss and Tomcat. (Though tomcat is not a full-fledged application server and there is a debate about it.)

In this post, we will discuss the basic concepts of IBM Websphere Application Server. If you have any questions, please post them in the comment and I will try to answer them to the best of my abilities.

Application Server

The primary component of IBM WebSphere is an application server. The server runs the actual code of your application. Each server runs its own Java Virtual Machine (JVM). All configurations can have one or more application servers. In other words, an application server can run on only one node, but one node can support many application servers.

Node

It is a logical group of application server processes that share common configuration repositories. A single node is related to a single profile. Likewise, one machine can have more than one node. A node can contain zero or more application servers.  An XML file stores the configuration information that Node is useful for.

Cell

A cell is a grouping of nodes into a single administrative domain. A cell can consist of multiple nodes, all administered from a deployment manager server.

Node Agent

A node agent is created on Node when a node is federated. The node agent works with the deployment manager for administrative activities.

Deployment Manager

Above all, with the deployment manager, you can administer multiple nodes from one centralized manager. This deployment manager works with node agent on each node. Therefore, application server nodes must be federated with the deployment manager before they can be managed by the deployment manager.

In conclusion, we discussed the basic concepts of the IBM WebSphere application server. Hence, subscribe to my blog here.