Java CompletableFuture Cheat Sheet

If you keep forgetting what the CompletableFuture methods do, refer to this table from Kenneth Jorgensen.

HTTP headers for a more secure web application

The following headers are default when you enable Spring Security for a resource. If you are not using Spring Security you might want to add these manually. You might need to adjust the HSTS and X-Frame-Options to your needs so don’t just copy and paste here!

Cache-Control, Pragma, Expires

Prevent caching of resources that can leak information. Note that you might actually need to cache some resources in some systems.


Prevent browsers from guessing the content type to protect agains polyglots.


Require HTTPS for every connection after the first.


Deny embedding in iframes to prevent click jacking.


Always block CSS when a filter catches it rather then try to fix it.

Wait, you need more (CSP)

Also you really should get a proper Content Security Policy in there as well. You can run your application in report only mode to check what you need to fine tune. Google has a great guide and evaluator that will get you set up.

Java secure coding guidelines

Writing secure code is hard.

The following checklist contains at least some pointer of what to keep in mind. Note that this does not include web development checks. Please check the OWASP Application Security Verification Standard Project for more information on that.


  • Not validating input
  • Code has unnecessary permissions
  • Misusing public static variables
  • Ignoring changes to superclasses
  • Assuming exceptions are harmless
  • Beliving space of integers is unbounded
  • Trust user input to obey invariants
  • Beliving a constructor exception destroys the object
  • Beliving deserialisation in unrelated to constructors

0. Fundamentals

  • Prefer obviously no flaws to no obvious flaws
  • Design API’s to avoid security concern (i.e. final classes)
  • Avoid duplication
  • Restrict privileges (policy files,
  • Establish trust boundaries
  • Minimize number of permissions checks (single point of access)
  • Encapsulate methods, fields and classes to coherent sets of behaviour

1. Denial of Service

  • Beware of activities that may use dispropportionate resources
    • Image processing
    • Complex object graphs
    • Zip bombs
    • Billion laughs attack
    • Parsing and processing complex grammars
    • Deserialisation processing anomalies
  • Release sources in all cases
  • Resource limit checks should not suffer from integer overflow

2. Confidential information

  • Purge sensitive information from exceptions
  • Do not log highly sensitive information
  • Purge highly sensitive information after use
    • Do not depend on garbage collection
    • Keep information local
    • Use char[] to clear traces

3. Injection and inclusion

  • Generate valid formatting
  • Avoid dynamic SQL
  • XML and HTML generation requires care
  • Avoid untrusted data on command line
  • Restrict XML inclusion
  • Care with files
  • Disable HTML display in Swing components
  • Take care of interpreting untrusted code

4. Accessibility and extensibility

  • Limit accessibility of classes, methods and fields
  • Limit accessibility of packages
  • Isolate unrelated code
  • Limit exposure of classloader instances
  • Limit extensibility of classes and methods
  • Understand how a superclass modifications affects subclass behaviour
  • Prefer composition insted of inheritance

5. Input validation

  • Validate inputs
  • Validate output from untrusted objects as input
  • Define wrapper arounds native methods

6. Mutability

  • Prefer immatable value types
  • Create copies of mutable output values
  • Create safe copies of mutable and subclassable input values
  • Support copy functionality for a mutable class
  • Do not trust identy equality when overridable
  • Treat passing input to untrust object as output
  • Treat output from untrust object as input
  • Define wrapper methods around modifiable internal state
  • Make public static fields final
  • Ensure public static final values are constants
  • Make classes final
  • Do not expose mutable statics
  • Static variables are global across a JRE

7. Object construction

  • Avoid exposing constructors of sensitive classes
  • Prevent unauthorized construction of sensitive classes
  • Defend against partially initialized instances of non-final classes
    • Throwing an exception from a constructor does not precent a partially constructed instance from being acquired
    • Attacker can override finalize() to obtain object
    • Constructors that call into outside code often naivelt propagate exceptions
  • Leaking this enables the same attack as if the constructor directly thre the exception
  • Prevent constructors from calling into methods tht can be overridden
  • Defend agains cloning of non-final classes
  • Throw exception BEFORE super() to destroy object

8. Serialisation and deserialisation

  • Avoid serialisation for security-sensitive classes
  • Guard data during serialisation
  • View serialisation the same as object construction
  • Duplicate SecurityManager checks during serialisation and deserialisation
  • Understand security permissions given to serialisation and deserialisation
  • Validate the data

9. Access control

  • Understand how permissions are checked
  • Beware of callback methods
  • Safely invoke AccesssController.doPrivileged
  • Know to restrict privileges through AccesssController.doPrivileged
  • Be careful caching results
  • Understand the context transfer
  • Understand how thread constructors transfer context
  • Safely invoke standard API’s that bypass SecurityManager checkes depending on the callers class loaer
  • Safely invoke standard API’s that perform tasks using the callers class loader instance
  • Be aware of standard API’s that perform Java language access checks against the caller
  • Be aware of java.lang.reflext.Method.invoke is ignored for checking the caller

AWS Overview

This is an overview of the Amazon Web Services most common components and some information about the AWS security model.

Infrastructure and Services

  1. Regions and availability zones
  2. Foundation services
  3. Platform services

1. Infrastructure


  • Regions are split into Availability zones
  • Availability zones can have multiple data centers

Edge locations

  • Instead of using the data centers data can be cached in edge locations
  • Used as CDN

2. Foundation services

  • Compute (EC2, Lambda, Auto-scaling)
  • Networking (Load-balancing, Route53, VPC)
  • Storage (S3, Block storage, glacies, EFS)

3. Platform services

  • Databases (DynamoDB, Relational DBs, Redshift)
  • Analytics (Kinesis, EMR, Data pipeline)
  • Deployment (Elastic beanstalk, CodeDeploy)
  • Mobile (Cognito, SNS)

AWS Elastic Compute Cloud (EC2)

  • Infrastructure as a Service (IaaS)
  • Spins up virtual machines in the cloud
  • Custom VM’s
  • Fully manages infrastructure
  • Fast provisioning
  • Elastic scaling
  • Pre-built images or bring your own
  • Configurable network
  • Use security groups to open/close ports

Amazon Machine Images (AMI)

  • Different images available
  • Configures OS and Root Volume
  • Public images available in AMI repo
  • AMI defines EBS backend (most common, flexible) or instance backend (faster and restricted)
  • AMI marketplace includes pre-build images with popular configurations

Storage options

  1. Root volume configuration
  2. Instance backend vs EBS backend
  3. Lifecycle of an instance

Root volume configuration

Defines where should OS be stored

Instance stored backed

Fast IO Drive directly connected to the instance Ephemereal storage Cannot be stopped

EBS stored backend

Slower IO Persistant storage Can be stopped


Advanced features

  1. Machine types with different optimisations (cpu/memory/storage/gpu etc.)
  2. Instance metadata (info on system) and user data (scripts can be launched on startup). NOT SECURE!
  3. Pricing models

AWS Simple Storage Service (S3)

  • Online HTTPS accessible storage
  • Built for unstructured binary data (files)
  • Highly scalable, durable, limitless


  • Access via SOAP/REST/Web/shell
  • Unlimited number of objects (each up to 5TB)
  • Secure with client-side or AWS provided server-side encryption
  • Bucket and object level access logs for auditing and compliance


  1. Architecture
  2. Buckets and Object
  3. Security options

1. Architecture

2. Buckets and Object

  • Top level containers for data (Objects)
  • Exist in gobal namespace
  • Created in a region
  • Cannot be nested
  • Usage/Charges can be aggregated by Bucket
  • Discrete data files betwenn 0-5 TB
  • Can be versioned
  • Bucket + Object + Version can map to unique URL

3. Security options

  • Access control at Bucket and Object
  • ACL’s
  • Identity and Access management policies
  • Bucket and Object policies can be defined with Access Policy Language (json)
  • Encrypt at rest with AES-256 or/and BYO and encrypt before sending

Advanced features

  1. Object Versioning
  2. Object Storage Classes
  3. Lifecycle Management

1. Object Versioning

  • Versioning set at bucket level
  • Existing objects have “null” version
  • New objects are assigned new version id
  • All versions are retained… even after delete

2. Object Storage Classes

  • Set at object level
  • Standard, Infrequently Accessed, Glacier, Reduced Redundancy
  • Different pricing, durability, and availablity

3. Lifecycle Management

  • Can delete old versions of files after some specified time
  • Can automatically move objects between storage classes
  • Configured with xml

Elastic Block Store (EBS)

  • Virtual hard drives in the cloud
  • Create volumes during EC2 creation or independently
  • SSD or Magnetic available
  • 1GB to 16TB available
  • Take snapshot into S3 at anytime
  • Use for root volumes, databases, application data
  • Pay per provision rather then usage

S3 comparasion

Virtual Private Cloud (VPC)

  • Private, isolated, virtual network
  • Create logically isolated subntes
  • Resolve ip adress ranges and assign to resources
  • Remotely connect to on-pre network with VPN
  • Supports both public and private networks
  • Available per Availability Zone

Security inside a VPC

  • Use network ACL’s and IAM Security Groups to controll access
  • Security groups control inbound and outbound traffic at intance level
  • Network ACL control inbound and outbound traffic at subnet level
  • Use a NAT gateway instance to allow access from private network to WAN
  • Setup route tables, firewalls, gateways

AWS Shared Responsibility Model

Defines who is responsible for what. Security in the cloud is up to user. Security of the cloud is handled by Amazon.

  1. Shared responsibility
  2. Physical security
  3. Hardware, software, network

EC2 Example

  • Amazon controls physical security
  • The user controls patching, firewall, security groups of the instance

S3 Example

  • Amazon controls patching and firewalls
  • The user controls access to filesm encryption, transport etc

2. Physical security

  • Non-descript, undisclosed locations
  • 24/7 security staff
  • Two factor auth for entry
  • Continual monitoring, logging and auditing

3. Hardware, software and network security

  • Automated change control process
  • Physical acces requires authorization with frequent renewal
  • Bastion servers act as gateways for privileged users
  • Network bboundary devices monitor and audit access
  • Unusual or abnormal activity monitoring of application usage, intrusion etc.

Regulatory compliance

  • PCI
  • ISO 27001
  • Many many more…

ISO 27001 – The big picture

The ISO27001 protects Confidentiality, Integrity and Availability (CIA) of information. This is a quick overview of what it covers and how the process works.


4 main areas

  • Clauses 0-3 General definitions and content
  • Clauses 4-10 ISMS mandatory compliance
  • Annex A Technical controls
  • Bibliography

Clauses 4-10

7 clauses relating to the nature and operation of the ISMS.

4 – Context of the organisation

  • Boundaries of ISMS and its scope
  • Makes sure you understand the organisation
  • Makes sure you understand interested parties
  • States that the organisation shall implement a information security management system

5 – Leadership

  • Support from leadership
  • Documented information security policy that is communicated properly
  • Define and assign responsibilities for the policies

6 – Planning

  • Determine risk and opportunities
  • How to apply risk assessment process
  • How to identify and analyse risk
  • How to treat those risks
  • How to set and reach security objectives

7 – Support

  • Ensure enough support is available for the information security management system
  • Ensure organisation has adequate resources, competence and awareness
  • Requirements for documentation and how it can be controlled and updated

8 – Operation

  • Operating the ISMS processes
  • Operating risk assessments
  • Operating risk treatment

9 – Performance evaluation

  • Evaluate the effectiveness of the ISMS
  • Monitoring and measuring and analysing the performance
  • Handles management reviews

10 – Improvement

  • ISMS should be continuous process

Annex A

  • Lists control objectives and domains used in ISMS
  • 114 controls in total


  • Set scope as early as possible
  • Applies to process, data, people, places, activities
  • Consider internal and external factors
  • Consider interested parties
  • Consider relationship between activities in your and other organisations


  • Business activities, data
  • Location specific data (production/test in different place)
  • Channel specific transactions
  • Specific products/services
  • What’s important from customer point of view

Risk assessment

Key part of ISMS. Repeatable method for risk assessment.

  • Criteria for accepting risk (appetite)
  • Identifying risks
  • Analyzing risks
  • Evaluating risks

Statement of applicability

Contains a list of controls necessary to treat identified risks.

  • Go through all 114 controls
  • Justify inclusion of controls
  • Justify exclusion of controls
  • Whether implemented or not

Required documents

16 mandatory documents

  • Procedures
  • Policies

7 mandatory records

  • Internal audit records
  • Correct action records

Case study Background

Globomantics is an online web service that allows a user to fill in their personal info and request a brochure from a company for some specific service.

  • 25 staff in total, IT team of 4
  • 2 developer, 1dba, 1 sysadmin
  • Want to be 27001 as customers ar financial services and they capture PII


Brochure request

  • Requester web site
  • Requester database
  • Mailing labels

New client onboarding

  • Configure new client and campaign

Statement of applicability

  • Tailor ISO 27001 to your business
  • Go through all 114 controls
  • List include/exclude information in columns

Certification lifecycle

  1. Start with scope
  2. Risk assessment, Statement of applicability, Internal audit, Management review, Mandatory documents
  3. State 1 audit with external auditor (all should be done)
  4. Stage 2 audit with external auditor (more strict)
  5. Recommended for certification
  6. Audit findings

Toolset and support

Tool support

  • File share (no versioning or history)
  • Templates and toolkits (rapid generation, might not align to organisation needs)
  • Document management system (VCS, Sharepoint)
  • Risk management and governance system

Organisational support

  • Human resources
  • Facilities
  • Training
  • IT operations
  • Software development
  • Business stakeholders

3rd party support

  • Gap analysis prior to Stage 1 audit to find issues
  • Other external help

Animation of height of LinearLayout container with ValueAnimator

Had some issues with animation in Android a couple of years ago and I posted the solution to StackOverflow. I thought I might post it here as well :)

Looking at chitgoks blog post I found that I shouldn’t use view.invalidate() to have the layout redrawn. I should use view.requestLayout().

Thus the code becomes something like this:

I just wanted to add a note on how to get the height of the LinearLayout as well to make the animation dynamic. To get the height all the views need to be drawn first. Therfor we have to listen for an event that tells us that the drawing is done. This can be done from the onResume() method like this (note that in my xml I have declared the container to wrap_content for height and it is also visible, since I want to hide it from the start I do that efter measuring it):

Dynamic localization of JSR 303 validation messages with wildcards

Lets say you have a class like this

And you want to localize the messages in a file, you might do something like this:

Now you have hardcoded the values in multiple places, imagine if you have multiple properties files for different languages, you would define the values everywhere!

Instead you can do this:

And this:

Now, why are we using {2} and {1}?

The attributes are ordered alphabetically! From the board:

For the first option, Spring-managed field error arguments include the actual constraint annotation attributes in alphabetical order now. So for @Size(min=1,max=5), it’ll include the field name as {0} , the max value as {1} , and the min value as {2}

Has caught me many times.

Adding Mojarra manually when Eclipse Luna JSF Download Library is empty

When I was setting up a fresh install of JavaEE on my laptop today, the JSF Download Library would not return any results to download. Some searching suggested that I had to change my proxy settings but since I was not behind a proxy, it would not help me. Lucky enough, JSF are just another bunch of jars that can be added to a user library. You can download the JSF jars here (scroll down for newest versions): Then simply; * click the “Manage Libraries” icon on the JSF capabilities page * click “New” and name your library * click “Add external jars” and browse to the jars you downloaded Have fun!

Run tests in different packages and linked sources with JUnit TestSuite

In a project that I’m working on we’re using linked sources and we have multiple sub-packages with JUnit tests. We ran into some issues with running the test. Thankfully, although the eclipse wizards wouldn’t help us create a test suite that would run all the tests it was trivial to write the suite by hand.

It can look like this:

This will allow you to test any class that you import no matter what package it is in. To run this in eclipse you just right click the AllTests class and run it as JUnit test. It will then run all the tests you define in @SuiteClasses.

This will work with linked sources as well, I use it all the time.

Send a JSON object to server over TCP connection in Java using Socket

So the other day I was struggling with sending a JSON object to a server. The JSON service would not accept this special object over HTTP so I had do dig into some Socket handling to send it. Of course, we could use Netcat to send the object like this:
echo '{"id":1, "method":"object.deleteAll", "params":["myParam"]}' | nc x.x.x.x 3994

But since the application I was working on needed to run some tests on creating and deleting stuff from the server we really needed a Java method to do this for us.

Here’s the code:

Creating the Socket is straight forward, the most noteworthy thing here the Writer that is being used. I tried with so many different Writers that I forgot what they all where called. Also note that the PrintWriter.println() method is used rather then the PrintWrite.print() method.