Adam Bien's Weblog

Angular 2: Styling The Generated Host Tag

Angular 2 replaces / generates a "synthetic" tag for each component without any styling with the name specified in the selector

The component below:


import { Component } from '@angular/core';
@Component({
  selector: 'hello-app',
  template: '<h1>Styling the host component</h1>',
})
export class AppComponent { }

generates the following markup:

<hello-app>
 <h1>Styling the host component</h1>
</hello-app>

Additional styling of the "host" tag can be added with the host object:


import { Component } from '@angular/core';
@Component({
  selector: 'hello-app',
  template: '<h1>Styling the host component</h1>',
  host: {"class":"nice"}
})
export class AppComponent { }

which generates the following output:

<hello-app class="nice">
	<h1>Styling the host component</h1>
</hello-app>

Putting the selector into angle brackets: selector: '[hello-app]' searches for an attribute, not a tag, with the name of the selector, e.g.:


<div hello-app></div>

See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Building Angular 2 Applications and Building React Applications.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Oracle on Java EE 8 News, Monitoring, Sonar Setup, BCE Entities or 29th airhacks.tv Questions and Answers

90 live attendees from all over the world (according to chat: France, Nigeria, Costa Rica, Netherlands (...)) participated in the 29th edition of airhacks.tv starting with the "Oracle and Java EE 8" discussion including press releases, then I answered questions ranging from Akka interoperability, over Java EE monitoring, to file access from EJBs and Sonar Setup:

Any questions left? Ask now and see your topic discussed at the first Monday of the month, 6 pm CET.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

How to merge javax.json.JsonObject instances

Combining multiple javax.json.JsonObject instances requires copying their contents into a single JsonObjectBuilder instance:


@Test
public void merge() {
	JsonObject dev = Json.createObjectBuilder().
			add("developer", "duke").
			build();
	JsonObject lang = Json.createObjectBuilder().
			add("language", "java").
			build();

	JsonObjectBuilder result = Json.createObjectBuilder();
	dev.entrySet().forEach(s -> result.add(s.getKey(), s.getValue()));
	lang.entrySet().forEach(s -> result.add(s.getKey(), s.getValue()));
	JsonObject merged = result.build();
	assertThat(merged.getString("developer"), is("duke"));
	assertThat(merged.getString("language"), is("java"));
}

Adding additional attribute to a JsonObject instance works similarly.

See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7! Is MUC too far? Checkout effectivejavaee.com


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

How to add an attribute to javax.json.JsonObject

Although javax.json.JsonObject implements Map<String, JsonValue> -- it is immutable. Any modification attempt results in UnsupportedOperationException:


    @Test(expected = UnsupportedOperationException.class)
    public void immutable() {
        JsonObject dev = Json.createObjectBuilder().build();
        dev.put("dev", JsonValue.NULL);
    }

To add a new attribute to an existing JsonObject instance, you will have to copy it's attributes into a JsonObjectBuilder instance, add any attributes and eventually build a new instance:

package com.airhacks.jsonp;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class JsonTest {

    static final String STATUS_KEY = "status";

	
    @Test
    public void addAttributeToObject() {
        JsonObject dev = Json.createObjectBuilder().
                add("developer", "duke").
                build();
        String expected = "master";

        JsonObject devWithStatus = enrich(dev, STATUS_KEY, expected);
        assertThat(devWithStatus.getString(STATUS_KEY), is(expected));
        System.out.println(devWithStatus);
    }
	

    public JsonObject enrich(JsonObject source, String key, String value) {
        JsonObjectBuilder builder = Json.createObjectBuilder();
        builder.add(key, value);
        source.entrySet().
                forEach(e -> builder.add(e.getKey(), e.getValue()));
        return builder.build();
    }

}

See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7! Is MUC too far? Checkout effectivejavaee.com


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Using Excel As Source For Unit Tests

Sophisticated business logic requires a high amount of high quality data for test purposes. Tabular data is easier maintainable in Excel then directly in Java code.

With Java 8 it is easy to provide a function which converts an Excel Row (actually a HSSF Row) into whatever POJO you like:


 Function pojoMapper() {
        return (row) -> {
            Iterator cells = row.cellIterator();
            return new Input(
                    asLong(cells.next()),
                    asLong(cells.next()),
                    asLong(cells.next()));
        };
    }


A few additional lines of code convert a Stream<Row> into a Stream<POJO>:


public static <T> Stream<T> load(Function<Row, T> mapper,...) {
        int skipCount = 0;
        if (hasHeader) {
            skipCount = 1;
        }
        String fileName = //...
        try (InputStream inp = new BufferedInputStream(new FileInputStream(fileName));) {
            try (XSSFWorkbook wb = new XSSFWorkbook(inp)) {
                XSSFSheet sheet = wb.getSheetAt(tab);
                Stream<Row> stream = StreamSupport.stream(sheet.spliterator(), false);
                return stream.skip(skipCount).map(mapper);

            }
        } catch (IOException ex) {
            throw new IllegalStateException("Problems processing file: " + fileName, ex);
        }
    }


Parameterized JUnit tests can be used to define the locations of excel files and load the sheets representing different use cases, test suites or regression tests.

Hence the code above is reusable, andit was extracted and released as: https://github.com/AdamBien/sheetfit/ (the pronunciation is semi-accidental :-)). This one-class utility is also available directly from maven central:

<dependency>
	<groupId>com.airhacks</groupId>
	<artifactId>sheetfit</artifactId>
	<version>0.0.1</version>
</dependency>


Example is implemented as system test: https://github.com/AdamBien/sheetfit/tree/master/sheetfit-st.

Also checkout javaeetesting.com or come to MUC: http://workshops.adam-bien.com/about-testing.htm


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Sending An OPTIONS Request With Angular 2

The Angular 2 Http class does not offer an OPTIONS convenience method out-of-the box. Interestingly, all the major HTTP methods are supported: GET, POST, PUT, delete, patch and head, but the OPTIONS was not implemented. To perform an e.g. POST request, you can use the built-in method:


import { Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

export default class XYZService{
   
    constructor(private http:Http){}

    performPost(uri,payload):Promise<Workshop[]>{
        return this.http.post(uri,payload).
        toPromise().
        then(r => r.json()).
        catch(this.handleError);
    }

   handleError(error){
        return Promise.reject(error.messages || error);
    }
//(...)

For the initiation of an OPTIONS request you will have to rely on the generic request method of the same Http class:

    options(uri):Promise{
        return this.http.request(uri,{method:'OPTIONS'}).
        toPromise().
        then(r => r.json()).
        catch(this.handleError);
    }

See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Building Angular 2 Applications or Building React Applications.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Java EE 8 Plans, Oracles Statement, Performance Smoke, Software Quality Rules, Cross-Jars Alternatives or 29th airhacks.tv Questions and Answers

Questions for the 29th a airhacks.tv, Today (August, 1st) at 6pm CET (see archives):

  1. Java EE 8 news: semi-official Oracle plans for Java EE 8, JavaOne (discussion)
  2. Serving files without a WAR
  3. Java EE performance monitoring and results interpretation
  4. Software quality with Sonar and Java EE: rules, defaults and real world
  5. Accessing EJBs from EntityListener's
  6. Running "Server Smoke" on 141 Processors and 10 TB
  7. Cross-Jar @Alternative's
  8. Referencing Entity Manager from JPA Entities
  9. JAX-RS ExceptionMappers in internet-facing API
  10. EntityManager, serialization and clustering
  11. BCE: referencing JPA entities from other components

The questions above are going to be answered during the next "Airhacks Q & A" http://airhacks.io live. You can subscribe to the channel and / or for the next event: http://www.ustream.tv/channel/adambien (both is optional, no registration required to watch this event live).

If you still miss a question, ask at https://gist.github.com/AdamBien/48148f11f649dd756993a876f7354061, write a comment on this post, tweet your question with the hashtag "#airhacks" or mention me https://twitter.com/AdamBien.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

Oracle Commits To Java EE, WildFly Swarm, Payara Micro, Docker and Microservices, Smells Like CDI or the 28th airhacks.tv Questions and Answers

This time 110 live attendees participated in the 28th edition of airhacks.tv with topics from dynamic DI, over Oracle Java EE announcements, logging strategies over Payara and WildFly microservices, to introducing a new shiny hardware:

Any questions left? Ask now and see your topic discussed at the first Monday of the month, 6 pm CET.

See you at Java EE Workshops at Munich Airport, Terminal 2 and particularly at Java EE 7 Microservices.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

July 2016: Java is #1 And Raising

The Java programming language becomes even more popular (19.804%) and gains 2.08%. Second is the C programming language (12.238%) which lost 3.91% -- the gap is larger. C was number #1 in 2001.

Java is also doing well comparing the "Monthly Commits" of JavaScript, C, Clojure, Scala and Go.

One of the recurring airhacks.tv questions is: "As I student, should I still invest in Java?" :-)

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

xplr: Utility For Migrations To Maven

Java projects without dependency management directly rely on JARs contained in the project structure for compilation and deployment purposes.

A migration to maven requires the analysis of the JARs origin. All JARs needs to be replaced by dependencies defined in Maven's pom.xml. Sometimes the used JARs already contain maven information, in some cases the meta information is stored in the JAR's manifest.mf.

xplr is a self-contained, 15 kB, Java 8 CLI utility, which recursively traverses folders, searches for JARs and extracts any pom or manifest information. xplr also generates the mvn install:install-file statements which help you to install any proprietary libraries to the maven repository.

Applied to itself with java -jar target/xplr.jar . xplr produces the following output:


(...)
#####################################
Directory: ./target
#####################################

# Jar: ./target/xplr.jar
## Manifest: 
## Package: com.airhacks.xplr
Archiver-Version:Plexus Archiver
Built-By:abien
Created-By:Apache Maven 3.3.3
Build-Jdk:1.8.0_77
Manifest-Version:1.0
Main-Class:xplr.Explorer

## POM: 
<dependency>
 <groupId>com.airhacks</groupId>
 <artifactId>xplr</artifactId>
 <version>0.0.1</version>
 <packaging>jar</packaging>
</dependency>
## MVN install command: 
mvn install:install-file -Dfile=./target/xplr.jar 
-DgroupId=com.airhacks -DartifactId=xplr -Dversion=0.0.1 -Dpackaging=jar
---
(...)

With two parameters: java -jar xplr.jar [FOLDER] [CLASS NAME] xplr lists all JARs containing the specified class name (excerpts are supported). E.g.

java -jar target/xplr.jar . Injector will find:

#####################################
Directory: ./src/test/jars
#####################################

# Jar: ./src/test/jars/afterburner.fx-1.6.2.jar
## Manifest: 
## Package: com.airhacks.afterburner.configuration
Archiver-Version:Plexus Archiver
Built-By:abien
Created-By:Apache Maven 3.2.1
Build-Jdk:1.8.0_31
Manifest-Version:1.0

## POM: 
<dependency>
 <groupId>com.airhacks</groupId>
 <artifactId>afterburner.fx</artifactId>
 <version>1.6.2</version>
 <packaging>jar</packaging>
</dependency>
## MVN install command: 
mvn install:install-file -Dfile=./src/test/jars/afterburner.fx-1.6.2.jar 
-DgroupId=com.airhacks -DartifactId=afterburner.fx -Dversion=1.6.2 -Dpackaging=jar
---


xplr is apache licensed GitHub project: https://github.com/AdamBien/xplr. First release is available for download (15 kB).

Happy migrations! See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


NEW workshop: Building HTML 5 Applications With Angular 2
Full week in December 2016: from Java EE 7 Bootstrap, Effective, Architectures over Testing to Microservices
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacksnews.com

A book about rethinking Java EE Patterns

realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License