SimpleHttpTicker.java

package org.flasby.christmas.monitor;

import java.io.IOException;
import java.util.Arrays;

import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import lombok.extern.log4j.Log4j2;

@Log4j2
public abstract class SimpleHttpTicker implements PollingRunner {

    public abstract RawMeasurements handleResponse(String[] params, final String responseBody) throws PollException;

    @Override
    public final RawMeasurements run(String[] params) throws PollException {
        log.debug("    ---- Ticker ---- : (" + params.length + ") " + Arrays.toString(params));
        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final HttpGet httpget = new HttpGet(params[0]);

            // Create a custom response handler
            final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
                @Override
                public String handleResponse(final ClassicHttpResponse response) throws IOException {
                    final int status = response.getCode();
					if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
						final HttpEntity entity = response.getEntity();
						try {
							return entity != null ? EntityUtils.toString(entity) : null;
						} catch (final ParseException ex) {
							throw new ClientProtocolException(ex);
						}
					} else {
						throw new ClientProtocolException("Unexpected response status: " + status);
					}
                }
            };

            final String responseBody = httpclient.execute(httpget, responseHandler);
            if (log.isDebugEnabled()) {
                log.debug("----------------------------------------");
                log.debug(responseBody);
            }
            return handleResponse(params, responseBody);

        } catch( IOException ex ) {
            throw new PollException(ex.getMessage(), ex);
        }
    }
}