Java

Spring Configurations

Example of minimal annotation injection based config file @Configuration @Import({MyExternalAppSpringConfiguration.class}) @ComponentScan(basePackages = {"org.app.my"}, excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = IgnoreDuringScan.class)) public class MyAppSpringConfiguration{}

Value annotation and SpEL

//Let Spring translate a single configuration value into list of Strings @Value("#{'${valList}'.split(',')}") List<String> keyValuePairs, //Let Spring translate a command line argument into String variable @Value("${"+ MyApp.OUTPUT_FOLDER + "}") String outputFolder, //Let Spring translate a command line argument into path variable @Value("${"+ MyApp.INPUT_PATH+ ":#{null}}") Path input,

Command line execution in Java

Run command line command silently on background String cmd = "ls -al" CommandLine cmdLine = new CommandLine(cmd); DefaultExecutor executor = new DefaultExecutor(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); log.info("Command is exiting with value "+ exitValue); if (exitValue !=0){ String errorMessage = "Execution of " + cmdLine.toString() + " failed with Exit code " + exitValue; log.error(errorMessage, resultHandler.getException()); throw new CommandLineExecutorException(errorMessage, resultHandler.getException()); } Run command line command and use output as inputstream for further processing Runtime rt = Runtime.

Classes with static main

Checking command line arguments private static final String OUTPUT_FILE = "output"; OptionSet optionSet = checkArgs(args); String outFile = optionSet.valueOf(OUTPUT_FILE).toString(); private static OptionSet checkArgs(String[] args) throws IOException { OptionParser optionParser = new OptionParser(){ { accepts(OUTPUT_FILE).withRequiredArg().ofType(String.class).required().describedAs("output file"); } }; try { return optionParser.parse(args); }catch(OptionException e){ logger.error("Invalid arguments:"); optionParser.printHelpOn(System.out); throw e; } }

Statistics in Java

Dependencies <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math</artifactId> <version>3.6.1</version> </dependency>

Maven

Maven Assembly plugin POM file <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.dan.sandbox</groupId> <artifactId>my-package</artifactId> <version>1.0.0-SNAPSHOT</version> <dependencies> <!-- Spring dependencies managed via BOM --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-assembly-plugin</artifactId> </plugin> </plugins> </build> </project> Assembly file (in src/main/assembly) <assembly> <id>package</id> <formats> <format>dir</format> <format>zip</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <outputDirectory>/lib</outputDirectory> <useProjectArtifact>true</useProjectArtifact> </dependencySet> </dependencySets> <fileSets> <fileSet> <directory>src/main/conf</directory> <outputDirectory>/config</outputDirectory> <lineEnding>unix</lineEnding> </fileSet> <fileSet> <directory>src/main/assembly/scripts</directory> <outputDirectory>/scripts</outputDirectory> <lineEnding>unix</lineEnding> </fileSet> <fileSet> <directory>target/generated-resources/appassembler/jsw/liquidbiopsies/</directory> <outputDirectory></outputDirectory> <fileMode>0770</fileMode> <directoryMode>0770</directoryMode> </fileSet> </fileSets> </assembly> Super POM <parent> <groupId>org.

Data structures

HashMap is container for key-value pairs LinkedHashMap keeps order of added elements Looping through Hashmap Map<String,LinkedList<String>> intervals = new LinkedHashMap<>() ; // Only values for (LinkedList<String>> iValues : intervals.values()) { //...do something } // Keys and values for (Map.Entry<String, LinkedList<String>> entry : intervals.entrySet()) { String key = entrySet.getKey(); LinkedList<String> values = entrySet.values(); } // lambda expression intervals.forEach((k,v) -> String key = k; LinkedList<String> values = v;//do something);

Jackson Object mapping

Create List of objects from JSON ObjectMapper mapper = new ObjectMapper(); String fileName = "dsdm.json"; File json = new File(fileFolder, fileName); try { // start reading from samples tag onwards final JsonNode node = mapper.readTree(json).path("samples"); final CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, TSOSample.class); return mapper.readerFor(collectionType).readValue(node); } catch (IOException e){ System.out.println(e.getMessage()); }

Data Plotting

Plotting For plotting in Java, some libraries are necessary. Plots are new windows with visual content using the JavaFX library. Thus, new plots are created calling the launch method. import javafx.application.Application; public class MyPlot extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); // call of implementation of start() } @Override public void start(Stage stage) { // create your plot here } } A plot is an object added to Scene, which is added to a Stage.

Spring Boot

@SpringBootApplication public class SpringBootBasicApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(SpringBootBasicApplication.class, args); } @Override public void run(String... args) throws Exception { System.out.println("Hello Spring Boot."); } } @Component public class SpringApplicationBuilder implements CommandLineRunner { public static void main(String[] args) { new SpringApplicationBuilder(MyRunnerClass.class). bannerMode(Banner.Mode.CONSOLE). sources(SpringConfiguration.class). // if spring boot web starter is included and no embedded tomcat is wanted // web(WebApplicationType.NONE). run(args); }

The Java Collection Framework

The Collection interfaces Duplicates Sortability The Collection interface The Set interface The List Interface The Queue Interface The SortedSet Interface The Map Interface The SortedMap Interface The Collection interfaces Collections a container for objects, Maps are container for key-value pairs. Three criteria specify the sort of container: - Sortability - Uniqueness / Duplicates - Order of elements Duplicates Duplicates are defines as objects returning true on the equals(E e )-method call.

Linear Structures and Trees

Efficiency of an algorithm Linear datastructures IndexList PositionList Sequence Iterators Trees Traversals Binary tree Efficiency of an algorithm The efficiency of an algorithm can be specified with the big-oh notation: O(n) linear increase in processing time O(1) constant processing time O(2powerN) exponential increase in processing time O(logN) Linear datastructures Linear datastructures are abstract data types allowing to add new data or remove existing data at every possible position in the structure.

Stacks and Queues

Stacks Queue Linked lists Sortability Iterator Data structures are ways to organize data and make it available. Algorithms are instructions to solve in a certain amount of time a certain problem. Abstract data types (ADT) are models of a data structure specifying the type of data and operations to perform on. In Java these are often interfaces. Stacks A stack is a relatively simple data structure storing data following the Last-In-First-Out (LIFO) principle.

Recursive Methods

Designing a recursive method Example Another example Types of recursion Extra requirements Recursive methods are useful when you want to break down a complex problem into several smaller problems. You can apply them whenever a iterative method is also possible. Designing a recursive method Designing a recursive method comprises 3 steps 1. Divide problem into problems of the same kind. 2. Find a solution for the most basic, simple problem.

Databases

Connect to a database SELECT and UPDATE Retreiving metadata Important other aspects Design aspects Date transform Primary key is unique value (id) in a column. The combination of columns forming an unqiue ID is called Alternative key. The column of a table referring to the key of another table is called reference key. We can display the structure of a database with a strokendiagram. (p)rimary key: two-sided arrow above column (a)lternative key: two-sided arrow above column(s) name of column that references to different table can best get value of reference table name.

Enumeration types

Enumeration types Use Enum type to define constants and use these to loop through Enumeration types Enumeration types are special classes that define constants. These constants have a numeric value, meaning that you can use them e.g. in a switch statement. On top of that, each constant value of a enum class can have attributes, which can be accessed by e.g. getter functions. /** * Name of different studies */ public enum Studies { MATHEMATICS("Mathematics", 160.

Event handling

Event Handling How to implement event handling Adapter classes Where to define the listener class Difference between different EventListeners Event handling Threads Thread-safe event handling Event Handling Java’s event handling is based on delegation: the source delegates event handling to listener. To do this, 3 things are necessary: the component or source triggering an event the event self containing info about the event the handler which implements the processing of the event Regarding 2: Java knows a bunch of event classes that can be created by different sources as e.

Exceptions

Error handling and Exceptions Exceptions Run-time errors Checked Exception handling Order of exceptions handling Try-with resources Error handling and Exceptions Debugging can be done using: - debugger - logging (check log4j framework) Stack: sorted pile of not completed processing routines Exceptions Exceptions are objects. These objects are instances of subclasses of one of following three error classes: - Error: system errors (nothing to do about) - Runtime Exceptions: Programming errors (unchecked) - Exceptions all other (checked).

Generic classes

Generic types Advantage Generic types Generic types are classes or interfaces that are useable with different classes. Instantiation of these types are done with an extra type parameter. public class ArrayList<E> extends ClassX { ... } // <E> id class definition is called type parameter // ClassX is a restriction which (sub)class is accepted ArrayList<String> lijst = new ArrayList<String>(); // ArryList<String> is called parametized type of generic class ArrayList // the 'new' ArrayList<String> is called actual typeparameter Example

Handy classes

Datum String sdatum = "02-11-2018"; SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy"); GregorianCalendar datum = new GregorianCalendar(); try { datum.setTime(fmt.parse(sdatum)); } catch (ParseException exception){ }

Java Swing

Java Swing JFrame Layout manager Color and Lettertype Buttons and Lists JFileChooser Java Swing Swing elements are subclasses from AWT package. Three classes are known: top-levelcontainers such as JFrame, JDialog and JApplet. These are components which can have an own window and form the outer layer which can contain a menu (optional) and a contentpane. Container classes that can contain other components such as JPanel or JScrollPane.

Object oriented design

Object oriented design Use cases Object oriented design Implementation of an application might appear as the primary task of a programmer. From a technical side, this is true. The applications’ design, however, which precedes the implementation, is a task, which deserves at least as much attention, because it forms the backbone of the application and helps to view the application from a birds perspective (e.

Observer pattern

Aim is to tear apart domain (model) and gui (view) layer. Question how can the view know about changes of the model? Gui needs to implement the Observer-interface. By doing so, it will need to implement a update() method. The domain, on the other side, needs to inherit of the superclass ‘Observable’. By doing so, it inherits all important methods to register observers, track changes and inform observers about these.

Streams

Character input stream Byte Input stream Character output stream Byte Output stream Serialization and De-serialization Parser Streams need to perform 4 important operations: open() read() write() close() Stream operation on files are expensive operation, so not to use for single characters. Package java.io contains all important classes for reading and writing of character and byte streams. For Bytes: - Abstract classes are InputStream and OutputStream - Concrete classes are File/ByteArray/Piped Stream

Threads

What we want to achieve is concurrency. Why? - Responsivity - Efficiency - Ecological validity On a machine with two CPU’s there can be real parallelism, one one machine concurrency. JVM has a scheduler that will manage threads, processor time etc What is thread? A thread is a sequential execution of processing tasks of an application. Every thread has its own stack but shared memory. There are also methods to exchange info between threads.

Inheritance

Characteristics of good software Object-oriented independent characteristics Object-oriented dependent characteristics Principles leading to good software How to achieve Concept Errors Inheritance vs. delegation Abstract classes Interfaces Characteristics of good software Object-oriented independent characteristics correctness: does program what it is supposed to do? robustness: can program handle wrong user input / circumstances? efficiency: does program optimally use resources Object-oriented dependent characteristics Re-usability Maintainability Extensibility Compatibility