Description

While converting c# code to java there are several lambdas that c# has that were a little difficult to find a port to java. One of these was C Sharp’s FirstOrDefault lambda expression. Java has an equivalent stream. We can use the findFirst and if it doesn’t find anything then we can return a null. This in essence is the same as the method in c# – return first or null unless I specify otherwise. While the java version is slightly more verbose, the functionality is the same.

Porting from C# to Java – The Delegate

The delegate function is kind of cool in C# land. It allows you to pass a bunch of functions as a parameter. Java has a handful of different ways you can do this. I personally like just passing an object that implements Runnable and then have an anonymous inner class that defines the run method. The following is an example in C Sharp code and how I ported it over to Java.

Example

C#

This first class calls the delegate function that passes a series of functions to run to another class.

WordPress Development Problem

Anybody who has developed for php applications knows it can be tricky to have the right environmental setup to do development work. I love WordPress, but it is no exception, until now . . . I found the fastest way to have a development environment for WordPress that can be blown away and brought up within seconds. The solution is to use Docker. I won’t go into detail in this article about how awesome docker is, but you should definitely check it out. This makes iterating new themes and plugins for WordPress simple and no need for having a separate computer with all the hosting configured.

Use Docker

We can bring up two separate containers. One image is the supported WordPress docker image and the second is the supported MySQL image. You tie the two together using docker compose. The key to make this work so well is we mount a drive from our local machine to a path in the docker image. This allows us to have a git repo with our plugin so we can do active development. When you are satisfied with the plugin or theme you can simply zip up the files you need using whatever automation you prefer and ship the code. You can start developing within 15 minutes. There is no need to set up a server with apache and mysql just to do development work.

Just copy this file, change the directory underneath volumes, and run docker-compose up to start the two docker containers. You can then browse to the IP of the WordPress docker container and viola – you are able to start developing. NOTE: On a Mac you will need to use docker-machine ip default to get the virtual machine’s IP address and then go to the right port in a web browser to view your WordPress install. Being able to get up and running fast and iterate over a clean WordPress install makes this the perfect WordPress development environment.

Problem Addressed

In a service oriented architecture, known as SOA, we have several microservices that get regularly deployed. The strategy and various needs of deployment of such services has already been solved by applications like kubernetes. From a quality perspective there needs to be a high level test after any service is deployed or any configuration change is made to that service. One legacy method is to have a bunch of manual testers validate that the service behavior is working as expected. A better alternative is to use make an endpoint that gets called in every service whenever a service receives load or a configuration update. This endpoint then runs a series of tests that will validate that the service is in a good condition. When it is done it reports back to the endpoint that was called the status. You can then consume this anyway you prefer. Log it, trigger alerts, and etc.

SmokeTestResult Class

This is pretty much a copy of DropWizard’s HealthCheck class, except we need this to be serializable so that Spring can send the object into JSON. Jackson needs a public constructor to do this because it determines the class structure from Java’s reflection.

Unit Test Endpoint With MockMVC

This has extra dependencies because of our deployment manager and preauthentication strategies, but this allows us to create a mock of the event and make sure that the endpoint returns what is expected. There is a better way to validate this – using json to do the validation, but we had conflicts with the various versions.

Description

My house is between a busy highway and a railroad. Living by a railroad doesn’t really bother me, but we have a street crossing really close to my house and by law railroads are required to blow their whistle for the international morse code “Q”, which comes from the times when a queen would be on board a ship and they would blow “Q” to say they have the right of passage because of royalty onboard. Either way the whistle is loud, and having a highway right outside my bedroom window brings lots of traffic noise, trucks clinking and clashing, and random high frequency/pitch sounds. During the summer I just put a window fan in because the nights cool off enough I can blow cool air into my bedroom. The fan produces a great white noise, but during the winter I take the fan out of the window for obvious reasons . . . All of these random sounds wake me up in the middle of the night and cause me to toss and turn quite a bit. I’m so tired of not getting a restful night sleep. After hunting for a while I decided to buy a white noise machine.

Solution

I need a machine to make white noise for sleeping. There are several cheap ways to do this – anything from apps on the phone to having a bedroom phone making noise. I have tried phone apps and I don’t really like them because the speaker’s noise just doesn’t create a restful sleep – for whatever reason I am more awake when I use my phone for white noise. During the winter I really don’t want a fan because my wife will get too cold. The solution is to just get a white noise machine. I ended up buying the Sleep Easy listed below. I like this much better than a phone because a phone only has one speaker which means you only get one position in the wavelength of the sound being generated. Having the Sleep Easy produces sound in a circle location so the waves of sound propagating are more fulfilled. I hear more positions of the waves making the white noise more relaxing. It just sounds deeper and richer.

After getting a white noise machine I have been able to sleep without interruptions better. My wife grinds her teeth at night and I even sleep through that and she can sleep better through my sleep talking. Occasionally I will also work from home and having a house full of people gets noisy quick. I will take the machine to my office and turn it on, which helps me focus better for work rather than hearing the television upstairs. I am going to buy another one for my newborn daughter because it helps her sleep even when there are noises going on around the house. It’s a nice filter. She loves to see what’s going on around her and this helps drown the excitement. The only complaint I have about these white noise machines is they don’t have battery power, which makes taking them for traveling harder as not everywhere my family goes has standard 120V power or power in general.

[AMAZONPRODUCTS asin=”B000KUHFGM”]This is the main brand machine for generating white noise. My has one of these and he loves it. Dohm white noise has been around for a long time and is well tested. [/AMAZONPRODUCTS]

[AMAZONPRODUCTS asin=”B00GFSF402″]The Sleep Easy is the off brand white noise machine that has all the same functionality as the main brand, but for half the cost. This is how I am able to buy one for my bedroom and my daughter’s bedroom. My dad has tried both the DOHM and Sleep Easy and says they are the same in his mind. He prefers this sleep easy because of the price also. He has bought two extra Sleep Easy white noise machines for other reasons just because of the good price.[/AMAZONPRODUCTS]

What is an API

API stands for application program interface. In a nutshell an API is a way for external applications to access information and queries from your program. Twitter for example has a a REST API that allows you to access all types of data from twitter. REST API’s are among the most common types of APIs. A REST API allows you to make requests using standard http methods. You can make a GET request to get data, POST request to insert data, PUT request to update data, and DELETE request to remove data. Most companies give a limited number of free API calls into their applications. As your need for their APIs increases they start charging more for API calls. A call is counted each time you call an endpoint. When a company limits their endpoint requests you can be smart and request more data through a single endpoint query.

I have a good example of working around limited API calls. Salesforce is the worlds leading CRM and they have an open api you can use to access data, however, they severely limit the number of times you can call an endpoint in their system. I have worked for companies that interface for Salesforce and we needed to get Lead data from them. Instead of calling an http GET endpoint to get each lead individually we would query as many as we can and just store them on a local server. Another thing we did to limit our endpoint calls was to batch process them. We would store all the information we needed to access and then every 15 minutes or so make batch queries. This limited the number of queries we needed to call by about 70%.

Why an API

There are several reasons large applications should use an API as one of their layers of abstraction. An API is not the same thing as a plugin or an application, but the business models are similar. One reason the iPhone became so successful is because by the third generation apple introduced the app store. Salesforce generates revenue for so many people by allow apps or plugins to be installed on their application from third parties. An API is the same idea. You want to have people be able to access, share, and improve your software by any means. The following are just a few highlighted reasons for having an API built into your application.

Separation of functionality. A programming concept any software engineer should know well is the separation of functionality. You want your user interface, persistence, and user/business logic to be in separate layers. PHP has been notorious for making it easy to violate this idea. So many php applications have their user interface, persistence to sql, and other user logic all in the same class. By making an API and having your own application access it for data helps separate the parts of your program.

Easily access application on multiple devices. This is probably the biggest reason to have an open API. Say for example you are making some type of SAAS application. About half of all web traffic is through high end mobile devices today. If you build your application and it’s just for a desktop you are losing lots of potential clients and traffic. By having an API you can make your desktop website UI and IOS or Android mobile application call into the same API. This means that you can make as many UI’s as you want and not have to rewrite the persistence layer or business logic for each application.

Makes you money. As we mentioned before, most large applications have some type of an api available to people for free, but it’s limited. Some companies can make a lot of money through their APIs by charging for high usage. Having an API for your application means you can earn money from people who will want to access it directly.

Allow other people to access and contribute to your data. A good API makes your data collection bigger because people will be contributing information to your database. We live in an age of big data. The more data you have the more you can mine it. Data mining is seriously awesome and can also contribute to making more money. For example you can take customer information and show based off of input information if they are likely to buy your product or not. You can even take it a step further and determine what would be needed to most likely close deals.

Various examples of how to build an API

Ultimately if you decide to add an API to your business application you need to do what is best for you and the company who owns the application. If you wrote all your business logic in PHP there are some great rest frameworks for doing a PHP REST API. If you have your business logic in C# then that is what you should use to program your API endpoints. The following are just a few of the industry leading frameworks for making an open REST API.

Javascript Node. I have not always been a fan of javascript, but node has been kicking ass with Express. Express is a very easy framework for making a REST API. PayPal made the conversion from Java to Node and here are the measured response time differences. Another thing I have come to love about using Node with Express is the amount of lines of code I need to use. I made a simple recipe application. One backend was in Spring and the other used Node’s Express. The total number of lines in the Spring application was about 3000 and the total number of lines in Node’s application were about 300. Spring requires a lot more verbosity because all DTO (data transfer objects) have to be defined – even when using a noSql persistence layer.

Java Spring. Even if I am slowly being convinced of how awesome NodeJS is a lot of places still use Spring or are in the process of converting to spring. Spring has a REST Client framework that makes creating a rest application super easy and simple. Spring is all in Java and with that you can write your application in either Scala or Groovy too. I still love the Java language and Spring takes out so much verbosity in building an API.

There are plenty of examples in both node and spring on how to build an API. The body of the requests is most easily done using JSON, but XML or plane text can also work. Just remember that best practices dictate the following REST requests.

GET is used to get data from your application. Use this for a single object or a list of objects to return.

GET: www.domain.com/api/object/id

PUT requests are used to upsert data. If data doesn’t exist it creates it, and if it already exists it will update it.

PUT: www.domain.com/api/object
BODY: { "id":"12345", "foo":"bar"}

This example takes an id should find the ID in your database and update the field “foo” and set the value of “bar.” Normally you return the full object with the id. If there is no object the response will return the id of the newly inserted object.

This type of request should insert a new object into the database for Bilbo Baggins and the response should return either the full object or just the ID of the newly inserted object.

DELETE removes the persistence of the object – deletes it from the database or adds a ‘deleted’ attribute to the entry in the database. Big data never really should delete date, only insert and modify it.

DELETE: www.domain.com/api/object/id

OPTIONS are used to get the available list of options you can use with a method or object.

There are other types of http requests that you can use in your rest application, but these are the most common. I have seen applications where you go to delete the object and you did a post with a JSON body that said delete = true. This is terrible! You should simple just use http DELETE to api.application/object/id in order to remove an object. Using the HTTP standard requests will actually save you network traffic as the scope of what is carried in them is limited to the function they are performing. This is great when you make a mobile application and all data being transferred is precious.

There are several ways of making http requests through java and groovy. You can use anything from Netflix’s feign client to standard http url connection classes built into java. I have used many different classes/frameworks for testing system integrations. My favorite choice by far is to use either groovy’s http builder or another class that extends it called RESTClient. Typically I build a wrapper class that logs into the service and stores server authentication credentials. This wrapper class works best as a singleton or using dependency injection to keep only once instance of the class available for use throughout the test suite. The reason I love groovy’s restclient is because it is so easy to make the standard http requests for any different type of endpoint. You can then make objects that represent the basic crud operations to wrap your api’s endpoints. Next you make a bunch of Spock specifications making great endpoint testing specs.

Wrapping the RESTClient

The following is just an example of wrapping the rest client into a singleton. When the object gets initialized you can log into your api. Making this a singleton is great because you can just store the authentication credentials and every request you make doesn’t need to reauthenticate. If you ever need to store various user roles you can just store the authentication keys in the singleton too.

Share this:

The first development job I had was working for BYU’s Independent Study program converting lessons into website material. The bane our existence was Internet Explorer. Anybody who has developed javascript a few years ago knows that every version of IE had a different engine. The css is also rendered different for each version of IE. We would have to find ways adjust for each version of IE. Below are several comics I have seen and collected over the years bashing internet explorer – hence the title Internet Explorer Bashing.

If each browser had a cartoon representing its awesomeness.

Be the designated friend who doesn’t allow his or her friends to use IE

Almost as bad as being picked last for a sports game.

This rings so true!

This one is probably my favorite – reminds me of Ralph from The Simpsons

Share this:

I have a terrible beef to pick with Apple Inc. I originally started switching to Apple’s products years ago because they spent time to quality control their hardware and software. I was so tired of spending time fixing my development environment just so I can write code. The iPhone was a natural progression of jumping on this bandwagon. There are still several things that I love about my iPhone, but there is one default keyboard layout that is absolutely atrocious! Starting off most of us know what muscle memory is. Piano players have it when learning songs or site reading music. In order to site read music well a pianist needs to relate where the note on the sheet music is in relation to where his or her fingers are on the piano’s keyboard. The more a pianist plays the piano the more they know where the fingers go just due to muscle memory. Sending texts or SMS on a phone is no exception. People can type faster as they build muscle memory. Well Apple went and screwed this one up!

This is an iPhone 6 keyboard in landscape mode. Observe how the emoticons are on the left and the numbers are on the right. If I always type in one layout this is fine, but contrast that to the other photograph of the keyboard in vertical mode.

This is the iPhone 6’s keyboard layout in vertical mode. Notice how the numbers and emoticon positions switched from the horizontal or landscape layout.

I don’t know what usability tests Apple did in deciding to make one layout a certain direction and change it for a different layout. How am I suppose to be fast at texting or taking notes if the stupid keyboard layout changes every time I change my phone’s orientation by 90 degrees. The person who decided this should be fired.

Share this:

Groovy Spock vs Java jUnit

Because Spock is just jUnit under the hood we can do everything we can in jUnit and more because Spock uses groovy. One aspect of the jUnit test framework that most people don’t take advantage of is using parameterized classes – making the test class be test driven. The best part of this is you can run the same test with different variables, allowing all sorts of edge cases to be tested without having to rewrite the test class. Spock makes this visually very easy by using a where block. The first line of the where block is the variables that you want to use through out the test. The second line (and every line after that) is a new set of data that you want to test. Remember the test will run as many times as there are lines in the where block.

The blessings of using Groovy with Spock

Using Groovy in Spock has one amazing perk. The example above lets you define a variable in the where block called specialAssertion. You can take advantage of closures in groovy by placing closures inside your where block and then calling them in your spec class. I occasionally use this if I want to do some special type of assertion with the data that I am passing to the spec. You don’t have to do assertions, but any type of code that needs to be called just for that line of data in the where block. This can be thought of as a similar polymorphic approach of abstract classes and methods.