Java Keytool

As someone who frequently works with digital ids and signatures, keytool is a must have. Here are a few common commands I use when working with keytool. You can also find the complete documentation here.

Generate a new digital id:

keytool -genkey -keystore c:\test\keystore.p12 -storetype pkcs12 -storepass password -keypass password -alias myAlias -keyalg RSA -validity 3650

To create a chained certificate, generate both the parent and the child using the command above. Then use the command below to chain the two and export the child certificate:

keytool -alias child -keystore c:\test\child.p12 -storepass password -certreq |keytool -alias parent -keystore c:\test\parent.p12 -storepass password -gencert > child.cert

Android: Intents (Kotlin)

There are two types of intents: Explicit and Implicit. The following examples and info come from this codelab.

Explicit intents are generally used to start another activity within your app. You can construct it with the constructor that takes the Context and the Activity class as parameters. Use Intent.putExtra to send parameters to the new activity. For example:

val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(DetailActivity.LETTER, item.toString())
context.startActivity(intent)

Implicit intents are generally used to start an activity of the user’s choosing. For example you may have several browsers on your device that could be used to open a URL. You can construct it with the constructor that takes the Intent type and the Uri. For example:

val query = Uri.parse(DetailActivity.SEARCH_PREFIX + item)
val intent = Intent(Intent.ACTION_VIEW, query)
context.startActivity(intent)

Android: RecyclerView (Kotlin)

XML Layout
Create a new layout file with a LinearLayout at the top level if you plan to display multiple Views for each item. If you will only have one view, i.e. a TextView, you can make that your top level View instead. Give it an id and set the layout_width and layout_height to “wrap_content”.

Adapter
MyAdapter extends RecyclerView.Adapter<MyViewHolder>
Once you have created the Adapter class, go ahead and create the inner ViewHolder class so the implemented methods will have the correct type. Then implement the Adapter classes:
onCreateViewHolder – Inflate the xml layout, and use it to create and return an instance of your ViewHolder.

val adapterLayout = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)

onBindViewHolder – Get the item from the cached list of items, and use it to set the content of the View inside the ViewHolder (be sure to handle a null list of items).
getItemCount – Return the size of the cached list of items – handle null case.

ViewHolder
MyViewHolder extends RecyclerView.ViewHolder. This can be an inner class of the Adapter. The constructor takes a View as a parameter. This is the layout that gets inflated by the adapter. Get any Views from the parent and store them as a member variables. You can call findViewById on the parent View to get its children.

MainActivity
onCreate – Set up the RecyclerView

// Kotlin
// Initialize data.
val myDataset = Datasource().loadAffirmations()
val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.adapter = ItemAdapter(this, myDataset)

// Java
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setAdapter(new MyAdapter(this));
// a layout manager must be provided for the RecyclerView to function
recyclerView.setLayoutManager(new LinearLayoutManager(this));

Android: View Binding

In your app build.gradle file, add the following lines to the “android” section:

buildFeatures {
    viewBinding = true
}

In your main class, create a member variable called, “binding”, where the name of the binding class is the name of the layout converted to camelCase:

 lateinit var binding: ActivityMainBinding

In onCreate(), initialize the view binding:

binding = ActivityMainBinding.inflate(layoutInflater)

Call setContentView with “binding.root” instead of the main layout file:

setContentView(binding.root)

Now you can access views using the binding object like this, where the name of the view is its id converted to camelCase.:

binding.myViewId

Options Trading Rundown

The following info was gathered from E*TRADE’s Options Trading for Beginners Series.

Call

This is a strategy to use if you expect the price to go up.

Buying a call is like buying a coupon. Maybe I don’t want to buy pizza today even though it’s only $8, but I think the price is going up so I can buy a coupon for $10 to use if/when the price goes above $10 (factoring in the cost I paid for the coupon). Same with stocks – I buy the choice, “option”, to buy it at a certain price even if the price goes above that. If it doesn’t hit that certain price I do not have to buy it. This is great if I can use a $10 coupon on a $20 pizza!

You earn/save money if the price goes up beyond the value of the coupon plus what you paid for that coupon. If you pay $1 for the option to buy at $10, you won’t make a profit selling the stock until the price is at least $11+.

You lose money with this strategy if you’ve paid for a coupon, “option”, that you never get to use when the price doesn’t go up as expected. i.e. You paid $1 for the option to buy at $10, but the price doesn’t rise beyond $10 before the option expires.

Put

This is a strategy to use if you expect the price to drop.

Buying a put is like buying insurance. I already own my car, but I expect the value to drop. Buying a put allows me to sell my $8000 car (or stock) for $7000 even if the actual value drops below that.

You earn/save money if the value drops below the value of the option. If I buy a stock for $10 but I’m worried the price will fall, I can buy a put for $9 and if the price drops to $5, I can still sell for $9. If I paid $1 for the option to do this, I essentially get rid of this stock for $8 instead of only $5. So this is a strategy to use if you expect the price to drop.

You lose the amount you paid for the option if the stock doesn’t drop.

Covered Call

This is a strategy to use if you expect the price to drop.

This is when I’m on the other side of a call, selling someone else a coupon for a stock I own. If I’m willing to sell a stock I paid $10 for once it reaches $12, I make not only the $2 profit, but the amount I was paid to sell it (which I get up front).

You earn money if the stock doesn’t go up and the “coupon” is never used.

You lose money if the stock rises more than anticipated and you have to sell your stock that’s worth $20 for only $12.

Cash Secured Put

This is a strategy to use if you expect the price to go up.

This is when I’m selling someone else insurance (agreeing to buy their stock if it drops). If a stock costs more than I’m willing to pay for it, someone pays me to buy it from them if/when it drops. I get the premium even if it doesn’t drop, but if it does drop I get the stock at the price I wanted it for.

You gain money if the stock doesn’t drop (because you keep the premium) or if it drops to the price you’ve agreed to buy it for, but not lower.

You lose money if the stock drops below what you’ve agreed to pay for it. i.e. A stock is currently worth $100, I agree to buy if/when it drops to $95, but it drops all the way to $90.

How To: Using Jersey Client to Upload in Java

Ajax and especially jQuery make HTTP requests very simple when you’re writing javascript. But what if you need to make a request in Java? Jersey is great for writing the backend of your jax-rs service and it turns out it makes writing a client simple too. Here are a few common requests and how to make them:

Multipart Form Data

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); final FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:/mydoc.pdf")); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart); final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType())); // do something with the response System.out.println(response); formDataMultiPart.close(); multipart.close();

File Upload

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); final File fileToUpload = new File("C:/mydoc.pdf"); final Response response = target.request().put(Entity.entity(new FileInputStream(fileToUpload), new MediaType("application", "pdf"))); // do something with the response System.out.println(response);

POST data

final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); WebTarget target = client.target("http://localhost:8080/resource/mydoc"); Response response = target.request().post(Entity.json(myJson)); // do something with the response System.out.println(response);

Basic Authentication

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password"); final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build(); client.register(feature);

Java Plugin Architecture

Sometimes you need to design an application in such a way that users (devs) can drop in their own implementation of a service. Generally this is done via interfaces. But how do we communicate to our application that a new implementation has been created and how do we know which implementation of the service to use? This is where the plugin architecture comes in. In this blog I’ll be summarizing the Java Tutorial for Creating Extensible Applications. Their example uses a Dictionary that allows to you look up the definition of a word. Let’s take a look at classes and what each one of them does.

Sample Code Explained

DictionaryDemo.class is the main class that uses the Dictionary to look up words. It’s simply the caller of the service.

public class DictionaryDemo { public static void main(String[] args) { DictionaryService dictionary = DictionaryService.getInstance(); String definition = dictionary.getDefinition("book"); } }

Dictionary.class is the service provider interface (SPI). This is what the service knows about and what the service providers must implement.

public interface Dictionary { public String getDefinition(String word); }

DictionaryService.class is a singleton that uses the ServiceLoader to get the implementations of Dictionary.class and does the work of interacting with the actual implementation.

public class DictionaryService { private static DictionaryService service; private ServiceLoader loader; private DictionaryService() { loader = ServiceLoader.load(Dictionary.class); } public static synchronized DictionaryService getInstance() { if (service == null) { service = new DictionaryService(); } return service; } public String getDefinition(String word) { String definition = null; try { Iterator dictionaries = loader.iterator(); while (definition == null && dictionaries.hasNext()) { Dictionary d = dictionaries.next(); definition = d.getDefinition(word); } } catch (ServiceConfigurationError serviceError) { definition = null; serviceError.printStackTrace(); } return definition; } }

Then you have GeneralDictionary.class and ExtendedDictionary.class which are two actual implementations of Dictionary. They are the service providers. I’m not going to show the code here because the whole point is that the exact implementation doesn’t matter!

Configuration

So let’s say you are the dev who wants to provide the implementation of Dictionary, how do you actually communicate to the application that you have created the implementation? You do this by registering your service provider. Do this by creating a configuration file that contains the fully qualified class name of your service provider implementation. The name of the file must match the fully qualified class name of the service provider interface. Then, the configuration file should be stored in the META-INF/services directory of the service provider’s JAR file.

For example, if you have created the GeneralDictionary implementation of Dictionary, then the config file name is dictionary.spi.Dictionary (since Dictionary lives in the dictionary.spi package). The file contains one line, dictionary.GeneralDictionary (since GeneralDictionary lives in the dictionary package). Finally, the implementation and config file need to be packaged in a jar that should be placed in the application’s classpath.

Jeff’s Favorite Chili

Ingredients:

1 Onion (diced)
1 Green Pepper (diced)
2 cloves Garlic (minced)
1 Jalapeno (diced)
28oz Can crushed or diced tomatoes
15oz Can tomato sauce
1 can original rotel
1-1.5 cans of water (15oz)
1 can black beans
1 can dark red kidney beans
1 can pinto beans

Seasoning:
2tsp salt
1tsp black pepper
2tsp Oregano
2Tbsp Chili Powder
1Tbsp Cumin

Optional Garnish & Serving suggestion:
Green onions
Sliced black olives
Tortilla chips

Directions:

Add all ingredients EXCEPT the beans to a large dutch oven and simmer for 1 hour.
Add the beans (with their juices) and cook for another hour.
Check on it and stir periodically as you may need to add more water during cooking.

We like to garnish it with green onions and sliced black olives. Scooping it with tortilla chips is also tasty!

Spinach Lasagna

Ingredients:

8oz Lasagna noodles (look for the no boil kind)
12oz package frozen chopped spinach (thawed)
4 cups thick spaghetti sauce (I used Kroger’s Chunky Mushroom & Onion)
1/2 cup water
1 tsp salt
1 tsp Italian Seasoning
2 cups Ricotta cheese
3 cups shredded Mozzarella cheese
1/2 cup grated Parmesan cheese

Directions:

Mix spaghetti sauce, spinach, water, salt, and seasoning in a bowl.
Spray 9 x13 pan with cooking spray and put 1/3 of the sauce in the bottom of the pan.
Place 1/2 of the uncooked noodles on top of the sauce, then add a layer of 1 cup of Ricotta cheese and a layer of 1 cup of Mozzarella cheese.
Repeat layers of sauce, noodles, Ricotta, and Mozzarella.
Top with remaining sauce, then remaining cup of Mozzarella, and then the Parmesan cheese.
Bake at 350 for 55-60 minutes. (You may need to cover it with foil near the end if the cheese gets too brown).
Let stand 10 minutes before cutting and serving.

The Protein Project: Spreading Awareness that Plants have Protein

“If I didn’t eat meat I don’t know where I’d get my protein.”

Has anyone ever said this to you? Or have you wondered this yourself? Or maybe you’re a vegan and have heard that “as long as you eat a variety of foods you’ll meet your daily protein needs”, but have your doubts… I have generally accepted that the vegan community knew what they were talking about and that I could trust people who have been living this lifestyle far longer than I have. BUT, instead of just repeating what I’ve heard or trusting others that I am eating a healthy diet, I prefer to do my own research and back up what I’m saying with hard facts. So that’s what I did.

So how much protein does a person *really* need to consume? According to Harvard Health, for each pound of body weight you should consume .36 grams of protein per day. This means a 140 pound woman needs to get around 50g of protein per day from her 2000 calorie diet. And a 200 pound man needs 72g of protein per day from a 2500 calorie diet. To simplify this into smaller units let’s look at how much protein these people need on average from every 100 calories they eat. 50 grams of protein from 2000 calories translates to 2.8g of protein from 100 calories. 72 grams of protein from 2500 calories translates to 2.88g of protein from 100 calories. This means for every 100 calories of food you eat, you should be getting just under 3 grams of protein. Of course, this is on average! Fruit tends to fall under that number, but many veggies pack close to 3 times that amount! Take a look at the list below of common foods and their corresponding grams of protein per 100 calories of that item. I’m including lists of animal products for comparison, but you’ll find that there are MANY plant sources that contain above and beyond the ~3g/100cal average. So if you’re a vegan or are interested in a plant based diet, you can rest easy that as long as you incorporate a variety of foods each day you will meet or exceed your daily protein requirements. If you have any other foods you’d like to see included on this list please let me know in the comments below!

Source: NutritionIX Database
*All values are grams of protein per 100 calories

Meat

Tuna 22.5
Salmon 10.7
Pork 10.9
Chicken 10.7
Beef 8.9
Bacon 7.5

Dairy & Eggs

Parmesan Cheese 9
Eggs 8.8
Yogurt 8.3
Mozzarella Cheese 7.4
Milk 6.8
Cheddar Cheese 5.7

Soy

Tofu 12
Tempeh 10.2
Soymilk 7

Nuts

Almonds 4
Peanuts 3.4
Cashews 2.2
Walnuts 2.3
Macadamia Nuts 1.1
Pecans 1

Beans & Legumes

Lentils 8
Black Beans 6.7
Peas 6.4
Pinto Beans 6.1
Chick Peas 5.6
Green Beans 4.5

Greens

Spinach 12.9
Romaine Lettuce 7.3
Kale 6.9
Cabbage 5.3

Mushrooms

Portabella Mushroom 11.3
Button Mushroom 8.8
Shiitake Mushroom 6.2

Vegetables

Asparagus 10.6
Cauliflower 8.3
Zucchini 7.6
Broccoli 6.7
Tomato 5
Cucumber 4.3
Corn 3.5
Onions 3.2
Green Pepper 3.1
Carrots 1.9

Fruits

Blackberries 3.6
Canteloupe 2.5
Strawberries 2
Watermelon 2
Kiwi 2
Oranges 1.9
Pineapple 1.2
Banana 1.2
Grapes 1.2
Avocado 1
Apple .5

Potatoes

Gold Potatoes 2.7
Red potato 2.6
Sweet Potatoes 1.8

Grains

Wheat Bread 4
Quinoa 3.7
Oatmeal 3.6
White Bread 3.4
White Rice 2.1
Brown Rice 2.1