001/* 
002 * Copyright (C) 2016 Hobrasoft s.r.o.
003 *
004 * This program is free software: you can redistribute it and/or modify
005 * it under the terms of the GNU Affero General Public License as published by
006 * the Free Software Foundation, either version 3 of the License, or
007 * (at your option) any later version.
008 *
009 * This program is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012 * GNU Affero General Public License for more details.
013 *
014 * You should have received a copy of the GNU Affero General Public License
015 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
016 */
017package cz.hobrasoft.pdfmu;
018
019import cz.hobrasoft.pdfmu.error.ErrorType;
020import cz.hobrasoft.pdfmu.operation.OperationException;
021import java.util.LinkedHashMap;
022import java.util.List;
023import java.util.Map;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027/**
028 *
029 * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a>
030 */
031public class ExceptionMessagePattern {
032
033    private final ErrorType errorType;
034    private final String regex;
035    private final List<String> groupNames;
036
037    public ExceptionMessagePattern(ErrorType errorType, String regex, List<String> groupNames) {
038        this.errorType = errorType;
039        this.regex = regex;
040        this.groupNames = groupNames;
041    }
042
043    /**
044     * Tries to convert an exception to an {@link OperationException}.
045     *
046     * @param e the exception to parse
047     * @return an instance of {@link OperationException} if the pattern matches
048     * the message of e, or null otherwise.
049     */
050    public OperationException getOperationException(Exception e) {
051        String message = e.getMessage();
052        Pattern p = Pattern.compile(regex);
053        Matcher m = p.matcher(message);
054        if (m.matches()) {
055            Map<String, String> arguments = PdfmuUtils.getMatcherGroups(m, groupNames);
056            Map<String, Object> argumentsObjects = new LinkedHashMap<>();
057            argumentsObjects.putAll(arguments);
058            return new OperationException(errorType, e, argumentsObjects);
059        }
060        return null;
061    }
062}