text:
package org.perfcake.ide.core.model.converter.xml;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.perfcake.ide.core.docs.DocsService;
import org.perfcake.ide.core.exception.ModelConversionException;
import org.perfcake.ide.core.model.AbstractModel;
import org.perfcake.ide.core.model.Model;
import org.perfcake.ide.core.model.Property;
import org.perfcake.ide.core.model.PropertyInfo;
import org.perfcake.ide.core.model.components.CorrelatorModel;
import org.perfcake.ide.core.model.components.DestinationModel;
import org.perfcake.ide.core.model.components.GeneratorModel;
import org.perfcake.ide.core.model.components.MessageModel;
import org.perfcake.ide.core.model.components.ReceiverModel;
import org.perfcake.ide.core.model.components.ReporterModel;
import org.perfcake.ide.core.model.components.ScenarioModel;
import org.perfcake.ide.core.model.components.ScenarioModel.PropertyNames;
import org.perfcake.ide.core.model.components.SenderModel;
import org.perfcake.ide.core.model.components.SequenceModel;
import org.perfcake.ide.core.model.components.ValidatorModel;
import org.perfcake.ide.core.model.properties.KeyValue;
import org.perfcake.ide.core.model.properties.KeyValueImpl;
import org.perfcake.ide.core.model.properties.SimpleValue;
import org.perfcake.ide.core.model.properties.Value;
import org.perfcake.model.HeaderType;
import org.perfcake.model.ObjectFactory;
import org.perfcake.model.PropertyType;
import org.perfcake.model.Scenario;
import org.perfcake.model.Scenario.Messages.Message;
import org.perfcake.model.Scenario.Messages.Message.ValidatorRef;
import org.perfcake.model.Scenario.Receiver;
import org.perfcake.model.Scenario.Receiver.Correlator;
import org.perfcake.model.Scenario.Reporting.Reporter;
import org.perfcake.model.Scenario.Reporting.Reporter.Destination;
import org.perfcake.model.Scenario.Reporting.Reporter.Destination.Period;
import org.perfcake.model.Scenario.Sequences.Sequence;
import org.perfcake.model.Scenario.Validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * XmlConvertor can convert model between pc4ide model and perfcake model.
 *
 * @author Jakub Knetl
 */
public class XmlConverter {

    static final Logger logger = LoggerFactory.getLogger(XmlConverter.class);

    public static final String POST_PROCESSING_PROPERTY_NAME = "org.perfcake.ide.postprocessing.xml.xpath";

    private DocsService docsService;

    private ObjectFactory objectFactory = new ObjectFactory();

    public XmlConverter(DocsService docsService) {
        this.docsService = docsService;
    }

    private class PostProcessingContext extends Message {
        private int postProcessorCounter = 0;
        private XPathPostProcessor xPathPostProcessor = new XPathPostProcessor();
        private XpathNodeRemoverPostProcessor xpathNodeRemoverPostProcessor = new XpathNodeRemoverPostProcessor();

        public int getPostProcessorCounter() {
            return postProcessorCounter;
        }

        public void increaseCounter() {
            postProcessorCounter++;
        }

        public XPathPostProcessor getXPathPostProcessor() {
            return xPathPostProcessor;
        }

        public XpathNodeRemoverPostProcessor getXpathNodeRemoverPostProcessor() {
            return xpathNodeRemoverPostProcessor;
        }
    }

    /**
     * Converts Scenario represented as PerfCake XML model into scenario represented by pc4ide model.
     *
     * @param xmlModel valid Scenario in PerfCake XML model.
     * @return pc4ide model of a Scenario
     * @throws ModelConversionException When model cannot be converted.
     */
    public ScenarioModel convertToPc4ideModel(Scenario xmlModel) throws ModelConversionException {

        if (xmlModel == null) {
            throw new IllegalArgumentException("Model can't be null.");
        }

        ScenarioModel pc4ideModel = new ScenarioModel(docsService);

        // Convert scenario properties
        if (xmlModel.getProperties() != null) {
            PropertyInfo propertyInfo = pc4ideModel.getSupportedProperty(PropertyNames.PROPERTIES.toString());
            for (PropertyType xmlProperty : xmlModel.getProperties().getProperty()) {
                KeyValue pc4ideProperty = new KeyValueImpl(xmlProperty.getName(), xmlProperty.getValue());
                pc4ideModel.addProperty(propertyInfo, pc4ideProperty);
            }
        }

        // Convert generator
        if (xmlModel.getGenerator() != null) {
            convertGeneratorToModel(xmlModel, pc4ideModel);
        }

        // Convert sender
        if (xmlModel.getSender() != null) {
            convertSenderToModel(xmlModel, pc4ideModel);
        }

        // convert sequences
        if (xmlModel.getSequences() != null && xmlModel.getSequences().getSequence() != null) {
            convertSequencesToModel(xmlModel.getSequences().getSequence(), pc4ideModel);
        }

        // convert Receiver
        if (xmlModel.getReceiver() != null) {
            convertReceiverToModel(xmlModel.getReceiver(), pc4ideModel);
        }

        // convert reporters
        if (xmlModel.getReporting() != null) {
            if (xmlModel.getReporting().getReporter() != null) {
                convertReportersToModel(xmlModel.getReporting().getReporter(), pc4ideModel);
            }

            PropertyInfo propertyInfo = pc4ideModel.getSupportedProperty(PropertyNames.REPORTERS_PROPERTIES.toString());
            for (PropertyType xmlProperty : xmlModel.getReporting().getProperty()) {
                Property property = new KeyValueImpl(xmlProperty.getName(), xmlProperty.getValue());
                pc4ideModel.addProperty(propertyInfo, property);
            }
        }

        //
        if (xmlModel.getMessages() != null && xmlModel.getMessages().getMessage() != null) {
            convertMessagesToModel(xmlModel.getMessages().getMessage(), pc4ideModel);
        }

        if (xmlModel.getValidation() != null && xmlModel.getValidation().getValidator() != null) {
            convertValidatorsToModel(xmlModel.getValidation().getValidator(), pc4ideModel);
        }

        if (xmlModel.getValidation() != null) {

            PropertyInfo enabledInfo = pc4ideModel.getSupportedProperty(PropertyNames.VALIDATION_ENABLED.toString());
            Property enabled = new SimpleValue(String.valueOf(xmlModel.getValidation().isEnabled()));
            pc4ideModel.addProperty(enabledInfo, enabled);

            PropertyInfo fastForwardInfo = pc4ideModel.getSupportedProperty(PropertyNames.VALIDATION_FAST_FORWARD.toString());
            Property fastForward = new SimpleValue(String.valueOf(xmlModel.getValidation().isFastForward()));
            pc4ideModel.addProperty(fastForwardInfo, fastForward);
        }

        return pc4ideModel;

    }

    /**
     * Converts valid pc4ide scenario model into PerfCake xml model. It may store required post processors int postProcessor arguments.
     * These post processor should client execute after serialization of returned scenario in order to ensure proper conversion.
     *
     * @param scenarioModel  Model to be converted.
     * @param postProcessors List to which required post processor will be stored.
     * @return XML representation of PerfCake scenario.
     * @throws ModelConversionException if scenarioModel cannot be converted.
     */
    public Scenario convertToXmlModel(ScenarioModel scenarioModel, List<SerializationPostProcessor> postProcessors)
            throws ModelConversionException {

        PostProcessingContext postProcessingContext = new PostProcessingContext();
        Scenario scenario = objectFactory.createScenario();

        // convert scenario properties
        List<Property> scenarioPropertiesModel = scenarioModel.getProperties(PropertyNames.PROPERTIES.toString());
        List<PropertyType> scenarioProperties = extractStandardProperties(scenarioPropertiesModel);
        if (!scenarioProperties.isEmpty()) {
            Scenario.Properties properties = objectFactory.createScenarioProperties();
            properties.getProperty().addAll(scenarioProperties);
            if (scenario.getProperties() == null) {
                scenario.setProperties(objectFactory.createScenarioProperties());
            }
            scenario.getProperties().getProperty().addAll(scenarioProperties);
        }

        // convert generator
        Model generatorModel = scenarioModel.getSingleProperty(PropertyNames.GENERATOR.toString(), Model.class);
        if (generatorModel != null) {
            Scenario.Generator generator = convertGeneratorToXml(generatorModel, postProcessingContext);
            scenario.setGenerator(generator);

            KeyValue runKeyValue = extractSinglePropertyKeyValue(generatorModel, GeneratorModel.PropertyNames.RUN.toString());

            // convert run separately since it is not part of generator in XML scenarioModel
            if (runKeyValue != null) {
                Scenario.Run run = objectFactory.createScenarioRun();
                run.setType(runKeyValue.getKey());
                run.setValue(runKeyValue.getValue());
                scenario.setRun(run);
            }
        }

        // convert sender
        Model senderModel = scenarioModel.getSingleProperty(PropertyNames.SENDER.toString(), Model.class);
        if (senderModel != null) {
            Scenario.Sender sender = convertSenderToXml(senderModel, postProcessingContext);

            scenario.setSender(sender);
        }

        // convert sequences
        List<Property> sequencesModel = scenarioModel.getProperties(PropertyNames.SEQUENCES.toString());
        if (!sequencesModel.isEmpty()) {
            Scenario.Sequences sequences = objectFactory.createScenarioSequences();
            for (Property sequenceModel : sequencesModel) {
                Sequence sequence = convertSequenceToXml(sequenceModel.cast(Model.class), postProcessingContext);
                sequences.getSequence().add(sequence);
            }
            scenario.setSequences(sequences);
        }

        // convert receiver
        Model receiverModel = scenarioModel.getSingleProperty(PropertyNames.RECEIVER.toString(), Model.class);
        if (receiverModel != null) {
            Receiver receiver = convertReceiverToXml(receiverModel, postProcessingContext);

            scenario.setReceiver(receiver);
        }

        // convert reporting properties
        List<Property> reportingPropertiesModel = scenarioModel.getProperties(PropertyNames.REPORTERS_PROPERTIES.toString());
        List<PropertyType> reportingProperties = extractStandardProperties(reportingPropertiesModel);
        if (!reportingProperties.isEmpty()) {

            if (scenario.getReporting() == null) {
                scenario.setReporting(objectFactory.createScenarioReporting());
            }
            scenario.getReporting().getProperty().addAll(reportingProperties);
        }

        // convert reporters
        List<Property> reportersModel = scenarioModel.getProperties(PropertyNames.REPORTERS.toString());
        if (!reportersModel.isEmpty()) {
            if (scenario.getReporting() == null) {
                scenario.setReporting(objectFactory.createScenarioReporting());
            }
            for (Property reporterModel : reportersModel) {
                Reporter reporter = convertReporterToXml(reporterModel.cast(Model.class), postProcessingContext);
                scenario.getReporting().getReporter().add(reporter);
            }
        }

        // convert messages
        List<Property> messagesModel = scenarioModel.getProperties(PropertyNames.MESSAGES.toString());
        if (!messagesModel.isEmpty()) {
            Scenario.Messages messages = objectFactory.createScenarioMessages();

            for (Property messageModel : messagesModel) {
                messages.getMessage().add(convertMessageToXml(messageModel.cast(Model.class), postProcessingContext));
            }

            scenario.setMessages(messages);
        }

        // convert validators
        List<Property> validatorsModel = scenarioModel.getProperties(PropertyNames.VALIDATORS.toString());
        if (!validatorsModel.isEmpty()) {
            Scenario.Validation validation = objectFactory.createScenarioValidation();
            for (Property validatorModel : validatorsModel) {
                validation.getValidator().add(convertValidatorToXml(validatorModel.cast(Model.class), postProcessingContext));
            }
            scenario.setValidation(validation);
        }

        // convert validators fast forward and validators enabled
        if (scenario.getValidation() != null) {
            Value enabled = extractSinglePropertyValue(scenarioModel, PropertyNames.VALIDATION_ENABLED.toString());
            if (enabled != null) {
                scenario.getValidation().setEnabled(Boolean.valueOf(enabled.getValue()));

                if (!enabled.getValue().equalsIgnoreCase("true") && !enabled.getValue().equalsIgnoreCase("false")) {
                    postProcessingContext.getXPathPostProcessor().getExpressions().put("/scenario/validation/@enabled", enabled.getValue());
                }

            }
            Value fastForward = extractSinglePropertyValue(scenarioModel, PropertyNames.VALIDATION_FAST_FORWARD.toString());
            if (fastForward != null) {
                scenario.getValidation().setFastForward(Boolean.valueOf(fastForward.getValue()));
                if (!fastForward.getValue().equalsIgnoreCase("true") && !fastForward.getValue().equalsIgnoreCase("false")) {
                    postProcessingContext.getXPathPostProcessor().getExpressions()
                            .put("/scenario/validation/@fastForward", fastForward.getValue());
                }
            }
        }

        if (!postProcessingContext.getXPathPostProcessor().getExpressions().isEmpty()) {
            String postProcessingProps = String.format("//property[@name=\"{}\"]", POST_PROCESSING_PROPERTY_NAME);
            postProcessingContext.getXpathNodeRemoverPostProcessor().getExpressions().add(postProcessingProps);
        }

        return scenario;
    }

    private Validator convertValidatorToXml(Model validatorModel, PostProcessingContext postProcessingContext) {
        Validator validator = objectFactory.createScenarioValidationValidator();

        Value clazz = extractSinglePropertyValue(validatorModel, ValidatorModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            validator.setClazz(clazz.getValue());
        }

        Value id = extractSinglePropertyValue(validatorModel, ValidatorModel.PropertyNames.ID.toString());
        if (id != null) {
            validator.setId(id.getValue());
        }

        validator.getProperty().addAll(extractImplProperties(validatorModel));

        return validator;
    }

    private Message convertMessageToXml(Model messageModel, PostProcessingContext postProcessingContext) {

        Message message = objectFactory.createScenarioMessagesMessage();

        Value uri = extractSinglePropertyValue(messageModel, MessageModel.PropertyNames.URI.toString());
        if (uri != null) {
            message.setUri(uri.getValue());
        }
        Value multiplicity = extractSinglePropertyValue(messageModel, MessageModel.PropertyNames.MULTIPLICITY.toString());
        if (multiplicity != null) {
            message.setMultiplicity(multiplicity.getValue());
        }
        Value content = extractSinglePropertyValue(messageModel, MessageModel.PropertyNames.CONTENT.toString());
        if (content != null) {
            message.setContent(content.getValue());
        }

        // convert headers
        List<Property> headersModel = messageModel.getProperties(MessageModel.PropertyNames.HEADERS.toString());
        for (Property headerModel : headersModel) {
            HeaderType header = objectFactory.createHeaderType();
            header.setName(headerModel.cast(KeyValue.class).getKey());
            header.setValue(headerModel.cast(KeyValue.class).getValue());

            message.getHeader().add(header);

        }

        // convert properties
        List<Property> propertiesModel = messageModel.getProperties(MessageModel.PropertyNames.PROPERTIES.toString());
        for (Property propertyModel : propertiesModel) {
            PropertyType property = objectFactory.createPropertyType();
            property.setName(propertyModel.cast(KeyValue.class).getKey());
            property.setValue(propertyModel.cast(KeyValue.class).getValue());

            message.getProperty().add(property);

        }
        // convert validator references
        List<Property> validatorRefsModel = messageModel.getProperties(MessageModel.PropertyNames.VALIDATOR_REFS.toString());
        for (Property validatorRefModel : validatorRefsModel) {
            ValidatorRef validatorRef = objectFactory.createScenarioMessagesMessageValidatorRef();
            validatorRef.setId(validatorRefModel.cast(Value.class).getValue());

            message.getValidatorRef().add(validatorRef);
        }

        return message;
    }

    private Reporter convertReporterToXml(Model reporterModel, PostProcessingContext postProcessingContext) {
        Reporter reporter = objectFactory.createScenarioReportingReporter();

        Value clazz = extractSinglePropertyValue(reporterModel, ReporterModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            reporter.setClazz(clazz.getValue());
        }

        // convert implementation properties
        reporter.getProperty().addAll(extractImplProperties(reporterModel));

        // convert destinations
        List<Property> destinationsModel = reporterModel.getProperties(ReporterModel.PropertyNames.DESTINATION.toString());

        if (!destinationsModel.isEmpty()) {
            for (Property destinationModel : destinationsModel) {
                Destination destination = convertDestinationToXml(destinationModel.cast(Model.class), postProcessingContext);
                reporter.getDestination().add(destination);
            }
        }

        Value enabledValue = extractSinglePropertyValue(reporterModel, ReporterModel.PropertyNames.ENABLED.toString());
        if (enabledValue != null) {

            Boolean enabled = Boolean.valueOf(enabledValue.getValue());
            reporter.setEnabled(enabled);

            // if value is not simply true or false, then store postprocessing request into the post processing context
            if (!enabledValue.getValue().equalsIgnoreCase("true") && !enabledValue.getValue().equalsIgnoreCase("false")) {
                PropertyType postProccessingProperty = createPostProcessingProperty(postProcessingContext);
                reporter.getProperty().add(postProccessingProperty);

                // construct post processing xpath
                String xPathExp = createEnabledPostProcessingXpath(Reporter.class, postProccessingProperty);

                postProcessingContext.getXPathPostProcessor().getExpressions().put(xPathExp, enabledValue.getValue());
            }
        }

        return reporter;
    }

    private Destination convertDestinationToXml(Model destinationModel, PostProcessingContext postProcessingContext) {
        Destination destination = objectFactory.createScenarioReportingReporterDestination();

        Value clazz = extractSinglePropertyValue(destinationModel, DestinationModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            destination.setClazz(clazz.getValue());
        }

        Value enabledValue = extractSinglePropertyValue(destinationModel, DestinationModel.PropertyNames.ENABLED.toString());
        if (enabledValue != null) {
            Boolean enabled = Boolean.valueOf(enabledValue.getValue());
            destination.setEnabled(Boolean.valueOf(enabledValue.getValue()));

            // if value is not simply true or false, then store postprocessing request into the post processing context
            if (!enabledValue.getValue().equalsIgnoreCase("true") && !enabledValue.getValue().equalsIgnoreCase("false")) {
                PropertyType postProccessingProperty = createPostProcessingProperty(postProcessingContext);
                destination.getProperty().add(postProccessingProperty);

                // construct post processing xpath
                String xPathExp = createEnabledPostProcessingXpath(Destination.class, postProccessingProperty);

                postProcessingContext.getXPathPostProcessor().getExpressions().put(xPathExp, enabledValue.getValue());
            }
        }

        // parse periods
        List<Property> periodsModel = destinationModel.getProperties(DestinationModel.PropertyNames.PERIOD.toString());
        for (Property periodModel : periodsModel) {
            Period period = objectFactory.createScenarioReportingReporterDestinationPeriod();
            period.setType(periodModel.cast(KeyValue.class).getKey());
            period.setValue(periodModel.cast(KeyValue.class).getValue());
            destination.getPeriod().add(period);
        }

        destination.getProperty().addAll(extractImplProperties(destinationModel));

        return destination;
    }

    private Receiver convertReceiverToXml(Model receiverModel, PostProcessingContext postProcessingContext) {
        Receiver receiver = objectFactory.createScenarioReceiver();

        Value clazz = extractSinglePropertyValue(receiverModel, ReceiverModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            receiver.setClazz(clazz.getValue());
        }

        Value threads = extractSinglePropertyValue(receiverModel, ReceiverModel.PropertyNames.THREADS.toString());
        if (threads != null) {
            receiver.setThreads(threads.getValue());
        }

        Value source = extractSinglePropertyValue(receiverModel, ReceiverModel.PropertyNames.SOURCE.toString());
        if (source != null) {
            receiver.setSource(source.getValue());
        }

        receiver.getProperty().addAll(extractImplProperties(receiverModel));

        Model correlatorModel = receiverModel.getSingleProperty(ReceiverModel.PropertyNames.CORRELATOR.toString(), Model.class);
        if (correlatorModel != null) {
            Correlator correlator = convertCorrelatorToXml(correlatorModel);
            receiver.setCorrelator(correlator);
        }

        return receiver;
    }

    private Correlator convertCorrelatorToXml(Model correlatorModel) {
        Correlator correlator = objectFactory.createScenarioReceiverCorrelator();

        Value clazz = extractSinglePropertyValue(correlatorModel, CorrelatorModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            correlator.setClazz(clazz.getValue());
        }

        correlator.getProperty().addAll(extractImplProperties(correlatorModel));

        return correlator;
    }

    private Sequence convertSequenceToXml(Model sequenceModel, PostProcessingContext postProcessingContext) {
        Sequence sequence = objectFactory.createScenarioSequencesSequence();
        Value clazz = extractSinglePropertyValue(sequenceModel, SequenceModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            sequence.setClazz(clazz.getValue());
        }

        Value id = extractSinglePropertyValue(sequenceModel, SequenceModel.PropertyNames.ID.toString());
        if (id != null) {
            sequence.setId(id.getValue());
        }

        sequence.getProperty().addAll(extractImplProperties(sequenceModel));

        return sequence;
    }

    private Scenario.Sender convertSenderToXml(Model senderModel, PostProcessingContext postProcessingContext) {
        Scenario.Sender sender = objectFactory.createScenarioSender();

        Value target = extractSinglePropertyValue(senderModel, SenderModel.PropertyNames.TARGET.toString());
        if (target != null) {
            sender.setTarget(target.getValue());
        }

        Value clazz = extractSinglePropertyValue(senderModel, SenderModel.PropertyNames.IMPLEMENTATION.toString());
        if (clazz != null) {
            sender.setClazz(clazz.getValue());
        }

        sender.getProperty().addAll(extractImplProperties(senderModel));

        return sender;
    }

    private Scenario.Generator convertGeneratorToXml(Model generatorModel, PostProcessingContext postProcessingContext) {
        Scenario.Generator generator = objectFactory.createScenarioGenerator();

        Value clazz = extractSinglePropertyValue(generatorModel, GeneratorModel.PropertyNames.IMPLEMENTATION.toString());

        if (clazz != null) {
            generator.setClazz(clazz.getValue());
        }

        Value threads = extractSinglePropertyValue(generatorModel, GeneratorModel.PropertyNames.THREADS.toString());
        if (threads != null) {
            generator.setThreads(threads.getValue());
        }

        generator.getProperty().addAll(extractImplProperties(generatorModel));

        return generator;
    }

    private ScenarioModel convertGeneratorToModel(Scenario xmlModel, ScenarioModel pc4ideModel) {
        final PropertyInfo generatorInfo = pc4ideModel.getSupportedProperty(PropertyNames.GENERATOR.toString());
        Model generatorModel = new GeneratorModel(docsService);

        // convert implementation
        if (xmlModel.getGenerator().getClazz() != null) {
            PropertyInfo implInfo = generatorModel.getSupportedProperty(GeneratorModel.PropertyNames.IMPLEMENTATION.toString());
            Property impl = new SimpleValue(xmlModel.getGenerator().getClazz());
            generatorModel.addProperty(implInfo, impl);
        }

        // convert run
        if (xmlModel.getRun() != null) {
            PropertyInfo runInfo = generatorModel.getSupportedProperty(GeneratorModel.PropertyNames.RUN.toString());
            KeyValue run = new KeyValueImpl(xmlModel.getRun().getType(), xmlModel.getRun().getValue());
            generatorModel.addProperty(runInfo, run);
        }

        // convert threads
        if (xmlModel.getGenerator().getThreads() != null) {
            PropertyInfo threadsInfo = generatorModel.getSupportedProperty(GeneratorModel.PropertyNames.THREADS.toString());
            Property threads = new SimpleValue(xmlModel.getGenerator().getThreads());
            generatorModel.addProperty(threadsInfo, threads);
        }

        //convert implementation specific properties
        if (xmlModel.getGenerator().getProperty() != null) {
            convertImplementationPropertiesToModel(xmlModel.getGenerator().getProperty(), generatorModel);
        }

        pc4ideModel.addProperty(generatorInfo, generatorModel);

        return pc4ideModel;
    }

    private void convertSenderToModel(Scenario xmlModel, ScenarioModel pc4ideModel) {
        final PropertyInfo senderInfo = pc4ideModel.getSupportedProperty(PropertyNames.SENDER.toString());
        Model senderModel = new SenderModel(docsService);

        // Convert implementation
        if (xmlModel.getSender().getClazz() != null) {
            PropertyInfo implInfo = senderModel.getSupportedProperty(SenderModel.PropertyNames.IMPLEMENTATION.toString());
            Property impl = new SimpleValue(xmlModel.getSender().getClazz());
            senderModel.addProperty(implInfo, impl);
        }

        // Convert target
        if (xmlModel.getSender().getTarget() != null) {
            PropertyInfo targetInfo = senderModel.getSupportedProperty(SenderModel.PropertyNames.TARGET.toString());
            Property target = new SimpleValue(xmlModel.getSender().getTarget());
            senderModel.addProperty(targetInfo, target);
        }

        // convert implementation properties
        if (xmlModel.getSender().getProperty() != null) {
            convertImplementationPropertiesToModel(xmlModel.getSender().getProperty(), senderModel);
        }

        pc4ideModel.addProperty(senderInfo, senderModel);
    }

    private void convertSequencesToModel(List<Sequence> sequences, ScenarioModel pc4ideModel) {
        for (Sequence xmlSequence : sequences) {
            final PropertyInfo sequenceInfo = pc4ideModel.getSupportedProperty(PropertyNames.SEQUENCES.toString());
            Model sequenceModel = new SequenceModel(docsService);

            if (xmlSequence.getClazz() != null) {
                PropertyInfo implInfo = sequenceModel.getSupportedProperty(SequenceModel.PropertyNames.IMPLEMENTATION.toString());
                Property implProperty = new SimpleValue(xmlSequence.getClazz());
                sequenceModel.addProperty(implInfo, implProperty);
            }

            if (xmlSequence.getId() != null) {
                PropertyInfo idInfo = sequenceModel.getSupportedProperty(SequenceModel.PropertyNames.ID.toString());
                Property idProperty = new SimpleValue(xmlSequence.getId());
                sequenceModel.addProperty(idInfo, idProperty);
            }

            if (xmlSequence.getProperty() != null) {
                convertImplementationPropertiesToModel(xmlSequence.getProperty(), sequenceModel);
            }

            pc4ideModel.addProperty(sequenceInfo, sequenceModel);
        }

    }

    private void convertReceiverToModel(Receiver xmlReceiver, ScenarioModel pc4ideModel) {

        final PropertyInfo receiverInfo = pc4ideModel.getSupportedProperty(PropertyNames.RECEIVER.toString());
        Model receiverModel = new ReceiverModel(docsService);

        if (xmlReceiver.getClazz() != null) {
            PropertyInfo implInfo = receiverModel.getSupportedProperty(ReceiverModel.PropertyNames.IMPLEMENTATION.toString());
            Property impl = new SimpleValue(xmlReceiver.getClazz());
            receiverModel.addProperty(implInfo, impl);
        }

        if (xmlReceiver.getThreads() != null) {
            PropertyInfo threadsInfo = receiverModel.getSupportedProperty(ReceiverModel.PropertyNames.THREADS.toString());
            Property threads = new SimpleValue(xmlReceiver.getThreads());
            receiverModel.addProperty(threadsInfo, threads);
        }

        if (xmlReceiver.getSource() != null) {
            PropertyInfo sourceInfo = receiverModel.getSupportedProperty(ReceiverModel.PropertyNames.SOURCE.toString());
            Property source = new SimpleValue(xmlReceiver.getSource());
            receiverModel.addProperty(sourceInfo, source);
        }

        if (xmlReceiver.getProperty() != null) {
            convertImplementationPropertiesToModel(xmlReceiver.getProperty(), receiverModel);
        }

        if (xmlReceiver.getCorrelator() != null) {
            convertCorrelatorToModel(xmlReceiver.getCorrelator(), receiverModel);
        }

        pc4ideModel.addProperty(receiverInfo, receiverModel);
    }

    private void convertCorrelatorToModel(Correlator xmlCorrelator, Model receiverModel) {
        PropertyInfo correlatorInfo = receiverModel.getSupportedProperty(ReceiverModel.PropertyNames.CORRELATOR.toString());
        Model correlatorModel = new CorrelatorModel(docsService);

        if (xmlCorrelator.getClazz() != null) {
            PropertyInfo implInfo = correlatorModel.getSupportedProperty(ReceiverModel.PropertyNames.IMPLEMENTATION.toString());
            Property impl = new SimpleValue(xmlCorrelator.getClazz());
            correlatorModel.addProperty(implInfo, impl);
        }

        if (xmlCorrelator.getProperty() != null) {
            convertImplementationPropertiesToModel(xmlCorrelator.getProperty(), correlatorModel);
        }

        receiverModel.addProperty(correlatorInfo, correlatorModel);
    }

    private void convertReportersToModel(List<Reporter> xmlReporters, ScenarioModel pc4ideModel) {
        PropertyInfo reporterInfo = pc4ideModel.getSupportedProperty(PropertyNames.REPORTERS.toString());

        for (Reporter xmlReporter : xmlReporters) {
            Model reporterModel = new ReporterModel(docsService);

            if (xmlReporter.getClazz() != null) {
                PropertyInfo implInfo = reporterModel.getSupportedProperty(ReporterModel.PropertyNames.IMPLEMENTATION.toString());
                Property impl = new SimpleValue(xmlReporter.getClazz());
                reporterModel.addProperty(implInfo, impl);
            }

            if (xmlReporter.isEnabled()) {
                PropertyInfo enabledInfo = reporterModel.getSupportedProperty(ReporterModel.PropertyNames.ENABLED.toString());
                Property enabled = new SimpleValue("true");
                reporterModel.addProperty(enabledInfo, enabled);
            }

            if (xmlReporter.getDestination() != null) {
                convertDestinationsToModel(xmlReporter.getDestination(), reporterModel);
            }

            if (xmlReporter.getProperty() != null) {
                convertImplementationPropertiesToModel(xmlReporter.getProperty(), reporterModel);
            }

            pc4ideModel.addProperty(reporterInfo, reporterModel);
        }

    }

    private void convertDestinationsToModel(List<Destination> xmlDestinations, Model reporterModel) {
        PropertyInfo destinationInfo = reporterModel.getSupportedProperty(ReporterModel.PropertyNames.DESTINATION.toString());

        for (Destination xmlDestination : xmlDestinations) {
            Model destinationModel = new DestinationModel(docsService);

            if (xmlDestination.getClazz() != null) {
                PropertyInfo implInfo = destinationModel.getSupportedProperty(DestinationModel.PropertyNames.IMPLEMENTATION.toString());
                Property impl = new SimpleValue(xmlDestination.getClazz());
                destinationModel.addProperty(implInfo, impl);
            }

            if (xmlDestination.getPeriod() != null) {
                PropertyInfo periodInfo = destinationModel.getSupportedProperty(DestinationModel.PropertyNames.PERIOD.toString());
                for (Period xmlPeriod : xmlDestination.getPeriod()) {
                    final Property period = new KeyValueImpl(xmlPeriod.getType(), xmlPeriod.getValue());
                    destinationModel.addProperty(periodInfo, period);
                }
            }

            if (xmlDestination.isEnabled()) {
                PropertyInfo enabledInfo = destinationModel.getSupportedProperty(DestinationModel.PropertyNames.ENABLED.toString());
                Property enabled = new SimpleValue("true");
                destinationModel.addProperty(enabledInfo, enabled);
            }

            if (xmlDestination.getProperty() != null) {
                convertImplementationPropertiesToModel(xmlDestination.getProperty(), destinationModel);
            }

            reporterModel.addProperty(destinationInfo, destinationModel);
        }
    }

    private void convertMessagesToModel(List<Message> xmlMessages, ScenarioModel pc4ideModel) {
        PropertyInfo messageInfo = pc4ideModel.getSupportedProperty(PropertyNames.MESSAGES.toString());

        for (Message xmlMessage : xmlMessages) {
            Model messageModel = new MessageModel(docsService);

            if (xmlMessage.getContent() != null) {
                PropertyInfo contentInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.CONTENT.toString());
                Property content = new SimpleValue(xmlMessage.getContent());
                messageModel.addProperty(contentInfo, content);
            }

            if (xmlMessage.getUri() != null) {
                PropertyInfo uriInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.URI.toString());
                Property uri = new SimpleValue(xmlMessage.getUri());
                messageModel.addProperty(uriInfo, uri);
            }

            if (xmlMessage.getMultiplicity() != null) {
                PropertyInfo multiplicityInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.MULTIPLICITY.toString());
                Property multiplicity = new SimpleValue(xmlMessage.getMultiplicity());
                messageModel.addProperty(multiplicityInfo, multiplicity);
            }

            if (xmlMessage.getProperty() != null) {
                PropertyInfo propertyInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.PROPERTIES.toString());

                for (PropertyType xmlProperty : xmlMessage.getProperty()) {
                    Property message = new KeyValueImpl(xmlProperty.getName(), xmlProperty.getValue());
                    messageModel.addProperty(propertyInfo, message);
                }
            }

            if (xmlMessage.getHeader() != null) {
                PropertyInfo headerInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.HEADERS.toString());

                for (HeaderType xmlHeader : xmlMessage.getHeader()) {
                    Property header = new KeyValueImpl(xmlHeader.getName(), xmlHeader.getValue());
                    messageModel.addProperty(headerInfo, header);
                }
            }

            if (xmlMessage.getValidatorRef() != null) {
                PropertyInfo validatorRefInfo = messageModel.getSupportedProperty(MessageModel.PropertyNames.VALIDATOR_REFS.toString());

                for (ValidatorRef xmlValidatorRef : xmlMessage.getValidatorRef()) {
                    Property validatorRef = new SimpleValue(xmlValidatorRef.getId());
                    messageModel.addProperty(validatorRefInfo, validatorRef);
                }
            }

            pc4ideModel.addProperty(messageInfo, messageModel);
        }
    }

    private void convertValidatorsToModel(List<Validator> xmlValidators, ScenarioModel pc4ideModel) {
        PropertyInfo validatorInfo = pc4ideModel.getSupportedProperty(PropertyNames.VALIDATORS.toString());

        for (Validator xmlValidator : xmlValidators) {
            Model validatorModel = new ValidatorModel(docsService);

            if (xmlValidator.getClazz() != null) {
                PropertyInfo implInfo = validatorModel.getSupportedProperty(ValidatorModel.PropertyNames.IMPLEMENTATION.toString());
                Property impl = new SimpleValue(xmlValidator.getClazz());
                validatorModel.addProperty(implInfo, impl);
            }

            if (xmlValidator.getId() != null) {
                PropertyInfo idInfo = validatorModel.getSupportedProperty(ValidatorModel.PropertyNames.ID.toString());
                Property id = new SimpleValue(xmlValidator.getId());
                validatorModel.addProperty(idInfo, id);
            }

            convertImplementationPropertiesToModel(xmlValidator.getProperty(), validatorModel);

            pc4ideModel.addProperty(validatorInfo, validatorModel);
        }
    }

    private void convertImplementationPropertiesToModel(List<PropertyType> xmlProperties, Model componentModel) {
        for (PropertyType xmlProperty : xmlProperties) {
            PropertyInfo propertyInfo = componentModel.getSupportedProperty(xmlProperty.getName());

            // if the defined property is supported by current implementation
            if (propertyInfo != null) {
                Property property = new SimpleValue(xmlProperty.getValue());
                componentModel.addProperty(propertyInfo, property);
            } else {
                PropertyInfo implInfo = componentModel.getSupportedProperty(AbstractModel.IMPLEMENTATION_CLASS_PROPERTY);
                Iterator<Property> iterator = componentModel.propertyIterator(implInfo);
                Property currentImplementation = iterator.next();

                logger.warn("Ignoring property {} which is not supported by current inspector ({})",
                        xmlProperty.getName(), currentImplementation.cast(Value.class).getValue());
            }
        }
    }

    private Property extractSingleProperty(Model model, String propertyName) {
        PropertyInfo propertyInfo = model.getSupportedProperty(propertyName);
        if (propertyInfo == null) {
            logger.warn("Trying to get single property with name {}, but no such property found.", propertyName);
            return null;
        }

        List<Property> properties = model.getProperties(propertyInfo);

        if (properties.size() > 1) {
            logger.warn("Multiple properties '{}' exists when trying to get single one.", propertyName);
        }

        Property result = null;

        if (!properties.isEmpty()) {
            result = properties.get(0);
        }

        return result;
    }

    private Value extractSinglePropertyValue(Model model, String propertyName) {
        Property property = extractSingleProperty(model, propertyName);
        Value result = null;

        if (property != null) {
            result = property.cast(Value.class);
        }

        return result;
    }

    private KeyValue extractSinglePropertyKeyValue(Model model, String propertyName) {
        Property property = extractSingleProperty(model, propertyName);
        KeyValue result = null;

        if (property != null) {
            result = property.cast(KeyValue.class);
        }

        return result;
    }

    private List<PropertyType> extractStandardProperties(List<Property> scenarioPropertiesModel) {
        List<PropertyType> scenarioProperties = new ArrayList<>(scenarioPropertiesModel.size());
        for (Property p : scenarioPropertiesModel) {
            PropertyType property = objectFactory.createPropertyType();

            property.setName(p.cast(KeyValue.class).getKey());
            property.setValue(p.cast(KeyValue.class).getValue());
            scenarioProperties.add(property);

            //TODO(jknetl): handle "any" element
        }
        return scenarioProperties;
    }

    private List<PropertyType> extractImplProperties(Model model) {
        List<PropertyType> properties = new ArrayList<>();

        for (PropertyInfo propertyInfo : model.getSupportedImplProperties()) {
            List<Property> propertyModel = model.getProperties(propertyInfo);
            for (Property p : propertyModel) {
                PropertyType propertyType = new PropertyType();
                propertyType.setName(propertyInfo.getName());
                propertyType.setValue(p.cast(Value.class).getValue());
                properties.add(propertyType);
            }
        }

        return properties;
    }

    /**
     * Creates xpath from the class name.
     *
     * @param clazz PerfCake XML model class (Except property and header)
     * @return xpath from root of xml document to the given class.
     */
    private String constructXpath(Class<?> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("clazz cannot be null");
        }

        StringTokenizer tokenizer = new StringTokenizer(clazz.getCanonicalName(), ".");
        StringBuilder builder = new StringBuilder();
        while (tokenizer.hasMoreTokens()) {
            builder.append("/")
                    .append(tokenizer.nextToken().toLowerCase());
        }

        return builder.toString();
    }

    /**
     * Creates post processing xpath expression for enabled attribute of perfcake xml representation of a component.
     *
     * @param clazz    clazz of the PerfCake XML model which accept properties
     * @param property postprocessing property
     * @return xpath describing the node with given class
     */
    private String createEnabledPostProcessingXpath(Class<?> clazz, PropertyType property) {
        StringBuilder xPathExp = new StringBuilder();
        xPathExp.append(constructXpath(clazz))
                .append(String.format("/property[@name=\"{}\" and @value=\"{}\"]", property.getName(), property.getValue()))
                .append("/../@enabled");

        return xPathExp.toString();
    }

    /**
     * Creates property with post-processing identifier. It also automatically increases context counter
     *
     * @param context post processing  context
     * @return Property which uniquely specifies point of post processing
     */
    private PropertyType createPostProcessingProperty(PostProcessingContext context) {
        PropertyType postProccessingProperty = objectFactory.createPropertyType();
        postProccessingProperty.setName(POST_PROCESSING_PROPERTY_NAME);
        postProccessingProperty.setValue(String.valueOf(context.getPostProcessorCounter()));
        context.increaseCounter();

        return postProccessingProperty;
    }

}


text:
package com.github.swalffy.utils;

import com.github.swalffy.api.AEntity;

import java.util.List;

public final class Printer {

	public static void print(final String line) {
		System.out.println(line);
	}

	public static void print(final AEntity entity) {
		System.out.println(entity);
	}

	public static void print(final Integer value) {
		System.out.println(value);
	}

	public static void print (final Float value) {
		System.out.println(value);
	}

	public static <T extends AEntity> void print(final List<T> list) {
		final StringBuilder sb = new StringBuilder();
		for (final T item : list) {
			sb.append(item).append("\n");
		}
		System.out.println(sb);
	}
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.

/*!
 * @file MockAuthenticationPlugin.h
 */

#ifndef _SECURITY_MOCKAUTHENTICATIONPLUGIN_H_
#define _SECURITY_MOCKAUTHENTICATIONPLUGIN_H_

// TODO(Ricardo) Change when GMock supports r-values.

#include <fastrtps/rtps/security/authentication/Authentication.h>
#include <security/authentication/PKIIdentityHandle.h>

#include <gmock/gmock.h>

#pragma warning(push)
#pragma warning(disable : 4373)

namespace eprosima {
namespace fastrtps {
namespace rtps {
namespace security {

class MockAuthenticationPlugin : public Authentication
{
public:

    using PKIIdentityHandle = HandleImpl<PKIIdentity, MockAuthenticationPlugin>;
    using SharedSecretHandle = HandleImpl<SharedSecret, MockAuthenticationPlugin>;

    MOCK_METHOD(ValidationResult_t, validate_local_identity, (IdentityHandle * *local_identity_handle,
            GUID_t & adjusted_participant_key,
            const uint32_t domain_id,
            const RTPSParticipantAttributes& participant_attr,
            const GUID_t& candidate_participant_key,
            SecurityException & exception), (override));

    MOCK_METHOD5(validate_remote_identity_rvr, ValidationResult_t(IdentityHandle * *remote_identity_handle,
            const IdentityHandle& local_identity_handle,
            IdentityToken remote_identity_token,
            const GUID_t& remote_participant_key,
            SecurityException & exception));

    MOCK_METHOD(ValidationResult_t, begin_handshake_request, (HandshakeHandle * *handshake_handle,
            HandshakeMessageToken * *handshake_message,
            const IdentityHandle& initiator_identity_handle,
            IdentityHandle & replier_identity_handle,
            const CDRMessage_t& cdr_participant_data,
            SecurityException & exception), (override));

    MOCK_METHOD7(begin_handshake_reply_rvr, ValidationResult_t(HandshakeHandle * *handshake_handle,
            HandshakeMessageToken * *handshake_message_out,
            HandshakeMessageToken handshake_message_in,
            IdentityHandle & initiator_identity_handle,
            const IdentityHandle& replier_identity_handle,
            const CDRMessage_t& cdr_participant_data,
            SecurityException & exception));

    MOCK_METHOD4(process_handshake_rvr, ValidationResult_t(HandshakeMessageToken * *handshake_message_out,
            HandshakeMessageToken handshake_message_in,
            HandshakeHandle & handshake_handle,
            SecurityException & exception));

    MOCK_METHOD(bool, set_listener, (AuthenticationListener * listener,
            SecurityException & exception), (override));

    MOCK_METHOD(bool, get_identity_token, (IdentityToken * *identity_token,
            const IdentityHandle& handle,
            SecurityException & exception), (override));

    MOCK_METHOD(bool, return_identity_token, (IdentityToken * token,
            SecurityException & exception), (override));

    MOCK_METHOD(bool, return_handshake_handle, (HandshakeHandle * handshake_handle,
            SecurityException & exception), (override));

    MOCK_METHOD(bool, set_permissions_credential_and_token, (IdentityHandle & identity_handle,
            PermissionsCredentialToken & permissions_credential_token,
            SecurityException & ex), (override));

    MOCK_METHOD(bool, get_authenticated_peer_credential_token, (PermissionsCredentialToken * *token,
            const IdentityHandle& identity_handle, SecurityException & exception), (override));

    MOCK_METHOD(bool, return_authenticated_peer_credential_token, (PermissionsCredentialToken * token,
            SecurityException & ex), (override));

    ValidationResult_t validate_remote_identity(
            IdentityHandle** remote_identity_handle,
            const IdentityHandle& local_identity_handle,
            const IdentityToken& remote_identity_token,
            const GUID_t& remote_participant_key,
            SecurityException& exception) override
    {
        return validate_remote_identity_rvr(remote_identity_handle, local_identity_handle,
                       remote_identity_token, remote_participant_key, exception);
    }

    ValidationResult_t begin_handshake_reply(
            HandshakeHandle** handshake_handle,
            HandshakeMessageToken** handshake_message_out,
            HandshakeMessageToken&& handshake_message_in,
            IdentityHandle& initiator_identity_handle,
            const IdentityHandle& replier_identity_handle,
            const CDRMessage_t& cdr_participant_data,
            SecurityException& exception) override
    {
        return begin_handshake_reply_rvr(handshake_handle, handshake_message_out, handshake_message_in,
                       initiator_identity_handle, replier_identity_handle, cdr_participant_data, exception);
    }

    ValidationResult_t process_handshake(
            HandshakeMessageToken** handshake_message_out,
            HandshakeMessageToken&& handshake_message_in,
            HandshakeHandle& handshake_handle,
            SecurityException& exception) override
    {
        return process_handshake_rvr(handshake_message_out, handshake_message_in,
                       handshake_handle, exception);
    }

    MOCK_METHOD(IdentityHandle*, get_identity_handle, (
                SecurityException &), (override));

    IdentityHandle* get_dummy_identity_handle()
    {
        return new (std::nothrow) PKIIdentityHandle();
    }

    MOCK_METHOD(bool, return_identity_handle, (
                IdentityHandle * identity_handle,
                SecurityException &), (override));

    bool return_dummy_identity_handle(
            IdentityHandle* identity_handle)
    {
        delete dynamic_cast<PKIIdentityHandle*>(identity_handle);
        return true;
    }

    MOCK_METHOD(std::shared_ptr<SecretHandle>, get_shared_secret, (
                const HandshakeHandle&,
                SecurityException &), (const, override));

    std::shared_ptr<SecretHandle> get_dummy_shared_secret() const
    {
        // create ad hoc deleter because this object can only be created/release from the friend factory
        auto p = new (std::nothrow) SharedSecretHandle;
        return std::dynamic_pointer_cast<SecretHandle>(std::shared_ptr<SharedSecretHandle>(p,
                       [](SharedSecretHandle* p)
                       {
                           delete p;
                       }));
    }

    MOCK_METHOD(bool, return_sharedsecret_handle, (
                std::shared_ptr<SecretHandle>& sharedsecret_handle,
                SecurityException &), (const, override));

    bool return_dummy_sharedsecret(
            std::shared_ptr<SecretHandle>& sharedsecret_handle) const
    {
        sharedsecret_handle.reset();
        return true;
    }

};

} // namespace security
} // namespace rtps
} // namespace fastrtps
} // namespace eprosima

#pragma warning(pop)

#endif // _SECURITY_MOCKAUTHENTICATIONPLUGIN_H_


text:
package layer3

import (
	"testing"

	"github.com/gophercloud/gophercloud/acceptance/clients"
	networking "github.com/gophercloud/gophercloud/acceptance/openstack/networking/v2"
	"github.com/gophercloud/gophercloud/acceptance/tools"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/layer3/routers"
	"github.com/gophercloud/gophercloud/openstack/networking/v2/networks"
)

func TestLayer3RouterList(t *testing.T) {
	client, err := clients.NewNetworkV2Client()
	if err != nil {
		t.Fatalf("Unable to create a network client: %v", err)
	}

	listOpts := routers.ListOpts{}
	allPages, err := routers.List(client, listOpts).AllPages()
	if err != nil {
		t.Fatalf("Unable to list routers: %v", err)
	}

	allRouters, err := routers.ExtractRouters(allPages)
	if err != nil {
		t.Fatalf("Unable to extract routers: %v", err)
	}

	for _, router := range allRouters {
		tools.PrintResource(t, router)
	}
}

func TestLayer3ExternalRouterCreateDelete(t *testing.T) {
	client, err := clients.NewNetworkV2Client()
	if err != nil {
		t.Fatalf("Unable to create a network client: %v", err)
	}

	router, err := CreateExternalRouter(t, client)
	if err != nil {
		t.Fatalf("Unable to create router: %v", err)
	}
	defer DeleteRouter(t, client, router.ID)

	tools.PrintResource(t, router)

	newName := tools.RandomString("TESTACC-", 8)
	updateOpts := routers.UpdateOpts{
		Name: newName,
	}

	_, err = routers.Update(client, router.ID, updateOpts).Extract()
	if err != nil {
		t.Fatalf("Unable to update router: %v", err)
	}

	newRouter, err := routers.Get(client, router.ID).Extract()
	if err != nil {
		t.Fatalf("Unable to get router: %v", err)
	}

	tools.PrintResource(t, newRouter)
}

func TestLayer3RouterInterface(t *testing.T) {
	client, err := clients.NewNetworkV2Client()
	if err != nil {
		t.Fatalf("Unable to create a compute client: %v", err)
	}

	choices, err := clients.AcceptanceTestChoicesFromEnv()
	if err != nil {
		t.Fatalf("Unable to get choices: %v", err)
	}

	netid, err := networks.IDFromName(client, choices.NetworkName)
	if err != nil {
		t.Fatalf("Unable to find network id: %v", err)
	}

	subnet, err := networking.CreateSubnet(t, client, netid)
	if err != nil {
		t.Fatalf("Unable to create subnet: %v", err)
	}
	defer networking.DeleteSubnet(t, client, subnet.ID)

	tools.PrintResource(t, subnet)

	router, err := CreateExternalRouter(t, client)
	if err != nil {
		t.Fatalf("Unable to create router: %v", err)
	}
	defer DeleteRouter(t, client, router.ID)

	aiOpts := routers.AddInterfaceOpts{
		SubnetID: subnet.ID,
	}

	iface, err := routers.AddInterface(client, router.ID, aiOpts).Extract()
	if err != nil {
		t.Fatalf("Failed to add interface to router: %v", err)
	}

	tools.PrintResource(t, router)
	tools.PrintResource(t, iface)

	riOpts := routers.RemoveInterfaceOpts{
		SubnetID: subnet.ID,
	}

	_, err = routers.RemoveInterface(client, router.ID, riOpts).Extract()
	if err != nil {
		t.Fatalf("Failed to remove interface from router: %v", err)
	}
}


text:
/* -*- c++ -*- */
/*
 * Copyright 2013 Jiří Pinkava <j-pi@seznam.cz>.
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include "noise_level_estimator2_impl.h"
#include <algorithm>
#include <boost/foreach.hpp>
#include <cmath>
#include <stdexcept>

#include <stdio.h>

namespace gr {
  namespace rstt {

    noise_level_estimator2::sptr
    noise_level_estimator2::make(float coverage, float chunk_size)
    {
      if (!(coverage > 0.))
        throw std::out_of_range("noise_level_estimator2 coverage must be > 0.");
      if (!(coverage <= 1.))
        throw std::out_of_range("noise_level_estimator2 coverage must be <= 1.");
      if (!(chunk_size > 0.))
        throw std::out_of_range("noise_level_estimator2 chunk_size must be > 0.");
      if (!(chunk_size <= coverage))
        throw std::out_of_range("noise_level_estimator2 chunk_size must be <= coverage");
      return sptr(new noise_level_estimator2_impl(coverage, chunk_size));
    }

    noise_model
    noise_level_estimator2_impl::estimate(const float *data, int data_items) const
    {
      const int coverage = data_items * this->coverage;
      const int chunk_size = data_items * this->chunk_size;

      const int ms_size = data_items - chunk_size + 1;
      float mean[ms_size];
      float mean2[ms_size];

      // moving average, first point
      mean[0] = 0.;
      mean2[0] = 0.;
      for (int i = 0; i < chunk_size; ++i) {
        mean[0] += data[i];
        mean2[0] += data[i] * data[i];
      }

      // moving average, other points
      for (int i = chunk_size, j = 1; i < data_items; ++i, ++j) {
       mean[j] = mean[j-1] - data[j-1] + data[i];
       mean2[j] = mean2[j-1] - (data[j-1] * data[j-1]) + (data[i] * data[i]);
      }

      for (int i = 0; i < ms_size; ++i) {
        mean[i] /= chunk_size;
        mean2[i] /= chunk_size;
      }

      // moving standard deviation (s^2)
      float s2[ms_size];
      for (int i = 0; i < ms_size; ++i) {
        s2[i] = mean2[i] - mean[i] * mean[i];
      }

      // get the average of lower bound values for mean and deviation
      std::sort(s2, s2 + ms_size);
      float s = 0.;
      for (int i = 0; i < coverage; ++i) {
        s += std::sqrt(s2[i]);
      }
      s /= coverage;

      std::sort(mean, mean + ms_size);
      float m = 0.;
      for (int i = 0; i < coverage; ++i) {
        m += mean[i];
      }
      m /= coverage;

      return noise_model(m, s);
    }

  } // namespace rstt
} // namespace gr


text:
"""
#  @package   coursera2012
#  @author    Rolf Hemmerling <hemmerling@gmx.net>
#  @version   1.00
#  @date      2015-01-01
#  @copyright Apache License, Version 2.0
#
#  Implementation of the game
#  "Pairs"
#  for the Coursera course
#  "An Introduction to Interactive Programming in Python"
#
#  Copyright 2012-2015 Rolf Hemmerling
#
#  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.
"""

# import modules
import unittest
from simplegui import Canvas
from pairs import PairsGame

def dummy(self):
    """ Dummy function for comparison of the return values """
    return

class initCardPoolTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testInitCardPool(self):
        card_pool_static = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8]
        card_pool = self.pairs.init_card_pool()
        assert card_pool == card_pool_static, 'init_card_pool() does not provide the right return value'

class initCardDeckTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testInitDeckPool(self):
        card_deck_static = [5, 3, 4, 8, 8, 7, 1, 2, 6, 6, 1, 7, 4, 3, 5, 2]
        card_pool = self.pairs.init_card_pool()
        card_deck = self.pairs.init_card_deck(card_pool)
        assert card_deck == card_deck_static, 'init_card_deck() does not provide the right return value'

class initExposed(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testInitExposed(self):
        exposed_static = [False, False, False, False, False, False, False, False,
                          False, False, False, False, False, False, False, False]
        exposed = self.pairs.init_exposed(None)
        assert exposed == exposed_static, 'init_exposed() does not provide the right return value'

        exposed_static = [False, False, False, False, False, False, False, False,
                          False, False, False, False, False, False, False, False]
        exposed = self.pairs.init_exposed(exposed_static)
        assert exposed == exposed_static, 'init_exposed() does not provide the right return value'

class initFontsize(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testFontSize(self):
        fontsize_static = self.pairs.CARD_HEIGHT/2
        assert self.pairs.fontsize() == fontsize_static, 'fontsize() does not provide the right return value'

class initTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testInit(self):
        assert self.pairs.init() == dummy(self), 'init() does not provide the right return value'

class initCoordinatesOfNumber(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testCoordinatesOfNumber(self):
        self.pairs.init()
        coordinates = [self.pairs.CARD_WIDTH,
                       self.pairs.CARD_HEIGHT+(self.pairs.HEIGHT-self.pairs.CARD_HEIGHT)/4]
        assert self.pairs.coordinates_of_number(1) == coordinates, 'coordinates_of_number() does not provide the right return value'

class initCoordinatesOfNonexposedCardCorner(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testInitCoordinatesOfNonexposedCardCorner(self):
        self.pairs.init()
        coordinates = [self.pairs.CARD_WIDTH,
                       0+self.pairs.HEIGHT/4]
        assert self.pairs.coordinates_of_nonexposed_card_corner(1, 0) == coordinates, 'coordinates_of_nonexposed_card_corner does not provide the right return value'

class drawTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testDrawInit(self):
        self.pairs.init()
        testCanvas = Canvas()
        assert self.pairs.draw(testCanvas) == dummy(self), 'draw() does not provide the right return value'

class mouseclickTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testMouseclickInit(self):
        self.pairs.init_gui()
        self.pairs.init()
        pos = [self.pairs.CARD_WIDTH/2, self.pairs.HEIGHT/4+self.pairs.CARD_HEIGHT/2]
        card_index = 1
        card_value = 7
        assert self.pairs.mouseclick(pos) == (0, 5), 'mouseclick() does not provide the right return value'

class pairsTest(unittest.TestCase):

    def setUp(self):
        """Call before every test case."""
        self.pairs = PairsGame()

    def tearDown(self):
        """Call after every test case."""

    def testGuessTheNumber(self):
        assert self.pairs.main() == dummy(self), 'main() does not provide the right return value'

# run all tests
if __name__ == "__main__":
    try:
        unittest.main()
    except SystemExit as inst:
        if inst.args[0] is True: # raised by sys.exit(True) when tests failed
            raise


text:
//var phantom = require('phantom');

module.exports = {

	obtenerTablaNorma: function(IDSector,IDRubro){
	switch(IDSector){
  	  case 'CA':
  	    tabla = 'NS_CA';
  	  break;
  	  case 'GA':
  	    tabla = 'NS_GA';
  	  break;
  	  case 'FL':
  	    tabla = 'NS_FL';
  	  break;
  	  case 'FR':
		switch(IDRubro){
		  case 'PO':
		    tabla = 'NS_RE';
		  break;
		  case 'VID':
		    tabla = 'NS_VID';
		  break;
		  default:
		    tabla = 'NS_DA';
		  break;
		}
  	  break;
  	}
return tabla;

	},

	execSisaQuery: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_sisa,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });

	},
	execSisaQueryProd: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_sisa_prod,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });
	},
	execSisaQueryDev: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_sisa_dev,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });
	},

	 exportPdf: function(data,cb){
	 	var jsreport = require('jsreport');
	 	jsreport.render(data).then(function(out) {
    			return cb(null,out);
  			}).catch(function(e) {
    			return cb(e.message,null);
  			});

	 },
	execWsQuery: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_ws,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });

	},

	execWsQueryProd: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_ws_prod,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });

	},
	execWsQueryDev: function(query,cb){
		var util            = require('util');
		var mssql       = require(sails.config.conexion.adapter);
		var connection4 = new mssql.Connection({
		      user:     sails.config.connections.sqlserver.user,
		      password: sails.config.connections.sqlserver.password,
		      server:   sails.config.connections.sqlserver.host,
		      database: sails.config.conexion.database_ws_dev,
	    	}, function (err) {
	      if (err) return cb(err,null);
	      new mssql.Request(connection4).query([query], function (err, results){
	        if (err){
	          console.log(util.inspect(query));
	          return cb(err,null);
	        }
	       // console.log(results);
	        return cb(null,results);
	      });
	    });

	},
	/*
	 * function para array de querys. // me salio a la primera (hay que revisar jajaja ).
	 *
	 */

	arrCallSql:function(arr,cb){
		 var nrecord = arr.length;
		 //console.log(nrecord);
		 var result  = new Array();
		 function recursive(arr,index,last,_cb){

		 		ToolService.execWsQuery(arr[index],function(err,data0){
		 				if(err) return _cb(err,null);
		 				if(index < last){
		 					if(data0[0]) result[index]=data0[0];
		 					else if (data0) result[index]=data0;
		 					recursive(arr,index+1,last,_cb);
		 				}else{
		 					return _cb(null,result);
		 				}
		 		});
		 }
		recursive(arr,0,nrecord,function(err,data){
			 return cb(err,data);
		 });

	},

	breadcrumb : function(datos,cb){
	var tipo     = datos['tipo'];
    var sector   = datos['sector'];
    var rubro    = datos['rubro'];
    var producto = datos['producto'];

    var query= "SELECT TOP 1 ";
    query+="(select CASE '"+tipo+"' when 'clim' then 'Seguros Agrícolas' when 'ganadero' then 'Seguros Pecuarios' when 'precio' then 'Cobertura de Precios' else '' end) as TipoSeguro";
    query+=" ,(select Descripcion from GEN_General WHERE IDValor = 'TEMPORADA_SIMULADOR') as Temporada ";
    query+=" ,(select top 1 Sector from GEN_Sector where IDSector = '"+sector+"') as Sector ";
    query+=" ,(select top 1 Rubro from GEN_Rubro where IDCategoria = '"+rubro+"') as Rubro ";
    query+=" ,(select top 1 NombreProducto from GEN_Producto where IDCategoria = '"+producto+"') as Producto ";
    query+=" FROM ";
    query+=" GEN_Sector ";

    ToolService.execSisaQuery(query,function(err,data){
       if(err) return cb(err,null)
       if(data.length < 1) return cb('Vacio',null);
       	return cb(null,data[0]);
    });

	},
	breadcrumbML : function(datos,cb){
	var tipo     = datos['tipo'];
    var sector   = datos['sector'];
    var rubro    = datos['rubro'];
    var producto = datos['producto'];

	//console.log(datos.lineas);

    var llamadas = new Array();
    var contador = 0;
    (function llamadaBC(cont){
      var record      = JSON.parse(datos.lineas[cont]);
      try{

	    var query= "SELECT TOP 1 ";
	    query+="(select CASE '"+tipo+"' when 'clim' then 'Seguros Agrícolas' when 'ganadero' then 'Seguros Pecuarios' when 'precio' then 'Cobertura de Precios' else '' end) as TipoSeguro";
	    query+=" ,(select Descripcion from GEN_General WHERE IDValor = 'TEMPORADA_SIMULADOR') as Temporada ";
	    query+=" ,(select top 1 Sector from GEN_Sector where IDSector = '"+sector+"') as Sector ";
	    query+=" ,(select top 1 Rubro from GEN_Rubro where IDCategoria = '"+rubro+"') as Rubro ";
	    query+=" ,(select top 1 NombreProducto from GEN_Producto where IDCategoria = '"+producto+"') as Producto ";
	    query+=" ,(select top 1 NombreProducto+' '+ISNULL(NombreVariedad,'') from GEN_Variedad where IDVariedad = '"+record.idVariedad+"') as Variedad ";
	    query+=" FROM ";
	    query+=" GEN_Sector ";

	    ToolService.execSisaQuery(query,function(err,data){
	      if(err) return cb(err,null);
	      if(data.length < 1) return cb('Vacio',null);
	       	//return cb(null,data[0]);

          contador++;
            var elemento =new Array();
            elemento = data[0];
            llamadas.push(elemento);
          if (contador>=datos.lineas.length) {

            return cb(null,llamadas);
          } else {
            llamadaBC(contador);
          }
	    });

      } catch (exception) {
        return cb('Excepcion',null);
      }
    })(contador);

	},
	obtenerValordiario: function(cb){
	   var query = "SELECT TOP 1 [ID],[Fecha],[Uf],[Dolar],[Euro] FROM [WS_CONTRATACION_ONLINE].[dbo].[WS_Valor_Diario]  order by fecha desc";
	    ToolService.execSisaQuery(query,function(err,data){
        if(err) return cb(err,null);
       	return cb(null,data[0]);
    });
	}

};


text:
layout: page
title: Frances Frederick's 68th Birthday
date: 2016-05-24
author: Grace Frederick
tags: weekly links, java
status: published
summary: Aliquam ut rutrum elit, vestibulum.
banner: images/banner/wedding.jpg
booking:
  startDate: 01/08/2017
  endDate: 01/09/2017
  ctyhocn: MCILEHX
  groupCode: FF6B
published: true
---
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec aliquam, tellus id viverra scelerisque, justo est aliquam magna, nec pulvinar ipsum sem sed nibh. Praesent nec nulla at quam fringilla auctor. Ut ut elit vitae felis semper mollis. Mauris in augue lobortis, facilisis metus quis, malesuada lacus. Integer quis gravida ipsum, at aliquam massa. Sed at libero metus. Nam quam ex, consectetur vel facilisis nec, tristique et nunc. Phasellus in placerat leo, et semper dui. Fusce ut lobortis massa. Fusce in sodales nulla. Nunc tempor pretium faucibus.
Integer feugiat magna a quam vestibulum cursus. Donec mollis, justo sed laoreet egestas, nisl leo convallis ligula, nec dapibus diam urna rutrum nisi. Etiam a vulputate neque. Nam sagittis lacus a ex egestas facilisis. Phasellus in euismod arcu. Mauris ultrices purus dui, at lobortis diam ultricies maximus. Suspendisse est nunc, facilisis eget massa eu, vestibulum blandit erat. Pellentesque pretium ex vel dui egestas tincidunt. Etiam in libero id purus laoreet volutpat quis in augue. Curabitur lorem arcu, vehicula non sodales id, cursus at ante. Integer fringilla aliquam orci id gravida.

* Nunc vestibulum justo eget leo euismod dapibus
* Etiam consectetur nunc eget sollicitudin congue
* Praesent quis odio malesuada, condimentum sapien lacinia, imperdiet mi
* Vivamus commodo enim eu metus rhoncus, in maximus leo semper
* Pellentesque feugiat lorem at elit tempor, quis lobortis tellus accumsan.

Nullam et congue orci. Cras tincidunt tristique sem et placerat. Fusce eget dolor vitae quam feugiat consectetur. Integer feugiat arcu sed purus tempus, sed mollis elit gravida. Duis ornare posuere neque et rhoncus. Aliquam efficitur a est quis malesuada. Ut vulputate nunc sed elementum malesuada. Integer in odio mollis, imperdiet est id, fringilla lectus. Praesent faucibus semper ex eget facilisis. Donec accumsan blandit nisi ut maximus.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.neo4j.contrib</groupId>
    <artifactId>noqm</artifactId>
    <version>1.1-SNAPSHOT</version>

    <!-- =========== -->
    <!-- = License = -->
    <!-- =========== -->
    <licenses>
        <license>
            <name>MIT</name>
            <url>https://raw.githubusercontent.com/sim51/noqm/master/LICENSE</url>
        </license>
    </licenses>

    <!-- ======= -->
    <!-- = SCM = -->
    <!-- ======= -->
    <scm>
        <url>https://github.com/sim51/NOQM</url>
        <connection>scm:git:git://github.com/sim51/NOQM.git</connection>
        <developerConnection>scm:git:git@github.com:sim51/NOQM.git</developerConnection>
      <tag>HEAD</tag>
  </scm>

    <!-- ============== -->
    <!-- = Bugtracker = -->
    <!-- ============== -->
    <issueManagement>
        <system>Github</system>
        <url>https://github.com/sim51/NOQM/issues</url>
    </issueManagement>

    <!-- ====================== -->
    <!-- = Project developers = -->
    <!-- ====================== -->
    <developers>
        <developer>
            <id>bsimard</id>
            <name>Benoît Simard</name>
            <email>github@bsimard.com</email>
        </developer>
    </developers>

    <!-- ============== -->
    <!-- = Properties = -->
    <!-- ============== -->
    <properties>
        <!-- Deps version -->
        <neo4j.version>3.2.2</neo4j.version>
        <neo4j.driver.version>1.4.1</neo4j.driver.version>
        <junit.version>4.12</junit.version>
        <lombok.version>1.16.18</lombok.version>

        <!-- Project configuration  -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>

        <!-- maven plugin configuration  -->
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>

        <!-- github server corresponds to entry in ~/.m2/settings.xml -->
        <!--
            <settings>
                 <servers>
                     <server>
                         <id>github</id>
                         <password>Generated token by `Personal access token`</password>
                     </server>
                 </servers>
             </settings>
        -->
        <github.global.server>github</github.global.server>
        <github.repo.owner>sim51</github.repo.owner>
        <github.repo.name>NOQM</github.repo.name>

        <!-- maven plugin version -->
        <maven.plugin.deploy>2.8.2</maven.plugin.deploy>
        <maven.plugin.site>3.6</maven.plugin.site>
        <maven.plugin.site.github>0.12</maven.plugin.site.github>
        <maven.plugin.jxr>2.5</maven.plugin.jxr>
        <maven.plugin.surefire>2.19.1</maven.plugin.surefire>
        <maven.plugin.javadoc>2.10.4</maven.plugin.javadoc>
        <maven.plugin.source>3.0.1</maven.plugin.source>
        <maven.plugin.checkstyle>2.17</maven.plugin.checkstyle>
        <maven.plugin.projectinfo>2.9</maven.plugin.projectinfo>
        <maven.plugin.pmd>3.8</maven.plugin.pmd>
        <maven.plugin.findbugs>3.0.4</maven.plugin.findbugs>
        <maven.plugin.version>2.4</maven.plugin.version>
        <maven.plugin.taglist>2.4</maven.plugin.taglist>
        <maven.plugin.changelog>2.3</maven.plugin.changelog>
        <maven.plugin.cobertura>2.7</maven.plugin.cobertura>
        <maven.plugin.coverall>4.1.0</maven.plugin.coverall>
        <maven.plugin.asciidoctor>1.5.5</maven.plugin.asciidoctor>
        <maven.plugin.scm-publish>1.1</maven.plugin.scm-publish>
        <maven.plugin.release>2.5.3</maven.plugin.release>

        <!-- Asciidoctor version -->
        <asciidoctorj.version>1.5.5</asciidoctorj.version>
        <jruby.version>1.7.22</jruby.version>

        <!-- Maven site skin -->
        <site.skin.groupId>org.apache.maven.skins</site.skin.groupId>
        <site.skin.artifactId>maven-fluido-skin</site.skin.artifactId>
        <site.skin.version>1.6</site.skin.version>

    </properties>

    <!-- ================ -->
    <!-- = Dependencies = -->
    <!-- ================ -->
    <dependencies>
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>${neo4j.driver.version}</version>
        </dependency>
        <dependency>
            <groupId>org.neo4j.driver</groupId>
            <artifactId>neo4j-java-driver</artifactId>
            <version>${neo4j.driver.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.neo4j.test</groupId>
            <artifactId>neo4j-harness-enterprise</artifactId>
            <version>${neo4j.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- ========= -->
    <!-- = Build = -->
    <!-- ========= -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>${maven.plugin.release}</version>
                <configuration>
                    <tagNameFormat>v@{project.version}</tagNameFormat>
                    <goals>deploy</goals>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <version>${maven.plugin.source}</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven.plugin.javadoc}</version>
                <configuration>
                    <failOnError>false</failOnError>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!-- Deploy artifact on a specific github branch as a maven repository -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>${maven.plugin.deploy}</version>
                <configuration>
                    <altDeploymentRepository>internal.repo::default::file://${project.build.directory}/mvn-repo</altDeploymentRepository>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.github.github</groupId>
                <artifactId>site-maven-plugin</artifactId>
                <version>${maven.plugin.site.github}</version>
                <configuration>
                    <!-- git commit message -->
                    <message>Maven artifacts for ${project.version}</message>
                    <!-- disable webpage processing -->
                    <noJekyll>true</noJekyll>
                    <!-- merge -->
                    <merge>true</merge>
                    <!-- matches distribution management repository url above -->
                    <outputDirectory>${project.build.directory}/mvn-repo</outputDirectory>
                    <!-- remote branch name -->
                    <branch>refs/heads/mvn-repo</branch>
                    <includes><include>**/*</include></includes>
                    <!-- github repo name -->
                    <repositoryName>${github.repo.name}</repositoryName>
                    <!-- github username  -->
                    <repositoryOwner>${github.repo.owner}</repositoryOwner>
                </configuration>
                <executions>
                    <!-- run site-maven-plugin's 'site' target as part of the build's normal 'deploy' phase -->
                    <execution>
                        <goals>
                            <goal>site</goal>
                        </goals>
                        <phase>deploy</phase>
                    </execution>
                </executions>
            </plugin>

            <!-- Maven site/reporting configuration -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-site-plugin</artifactId>
                <version>${maven.plugin.site}</version>
                <configuration>
                    <generateReports>true</generateReports>
                    <generateSitemap>true</generateSitemap>
                    <relativizeDecorationLinks>false</relativizeDecorationLinks>
                    <locales>en</locales>
                    <inputEncoding>UTF-8</inputEncoding>
                    <outputEncoding>UTF-8</outputEncoding>
                    <locales>en</locales>
                    <asciidoc>
                        <attributes>
                            <project-version>${project.version}</project-version>
                            <project-artifactId>${project.artifactId}</project-artifactId>
                            <neo4j-version>${neo4j.version}</neo4j-version>
                        </attributes>
                    </asciidoc>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-descriptor</id>
                        <goals>
                            <goal>attach-descriptor</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <!-- Just a hack for now to force this lib on version 1.7-->
                    <dependency>
                        <groupId>org.apache.maven.doxia</groupId>
                        <artifactId>doxia-core</artifactId>
                        <version>1.7</version>
                    </dependency>
                    <!-- Generate site with asciidoctor -->
                    <dependency>
                        <groupId>org.asciidoctor</groupId>
                        <artifactId>asciidoctor-maven-plugin</artifactId>
                        <version>${maven.plugin.asciidoctor}</version>
                    </dependency>
                    <!-- Comment this section to use the default jruby artifact provided by the plugin -->
                    <dependency>
                        <groupId>org.jruby</groupId>
                        <artifactId>jruby-complete</artifactId>
                        <version>${jruby.version}</version>
                    </dependency>
                    <!-- Comment this section to use the default AsciidoctorJ artifact provided by the plugin -->
                    <dependency>
                        <groupId>org.asciidoctor</groupId>
                        <artifactId>asciidoctorj</artifactId>
                        <version>${asciidoctorj.version}</version>
                    </dependency>
                    <!-- Adding custom skin -->
                    <dependency>
                        <groupId>${site.skin.groupId}</groupId>
                        <artifactId>${site.skin.artifactId}</artifactId>
                        <version>${site.skin.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <!-- Deploy site on github gh-pages -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-scm-publish-plugin</artifactId>
                <version>${maven.plugin.scm-publish}</version>
                <configuration>
                    <checkinComment>Publishing Site Docs for ${project.artifactId}:${project.version}</checkinComment>
                    <content>${project.reporting.outputDirectory}</content>
                    <scmBranch>gh-pages</scmBranch>
                    <tryUpdate>true</tryUpdate>
                </configuration>
                <executions>
                    <execution>
                        <id>scm-publish</id>
                        <phase>site</phase>
                        <goals>
                            <goal>publish-scm</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <!-- ============= -->
    <!-- = Reporting = -->
    <!-- ============= -->
    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>${maven.plugin.jxr}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>${maven.plugin.surefire}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>${maven.plugin.javadoc}</version>
                <configuration>
                    <failOnError>false</failOnError>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>${maven.plugin.checkstyle}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>${maven.plugin.projectinfo}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>${maven.plugin.pmd}</version>
                <configuration>
                    <sourceEncoding>${project.build.sourceEncoding}</sourceEncoding>
                    <!-- The minimum tokens before a violation -->
                    <minimumTokens>100</minimumTokens>
                    <!-- Turn off if no xref report -->
                    <linkXRef>true</linkXRef>
                    <verbose>true</verbose>
                    <targetJdk>${java.version}</targetJdk>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>findbugs-maven-plugin</artifactId>
                <version>${maven.plugin.findbugs}</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>versions-maven-plugin</artifactId>
                <version>${maven.plugin.version}</version>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>taglist-maven-plugin</artifactId>
                <version>${maven.plugin.taglist}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-changelog-plugin</artifactId>
                <version>${maven.plugin.changelog}</version>
            </plugin>
        </plugins>
    </reporting>

    <!-- =========== -->
    <!-- = Profile = -->
    <!-- =========== -->
    <profiles>

        <!-- Create the code coverage and publish it on coverall -->
        <profile>
            <id>coverage</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.codehaus.mojo</groupId>
                        <artifactId>cobertura-maven-plugin</artifactId>
                        <version>${maven.plugin.cobertura}</version>
                        <configuration>
                            <format>xml</format>
                            <maxmem>256m</maxmem>
                            <!-- aggregated reports for multi-module projects -->
                            <aggregate>true</aggregate>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.eluder.coveralls</groupId>
                        <artifactId>coveralls-maven-plugin</artifactId>
                        <version>${maven.plugin.coverall}</version>
                        <configuration>
                            <repoToken>${coverall.token}</repoToken>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

    </profiles>

    <!-- =========================== -->
    <!-- = Distribution management = -->
    <!-- =========================== -->
    <distributionManagement>
        <repository>
            <id>internal.repo</id>
            <name>Temporary Staging Repository</name>
            <url>file://${project.build.directory}/mvn-repo</url>
        </repository>
        <site>
            <id>github-site</id>
            <url>scm:git:git@github.com:sim51/NOQM.git</url>
        </site>
    </distributionManagement>

</project>


text:
package org.apereo.portal.groups.pags;

import java.util.Map;

/**
 * Interface for configuration providers for the Person Attributes Group Store.
 * Portal implementors may choose to override the default implementation of
 * this type, XMLPersonAttributesConfiguration, in order to
 * provide a list of group definitions for the PAGS to use.
 *
 * @author Al wold
 * @version $Revision$
 */
public interface IPersonAttributesConfiguration {
   /**
    * Get the group definitions for the store.  Implementations
    * should initialize a Map of PersonAttributesGroupStore.GroupDefinition
    * objects.
    *
    * @return Map consisting of group definitions, keyed by group key
    */
   public Map getConfig();
}