filechampion4j 0.9.8.3
File validation library for Java
Loading...
Searching...
No Matches
dev.filechampion.filechampion4j.CliPluginHelper Class Reference
Collaboration diagram for dev.filechampion.filechampion4j.CliPluginHelper:
Collaboration graph

Public Member Functions

 CliPluginHelper (StepConfig singleStepConfig)
 
Map< String, Map< String, String > > execute (String fileExtension, byte[] fileContent)
 

Private Member Functions

void logFine (String message)
 
void logWarn (String message)
 
Map< String, String > extractResponsePatterns (String results)
 
void prepEndpoint (String filePath, byte[] fileContent)
 
String timedProcessExecution (String command) throws IOException, InterruptedException, NullPointerException
 
Path saveFileToTempDir (String fileExtension, byte[] originalFile)
 
Boolean deleteTempDir (Path tempFilePath)
 
String calculateChecksum (byte[] fileBytes, String checksumAlgorithm)
 

Private Attributes

StepConfig singleStepConfig
 
int timeout
 
String errString = "Error: "
 
String endpoint
 
String responseConfig
 
StringBuilder logMessage = new StringBuilder()
 

Static Private Attributes

static final Logger LOGGER = Logger.getLogger(CliPluginHelper.class.getName())
 

Detailed Description

CliPluginHelper class is used to execute CLI commands Defined in the FileChampion Plugins. The class is responsible for injecting file path/content/hash into the CLI command, execute the command, and process the results.

Definition at line 30 of file CliPluginHelper.java.

Constructor & Destructor Documentation

◆ CliPluginHelper()

dev.filechampion.filechampion4j.CliPluginHelper.CliPluginHelper ( StepConfig  singleStepConfig)

Constructor for CliPluginHelper

Parameters
singleStepConfig(StepConfig) - the step configuration

Definition at line 53 of file CliPluginHelper.java.

References dev.filechampion.filechampion4j.PluginsHelper.StepConfig.getEndpoint(), dev.filechampion.filechampion4j.PluginsHelper.StepConfig.getName(), dev.filechampion.filechampion4j.PluginsHelper.StepConfig.getResponse(), dev.filechampion.filechampion4j.PluginsHelper.StepConfig.getTimeout(), dev.filechampion.filechampion4j.CliPluginHelper.logFine(), dev.filechampion.filechampion4j.CliPluginHelper.logMessage, and dev.filechampion.filechampion4j.CliPluginHelper.singleStepConfig.

Here is the call graph for this function:

Member Function Documentation

◆ calculateChecksum()

String dev.filechampion.filechampion4j.CliPluginHelper.calculateChecksum ( byte[]  fileBytes,
String  checksumAlgorithm 
)
private

Calculate the checksum of the file

Parameters
fileBytes(byte[]) the file bytes of the file being validated
Returns
String (String) the SHA-256 checksum of the file

Definition at line 293 of file CliPluginHelper.java.

293 {
294 try {
295 CalculateChecksum paralChecksum = new CalculateChecksum(fileBytes);
296 byte[] checksum = paralChecksum.getChecksum(checksumAlgorithm);
297 return new BigInteger(1, checksum).toString(16);
298 } catch (Exception e) {
299 e.printStackTrace();
300 return null;
301 }
302 }

References dev.filechampion.filechampion4j.CalculateChecksum.getChecksum().

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.prepEndpoint().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ deleteTempDir()

Boolean dev.filechampion.filechampion4j.CliPluginHelper.deleteTempDir ( Path  tempFilePath)
private

Deletes the temporary directory

Parameters
tempFilePath(Path) - the path to the temporary directory
Returns
Boolean - true if the directory was deleted successfully, false otherwise

Definition at line 275 of file CliPluginHelper.java.

275 {
276 try (Stream<Path> walk = Files.walk(tempFilePath)) {
277 walk.sorted(Comparator.reverseOrder())
278 .map(Path::toFile)
279 .forEach(File::delete);
280 return true;
281 } catch (Exception e) {
282 logMessage.replace(0, logMessage.length(), "Error deleteTempDir failed: ").append(e.getMessage());
283 logWarn(logMessage.toString());
284 return false;
285 }
286 }

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.execute().

Here is the caller graph for this function:

◆ execute()

Map< String, Map< String, String > > dev.filechampion.filechampion4j.CliPluginHelper.execute ( String  fileExtension,
byte[]  fileContent 
)

Executes the CLI command

Parameters
fileExtension(String) - the file extension
fileContent(byte[]) - the file content
Returns
Map<String, Map<String, String>> - the results map

Definition at line 68 of file CliPluginHelper.java.

68 {
69 String result = "";
70 Map<String, Map<String, String>> responseMap = new HashMap<>();
71 Map<String, String> responsePatterns = new HashMap<>();
72 Path filePathRaw;
73
74 filePathRaw = saveFileToTempDir(fileExtension, fileContent);
75 if (filePathRaw == null) {
76 responsePatterns.put(errString, "Failed to save file to temporary directory");
77 responseMap.put(errString, responsePatterns);
78 return responseMap;
79 }
80
81 String filePath = filePathRaw.toString();
82 prepEndpoint(filePath, fileContent);
83 logMessage.replace(0, logMessage.length(), singleStepConfig.getName()).append(" endpoint: ").append(endpoint);
84 logFine(logMessage.toString());
85
86 try {
88 logFine(singleStepConfig.getName() + " result: " + result);
89 } catch (IOException|NullPointerException|InterruptedException e) {
90 Thread.currentThread().interrupt();
91 responsePatterns.put(errString, e.getMessage());
92 }
93
94 String expectedResults = responseConfig.substring(0, responseConfig.indexOf("${")>-1?
95 responseConfig.indexOf("${") : responseConfig.length());
96
97 if (result.contains(expectedResults)) {
98 responsePatterns = extractResponsePatterns(result);
99 responseMap.put("Success", responsePatterns);
100 return responseMap;
101 } else {
102 logMessage.replace(0, logMessage.length(), "Error, expected: \"")
103 .append(expectedResults).append("\", received: ");
104 responsePatterns.put(logMessage.toString(), result);
105 responseMap.put(errString, responsePatterns);
106 deleteTempDir(filePathRaw);
107 return responseMap;
108 }
109 }
void prepEndpoint(String filePath, byte[] fileContent)
Path saveFileToTempDir(String fileExtension, byte[] originalFile)
Map< String, String > extractResponsePatterns(String results)

References dev.filechampion.filechampion4j.CliPluginHelper.deleteTempDir(), dev.filechampion.filechampion4j.CliPluginHelper.endpoint, dev.filechampion.filechampion4j.CliPluginHelper.errString, dev.filechampion.filechampion4j.CliPluginHelper.extractResponsePatterns(), dev.filechampion.filechampion4j.PluginsHelper.StepConfig.getName(), dev.filechampion.filechampion4j.CliPluginHelper.logFine(), dev.filechampion.filechampion4j.CliPluginHelper.logMessage, dev.filechampion.filechampion4j.CliPluginHelper.prepEndpoint(), dev.filechampion.filechampion4j.CliPluginHelper.responseConfig, dev.filechampion.filechampion4j.CliPluginHelper.saveFileToTempDir(), dev.filechampion.filechampion4j.CliPluginHelper.singleStepConfig, and dev.filechampion.filechampion4j.CliPluginHelper.timedProcessExecution().

Here is the call graph for this function:

◆ extractResponsePatterns()

Map< String, String > dev.filechampion.filechampion4j.CliPluginHelper.extractResponsePatterns ( String  results)
private

Extracts the response patterns from the results

Parameters
results(String) - the results
Returns
Map<String, String> - the response patterns map

Definition at line 116 of file CliPluginHelper.java.

116 {
117 Map<String, String> responsePatterns = new HashMap<>();
118
119 // Extract the placeholder name from the response pattern
120 Pattern placeholderPattern = Pattern.compile("\\$\\{(.+?)\\}");
121 Matcher placeholderMatcher = placeholderPattern.matcher(responseConfig);
122 if (!placeholderMatcher.find()) {
123 responsePatterns.put(results, results);
124 return responsePatterns;
125
126 }
127 do {
128 String placeholderName = placeholderMatcher.group(1);
129 String placeholderValue;
130
131 logMessage.replace(0, logMessage.length(), "Placeholder name: ")
132 .append(placeholderName)
133 .append(", ResponseConfig: ")
134 .append(responseConfig);
135 logFine(logMessage.toString());
136
137 String fixedPrefix = String.format("%s", responseConfig.substring(0, responseConfig.indexOf("${")));
138 logMessage.replace(0, logMessage.length(), "Fixed prefix: ").append(fixedPrefix);
139 logFine(logMessage.toString());
140
141 String fixedSuffix;
142 int suffixStartIndex = responseConfig.indexOf("${") + placeholderName.length() + 3;
143 if (suffixStartIndex == responseConfig.length()) {
144 fixedSuffix = "";
145 } else {
146 fixedSuffix = responseConfig.substring(suffixStartIndex);
147 logMessage.replace(0, logMessage.length(), "Fixed suffix: ").append(fixedSuffix);
148 logFine(logMessage.toString());
149 }
150
151 String captureGroupPattern = String.format("%s(.*)%s", fixedPrefix, fixedSuffix);
152 logMessage.replace(0, logMessage.length(), "Capture group pattern: ").append(captureGroupPattern);
153 logFine(logMessage.toString());
154
155 Pattern pattern = Pattern.compile(captureGroupPattern);
156 Matcher matcher = pattern.matcher(results);
157
158 if (matcher.find()) {
159 placeholderValue = matcher.group(1);
160 responsePatterns.put(placeholderName, placeholderValue);
161 }
162
163 } while (placeholderMatcher.find());
164
165 return responsePatterns;
166 }

References dev.filechampion.filechampion4j.CliPluginHelper.logFine(), dev.filechampion.filechampion4j.CliPluginHelper.logMessage, and dev.filechampion.filechampion4j.CliPluginHelper.responseConfig.

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.execute().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ logFine()

void dev.filechampion.filechampion4j.CliPluginHelper.logFine ( String  message)
private

◆ logWarn()

void dev.filechampion.filechampion4j.CliPluginHelper.logWarn ( String  message)
private

Definition at line 43 of file CliPluginHelper.java.

43 {
44 if (LOGGER.isLoggable(Level.WARNING)) {
45 LOGGER.warning(message);
46 }
47 }

References dev.filechampion.filechampion4j.CliPluginHelper.LOGGER.

◆ prepEndpoint()

void dev.filechampion.filechampion4j.CliPluginHelper.prepEndpoint ( String  filePath,
byte[]  fileContent 
)
private

Prepares the endpoint command by replacing the placeholders with the actual values

Parameters
filePath(String) - the path to the file
fileContent(byte[]) - the file content

Definition at line 173 of file CliPluginHelper.java.

173 {
174
175 String newEndpoint = endpoint.contains("${filePath}") ? endpoint.replace("${filePath}", filePath) : endpoint;
176 newEndpoint = newEndpoint.contains("${fileContent}") ? newEndpoint.replace("${fileContent}", Base64.getEncoder().encodeToString(fileContent)) : newEndpoint;
177 newEndpoint = newEndpoint.contains("${fileChecksum.md5}") ? newEndpoint.replace("${fileChecksum.md5}", calculateChecksum(fileContent, "MD5")) : newEndpoint;
178 newEndpoint = newEndpoint.contains("${fileChecksum.sha1}") ? newEndpoint.replace("${fileChecksum.sha1}", calculateChecksum(fileContent, "SHA-1")) : newEndpoint;
179 newEndpoint = newEndpoint.contains("${fileChecksum.sha256}") ? newEndpoint.replace("${fileChecksum.sha256}", calculateChecksum(fileContent, "SHA-256")) : newEndpoint;
180 newEndpoint = newEndpoint.contains("${fileChecksum.sha512}") ? newEndpoint.replace("${fileChecksum.sha512}", calculateChecksum(fileContent, "SHA-512")) : newEndpoint;
181 endpoint = newEndpoint;
182 }
String calculateChecksum(byte[] fileBytes, String checksumAlgorithm)

References dev.filechampion.filechampion4j.CliPluginHelper.calculateChecksum(), and dev.filechampion.filechampion4j.CliPluginHelper.endpoint.

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.execute().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ saveFileToTempDir()

Path dev.filechampion.filechampion4j.CliPluginHelper.saveFileToTempDir ( String  fileExtension,
byte[]  originalFile 
)
private

Saves the file to a temporary directory

Parameters
fileExtension(String) - the file extension
originalFile(byte[]) - the file content
Returns
Path - the path to the file

Definition at line 255 of file CliPluginHelper.java.

255 {
256 Path tempFilePath;
257 try {
258 // Create a temporary directory
259 Path tempDir = Files.createTempDirectory("tempDir");
260 tempFilePath = Files.createTempFile(tempDir, "tempFile", "." + fileExtension);
261 Files.write(tempFilePath, originalFile);
262 return tempFilePath;
263 } catch (Exception e) {
264 logMessage.replace(0, logMessage.length(), "Error saveFileToTempDir failed: ").append(e.getMessage());
265 logWarn(logMessage.toString());
266 return null;
267 }
268 }

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.execute().

Here is the caller graph for this function:

◆ timedProcessExecution()

String dev.filechampion.filechampion4j.CliPluginHelper.timedProcessExecution ( String  command) throws IOException, InterruptedException, NullPointerException
private

Executes the CLI command with a timeout

Parameters
command(String) - the command to execute
Returns
String - the results
Exceptions
IOException
InterruptedException
NullPointerException

Definition at line 192 of file CliPluginHelper.java.

192 {
193 ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\p{Zs}+"));
194 logMessage.replace(0, logMessage.length(), "Process starting: ").append(command);
195 logFine(logMessage.toString());
196
197 long timeoutCounter = System.currentTimeMillis();
198 Process process = processBuilder.start();
199 TimeUnit timeUnit = TimeUnit.SECONDS;
200 java.util.Timer timer = new java.util.Timer();
201 timer.schedule(
202 new java.util.TimerTask() {
203 @Override
204 public void run() {
205 process.destroy();
206 }
207 },
208 timeUnit.toMillis(timeout)
209 );
210 int exitCode = process.waitFor();
211 InputStream inputStream = process.getInputStream();
212 InputStream errorStream = process.getErrorStream();
213 SequenceInputStream sequenceInputStream = new SequenceInputStream(inputStream, errorStream);
214 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(sequenceInputStream));
215 try(Scanner scanner = new Scanner(bufferedReader).useDelimiter("\\A")){
216 String results;
217 if (exitCode == 143 || exitCode == 1) {
218 if (System.currentTimeMillis() - timeoutCounter > timeout * 1000) {
219 bufferedReader.close();
220 sequenceInputStream.close();
221 errorStream.close();
222 inputStream.close();
223 logMessage.replace(0, logMessage.length(), errString).append("Process timeout: ").append(command);
224 logWarn(logMessage.toString());
225 return logMessage.toString();
226 }
227 results = scanner.hasNext() ? scanner.next() : "";
228 bufferedReader.close();
229 sequenceInputStream.close();
230 errorStream.close();
231 inputStream.close();
232 timer.cancel();
233 logMessage.replace(0, logMessage.length(), errString).append(command) .append("Process failed: ").append(results);
234 logWarn(logMessage.toString());
235 return logMessage.toString();
236 }
237 results = scanner.hasNext() ? scanner.next() : "";
238 bufferedReader.close();
239 sequenceInputStream.close();
240 errorStream.close();
241 inputStream.close();
242 timer.cancel();
243 logFine(results);
244 return results;
245 }
246 }

References dev.filechampion.filechampion4j.CliPluginHelper.logFine(), and dev.filechampion.filechampion4j.CliPluginHelper.logMessage.

Referenced by dev.filechampion.filechampion4j.CliPluginHelper.execute().

Here is the call graph for this function:
Here is the caller graph for this function:

Member Data Documentation

◆ endpoint

String dev.filechampion.filechampion4j.CliPluginHelper.endpoint
private

◆ errString

String dev.filechampion.filechampion4j.CliPluginHelper.errString = "Error: "
private

◆ LOGGER

final Logger dev.filechampion.filechampion4j.CliPluginHelper.LOGGER = Logger.getLogger(CliPluginHelper.class.getName())
staticprivate

◆ logMessage

◆ responseConfig

String dev.filechampion.filechampion4j.CliPluginHelper.responseConfig
private

◆ singleStepConfig

StepConfig dev.filechampion.filechampion4j.CliPluginHelper.singleStepConfig
private

◆ timeout

int dev.filechampion.filechampion4j.CliPluginHelper.timeout
private

Definition at line 32 of file CliPluginHelper.java.


The documentation for this class was generated from the following file: