src/org/myorg/myscclient/ServiceLevelException.java

package org.myorg.myscclient;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.openide.util.NbBundle;
import org.w3c.dom.Document;


class ServiceLevelException extends IOException {

    private static final Logger LOG = Logger.getLogger(ServiceLevelException.class.getName());

    private static final String errorCode = "/error/error_code"; //NOI18N
    private static final String errorDetails = "/error/error_details"; //NOI18N

    private ServiceErrorType type = ServiceErrorType.OTHER;
    private String details = "";

    public ServiceLevelException(String xmlDoc) {
        super(xmlDoc);
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            Document xmlDocument = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlDoc.getBytes("UTF-8"))); //NOI18N
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xPath = xPathFactory.newXPath();
            XPathExpression xPathExpression = xPath.compile(errorCode);
            this.type = ServiceErrorType.findById((String) xPathExpression.evaluate(xmlDocument, XPathConstants.STRING));
            xPathExpression = xPath.compile(errorDetails);
            this.details = (String) xPathExpression.evaluate(xmlDocument, XPathConstants.STRING);
        } catch (Exception ex) {
            LOG.log(Level.INFO, "Received incorrecr response form the server: ", ex); // NOI18N
            LOG.log(Level.INFO, "Returned XML: {0}", xmlDoc); // NOI18N
        }
    }

    public ServiceErrorType getType() {
        return type;
    }

    public String getDetails() {
        return details;
    }

    public static enum ServiceErrorType {

        PARSE(1000, "MSG_Parse"),
        VALIDATION(1001, "MSG_Validation"),
        GENERATE(1002, "MSG_Generate"),
        OTHER(1010, "MSG_Other");

        private int code;
        private String message;

        ServiceErrorType(int code, String messageKey) {
            this.code = code;
            this.message = NbBundle.getMessage(ServiceLevelException.class, messageKey);
        }

        public int getCode() {
            return code;
        }

        public String getMessage() {
            return message;
        }

        public static ServiceErrorType findById(String code) {
            int codeInt = Integer.parseInt(code);
            for (ServiceErrorType x: values()) {
                if (x.getCode() == codeInt) {
                    return x;
                }
            }
            return null;
        }
    }
}