Echo your REST calls with a echo service

Echo services are a simple tool for developing and testing

When you implement a service are often in a situation where you have to call another web service, for example service B. And to complicate the situation, service B is not fully implemented or even not available. Than an echo service could make sense for you.

There a couple of services your could use. I tried an service as an docker image: https://github.com/mendhak/docker-http-https-echo.

Just start the docker container like this

docker run -p 8080:80 -p 8443:443 --rm -t mendhak/http-https-echo

And then you can request a resource via curl:

[code]
curl -d ‚{"key1":"value1", "key2":"value2"}‘ -H "Content-Type: application/json" -X POST http://localhost:8080/helloworld
[/code]

You get your request echoed and with docker logs you can see your request in a log too. I think that’s cool. If you like node.js that could find https://www.npmjs.com/package/http-echo-server more interesting.

I really like echo services for simple use cases. But if your interested in more advanced use cases than tools like mountebank or wiremock are more pwerful solutions. These tools are test doubles over the wire. Just point your test over http. And this way you can stub and mock web services in your tests.

Links

https://github.com/mendhak/docker-http-https-echo

https://www.npmjs.com/package/http-echo-server

http://www.mbtest.org/

http://wiremock.org/

Counting active accounts with Metrics

Based on a request parameter in a servlet context

Recently I had the task to report active accounts based on http requests. Here I’m going to show you my solution with Dropwizard Metrics.

Basically I am using a servlet filter togehter with an counter.

[code]
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
try {
chain.doFilter(request, response);
} catch (IOException | ServletException e) {
LOG.error("unexpected exception occurred", e);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "unexpected exception occurred");
} finally {
String accountNumber = request.getParameter("account");
countRequestForAccount(accountNumber);
}
}

private void countRequestForAccount(int account) {
if(activeAccounts.containsKey(account))
{
activeAccounts.get(account).inc();
} else if(activeAccounts.size() <= MAX_SIZE) {
metricsRegistry.counter(Integer.toString(account)).inc();
}
}
[/code]

Each account has its own counter. So I have a ConcurrentHashMap activeAccounts with account and counter. If there is a parameter „account“ in the request, I increase the counter for that account.

The second requirement was to save the active accounts with counter in a csv file.

[code]
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters,
SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
for (Entry<String, Counter> entry : counters.entrySet()) {
Counter value = entry.getValue();
writer.write(String.format("%s;%d%n", entry.getKey(), value.getCount()));
}
} catch (IOException e) {
LOG.error("couldn’t write report file " + path, e);
}
}
[/code]

I extended a ScheduledReporter as shown above. The csv file has the format

account;counter

And at last, I putted together all the pieces in my servlet class.

[code]

public void init() throws ServletException {

MetricRegistry metricsRegistry = (MetricRegistry) getServletContext().getAttribute(MetricsServlet.METRICS_REGISTRY);
Path path = Paths.get("/tmp/activeAccounts.cvs"));

reporter = new ActiveAccountsReporter(metricsRegistry, path);
reporter.start(ACTIVE_ACCOUNTS_REPORT_PERIOD_SEC, TimeUnit.SECONDS);
}
}
[/code]

That’s it. I hope you like my article.
On GistGitHub you can read the whole example.

Update your package dependencies

So why should I update the deps for my application?

Keeping your dependencies up-to-date is more important than ever
One reason is that if you update the dependencies regularly than you can do painless migrations. Nearly every 6 months major releases of frameworks e.g like angular or react with API breaking changes are available. And such a frequent release policy applies not only for frameworks, but also for libraries and tools you need for developing your app.

Another aspect is security. Today everything is connected to the internet. New vulnerabilities in libraries are found, exploited and patched within days. That means everytime a vulnerability is found, you have to update the dependency asap.

So not to be left behind, we have to chreck the dependencies on a regulary base. Tools like npm-check-updated or maven with the versions plugin help us to stay up-to-date.

Solid dependency management is a primary requirement. And package updates should be a regular step in your software development cycle.

Workaround – No tests found with Testrunner JUnit 5

Java 8, Eclipse, JUnit 5 & Gradle

It seems to be a bug in Eclipse and it’is fixed in the Oxgen Release 3 (4.7.3).

But I still have the problem in my Java 8 project. So I did a little trick.
I changed the version for the engine and the launcher back to 5.1.0.

[code]

testCompile group: ‚org.junit.jupiter‘, name: ‚junit-jupiter-engine‘, version: "5.1.0"
testCompile group: ‚org.junit.platform‘, name: ‚junit-platform-launcher‘, version: "5.1.0"

[/code]

Now, all the tests run in Eclipse too 😉

Links

https://gist.github.com/claudioaltamura/b4350d1ffa0f5597f8c1f4d019938e03

https://junit.org/junit5/docs/current/user-guide/

https://bugs.eclipse.org/bugs/show_bug.cgi?id=525948

Calculate memory usage of Java objects

With Twitter’s ObjectSizeCalculator

If you are looking for an easy way to estimate the object size than this could interest you.

[code]

// gradle dependency
// https://mvnrepository.com/artifact/com.twitter.common/objectsize 
compile group: ‚com.twitter.common‘, name: ‚objectsize‘, version: ‚0.0.12‘

System.out.println(
ObjectSizeCalculator.getObjectSize(myObject)
);

[/code]

The memory size of your object depends on the architecture, the actual vm implementation and whether the VM is 32 or 64-bit. ObjectSizeCalculator supports only the Hotspot JVM.

For more information see the javadoc ObjectSizeCalculator.

Links
https://twitter.github.io/commons/

https://stackoverflow.com/questions/9368764/calculate-size-of-object-in-java

https://dzone.com/articles/java-how-to-calculate-size-of-objects-amp-arrays-b

Hey SDKMAN!

This tool is great!

I came across SDKMAN in a Spring tutorial. It’s a tool like rvm which helps you to manage parallel version of a SDK for the JVM like:

* Java
* Gradle
* Groovy
* Kotlin
* Maven
* Scala
* Spring Boot
* Vert.x

It’s what compelling, so I installed it immediately:

[code]
$ curl -s "https://get.sdkman.io" | bash
[/code]

And the tool updates itselfs when it detects a newer version 🙂

Installation goes like that

[code]
$sdk install kotlin

Downloading: kotlin 1.2.30

In progress…

######################################################################## 100,0%

Installing: kotlin 1.2.30
Done installing!

Setting kotlin 1.2.30 as default.

[/code]

And an installed version is removed by

[code]
$sdk uninstall kotlin 1.2.30
[/code]

With $sdk list kotlin you get list of available versions. So if you decide to switch to a specific version, just type

[code]
$sdk use kotlin 1.2.20
[/code]

To check which version you use, do the following

[code]
$sdk current kotlin
[/code]

$sdk default kotlin 1.2.30 will ensure that all new terminals will use this kotlin version.
And at least, if a new version has a arrived, upgrade with this command

[code]
$sdk upgrade kotlin
[/code]

 

Resources
http://sdkman.io

 

Embedded Jetty with Servlet and Annotations

How do I programmatically configure Jetty that I can use Servlet Annotations?

If you doing just servlets with jetty, this article could be interesting for you.

I show you how I did it. Here comes the configuration:

[code]

server = new Server(port);
server.addBean(LOG);
WebAppContext webAppContext = new WebAppContext();
webAppContext.setContextPath("/");
String webxmlLocation = JettyServer.class.getResource("/webapp/WEB-INF/web.xml").toString();
webAppContext.setDescriptor(webxmlLocation);
String resLocation = JettyServer.class.getResource("/webapp").toString();
webAppContext.setResourceBase(resLocation); webAppContext.setParentLoaderPriority(true);
webAppContext.getMetaData().addContainerResource(Resource.newResource(
new File(JettyServer.class.getProtectionDomain().getCodeSource().getLocation().getPath())));
webAppContext.setConfigurations(new Configuration[] { new WebInfConfiguration(), new WebXmlConfiguration(),
new MetaInfConfiguration(), new FragmentConfiguration(), new EnvConfiguration(), new PlusConfiguration(),
new AnnotationConfiguration(), new JettyWebXmlConfiguration() });
server.setHandler(webAppContext);
server.start();

[/code]

And I defined the following dependencies in build.gradle.

[code]

def jettyVersion = ‚9.4.7.v20170914‘
dependencies {
providedCompile ‚javax.servlet:javax.servlet-api:3.1.0‘
compile group: ‚org.eclipse.jetty‘, name: ‚jetty-servlet‘, version: jettyVersion
compile group: ‚org.eclipse.jetty‘, name: ‚jetty-webapp‘, version: jettyVersion
compile group: ‚org.eclipse.jetty‘, name: ‚jetty-annotations‘, version: jettyVersion
compile group: ‚org.eclipse.jetty‘, name: ‚jetty-plus‘, version: jettyVersion
compile group: ‚org.eclipse.jetty‘, name: ‚apache-jsp‘, version: jettyVersion
compile group: ‚org.ow2.asm‘, name: ‚asm‘, version: ‚5.1‘
compile group: ‚org.slf4j‘, name: ’slf4j-api‘, version: ‚1.7.25‘
compile group: ‚org.slf4j‘, name: ’slf4j-log4j12′, version: ‚1.7.25‘
compile group: ‚log4j‘, name: ‚log4j‘, version: ‚1.2.17‘

}

[/code]

That’s all. Hope this helps!

GitHub-Mark-32pxHere is the link to an working github project:
jetty-embedded-webannotations-gradle

 

 

 

 

 

 

 

Why you should use new language features

A quick list

I put together a list with a number of reasons why you should use new language features.
The list includes points which are obvious, I learned or I found on the internet.

improved design
* easier to understand
* easier to change
* less defects

effectiveness
* using standards
* getting help on the internet is easy
* much easier for new colleagues getting started

efficiency
* faster
* writing less code
* leads to a smaller code base

Every push a build with Travis CI

Build and test your software projects automatically

I wanted that cool build passed badge for my projects as I have seen at Github.

So I had a look at Travis CI, which is a continuous integration service used to build and test software projects. Let’s have a look at the build file.

.travis.yml

[code]
language: java

[/code]

That’s it. I tried Travis with one of mine projects. I use gradle as a build tool.

Build errror!? Why? ./gradlew assemble doesn’t work? Mmmh, okay that’s right. I didn’t used that logging library.

Build failed. Again. What? The integration test failed? I did a really small change. I thought that change couldn’t break the test. False! I commited and pushed the changed without testing.

Unbelievable, I needed more than 3 attempts. Finally, my github project was built successfully with Travis. Now my current travis file looks like this:

[code]
language: java
notifications:
email:
recipients:
– my@mail.com
on_failure: always

[/code]

For that cool badge I added the following in my README file .

[code]
[![Build Status](https://travis-ci.org/your_account/you_project.svg?branch=master)](https://travis-ci.org/your_account/you_project)
[/code]

 

If you like, you can add a lot of other badges, e.g. for code coverage, docs, number of downloads, version or license. Travis CI is cool 🙂

 

Links

https:/travis-ci.org

https://shields.io/

Unit Testing Servlets with Mockito

A quick example how to write unit tests for servlets

Okay, I’m writing a Servlet. So I want to write a unit test too.
With Mockito this is a quite simple task.

Here I show you a simple unit test for a Hello World Servlet.
The Servlet returns only „Hello World“.

[code]
public class HelloWorldServletTest {

@Spy private HelloWorldServlet servlet;
@Mock private ServletConfig servletConfig;
@Mock private HttpServletRequest request;
@Mock private HttpServletResponse response;
@Mock private ServletOutputStream outputStream;

@Before public void setUp() {
MockitoAnnotations.initMocks(this);
}

@Test public void test() throws Exception {
when(servlet.getServletConfig()).thenReturn(servletConfig);
when(response.getOutputStream()).thenReturn(outputStream);
servlet.doGet(request, response);
verify(outputStream).println("Hello World!");
}

}
[/code]

Mockito offers various annotations. For partial mocking you can use @Spy.
I’m mocking the request and response object with @Mock.
Then I call the servlet.doGet() method. And of course,
I also have to mock ServletConfig and Outputstream too. That’s it.

Pretty easy, isn’t it? Quick note: If your programmic logic is too complex,
move the logic to an concrete class and write a simple unit test.

GitHub-Mark-32px Check out the whole example on Github.

 

Resources

http://site.mockito.org/

Consent Management Platform von Real Cookie Banner