com.alefissak.parsers.PlanningParserImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.alefissak.parsers.PlanningParserImpl.java

Source

/**
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2014 - Nabil Andriantomanga.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alefissak.parsers;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import org.dom4j.Document;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alefissak.AlefissakMessageConcret;
import com.alefissak.AlefissakReceiver;
import com.alefissak.AlefissakSender;
import com.alefissak.Message;
import com.alefissak.Planning;
import com.alefissak.TimeInterval;
import com.alefissak.io.AlefissakFileNotFoundException;
import com.alefissak.util.AlefissakUtil;

/**
 * @author Nabil
 */
public abstract class PlanningParserImpl implements IPlanningParser {

    private static final String CFG_NAME_ATTRIBUTE_NAME = "@name";

    private static final String CFG_VARS_DELIMITER = ";";

    private static final Logger LOG = LoggerFactory.getLogger(PlanningParserImpl.class);

    /**
     * <h5>French</h5> :
     * <p>
     * Permet de rcuprer l'objet document correspondant au fichier de
     * configuration fourni par l'utilisateur.
     * </p>
     * <h5>Anglais</h5> :
     * <p>
     * Used to retrieve the document object for the configuration file provided
     * by the user.
     * </p>
     * 
     * @return the document object
     * @throws AlefissakFileNotFoundException
     * @throws AlefissakParsingException
     */
    public abstract Document getDocument() throws AlefissakFileNotFoundException, AlefissakParsingException;

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Planning> parse() throws AlefissakFileNotFoundException, AlefissakParsingException {

        LOG.debug("Retrieving the document object from configuration file.");

        final Document document = getDocument();

        List<Planning> pList = new ArrayList<Planning>();

        try {

            Node plannings = document.selectSingleNode(Constants.CFG_ROOT_PATH);

            if (plannings == null) {
                throw new AlefissakParsingException("root element missing");
            }

            @SuppressWarnings("unchecked")
            List<Node> planningNodes = document.selectNodes(Constants.CFG_PLANNINGS_PATH);

            Node planningNode, timeNode, messageNode, fromNode, workingNode;
            String planningName;

            int rank = 1;

            for (Iterator<Node> iter = planningNodes.iterator(); iter.hasNext();) {
                planningNode = iter.next();

                Planning planning = new Planning();
                planningName = planningNode.valueOf(CFG_NAME_ATTRIBUTE_NAME);
                planning.setName(planningName);

                timeNode = planningNode.selectSingleNode(Constants.CFG_TIME_ATTRIBUTE_NAME);
                if (timeNode == null) {
                    throw new AlefissakParsingException(
                            "Time configuration attributes are not defined for the planning " + planningName);
                }

                workingNode = timeNode.selectSingleNode(Constants.CFG_START_TIME_ATTRIBUTE_NAME);
                if (workingNode == null) {
                    throw new AlefissakParsingException(
                            "Time configuration attributes are not defined for the planning " + planningName);
                }

                planning.setStartTime(AlefissakUtil.toDate(workingNode.getText().toString()));

                workingNode = timeNode.selectSingleNode(Constants.CFG_END_TIME_ATTRIBUTE_NAME);
                if (workingNode == null) {
                    throw new AlefissakParsingException(
                            "Time configuration attributes are not defined for the planning " + planningName);
                }

                planning.setEndTime(AlefissakUtil.toDate(workingNode.getText().toString().trim()));

                workingNode = timeNode.selectSingleNode(Constants.CFG_TIME_INTERVAL_ATTRIBUTE_NAME);
                if (workingNode == null) {
                    throw new AlefissakParsingException(
                            "Time configuration attributes are not defined for the planning " + planningName);
                }

                final TimeInterval timeInterval = AlefissakUtil.toTimeInterval(workingNode.getText().toString());

                planning.setTimeInterval(timeInterval);
                planning.setCronExpression(AlefissakUtil.getCronExpression(timeInterval));

                Message message = new AlefissakMessageConcret();

                if ((messageNode = planningNode.selectSingleNode(Constants.CFG_MESSAGE_TAG_NAME)) == null) {

                    throw new AlefissakParsingException("No message defined for the planning " + planningName);
                }

                workingNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_OBJECT_TAG_NAME);

                message.setObject(workingNode == null ? "" : workingNode.getText().toString());

                fromNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_FROM_TAG_NAME);

                if (fromNode == null) {

                    throw new AlefissakParsingException("From tag is missing in the configuration file");
                }

                workingNode = fromNode.selectSingleNode(Constants.CFG_NAME_TAG_NAME);
                AlefissakSender sender = new AlefissakSender();

                sender.setName(workingNode == null ? "" : workingNode.getText().toString());

                workingNode = fromNode.selectSingleNode(Constants.CFG_MAIL_TAG_NAME);

                sender.setMail(workingNode == null ? "" : workingNode.getText().toString());

                message.setSender(sender);

                workingNode = messageNode.selectSingleNode(Constants.CFG_MESSAGE_CONTENT_TAG_NAME);

                if (workingNode == null) {

                    throw new AlefissakParsingException(
                            "There is no message to send for the planning " + planningName);
                }

                message.setContent(workingNode.getText().toString());

                planning.setMessage(message);

                parseReceivers(planning, planningNode);

                planning.setRank(rank++);

                pList.add(planning); // Add the new planning to the plannings
                // list
            }

        } catch (Exception e) {

            throw new AlefissakParsingException(e);
        }

        return pList;
    }

    /**
     * Parse nodes of receivers, get all informations from these nodes, then
     * add them into planning receivers list
     * 
     * @param planning the planning to be fill
     * @param planningNode node containing informations on receivers
     * @throws AlefissakParsingException
     */
    private void parseReceivers(Planning planning, Node planningNode) throws AlefissakParsingException {

        @SuppressWarnings("unchecked")
        List<Node> receiverNodes = planningNode
                .selectNodes(Constants.CFG_RECEIVERS_TAG_NAME + "/" + Constants.CFG_RECEIVER_TAG_NAME);

        if (receiverNodes.isEmpty()) {
            throw new AlefissakParsingException("You have to specify at least one receiver");
        }

        Node workingNode;

        for (Iterator<Node> iter = receiverNodes.iterator(); iter.hasNext();) {
            Node receiverNode = iter.next();

            workingNode = receiverNode.selectSingleNode(Constants.CFG_NAME_TAG_NAME);

            if (workingNode == null) {
                throw new AlefissakParsingException("Please define all receiver's name");
            }

            AlefissakReceiver receiver = new AlefissakReceiver();
            receiver.setName(workingNode.getText().toString());

            workingNode = receiverNode.selectSingleNode(Constants.CFG_MAIL_TAG_NAME);
            if (workingNode == null) {
                throw new AlefissakParsingException("Please define all receiver's mail");
            }

            receiver.setMail(workingNode.getText().toString());

            workingNode = receiverNode.selectSingleNode(Constants.CFG_VARS_TAG_NAME);

            if (workingNode != null) {
                setVars(receiver, workingNode.getText().toString());
            }

            planning.addReceiver(receiver);
        }
    }

    /**
     * Split variables string, get values of variables and set them to the
     * receiver's variables list in the form {1}=>var1; {2}=>var2; ...
     * {N}=>varN. <br />
     * This will allow the user to write a parameterized message of the form:
     * <tt>Hello {1}, how are {2} ?</tt>
     * 
     * 
     * @param receiver
     *            the receiver to whom the variables are
     * @param variables
     *            a string variable in the form var1;var2;...;varN
     */
    private void setVars(AlefissakReceiver receiver, String variables) {

        final StringTokenizer tokenizer = new StringTokenizer(variables, CFG_VARS_DELIMITER);

        int sprinter = 1;

        while (tokenizer.hasMoreTokens()) {
            receiver.addPlanningVariable("{" + sprinter++ + "}", tokenizer.nextToken().trim());
        }

    }

}