1 /*
2 * Copyright (C) 2016 Hobrasoft s.r.o.
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package cz.hobrasoft.pdfmu;
18
19 import cz.hobrasoft.pdfmu.error.ErrorType;
20 import cz.hobrasoft.pdfmu.operation.OperationException;
21 import java.util.LinkedHashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 /**
28 *
29 * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
30 */
31 public class ExceptionMessagePattern {
32
33 private final ErrorType errorType;
34 private final String regex;
35 private final List<String> groupNames;
36
37 public ExceptionMessagePattern(ErrorType errorType, String regex, List<String> groupNames) {
38 this.errorType = errorType;
39 this.regex = regex;
40 this.groupNames = groupNames;
41 }
42
43 /**
44 * Tries to convert an exception to an {@link OperationException}.
45 *
46 * @param e the exception to parse
47 * @return an instance of {@link OperationException} if the pattern matches
48 * the message of e, or null otherwise.
49 */
50 public OperationException getOperationException(Exception e) {
51 String message = e.getMessage();
52 Pattern p = Pattern.compile(regex);
53 Matcher m = p.matcher(message);
54 if (m.matches()) {
55 Map<String, String> arguments = PdfmuUtils.getMatcherGroups(m, groupNames);
56 Map<String, Object> argumentsObjects = new LinkedHashMap<>();
57 argumentsObjects.putAll(arguments);
58 return new OperationException(errorType, e, argumentsObjects);
59 }
60 return null;
61 }
62 }