1 package org.imageconverter.config.health;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.IOException;
5 import java.util.Objects;
6
7 import javax.imageio.ImageIO;
8
9 import org.apache.commons.lang3.StringUtils;
10 import org.apache.commons.lang3.exception.ExceptionUtils;
11 import org.imageconverter.util.BeanUtil;
12 import org.springframework.beans.factory.annotation.Value;
13 import org.springframework.boot.actuate.health.Health;
14 import org.springframework.boot.actuate.health.HealthIndicator;
15 import org.springframework.core.io.Resource;
16 import org.springframework.stereotype.Component;
17
18 import net.sourceforge.tess4j.ITesseract;
19 import net.sourceforge.tess4j.TesseractException;
20
21
22
23
24
25
26 @Component("tesseract")
27 public class TesseractHealthService implements HealthIndicator {
28
29 private final Resource imageFile;
30
31
32
33
34
35
36 public TesseractHealthService(@Value("classpath:check-image.png") final Resource imageFile) {
37 super();
38 this.imageFile = imageFile;
39 }
40
41
42
43
44 @Override
45 public Health health() {
46
47 final var error = checkTesseract();
48
49 final Health result;
50
51 if (StringUtils.isNotBlank(error)) {
52 result = Health.down().withDetail("Error", error).build();
53 } else {
54 result = Health.up().build();
55 }
56
57 return result;
58 }
59
60
61
62
63
64
65 private String checkTesseract() {
66
67 final var tesseractBeanProvider = BeanUtil.getBeanProviderFrom(ITesseract.class);
68 final var tesseract = tesseractBeanProvider.getObject();
69
70 String result;
71
72 if (Objects.isNull(tesseract)) {
73
74 result = "Tesseract isn't configured";
75
76 } else {
77
78 try {
79
80 final var bufferedImage = ImageIO.read(new ByteArrayInputStream(imageFile.getInputStream().readAllBytes()));
81
82 final var numberOne = tesseract.doOCR(bufferedImage).replaceAll("\\D+", "");
83
84 if (StringUtils.equalsIgnoreCase(numberOne, "033")) {
85 result = StringUtils.EMPTY;
86 } else {
87 result = "Tesseract isn't work";
88 }
89
90 } catch (final IllegalArgumentException ex) {
91
92 result = "Tesseract has configurations issues";
93
94 } catch (final TesseractException | IOException ex) {
95 result = ExceptionUtils.getRootCauseMessage(ex);
96 }
97
98 }
99
100 return result;
101 }
102 }