/*
 * Copyright 2010 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:40:07 PM CET
//

package com.hack23.cia.model.external.riksdagen.dokumentstatus.impl;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.hack23.cia.model.common.api.ModelObject;

/**
 * The Class DocumentStatusContainer.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DocumentStatusContainer", propOrder = {
    "document",
    "documentProposal",
    "documentActivityContainer",
    "documentDetailContainer",
    "documentAttachmentContainer",
    "documentReferenceContainer",
    "documentPersonReferenceContainer",
    "documentCategory"
})
@Entity(name = "DocumentStatusContainer")
@Table(name = "DOCUMENT_STATUS_CONTAINER")
@Inheritance(strategy = InheritanceType.JOINED)
public class DocumentStatusContainer
    implements ModelObject
{

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/** The document. */
    @XmlElement(name = "dokument", required = true)
    protected DocumentData document;

    /** The document proposal. */
    @XmlElement(name = "dokforslag", required = true)
    protected DocumentProposalContainer documentProposal;

    /** The document activity container. */
    @XmlElement(name = "dokaktivitet", required = true)
    protected DocumentActivityContainer documentActivityContainer;

    /** The document detail container. */
    @XmlElement(name = "dokuppgift", required = true)
    protected DocumentDetailContainer documentDetailContainer;

    /** The document attachment container. */
    @XmlElement(name = "dokbilaga", required = true)
    protected DocumentAttachmentContainer documentAttachmentContainer;

    /** The document reference container. */
    @XmlElement(name = "dokreferens", required = true)
    protected DocumentReferenceContainer documentReferenceContainer;

    /** The document person reference container. */
    @XmlElement(name = "dokintressent", required = true)
    protected DocumentPersonReferenceContainer documentPersonReferenceContainer;

    /** The document category. */
    @XmlElement(name = "dokkategori", required = true)
    protected String documentCategory;

    /** The hjid. */
    @XmlAttribute(name = "Hjid")
    protected Long hjid;

    /**
	 * Gets the document.
	 *
	 * @return the document
	 */
    @ManyToOne(targetEntity = DocumentData.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_DOCUMENT_STATUS_CON_0")
    public DocumentData getDocument() {
        return document;
    }

    /**
	 * Sets the document.
	 *
	 * @param value the new document
	 */
    public void setDocument(final DocumentData value) {
        this.document = value;
    }

    /**
	 * Gets the document proposal.
	 *
	 * @return the document proposal
	 */
    @ManyToOne(targetEntity = DocumentProposalContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_PROPOSAL_DOCUMENT_S_0")
    public DocumentProposalContainer getDocumentProposal() {
        return documentProposal;
    }

    /**
	 * Sets the document proposal.
	 *
	 * @param value the new document proposal
	 */
    public void setDocumentProposal(final DocumentProposalContainer value) {
        this.documentProposal = value;
    }

    /**
	 * Gets the document activity container.
	 *
	 * @return the document activity container
	 */
    @ManyToOne(targetEntity = DocumentActivityContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_ACTIVITY_CONTAINER__0")
    public DocumentActivityContainer getDocumentActivityContainer() {
        return documentActivityContainer;
    }

    /**
	 * Sets the document activity container.
	 *
	 * @param value the new document activity container
	 */
    public void setDocumentActivityContainer(final DocumentActivityContainer value) {
        this.documentActivityContainer = value;
    }

    /**
	 * Gets the document detail container.
	 *
	 * @return the document detail container
	 */
    @ManyToOne(targetEntity = DocumentDetailContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_DETAIL_CONTAINER_DO_0")
    public DocumentDetailContainer getDocumentDetailContainer() {
        return documentDetailContainer;
    }

    /**
	 * Sets the document detail container.
	 *
	 * @param value the new document detail container
	 */
    public void setDocumentDetailContainer(final DocumentDetailContainer value) {
        this.documentDetailContainer = value;
    }

    /**
	 * Gets the document attachment container.
	 *
	 * @return the document attachment container
	 */
    @ManyToOne(targetEntity = DocumentAttachmentContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_ATTACHMENT_CONTAINE_0")
    public DocumentAttachmentContainer getDocumentAttachmentContainer() {
        return documentAttachmentContainer;
    }

    /**
	 * Sets the document attachment container.
	 *
	 * @param value the new document attachment container
	 */
    public void setDocumentAttachmentContainer(final DocumentAttachmentContainer value) {
        this.documentAttachmentContainer = value;
    }

    /**
	 * Gets the document reference container.
	 *
	 * @return the document reference container
	 */
    @ManyToOne(targetEntity = DocumentReferenceContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_REFERENCE_CONTAINER_0")
    public DocumentReferenceContainer getDocumentReferenceContainer() {
        return documentReferenceContainer;
    }

    /**
	 * Sets the document reference container.
	 *
	 * @param value the new document reference container
	 */
    public void setDocumentReferenceContainer(final DocumentReferenceContainer value) {
        this.documentReferenceContainer = value;
    }

    /**
	 * Gets the document person reference container.
	 *
	 * @return the document person reference container
	 */
    @ManyToOne(targetEntity = DocumentPersonReferenceContainer.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "DOCUMENT_PERSON_REFERENCE_CO_1")
    public DocumentPersonReferenceContainer getDocumentPersonReferenceContainer() {
        return documentPersonReferenceContainer;
    }

    /**
	 * Sets the document person reference container.
	 *
	 * @param value the new document person reference container
	 */
    public void setDocumentPersonReferenceContainer(final DocumentPersonReferenceContainer value) {
        this.documentPersonReferenceContainer = value;
    }

    /**
	 * Gets the document category.
	 *
	 * @return the document category
	 */
    @Basic
    @Column(name = "DOCUMENT_CATEGORY")
    public String getDocumentCategory() {
        return documentCategory;
    }

    /**
	 * Sets the document category.
	 *
	 * @param value the new document category
	 */
    public void setDocumentCategory(final String value) {
        this.documentCategory = value;
    }

    /**
	 * With document.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocument(final DocumentData value) {
        setDocument(value);
        return this;
    }

    /**
	 * With document proposal.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentProposal(final DocumentProposalContainer value) {
        setDocumentProposal(value);
        return this;
    }

    /**
	 * With document activity container.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentActivityContainer(final DocumentActivityContainer value) {
        setDocumentActivityContainer(value);
        return this;
    }

    /**
	 * With document detail container.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentDetailContainer(final DocumentDetailContainer value) {
        setDocumentDetailContainer(value);
        return this;
    }

    /**
	 * With document attachment container.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentAttachmentContainer(final DocumentAttachmentContainer value) {
        setDocumentAttachmentContainer(value);
        return this;
    }

    /**
	 * With document reference container.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentReferenceContainer(final DocumentReferenceContainer value) {
        setDocumentReferenceContainer(value);
        return this;
    }

    /**
	 * With document person reference container.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentPersonReferenceContainer(final DocumentPersonReferenceContainer value) {
        setDocumentPersonReferenceContainer(value);
        return this;
    }

    /**
	 * With document category.
	 *
	 * @param value the value
	 * @return the document status container
	 */
    public DocumentStatusContainer withDocumentCategory(final String value) {
        setDocumentCategory(value);
        return this;
    }

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public final String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

    /**
	 * Gets the hjid.
	 *
	 * @return the hjid
	 */
    @Id
    @Column(name = "HJID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getHjid() {
        return hjid;
    }

    /**
	 * Sets the hjid.
	 *
	 * @param value the new hjid
	 */
    public void setHjid(final Long value) {
        this.hjid = value;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#equals(java.lang.Object)
     */
    public boolean equals(final Object object) {
    	return EqualsBuilder.reflectionEquals(this,object,"hjid");
    }

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public final int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
 */
package com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.dussan.vaadin.dcharts.DCharts;
import org.dussan.vaadin.dcharts.base.elements.XYseries;
import org.dussan.vaadin.dcharts.data.DataSeries;
import org.dussan.vaadin.dcharts.options.Series;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hack23.cia.model.internal.application.data.document.impl.RiksdagenDocumentPartySummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.document.impl.ViewRiksdagenPartyDocumentDailySummary;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.PartyDocumentChartDataManager;
import com.vaadin.ui.AbstractOrderedLayout;

/**
 * The Class PartyDocumentChartDataManagerImpl.
 */
@Service
public final class PartyDocumentChartDataManagerImpl extends AbstractChartDataManagerImpl
		implements PartyDocumentChartDataManager {

	private static final String DOCUMENT_HISTORY_PARTY = "Document history party";

	/** The Constant NO_INFO. */
	private static final String NO_INFO = "NoInfo";

	/** The Constant LOG_MSG_MISSING_DATA_FOR_KEY. */
	private static final String LOG_MSG_MISSING_DATA_FOR_KEY = "missing data for key:{}";

	/** The Constant EMPTY_STRING. */
	private static final String EMPTY_STRING = "";

	/** The Constant UNDER_SCORE. */
	private static final String UNDER_SCORE = "_";

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(PartyDocumentChartDataManagerImpl.class);

	/** The Constant DD_MMM_YYYY. */
	private static final String DD_MMM_YYYY = "dd-MMM-yyyy";

	/**
	 * Instantiates a new party document chart data manager impl.
	 */
	public PartyDocumentChartDataManagerImpl() {
		super();
	}

	/**
	 * Gets the view riksdagen party document daily summary map.
	 *
	 * @return the view riksdagen party document daily summary map
	 */
	private Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> getViewRiksdagenPartyDocumentDailySummaryMap() {
		final DataContainer<ViewRiksdagenPartyDocumentDailySummary, RiksdagenDocumentPartySummaryEmbeddedId> politicianBallotSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewRiksdagenPartyDocumentDailySummary.class);

		return politicianBallotSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull)
				.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPartyShortCode().toUpperCase(Locale.ENGLISH)
						.replace(UNDER_SCORE, EMPTY_STRING).trim()));
	}

	@Override
	public void createDocumentHistoryPartyChart(final AbstractOrderedLayout content, final String org) {
		final DataSeries dataSeries = new DataSeries();
		final Series series = new Series();

		final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> allMap = getViewRiksdagenPartyDocumentDailySummaryMap();

		final List<ViewRiksdagenPartyDocumentDailySummary> itemList = allMap
				.get(org.toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING).trim());

		if (itemList != null) {

			final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> map = itemList.parallelStream()
					.filter(Objects::nonNull).collect(Collectors
							.groupingBy(t -> StringUtils.defaultIfBlank(t.getEmbeddedId().getDocumentType(), NO_INFO)));

			addDocumentHistoryByPartyData(dataSeries, series, map);
		}

		addChart(content, DOCUMENT_HISTORY_PARTY,
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLegendInsideOneColumn(series)).show(),
				true);
	}

	/**
	 * Adds the document history by party data.
	 *
	 * @param dataSeries the data series
	 * @param series the series
	 * @param map the map
	 */
	private static void addDocumentHistoryByPartyData(final DataSeries dataSeries, final Series series,
			final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> map) {
		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);

		for (final Entry<String, List<ViewRiksdagenPartyDocumentDailySummary>> entry : map.entrySet()) {

			series.addSeries(new XYseries().setLabel(entry.getKey()));

			dataSeries.newSeries();
			if (entry.getValue() != null) {
				for (final ViewRiksdagenPartyDocumentDailySummary item : entry.getValue()) {
					dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getPublicDate()), item.getTotal());
				}
			} else {
				LOGGER.info(LOG_MSG_MISSING_DATA_FOR_KEY, entry);
			}

		}
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.component.agent.impl.riksdagen.workgenerator;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.jms.Destination;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.hack23.cia.model.external.riksdagen.personlista.impl.PersonElement;
import com.hack23.cia.model.internal.application.data.impl.RiksdagenDataSources;
import com.hack23.cia.service.external.riksdagen.api.DataFailureException;
import com.hack23.cia.service.external.riksdagen.api.RiksdagenPersonApi;

/**
 * The Class RiksdagenPersonsWorkGeneratorImpl.
 */
@Service("RiksdagenPersonsWorkGeneratorImpl")
final class RiksdagenPersonsWorkGeneratorImpl extends AbstractRiksdagenDataSourcesWorkGenerator {

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(RiksdagenPersonsWorkGeneratorImpl.class);

	/** The person element workdestination. */
	@Autowired
	@Qualifier("com.hack23.cia.model.external.riksdagen.personlista.impl.PersonElement")
	private Destination personElementWorkdestination;

	/** The riksdagen api. */
	@Autowired
	private RiksdagenPersonApi riksdagenApi;

	/**
	 * Instantiates a new riksdagen persons work generator impl.
	 */
	public RiksdagenPersonsWorkGeneratorImpl() {
		super(RiksdagenDataSources.PERSONS);
	}

	@Override
	public void generateWorkOrders() {
		try {
			final List<PersonElement> personList = riksdagenApi.getPersonList().getPerson();

			for (final PersonElement personElement : personList) {
				LOGGER.info("Send Load Order:{}", personElement.getPersonUrlXml());
				getJmsSender().send(personElementWorkdestination, personElement);
			}
			for (final String personId : readMissingPersonList()) {
				LOGGER.info("Send Load Order:{}{}", "https://data.riksdagen.se/person/", personId);
				getJmsSender().send(personElementWorkdestination, new PersonElement().withId(personId));
			}
		} catch (final DataFailureException exception) {
			LOGGER.warn("Problem during generate work orders", exception);
		}
	}

	/**
	 * Read missing person list.
	 *
	 * @return the string[]
	 */
	private static String[] readMissingPersonList() {

		final Scanner sc = new Scanner(RiksdagenPersonsWorkGeneratorImpl.class.getResourceAsStream("/personlist.txt"),StandardCharsets.UTF_8.name());
		final List<String> lines = new ArrayList<>();
		while (sc.hasNextLine()) {
			lines.add(sc.nextLine());
		}
		sc.close();
		return lines.toArray(new String[0]);
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.common.converters;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
import com.vaadin.data.ValueProvider;

/**
 * The Class ListPropertyRenderer.
 */
public final class ListPropertyConverter implements Converter<String, List<?>>,ValueProvider<Object, String> {

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(ListPropertyConverter.class);

	private static final PropertyUtilsBean PROPERTY_UTILS_BEAN= new PropertyUtilsBean();

	private static final char CONTENT_SEPARATOR = ' ';

	private static final char START_TAG = '[';

	private static final char END_TAG = ']';

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The property. */
	private final String property;

	/** The column. */
	private final String column;

	private final String fallbackColumn;

	/**
	 * Instantiates a new collection property converter.
	 * @param property
	 *            the property
	 * @param column
	 *            the column
	 */
	public ListPropertyConverter(final String property, final String column) {
		super();
		this.property = property;
		this.column = column;
		this.fallbackColumn = null;
	}

	/**
	 * Instantiates a new list property converter.
	 * @param property
	 *            the property
	 * @param column
	 *            the column
	 * @param fallbackColumn
	 *            the fallback column
	 */
	public ListPropertyConverter(final String property, final String column, final String fallbackColumn) {
		super();
		this.property = property;
		this.column = column;
		this.fallbackColumn = fallbackColumn;
	}

	/**
	 * Gets the column.
	 *
	 * @return the column
	 */
	public String getColumn() {
		return column;
	}

	@Override
	public Result<List<?>> convertToModel(final String value, final ValueContext context) {
		return Result.ok(new ArrayList<>());
	}

	@Override
	public String convertToPresentation(final List value, final ValueContext context) {
		final StringBuilder stringBuilder = new StringBuilder();

		if (value != null) {
			stringBuilder.append(START_TAG);
			for (final Object object : value) {
				appendObjectPresentation(stringBuilder, object);
			}
			stringBuilder.append(END_TAG);
		}

		return stringBuilder.toString();
	}

	/**
	 * Append object presentation.
	 *
	 * @param stringBuilder
	 *            the string builder
	 * @param object
	 *            the object
	 */
	private void appendObjectPresentation(final StringBuilder stringBuilder, final Object object) {
		try {
			final String beanProperty = BeanUtils.getProperty(object, property);

			if (beanProperty != null) {
				stringBuilder.append(beanProperty);
			} else {
				addFallbackValue(stringBuilder, object);
			}

		} catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			LOGGER.warn("Problem getting property {}, object {} , exception {}", property, object, e);
		}
		stringBuilder.append(CONTENT_SEPARATOR);
	}

	/**
	 * Adds the fallback value.
	 *
	 * @param stringBuilder the string builder
	 * @param object        the object
	 * @throws IllegalAccessException    the illegal access exception
	 * @throws InvocationTargetException the invocation target exception
	 * @throws NoSuchMethodException     the no such method exception
	 */
	private void addFallbackValue(final StringBuilder stringBuilder, final Object object)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		if (fallbackColumn != null) {
			final String beanPropertyFallBack = BeanUtils.getProperty(object, fallbackColumn);
			if (beanPropertyFallBack != null) {
				stringBuilder.append(beanPropertyFallBack);
			}
		}
	}

	@Override
	public String apply(final Object source) {
		List<?> list;
		try {
			list = (List<?>) PROPERTY_UTILS_BEAN.getProperty(source, column);
			return convertToPresentation(list,null);
		} catch (final IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			LOGGER.warn("Problem getting list {}, object {} , exception {}", property, column, e);
		}
		return "";
	}

}


/*
 * Copyright 2010 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:40:07 PM CET
//

package com.hack23.cia.model.external.riksdagen.dokumentstatus.impl;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;

/**
 * A factory for creating Object objects.
 */
@XmlRegistry
public class ObjectFactory {

    /** The Constant _Dokumentstatus_QNAME. */
    private static final QName _Dokumentstatus_QNAME = new QName("http://dokumentstatus.riksdagen.external.model.cia.hack23.com/impl", "dokumentstatus");

    /**
	 * Instantiates a new object factory.
	 */
    public ObjectFactory() {
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document status container
	 */
    public DocumentStatusContainer createDocumentStatusContainer() {
        return new DocumentStatusContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document data
	 */
    public DocumentData createDocumentData() {
        return new DocumentData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document activity container
	 */
    public DocumentActivityContainer createDocumentActivityContainer() {
        return new DocumentActivityContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document activity data
	 */
    public DocumentActivityData createDocumentActivityData() {
        return new DocumentActivityData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document proposal data
	 */
    public DocumentProposalData createDocumentProposalData() {
        return new DocumentProposalData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document proposal container
	 */
    public DocumentProposalContainer createDocumentProposalContainer() {
        return new DocumentProposalContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document detail container
	 */
    public DocumentDetailContainer createDocumentDetailContainer() {
        return new DocumentDetailContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document detail data
	 */
    public DocumentDetailData createDocumentDetailData() {
        return new DocumentDetailData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document attachment container
	 */
    public DocumentAttachmentContainer createDocumentAttachmentContainer() {
        return new DocumentAttachmentContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document attachment
	 */
    public DocumentAttachment createDocumentAttachment() {
        return new DocumentAttachment();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document reference container
	 */
    public DocumentReferenceContainer createDocumentReferenceContainer() {
        return new DocumentReferenceContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document reference data
	 */
    public DocumentReferenceData createDocumentReferenceData() {
        return new DocumentReferenceData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document person reference container
	 */
    public DocumentPersonReferenceContainer createDocumentPersonReferenceContainer() {
        return new DocumentPersonReferenceContainer();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @return the document person reference data
	 */
    public DocumentPersonReferenceData createDocumentPersonReferenceData() {
        return new DocumentPersonReferenceData();
    }

    /**
	 * Creates a new Object object.
	 *
	 * @param value the value
	 * @return the JAXB element< document status container>
	 */
    @XmlElementDecl(namespace = "http://dokumentstatus.riksdagen.external.model.cia.hack23.com/impl", name = "dokumentstatus")
    public JAXBElement<DocumentStatusContainer> createDokumentstatus(final DocumentStatusContainer value) {
        return new JAXBElement<>(_Dokumentstatus_QNAME, DocumentStatusContainer.class, null, value);
    }

}


/*
 * Copyright 2010 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.impl.action.user;

import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hack23.cia.model.internal.application.secure.impl.EncryptedValue;
import com.hack23.cia.model.internal.application.secure.impl.EncryptedValue_;
import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.model.internal.application.system.impl.ApplicationOperationType;
import com.hack23.cia.model.internal.application.user.impl.UserAccount;
import com.hack23.cia.service.api.action.application.CreateApplicationEventRequest;
import com.hack23.cia.service.api.action.common.ServiceResponse.ServiceResult;
import com.hack23.cia.service.api.action.user.ChangePasswordRequest;
import com.hack23.cia.service.api.action.user.ChangePasswordResponse;
import com.hack23.cia.service.data.api.EncryptedValueDAO;
import com.hack23.cia.service.impl.action.application.encryption.VaultManager;
import com.hack23.cia.service.impl.action.common.AbstractBusinessServiceImpl;
import com.hack23.cia.service.impl.action.common.BusinessService;

/**
 * The Class ChangePasswordService.
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, timeout = 600)
public final class ChangePasswordService extends
		AbstractBusinessServiceImpl<ChangePasswordRequest, ChangePasswordResponse>
		implements
		BusinessService<ChangePasswordRequest, ChangePasswordResponse> {

	/** The Constant LOGGER. */
	private static final Logger LOGGER = LoggerFactory.getLogger(ChangePasswordService.class);

	/** The encrypted value DAO. */
	@Autowired
	private EncryptedValueDAO encryptedValueDAO;

	@Autowired
	private VaultManager vaultManager;

	/** The password encoder. */
	private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

	/** The password validator. */
	private final PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(8, 64),
			new CharacterRule(EnglishCharacterData.UpperCase, 1), new CharacterRule(EnglishCharacterData.LowerCase, 1),
			new CharacterRule(EnglishCharacterData.Digit, 1), new CharacterRule(EnglishCharacterData.Special, 1),
			new WhitespaceRule());

	/**
	 * Instantiates a new change password service.
	 */
	public ChangePasswordService() {
		super(ChangePasswordRequest.class);
	}

	@Override
	@Secured({ "ROLE_USER", "ROLE_ADMIN" })
	public ChangePasswordResponse processService(
			final ChangePasswordRequest serviceRequest) {
		final ChangePasswordResponse inputValidation = inputValidation(serviceRequest);
		if (inputValidation != null) {
			return inputValidation;
		}

		LOGGER.info("{}:{}", serviceRequest.getClass().getSimpleName(), serviceRequest.getSessionId());
		final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest);

		final UserAccount userAccount = getUserAccountFromSecurityContext();

		ChangePasswordResponse response = new ChangePasswordResponse(
				ServiceResult.SUCCESS);
		if (userAccount != null) {

			if (passwordEncoder.matches(
					userAccount.getUserId() + ".uuid" + serviceRequest.getCurrentPassword(), userAccount.getUserpassword()) && serviceRequest.getNewPassword().equals(serviceRequest.getRepeatNewPassword())) {

				final RuleResult passwordRuleResults = passwordValidator
						.validate(new PasswordData(serviceRequest.getNewPassword()));

				if (passwordRuleResults.isValid()) {

					userAccount.setUserpassword(passwordEncoder.encode(userAccount.getUserId() + ".uuid" + serviceRequest.getNewPassword()));
					getUserDAO().merge(userAccount);

					reencryptVaultValues(serviceRequest, userAccount);

				} else {
					response = new ChangePasswordResponse(ServiceResult.FAILURE);
					final String errorMessage = passwordValidator.getMessages(passwordRuleResults).toString();
					response.setErrorMessage(errorMessage);
					eventRequest.setErrorMessage(errorMessage);
				}

			} else {
				response = new ChangePasswordResponse(
						ServiceResult.FAILURE);
			}

		}

		eventRequest.setApplicationMessage(response.getResult().toString());
		createApplicationEventService.processService(eventRequest);

		return response;
	}

	/**
	 * Reencrypt vault values.
	 *
	 * @param serviceRequest the service request
	 * @param userAccount    the user account
	 */
	private void reencryptVaultValues(final ChangePasswordRequest serviceRequest, final UserAccount userAccount) {
		final String authKey= vaultManager.getEncryptedValue(serviceRequest.getCurrentPassword(), userAccount);
		if (authKey != null) {
			final EncryptedValue encryptedValue = encryptedValueDAO.findFirstByProperty(EncryptedValue_.userId, userAccount.getUserId());
			encryptedValue.setStorage(vaultManager.encryptValue(serviceRequest.getNewPassword(), userAccount.getUserId(), authKey));
			encryptedValueDAO.merge(encryptedValue);
		}
	}

	@Override
	protected CreateApplicationEventRequest createApplicationEventForService(
			final ChangePasswordRequest serviceRequest) {
		final CreateApplicationEventRequest eventRequest = createBaseApplicationEventRequest();
		eventRequest.setEventGroup(ApplicationEventGroup.USER);
		eventRequest.setApplicationOperation(ApplicationOperationType.CREATE);
		eventRequest.setActionName(ChangePasswordRequest.class.getSimpleName());
		eventRequest.setSessionId(serviceRequest.getSessionId());
		return eventRequest;
	}

	@Override
	protected ChangePasswordResponse createErrorResponse() {
		return new ChangePasswordResponse(ServiceResult.FAILURE);
	}

}


/*
 * Copyright 2010 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.02.24 at 11:39:52 PM CET
//

package com.hack23.cia.model.external.val.landstingvalkrets.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import com.hack23.cia.model.common.api.ModelObject;

/**
 * The Class SwedenCountyElectoralRegion.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SwedenCountyElectoralRegion", propOrder = {
    "code",
    "countyName",
    "seats",
    "landstingsvalkrets"
})
@Entity(name = "SwedenCountyElectoralRegion")
@Table(name = "SWEDEN_COUNTY_ELECTORAL_REGI_1")
@Inheritance(strategy = InheritanceType.JOINED)
public class SwedenCountyElectoralRegion
    implements ModelObject
{

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/** The code. */
    @XmlElement(name = "landstingskod", required = true)
    protected BigInteger code;

    /** The county name. */
    @XmlElement(name = "landstingsnamn", required = true)
    protected String countyName;

    /** The seats. */
    @XmlElement(name = "valkretsmandat", required = true)
    protected BigInteger seats;

    /** The landstingsvalkrets. */
    @XmlElement(required = true)
    protected List<SwedenCountyElectoralArea> landstingsvalkrets = new ArrayList<>();

    /** The hjid. */
    @XmlAttribute(name = "Hjid")
    protected Long hjid;

    /**
	 * Gets the code.
	 *
	 * @return the code
	 */
    @Basic
    @Column(name = "CODE", precision = 20)
    public BigInteger getCode() {
        return code;
    }

    /**
	 * Sets the code.
	 *
	 * @param value the new code
	 */
    public void setCode(final BigInteger value) {
        this.code = value;
    }

    /**
	 * Gets the county name.
	 *
	 * @return the county name
	 */
    @Basic
    @Column(name = "COUNTY_NAME")
    public String getCountyName() {
        return countyName;
    }

    /**
	 * Sets the county name.
	 *
	 * @param value the new county name
	 */
    public void setCountyName(final String value) {
        this.countyName = value;
    }

    /**
	 * Gets the seats.
	 *
	 * @return the seats
	 */
    @Basic
    @Column(name = "SEATS", precision = 20)
    public BigInteger getSeats() {
        return seats;
    }

    /**
	 * Sets the seats.
	 *
	 * @param value the new seats
	 */
    public void setSeats(final BigInteger value) {
        this.seats = value;
    }

    /**
	 * Gets the landstingsvalkrets.
	 *
	 * @return the landstingsvalkrets
	 */
    @OneToMany(targetEntity = SwedenCountyElectoralArea.class, cascade = {
        CascadeType.ALL
    })
    @JoinColumn(name = "LANDSTINGSVALKRETS_SWEDEN_CO_0")
    public List<SwedenCountyElectoralArea> getLandstingsvalkrets() {
        return this.landstingsvalkrets;
    }

    /**
	 * Sets the landstingsvalkrets.
	 *
	 * @param landstingsvalkrets the new landstingsvalkrets
	 */
    public void setLandstingsvalkrets(final List<SwedenCountyElectoralArea> landstingsvalkrets) {
        this.landstingsvalkrets = landstingsvalkrets;
    }

    /**
	 * Gets the hjid.
	 *
	 * @return the hjid
	 */
    @Id
    @Column(name = "HJID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getHjid() {
        return hjid;
    }

    /**
	 * Sets the hjid.
	 *
	 * @param value the new hjid
	 */
    public void setHjid(final Long value) {
        this.hjid = value;
    }

	@Override
	public final boolean equals(final Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj,"hjid");
	}

	@Override
	public final String toString() {
		return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
	}

	@Override
	public final int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}
}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hack23.cia.model.internal.application.data.committee.impl.ViewRiksdagenCommittee;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.DecisionFlowChartManager;
import com.hack23.cia.web.impl.ui.application.views.common.dataseriesfactory.api.DecisionDataFactory;
import com.hack23.cia.web.impl.ui.application.views.common.dataseriesfactory.api.ProposalCommitteeeSummary;
import com.hack23.cia.web.widgets.charts.SankeyChart;
import com.vaadin.ui.TextArea;

/**
 * The Class DecisionFlowChartManagerImpl.
 */
@Service
public final class DecisionFlowChartManagerImpl implements DecisionFlowChartManager {

	/** The decision data factory. */
	@Autowired
	private DecisionDataFactory decisionDataFactory;

	/**
	 * Instantiates a new decision flow chart manager impl.
	 */
	public DecisionFlowChartManagerImpl() {
		super();
	}

	@Override
	public SankeyChart createAllDecisionFlow(final Map<String, List<ViewRiksdagenCommittee>> committeeMap,final String rm) {
		final List<ProposalCommitteeeSummary> createCommitteeSummary = decisionDataFactory.createCommitteeSummary(rm);

		final SankeyChart chart = new SankeyChart();

		final Map<String, List<ProposalCommitteeeSummary>> orgProposalMap = createCommitteeSummary.stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getOrg));

		for (final Entry<String, List<ProposalCommitteeeSummary>> entry : orgProposalMap.entrySet()) {

			if (committeeMap.containsKey(entry.getKey())) {

				final Optional<ViewRiksdagenCommittee> vewRiksdagenCommittee = committeeMap.get(entry.getKey()).stream().findFirst();
				if (vewRiksdagenCommittee.isPresent()) {
					addDocTypeDataRows(chart, entry, vewRiksdagenCommittee.get());
					addDecisionDataRows(chart, entry, vewRiksdagenCommittee.get());
				}
			}
		}

		chart.drawChart();
		return chart;
	}

	@Override
	public TextArea createCommitteeeDecisionSummary(final Map<String, List<ViewRiksdagenCommittee>> committeeMap,final String rm) {
		final TextArea area = new TextArea("Summary");
		final StringBuilder stringBuilder = new StringBuilder();
		final List<ProposalCommitteeeSummary> createCommitteeSummary = decisionDataFactory.createCommitteeSummary(rm);

		final Map<String, List<ProposalCommitteeeSummary>> orgProposalMap = createCommitteeSummary.stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getOrg));

		for (final Entry<String, List<ProposalCommitteeeSummary>> entry : orgProposalMap.entrySet()) {
			if (committeeMap.containsKey(entry.getKey())) {
				addCommiteeSummary(stringBuilder, entry, committeeMap.get(entry.getKey()).stream().findFirst());
			}
		}
		area.setValue(stringBuilder.toString());
		return area;
	}

	/**
	 * Adds the commitee summary.
	 *
	 * @param stringBuilder         the string builder
	 * @param entry                 the entry
	 * @param vewRiksdagenCommittee the vew riksdagen committee
	 */
	private static void addCommiteeSummary(final StringBuilder stringBuilder,
			final Entry<String, List<ProposalCommitteeeSummary>> entry,
			final Optional<ViewRiksdagenCommittee> vewRiksdagenCommittee) {
		if (vewRiksdagenCommittee.isPresent()) {

			final Map<String, List<ProposalCommitteeeSummary>> docTypeMap = entry.getValue().stream()
					.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType));

			stringBuilder.append('\n').append(vewRiksdagenCommittee.get().getEmbeddedId().getDetail());
			for (final Entry<String, List<ProposalCommitteeeSummary>> docEntry : docTypeMap.entrySet()) {
				if (docEntry.getKey().length() > 0 && entry.getKey().length() > 0) {
					addEntry(stringBuilder, entry, docEntry);
				}
			}
		}
	}

	/**
	 * Adds the entry.
	 *
	 * @param stringBuilder the string builder
	 * @param entry         the entry
	 * @param docEntry      the doc entry
	 */
	private static void addEntry(final StringBuilder stringBuilder,
			final Entry<String, List<ProposalCommitteeeSummary>> entry,
			final Entry<String, List<ProposalCommitteeeSummary>> docEntry) {
		stringBuilder.append("( ").append(docEntry.getValue().size()).append(' ').append(docEntry.getKey()).append(" -> ");

		final Map<String, List<ProposalCommitteeeSummary>> decisionMap = docEntry.getValue().stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision));

		for (final Entry<String, List<ProposalCommitteeeSummary>> decisionEntry : decisionMap.entrySet()) {
			if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) {
				stringBuilder.append(decisionEntry.getValue().size()).append(' ').append(decisionEntry.getKey()).append(' ');

			}
		}
		stringBuilder.append(')');
	}

	/**
	 * Adds the decision data rows.
	 *
	 * @param chart
	 *            the chart
	 * @param entry
	 *            the entry
	 * @param vewRiksdagenCommittee
	 *            the vew riksdagen committee
	 */
	private static void addDecisionDataRows(final SankeyChart chart,
			final Entry<String, List<ProposalCommitteeeSummary>> entry,
			final ViewRiksdagenCommittee vewRiksdagenCommittee) {
		final Map<String, List<ProposalCommitteeeSummary>> decisionMap = entry.getValue().stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision));

		for (final Entry<String, List<ProposalCommitteeeSummary>> decisionEntry : decisionMap.entrySet()) {
			if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) {
				chart.addDataRow(vewRiksdagenCommittee.getEmbeddedId().getDetail(), decisionEntry.getKey(),
						decisionEntry.getValue().size());
			}
		}
	}

	/**
	 * Adds the doc type data rows.
	 *
	 * @param chart
	 *            the chart
	 * @param entry
	 *            the entry
	 * @param vewRiksdagenCommittee
	 *            the vew riksdagen committee
	 */
	private static void addDocTypeDataRows(final SankeyChart chart,
			final Entry<String, List<ProposalCommitteeeSummary>> entry,
			final ViewRiksdagenCommittee vewRiksdagenCommittee) {
		final Map<String, List<ProposalCommitteeeSummary>> docTypeMap = entry.getValue().stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType));

		for (final Entry<String, List<ProposalCommitteeeSummary>> docEntry : docTypeMap.entrySet()) {
			if (docEntry.getKey().length() > 0 && entry.getKey().length() > 0) {
				chart.addDataRow(docEntry.getKey(), vewRiksdagenCommittee.getEmbeddedId().getDetail(),
						docEntry.getValue().size());

			}
		}
	}

	@Override
	public SankeyChart createCommitteeDecisionFlow(final ViewRiksdagenCommittee viewRiksdagenCommittee,
			final Map<String, List<ViewRiksdagenCommittee>> committeeMap, final String rm) {
		final List<ProposalCommitteeeSummary> createCommitteeSummary = decisionDataFactory.createCommitteeSummary(rm);

		final SankeyChart chart = new SankeyChart();

		final Map<String, List<ProposalCommitteeeSummary>> orgProposalMap = createCommitteeSummary.stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getOrg));

		for (final Entry<String, List<ProposalCommitteeeSummary>> entry : orgProposalMap.entrySet()) {
			if (committeeMap.containsKey(entry.getKey())
					&& viewRiksdagenCommittee.getEmbeddedId().getOrgCode().equals(entry.getKey())) {
				addDocTypeDecisionDataRows(chart, entry);
			}
		}

		chart.drawChart();
		return chart;
	}

	/**
	 * Adds the doc type decision data rows.
	 *
	 * @param chart
	 *            the chart
	 * @param entry
	 *            the entry
	 */
	private static void addDocTypeDecisionDataRows(final SankeyChart chart,
			final Entry<String, List<ProposalCommitteeeSummary>> entry) {
		final Map<String, List<ProposalCommitteeeSummary>> docTypeMap = entry.getValue().stream()
				.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDocType));

		for (final Entry<String, List<ProposalCommitteeeSummary>> docEntry : docTypeMap.entrySet()) {

			final Map<String, List<ProposalCommitteeeSummary>> decisionMap = docEntry.getValue().stream()
					.collect(Collectors.groupingBy(ProposalCommitteeeSummary::getDecision));

			for (final Entry<String, List<ProposalCommitteeeSummary>> decisionEntry : decisionMap.entrySet()) {
				if (decisionEntry.getKey().length() > 0 && entry.getKey().length() > 0) {
					chart.addDataRow(docEntry.getKey(), decisionEntry.getKey(), decisionEntry.getValue().size());
				}
			}
		}
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.util;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.vaadin.server.Page;

/**
 * The Class UserContextUtil.
 */
public final class UserContextUtil {

	/**
	 * Gets the user id from security context.
	 *
	 * @return the user id from security context
	 */
	public static String getUserIdFromSecurityContext() {
		final SecurityContext context = SecurityContextHolder.getContext();
		if (context != null) {
			final Authentication authentication = context.getAuthentication();
			if (authentication != null) {
				return authentication.getPrincipal().toString();
			}
		}
		return null;
	}

	/**
	 * Gets the request url.
	 *
	 * @param current
	 *            the current
	 * @return the request url
	 */
	public static String getRequestUrl(final Page current) {
		if (current != null) {
			return current.getLocation().toString();

		} else {
			final HttpServletRequest httpRequest=((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
			return httpRequest.getRequestURL().toString();
		}
	}

	/**
	 * Allow role in security context.
	 *
	 * @param role
	 *            the role
	 * @return true, if successful
	 */
	public static boolean allowRoleInSecurityContext(final String role) {
		boolean result = false;
		final SecurityContext context = SecurityContextHolder.getContext();
		if (context != null && context.getAuthentication() != null) {
			final Collection<? extends GrantedAuthority> authorities = context.getAuthentication().getAuthorities();

			for (final GrantedAuthority grantedAuthority : authorities) {
				if (role.equalsIgnoreCase(grantedAuthority.getAuthority())) {
					result = true;
				}
			}
		}
		return result;
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
 */
package com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;

import org.dussan.vaadin.dcharts.DCharts;
import org.dussan.vaadin.dcharts.base.elements.XYseries;
import org.dussan.vaadin.dcharts.data.DataSeries;
import org.dussan.vaadin.dcharts.options.Series;
import org.springframework.stereotype.Service;

import com.hack23.cia.model.internal.application.data.impl.ApplicationActionEventPageElementPeriodSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.impl.ApplicationActionEventPageElementPeriodSummaryEmbeddedId_;
import com.hack23.cia.model.internal.application.data.impl.ApplicationActionEventPageModePeriodSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.impl.ApplicationActionEventPageModePeriodSummaryEmbeddedId_;
import com.hack23.cia.model.internal.application.data.impl.ApplicationActionEventPagePeriodSummaryEmbeddedId;
import com.hack23.cia.model.internal.application.data.impl.ViewApplicationActionEventPageDailySummary;
import com.hack23.cia.model.internal.application.data.impl.ViewApplicationActionEventPageElementDailySummary;
import com.hack23.cia.model.internal.application.data.impl.ViewApplicationActionEventPageElementDailySummary_;
import com.hack23.cia.model.internal.application.data.impl.ViewApplicationActionEventPageModeDailySummary;
import com.hack23.cia.model.internal.application.data.impl.ViewApplicationActionEventPageModeDailySummary_;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.AdminChartDataManager;
import com.vaadin.ui.AbstractOrderedLayout;

/**
 * The Class ChartDataManagerImpl.
 */
@Service
public final class AdminChartDataManagerImpl extends AbstractChartDataManagerImpl implements AdminChartDataManager {

	/** The Constant PAGE_RANK. */
	private static final String PAGE_RANK = "Page Rank";

	/** The Constant PAGE_HITS. */
	private static final String PAGE_HITS = "Page Hits";

	/** The Constant DD_MMM_YYYY. */
	private static final String DD_MMM_YYYY = "dd-MMM-yyyy";

	/**
	 * Instantiates a new admin chart data manager impl.
	 */
	public AdminChartDataManagerImpl() {
		super();
	}

	/**
	 * Gets the application action event page daily summary map.
	 *
	 * @return the application action event page daily summary map
	 */
	private Map<String, List<ViewApplicationActionEventPageDailySummary>> getApplicationActionEventPageDailySummaryMap() {
		final DataContainer<ViewApplicationActionEventPageDailySummary, ApplicationActionEventPagePeriodSummaryEmbeddedId> documentTypeSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewApplicationActionEventPageDailySummary.class);

		return documentTypeSummaryDailyDataContainer.getAll().parallelStream().filter(Objects::nonNull)
				.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPage()));
	}

	@Override
	public void createApplicationActionEventPageDailySummaryChart(final AbstractOrderedLayout content) {

		final Map<String, List<ViewApplicationActionEventPageDailySummary>> map = getApplicationActionEventPageDailySummaryMap();

		final DataSeries dataSeries = new DataSeries();

		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);

		final Series series = new Series();

		for (final Entry<String, List<ViewApplicationActionEventPageDailySummary>> entry : map.entrySet()) {

			if (entry.getKey() != null) {
				series.addSeries(new XYseries().setLabel(entry.getKey()));

				dataSeries.newSeries();
				final List<ViewApplicationActionEventPageDailySummary> list = entry.getValue();
				for (final ViewApplicationActionEventPageDailySummary viewRiksdagenVoteDataBallotPartySummaryDaily : list) {
					dataSeries.add(
							simpleDateFormat.format(
									viewRiksdagenVoteDataBallotPartySummaryDaily.getEmbeddedId().getCreatedDate()),
							viewRiksdagenVoteDataBallotPartySummaryDaily.getHits());
				}
			}

		}

		addChart(content, "Application Action Events daily Summary",
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(),
				true);
	}

	/**
	 * Gets the application action event page mode daily summary map.
	 *
	 * @param page the page
	 * @return the application action event page mode daily summary map
	 */
	private Map<String, List<ViewApplicationActionEventPageModeDailySummary>> getApplicationActionEventPageModeDailySummaryMap(
			final String page) {
		final DataContainer<ViewApplicationActionEventPageModeDailySummary, ApplicationActionEventPageModePeriodSummaryEmbeddedId> documentTypeSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewApplicationActionEventPageModeDailySummary.class);

		final List<ViewApplicationActionEventPageModeDailySummary> findOrderedListByEmbeddedProperty = documentTypeSummaryDailyDataContainer
				.findOrderedListByEmbeddedProperty(ViewApplicationActionEventPageModeDailySummary.class,
						ViewApplicationActionEventPageModeDailySummary_.embeddedId,
						ApplicationActionEventPageModePeriodSummaryEmbeddedId.class,
						ApplicationActionEventPageModePeriodSummaryEmbeddedId_.page, page,
						ApplicationActionEventPageModePeriodSummaryEmbeddedId_.createdDate);

		return findOrderedListByEmbeddedProperty.parallelStream().filter(Objects::nonNull)
				.collect(Collectors.groupingBy(t -> t.getEmbeddedId().getPageMode()));
	}

	@Override
	public void createApplicationActionEventPageModeDailySummaryChart(final AbstractOrderedLayout content,
			final String page) {

		final Map<String, List<ViewApplicationActionEventPageModeDailySummary>> map = getApplicationActionEventPageModeDailySummaryMap(
				page);

		final DataSeries dataSeries = new DataSeries();

		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);

		final Series series = new Series();

		for (final Entry<String, List<ViewApplicationActionEventPageModeDailySummary>> entry : map.entrySet()) {

			if (entry.getKey() != null) {
				series.addSeries(new XYseries().setLabel(entry.getKey()));

				dataSeries.newSeries();
				final List<ViewApplicationActionEventPageModeDailySummary> list = entry.getValue();
				for (final ViewApplicationActionEventPageModeDailySummary item : list) {
					dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getCreatedDate()), item.getHits());
				}
			}

		}

		addChart(content, "Page Action Events daily Summary",
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(),
				true);
	}

	/**
	 * Gets the application action event page element daily summary list.
	 *
	 * @param page the page
	 * @param elementId the element id
	 * @return the application action event page element daily summary list
	 */
	private List<ViewApplicationActionEventPageElementDailySummary> getApplicationActionEventPageElementDailySummaryList(
			final String page, final String elementId) {
		final DataContainer<ViewApplicationActionEventPageElementDailySummary, ApplicationActionEventPageElementPeriodSummaryEmbeddedId> documentTypeSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewApplicationActionEventPageElementDailySummary.class);

		final List<ViewApplicationActionEventPageElementDailySummary> findOrderedListByEmbeddedProperty = documentTypeSummaryDailyDataContainer
				.findOrderedListByEmbeddedProperty(ViewApplicationActionEventPageElementDailySummary.class,
						ViewApplicationActionEventPageElementDailySummary_.embeddedId,
						ApplicationActionEventPageElementPeriodSummaryEmbeddedId.class,
						ApplicationActionEventPageElementPeriodSummaryEmbeddedId_.elementId, elementId,
						ApplicationActionEventPageElementPeriodSummaryEmbeddedId_.createdDate);

		return findOrderedListByEmbeddedProperty.parallelStream()
				.filter(t -> t != null && t.getEmbeddedId().getPage().equals(page)).collect(Collectors.toList());
	}

	@Override
	public void createApplicationActionEventPageElementDailySummaryChart(final AbstractOrderedLayout content,
			final String page, final String elementId) {
		final List<ViewApplicationActionEventPageElementDailySummary> list = getApplicationActionEventPageElementDailySummaryList(
				page, elementId);

		final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DD_MMM_YYYY, Locale.ENGLISH);
		final Series series = new Series();
		final DataSeries dataSeries = new DataSeries();

		addViewApplicationActionEventPageElementDailySummaryValues(PAGE_HITS, series, list, dataSeries,
				simpleDateFormat, ViewApplicationActionEventPageElementDailySummary::getHits);
		addViewApplicationActionEventPageElementDailySummaryValues(PAGE_RANK, series, list, dataSeries,
				simpleDateFormat, ViewApplicationActionEventPageElementDailySummary::getRank);

		addChart(content, "Page element Action Events daily Summary",
				new DCharts().setDataSeries(dataSeries)
						.setOptions(getChartOptions().createOptionsXYDateFloatLogYAxisLegendOutside(series)).show(),
				true);
	}

	/**
	 * Adds the view application action event page element daily summary values.
	 *
	 * @param label the label
	 * @param series the series
	 * @param list the list
	 * @param dataSeries the data series
	 * @param simpleDateFormat the simple date format
	 * @param t the t
	 */
	private static void addViewApplicationActionEventPageElementDailySummaryValues(final String label,
			final Series series, final List<ViewApplicationActionEventPageElementDailySummary> list,
			final DataSeries dataSeries, final SimpleDateFormat simpleDateFormat,
			final ToLongFunction<ViewApplicationActionEventPageElementDailySummary> t) {
		series.addSeries(new XYseries().setLabel(label));
		dataSeries.newSeries();

		for (final ViewApplicationActionEventPageElementDailySummary item : list) {
			dataSeries.add(simpleDateFormat.format(item.getEmbeddedId().getCreatedDate()), t.applyAsLong(item));
		}
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.component.agent.impl.riksdagen.workers.data;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hack23.cia.model.external.riksdagen.documentcontent.impl.DocumentContentData;
import com.hack23.cia.model.external.riksdagen.documentcontent.impl.DocumentContentData_;
import com.hack23.cia.model.external.riksdagen.dokumentlista.impl.DocumentElement;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentData_;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer;
import com.hack23.cia.model.external.riksdagen.dokumentstatus.impl.DocumentStatusContainer_;
import com.hack23.cia.model.external.riksdagen.person.impl.AssignmentData;
import com.hack23.cia.model.external.riksdagen.person.impl.PersonAssignmentData;
import com.hack23.cia.model.external.riksdagen.person.impl.PersonData;
import com.hack23.cia.model.external.riksdagen.utskottsforslag.impl.CommitteeProposalComponentData;
import com.hack23.cia.model.external.riksdagen.utskottsforslag.impl.CommitteeProposalComponentData_;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteData;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataEmbeddedId;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteDataEmbeddedId_;
import com.hack23.cia.model.external.riksdagen.votering.impl.VoteData_;
import com.hack23.cia.service.data.api.CommitteeProposalComponentDataDAO;
import com.hack23.cia.service.data.api.DocumentContentDataDAO;
import com.hack23.cia.service.data.api.DocumentElementDAO;
import com.hack23.cia.service.data.api.DocumentStatusContainerDAO;
import com.hack23.cia.service.data.api.PersonDataDAO;
import com.hack23.cia.service.data.api.VoteDataDAO;

/**
 * The Class RiksdagenUpdateServiceImpl.
 */
@Component("RiksdagenUpdateService")
@Transactional(propagation = Propagation.MANDATORY)
final class RiksdagenUpdateServiceImpl implements RiksdagenUpdateService {

	/** The committee proposal component data DAO. */
	@Autowired
	private CommitteeProposalComponentDataDAO committeeProposalComponentDataDAO;

	/** The document content data DAO. */
	@Autowired
	private DocumentContentDataDAO documentContentDataDAO;

	/** The document element DAO. */
	@Autowired
	private DocumentElementDAO documentElementDAO;

	/** The document status container DAO. */
	@Autowired
	private DocumentStatusContainerDAO documentStatusContainerDAO;

	/** The person data DAO. */
	@Autowired
	private PersonDataDAO personDataDAO;

	/** The vote data DAO. */
	@Autowired
	private VoteDataDAO voteDataDAO;

	/**
	 * Instantiates a new riksdagen update service impl.
	 */
	public RiksdagenUpdateServiceImpl() {
		super();
	}

	@Override
	public void update(final PersonData personData) {
		final PersonData existData = personDataDAO.load(personData.getId());
		if (existData == null) {
			personDataDAO.persist(personData);
		} else {
			existData.setElectionRegion(personData.getElectionRegion());
			existData.setParty(personData.getParty());
			existData.setStatus(personData.getStatus());
			existData.setLastName(personData.getLastName());
			existData.setPlace(personData.getPlace());

			updatePersonAssignmentData(existData.getPersonAssignmentData(), personData.getPersonAssignmentData());

			personDataDAO.persist(existData);
		}
	}

	/**
	 * Update person assignment data.
	 *
	 * @param exist  the exist
	 * @param update the update
	 */
	private static void updatePersonAssignmentData(final PersonAssignmentData exist, final PersonAssignmentData update) {

		final List<AssignmentData> assignmentList = update.getAssignmentList();

		for (final AssignmentData assignmentData : assignmentList) {
			updateAssignmentData(exist.getAssignmentList(), assignmentData);
		}
	}

	/**
	 * Update assignment data.
	 *
	 * @param assignmentList the assignment list
	 * @param assignmentData the assignment data
	 */
	private static void updateAssignmentData(final List<AssignmentData> assignmentList, final AssignmentData assignmentData) {
		for (final AssignmentData matchAssignmentData : assignmentList) {
			if (matchAssignmentData.getFromDate().equals(assignmentData.getFromDate())
					&& matchAssignmentData.getOrgCode().equals(assignmentData.getOrgCode()) && matchAssignmentData.getRoleCode().equals(assignmentData.getRoleCode())) {

				matchAssignmentData.setStatus(assignmentData.getStatus());
				matchAssignmentData.setToDate(assignmentData.getToDate());
				return;
			}
		}
		assignmentList.add(assignmentData);
	}

	@Override
	public void updateCommitteeProposalComponentData(final CommitteeProposalComponentData committeeProposal) {
		if (committeeProposalComponentDataDAO.findFirstByProperty(CommitteeProposalComponentData_.document,
				committeeProposal.getDocument()) == null) {
			committeeProposalComponentDataDAO.persist(committeeProposal);
		}
	}

	@Override
	public void updateDocumentContentData(final DocumentContentData documentData) {
		if (documentContentDataDAO.findFirstByProperty(DocumentContentData_.id, documentData.getId()) == null) {
			documentContentDataDAO.persist(documentData);
		}
	}

	@Override
	public void updateDocumentData(final DocumentStatusContainer documentData) {
		final List<DocumentStatusContainer> exist = documentStatusContainerDAO.findListByEmbeddedProperty(DocumentStatusContainer_.document, DocumentData.class,
				DocumentData_.id, documentData.getDocument().getId());
		if (exist.isEmpty()) {
			documentStatusContainerDAO.persist(documentData);
		} else {
			final DocumentStatusContainer existData = exist.get(0);

			mergeDocumentStatusContainer(existData,documentData);

			documentStatusContainerDAO.persist(existData);
		}
	}

	private static void mergeDocumentStatusContainer(final DocumentStatusContainer existData, final DocumentStatusContainer documentData) {
		if (!"planerat".equals(documentData.getDocument().getStatus())) {
			existData.getDocument().setStatus(documentData.getDocument().getStatus());
			existData.getDocument().setCommitteeReportUrlXml(documentData.getDocument().getCommitteeReportUrlXml());
		}
	}

	@Override
	public void updateDocumentElement(final DocumentElement documentData) {
		final DocumentElement existDocumentElement = documentElementDAO.load(documentData.getId());
		if (existDocumentElement == null) {
			documentElementDAO.persist(documentData);
		} else {
			existDocumentElement.setCommitteeReportUrlXml(documentData.getCommitteeReportUrlXml());
			existDocumentElement.setStatus(documentData.getStatus());
			existDocumentElement.setDebateName(documentData.getDebateName());
			existDocumentElement.setRelatedId(documentData.getRelatedId());
			existDocumentElement.setSystemDate(documentData.getSystemDate());
			existDocumentElement.setMadePublicDate(documentData.getMadePublicDate());
			existDocumentElement.setLabel(documentData.getLabel());
			existDocumentElement.setNote(documentData.getNote());
			existDocumentElement.setNoteTitle(documentData.getNoteTitle());
			existDocumentElement.setTempLabel(documentData.getTempLabel());
			existDocumentElement.setTitle(documentData.getTitle());
			documentElementDAO.persist(existDocumentElement);
		}
	}

	@Override
	public void updateVoteDataData(final List<VoteData> list) {
		if (list != null && !list.isEmpty()
				&& voteDataDAO.findListByEmbeddedProperty(VoteData_.embeddedId, VoteDataEmbeddedId.class,
						VoteDataEmbeddedId_.ballotId, list.get(0).getEmbeddedId().getBallotId()).isEmpty()) {
			voteDataDAO.persist(list);
		}
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.service.impl.action.common;

import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.springframework.beans.factory.annotation.Autowired;

import com.hack23.cia.model.internal.application.user.impl.UserAccount;
import com.hack23.cia.service.api.action.application.CreateApplicationEventRequest;
import com.hack23.cia.service.api.action.application.CreateApplicationEventResponse;
import com.hack23.cia.service.api.action.common.AbstractResponse;
import com.hack23.cia.service.api.action.common.ServiceRequest;
import com.hack23.cia.service.api.action.common.ServiceResponse;

/**
 * The Class AbstractBusinessServiceImpl.
 *
 * @param <T>
 *            the generic type
 * @param <V>
 *            the value type
 */
public abstract class AbstractBusinessServiceImpl<T extends ServiceRequest, V extends ServiceResponse>
		extends AbstractCommonBusinessServiceImpl<T, V> implements BusinessService<T, V> {

	/** The create application event service. */
	@Autowired
	protected BusinessService<CreateApplicationEventRequest, CreateApplicationEventResponse> createApplicationEventService;

	/**
	 * Instantiates a new abstract business service impl.
	 *
	 * @param clazz
	 *            the clazz
	 */
	public AbstractBusinessServiceImpl(final Class<T> clazz) {
		super(clazz);
	}

	/**
	 * Gets the create application event service.
	 *
	 * @return the create application event service
	 */
	protected final BusinessService<CreateApplicationEventRequest, CreateApplicationEventResponse> getCreateApplicationEventService() {
		return createApplicationEventService;
	}

	/**
	 * Creates the error response.
	 *
	 * @return the v
	 */
	protected abstract V createErrorResponse();

	/**
	 * Input validation.
	 *
	 * @param serviceRequest
	 *            the service request
	 * @return the v
	 */
	protected final V inputValidation(final T serviceRequest) {
		final Set<ConstraintViolation<T>> validateRequest = validateRequest(serviceRequest);
		if (!validateRequest.isEmpty()) {
			final CreateApplicationEventRequest eventRequest = createApplicationEventForService(serviceRequest);
			final V response = createErrorResponse();
			handleInputViolations(eventRequest, validateRequest, response);
			createApplicationEventService.processService(eventRequest);
			return response;
		} else {
			return null;
		}
	}

	/**
	 * Creates the base application event request.
	 *
	 * @return the creates the application event request
	 */
	protected final CreateApplicationEventRequest createBaseApplicationEventRequest() {
		final CreateApplicationEventRequest eventRequest = new CreateApplicationEventRequest();
		final UserAccount userAccount = getUserAccountFromSecurityContext();

		if (userAccount != null) {
			eventRequest.setUserId(userAccount.getUserId());
		}
		return eventRequest;
	}

	/**
	 * Creates the application event for service.
	 *
	 * @param serviceRequest
	 *            the service request
	 * @return the creates the application event request
	 */
	protected abstract CreateApplicationEventRequest createApplicationEventForService(final T serviceRequest);

	/**
	 * Validate request.
	 *
	 * @param request
	 *            the request
	 * @return the sets the
	 */
	private Set<ConstraintViolation<T>> validateRequest(final T request) {
        final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        return factory.getValidator().validate( request );
	}

	/**
	 * Gets the human message.
	 *
	 * @param requestConstraintViolations
	 *            the request constraint violations
	 * @return the human message
	 */
	private String getHumanMessage(final Set<ConstraintViolation<T>> requestConstraintViolations) {
		return requestConstraintViolations.stream()
				.sorted((p1, p2) -> p1.getPropertyPath().toString().compareTo(p2.getPropertyPath().toString()))
				.map(p -> p.getPropertyPath().toString() + " " + p.getMessage()).collect(Collectors.joining(", "));
	}

	/**
	 * Handle input violations.
	 *
	 * @param eventRequest
	 *            the event request
	 * @param requestConstraintViolations
	 *            the request constraint violations
	 * @param response
	 *            the response
	 * @return the v
	 */
	private void handleInputViolations(final CreateApplicationEventRequest eventRequest,
			final Set<ConstraintViolation<T>> requestConstraintViolations,final V response) {
		final String errorMessage = getHumanMessage(requestConstraintViolations);
		((AbstractResponse) response).setErrorMessage(errorMessage);
		eventRequest.setErrorMessage(errorMessage);
	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.user.country.pagemode;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Component;

import com.hack23.cia.model.external.worldbank.data.impl.Indicator;
import com.hack23.cia.model.external.worldbank.data.impl.Indicator_;
import com.hack23.cia.model.external.worldbank.data.impl.WorldBankData;
import com.hack23.cia.model.external.worldbank.data.impl.WorldBankData_;
import com.hack23.cia.model.internal.application.data.impl.ViewWorldbankIndicatorDataCountrySummary;
import com.hack23.cia.model.internal.application.data.impl.WorldbankIndicatorDataCountrySummaryEmbeddedId;
import com.hack23.cia.model.internal.application.system.impl.ApplicationEventGroup;
import com.hack23.cia.service.api.DataContainer;
import com.hack23.cia.web.impl.ui.application.action.ViewAction;
import com.hack23.cia.web.impl.ui.application.views.common.chartfactory.api.WorldIndicatorChartDataManager;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode;
import com.vaadin.ui.Layout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;

/**
 * The Class WorldIndicatorsPageModContentFactoryImpl.
 */
@Component
public final class WorldIndicatorsPageModContentFactoryImpl extends AbstractCountryPageModContentFactoryImpl {

	private static final List<String> AS_LIST = Arrays.asList("indicatorName",
			   "sourceValue",
			   "topics",
			   "sourceNote",
			   "sourceOrganization");

	/** The Constant WORLD_INDICATORS. */
	private static final String WORLD_INDICATORS = "World Indicators";

	/** The chart data manager. */
	@Autowired
	private WorldIndicatorChartDataManager chartDataManager;

	/**
	 * Instantiates a new world indicators page mod content factory impl.
	 */
	public WorldIndicatorsPageModContentFactoryImpl() {
		super();
	}

	@Override
	public boolean matches(final String page, final String parameters) {
		return NAME.equals(page) && parameters.contains(PageMode.INDICATORS.toString());
	}

	@Secured({ "ROLE_ANONYMOUS", "ROLE_USER", "ROLE_ADMIN" })
	@Override
	public Layout createContent(final String parameters, final MenuBar menuBar, final Panel panel) {
		final VerticalLayout panelContent = createPanelContent();
		getCountryMenuItemFactory().createCountryTopicMenu(menuBar);

		final String pageId = getPageId(parameters);

		final String indicator = parameters.substring(PageMode.INDICATORS.toString().length()+"/".length(), parameters.length());

		createDataIndicatorSummaryChartPanel(panelContent,indicator);

		getPageActionEventHelper().createPageEvent(ViewAction.VISIT_COUNTRY_VIEW, ApplicationEventGroup.USER, NAME, parameters, pageId);
		panel.setCaption(NAME + "::" + WORLD_INDICATORS);

		return panelContent;

	}

	/**
	 * Creates the data indicator summary chart panel.
	 *
	 * @param verticalLayout
	 *            the vertical layout
	 * @param indicator
	 *            the indicator
	 */
	private void createDataIndicatorSummaryChartPanel(final VerticalLayout verticalLayout,final String indicator) {

		final DataContainer<ViewWorldbankIndicatorDataCountrySummary, WorldbankIndicatorDataCountrySummaryEmbeddedId> indicatorDataCountrSummaryDailyDataContainer = getApplicationManager()
				.getDataContainer(ViewWorldbankIndicatorDataCountrySummary.class);

		final Optional<ViewWorldbankIndicatorDataCountrySummary> indicatorSummary = indicatorDataCountrSummaryDailyDataContainer
				.getAll()
				.parallelStream()
				.filter(t -> t != null && t.getEmbeddedId().getIndicatorId().equals(indicator)).findFirst();

		ViewWorldbankIndicatorDataCountrySummary indicatorSummaryValue = null;
		if (indicatorSummary.isPresent()) {
			indicatorSummaryValue = indicatorSummary.get();

			getFormFactory().addFormPanelTextFields(verticalLayout,
					indicatorSummaryValue,
							ViewWorldbankIndicatorDataCountrySummary.class,
							AS_LIST);
		}

		final DataContainer<WorldBankData, Serializable> dataContainer = getApplicationManager()
		.getDataContainer(WorldBankData.class);

		final List<WorldBankData> dataList = dataContainer.findListByEmbeddedProperty(WorldBankData.class, WorldBankData_.indicator, Indicator.class, Indicator_.id, indicator);

		chartDataManager.createIndicatorChart(verticalLayout,dataList,indicatorSummaryValue);

	}

}


/*
 * Copyright 2010-2019 James Pether Sörling
 *
 * 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.
 *
 *	$Id$
 *  $HeadURL$
*/
package com.hack23.cia.web.impl.ui.application.views.common.menufactory.impl;

import com.hack23.cia.web.impl.ui.application.util.UserContextUtil;
import com.hack23.cia.web.impl.ui.application.views.common.pagelinks.api.PageModeMenuCommand;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.AdminViews;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.ApplicationPageMode;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.CommonsViews;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.DataSummaryPageMode;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode;
import com.hack23.cia.web.impl.ui.application.views.common.viewnames.UserViews;
import com.jarektoro.responsivelayout.ResponsiveRow;
import com.vaadin.icons.VaadinIcons;
import com.vaadin.server.Resource;
import com.vaadin.server.Responsive;
import com.vaadin.server.Sizeable.Unit;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;

/**
 * The Class AbstractMenuItemFactoryImpl.
 */
public abstract class AbstractMenuItemFactoryImpl {

	/** The Constant DATA_AUTHOR_SUMMARY. */
	private static final String DATA_AUTHOR_SUMMARY = "Data author summary";

	/** The Constant DISPLAY_SIZE_LG_DEVICE. */
	private static final int DISPLAY_SIZE_LG_DEVICE = 4;

	/** The Constant DISPLAY_SIZE_MD_DEVICE. */
	private static final int DISPLAY_SIZE_MD_DEVICE = 4;

	/** The Constant DISPLAYS_SIZE_XM_DEVICE. */
	private static final int DISPLAYS_SIZE_XM_DEVICE = 6;

	/** The Constant DISPLAY_SIZE_XS_DEVICE. */
	private static final int DISPLAY_SIZE_XS_DEVICE = 12;

	/** The Constant COMMAND_APPLICATION_EVENTS_CHARTS. */
	private static final PageModeMenuCommand COMMAND_APPLICATION_EVENTS_CHARTS = new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, PageMode.CHARTS);

	/** The Constant COMMAND_EMAIL. */
	private static final PageModeMenuCommand COMMAND_EMAIL = new PageModeMenuCommand(AdminViews.ADMIN_EMAIL_VIEW_NAME,
			"");

	/** The Constant COMMAND_MAINVIEW_PAGEVISITHISTORY. */
	private static final PageModeMenuCommand COMMAND_MAINVIEW_PAGEVISITHISTORY = new PageModeMenuCommand(CommonsViews.MAIN_VIEW_NAME,
			PageMode.PAGEVISITHISTORY);

	/** The Constant COMMAND_USERACCOUNT. */
	private static final PageModeMenuCommand COMMAND_USERACCOUNT = new PageModeMenuCommand(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME,
			"");

	/** The Constant COMMAND_APPLICATION_EVENTS. */
	private static final PageModeMenuCommand COMMAND_APPLICATION_EVENTS = new PageModeMenuCommand(
			AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "");

	/** The Constant COMMAND_APPLICATION_SESSION. */
	private static final PageModeMenuCommand COMMAND_APPLICATION_SESSION = new PageModeMenuCommand(
			AdminViews.ADMIN_APPLICATIONS_SESSION_VIEW_NAME, "");

	/** The Constant COMMAND_MONITORING. */
	private static final PageModeMenuCommand COMMAND_MONITORING = new PageModeMenuCommand(AdminViews.ADMIN_MONITORING_VIEW_NAME,
			"");

	/** The Constant COMMAND_DATASUMMARY. */
	private static final PageModeMenuCommand COMMAND_DATASUMMARY = new PageModeMenuCommand(
			AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "");

	private static final PageModeMenuCommand COMMAND_AUTHOR_DATASUMMARY = new PageModeMenuCommand(
			AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, DataSummaryPageMode.AUTHORS.toString());

	/** The Constant COMMAND_AGENT_OPERATION. */
	private static final PageModeMenuCommand COMMAND_AGENT_OPERATION = new PageModeMenuCommand(
			AdminViews.ADMIN_AGENT_OPERATIONVIEW_NAME, "");

	/** The Constant COMMAND_LANGUAGE_CONTENT. */
	private static final PageModeMenuCommand COMMAND_LANGUAGE_CONTENT = new PageModeMenuCommand(
			AdminViews.ADMIN_LANGUAGE_CONTENT_VIEW_NAME, "");

	/** The Constant COMMAND_LANGUAGE. */
	private static final PageModeMenuCommand COMMAND_LANGUAGE = new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_VIEW_NAME,
			"");

	/** The Constant COMMAND_COUNTRY. */
	private static final PageModeMenuCommand COMMAND_COUNTRY = new PageModeMenuCommand(AdminViews.ADMIN_COUNTRY_VIEW_NAME, "");

	/** The Constant COMMAND_PORTAL. */
	private static final PageModeMenuCommand COMMAND_PORTAL = new PageModeMenuCommand(AdminViews.ADMIN_PORTAL_VIEW_NAME, "");

	/** The Constant COMMAND_AGENCY. */
	private static final PageModeMenuCommand COMMAND_AGENCY = new PageModeMenuCommand(AdminViews.ADMIN_AGENCY_VIEW_NAME, "");

	/** The Constant COMMAND_APPLICATION_CONFIGURATION. */
	private static final PageModeMenuCommand COMMAND_APPLICATION_CONFIGURATION = new PageModeMenuCommand(
			AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "");

	/** The Constant COMMAND_REGISTER. */
	private static final PageModeMenuCommand COMMAND_REGISTER = new PageModeMenuCommand(CommonsViews.MAIN_VIEW_NAME,
			ApplicationPageMode.REGISTER.toString());

	/** The Constant COMMAND_LOGIN. */
	private static final PageModeMenuCommand COMMAND_LOGIN = new PageModeMenuCommand(CommonsViews.MAIN_VIEW_NAME,
			ApplicationPageMode.LOGIN.toString());

	/** The Constant COMMAND_LOGOUT. */
	private static final PageModeMenuCommand COMMAND_LOGOUT = new PageModeMenuCommand(CommonsViews.MAIN_VIEW_NAME,
			ApplicationPageMode.LOGOUT.toString());

	/** The Constant COMMAND_USERHOME. */
	private static final PageModeMenuCommand COMMAND_USERHOME = new PageModeMenuCommand(UserViews.USERHOME_VIEW_NAME, "");

	/** The Constant COMMAND_MAINVIEW_OVERVIEW. */
	private static final PageModeMenuCommand COMMAND_MAINVIEW_OVERVIEW = new PageModeMenuCommand(CommonsViews.MAIN_VIEW_NAME,
			PageMode.OVERVIEW);

	/** The Constant LINK_STYLE_NAME. */
	private static final String LINK_STYLE_NAME = "link";

	/** The Constant HEADER_STYLE_NAME. */
	private static final String HEADER_STYLE_NAME = "Header";

	/** The Constant MENU_BAR_WIDTH. */
	private static final String MENU_BAR_WIDTH = "80%";

	/** The Constant MAIN. */
	private static final String MAIN = "Main";

	/** The Constant REGISTER. */
	private static final String REGISTER = "Register";

	/** The Constant LOGIN. */
	private static final String LOGIN = "Login";

	/** The Constant LOGOUT. */
	private static final String LOGOUT = "Logout";

	/** The Constant APPLICATION. */
	private static final String APPLICATION = "Application";

	/** The Constant EMAIL. */
	private static final String EMAIL = "Email";

	/** The Constant USER_ACTIVITY. */
	private static final String USER_ACTIVITY = "User Activity";

	/** The Constant MANAGEMENT. */
	private static final String MANAGEMENT = "Management";

	/** The Constant CONFIGURATION. */
	private static final String CONFIGURATION = "Configuration";

	/** The Constant ROLE_USER. */
	private static final String ROLE_USER = "ROLE_USER";

	/** The Constant ROLE_ADMIN. */
	private static final String ROLE_ADMIN = "ROLE_ADMIN";

	/** The Constant START_TEXT. */
	private static final String START_TEXT = "Start";

	/** The Constant USERHOME. */
	private static final String USERHOME = "Userhome";

	/** The Constant LANGUAGE_CONTENT. */
	private static final String LANGUAGE_CONTENT = "Language Content";

	/** The Constant LANGUAGE. */
	private static final String LANGUAGE = "Language";

	/** The Constant COUNTRY. */
	private static final String COUNTRY = "Country";

	/** The Constant USERACCOUNT. */
	private static final String USERACCOUNT = "Useraccount";

	/** The Constant APPLICATION_EVENT. */
	private static final String APPLICATION_EVENT = "Application Event";

	/** The Constant APPLICATION_SESSION. */
	private static final String APPLICATION_SESSION = "Application Session";

	/** The Constant PORTAL. */
	private static final String PORTAL = "Portal";

	/** The Constant AGENCY. */
	private static final String AGENCY = "Agency";

	/** The Constant APPLICATION_CONFIGURATION. */
	private static final String APPLICATION_CONFIGURATION = "System settings";

	/** The Constant SYSTEM_PERFORMANCE. */
	private static final String SYSTEM_PERFORMANCE = "System Performance";

	/** The Constant DATA_SUMMARY_TEXT. */
	private static final String DATA_SUMMARY_TEXT = "Data Summary";

	/** The Constant AGENT_OPERATIONS_TEXT. */
	private static final String AGENT_OPERATIONS_TEXT = "Agent operations";

	/** The Constant ADMIN_TEXT. */
	private static final String ADMIN_TEXT = "Admin";

	/** The Constant PAGE_VISIT_HISTORY_TEXT. */
	private static final String PAGE_VISIT_HISTORY_TEXT = "Page Visit History";

	/** The Constant APPLICATION_EVENT_CHARTS. */
	private static final String APPLICATION_EVENT_CHARTS = "Application Event charts";

	/**
	 * Instantiates a new abstract menu item factory impl.
	 */
	public AbstractMenuItemFactoryImpl() {
		super();
	}

	/**
	 * Inits the application menu bar.
	 *
	 * @param menuBar
	 *            the menu bar
	 */
	protected final void initApplicationMenuBar(final MenuBar menuBar) {
		menuBar.removeItems();
		menuBar.setWidth(MENU_BAR_WIDTH);
		menuBar.setStyleName(HEADER_STYLE_NAME);
		final MenuItem mainViewItem = menuBar.addItem(APPLICATION, VaadinIcons.SERVER, null);

		mainViewItem.addItem(START_TEXT, VaadinIcons.STAR, COMMAND_MAINVIEW_OVERVIEW);

		final MenuItem mainItem = mainViewItem.addItem(MAIN, VaadinIcons.STAR, null);

		mainItem.addItem(PAGE_VISIT_HISTORY_TEXT, VaadinIcons.LINE_CHART, COMMAND_MAINVIEW_PAGEVISITHISTORY);

		if (UserContextUtil.allowRoleInSecurityContext(ROLE_ADMIN) || UserContextUtil.allowRoleInSecurityContext(ROLE_USER)) {
			mainViewItem.addItem(USERHOME, VaadinIcons.USER,COMMAND_USERHOME);
			createAdminMenu(mainViewItem);
			mainViewItem.addItem(LOGOUT, VaadinIcons.SIGN_OUT, COMMAND_LOGOUT);
		} else {
			mainViewItem.addItem(LOGIN, VaadinIcons.SIGN_IN, COMMAND_LOGIN);
			mainViewItem.addItem(REGISTER, VaadinIcons.FILE_ADD, COMMAND_REGISTER);
		}

	}

	/**
	 * Creates the admin menu.
	 *
	 * @param mainViewItem
	 *            the main view item
	 */
	private static void createAdminMenu(final MenuItem mainViewItem) {
		if (UserContextUtil.allowRoleInSecurityContext(ROLE_ADMIN)) {
			final MenuItem adminMenuItem = mainViewItem.addItem(ADMIN_TEXT, VaadinIcons.SERVER, null);

			final MenuItem configurationMenuItem = adminMenuItem.addItem(CONFIGURATION, VaadinIcons.TOOLS, null);
			configurationMenuItem.addItem(APPLICATION_CONFIGURATION,VaadinIcons.TOOLS, COMMAND_APPLICATION_CONFIGURATION);

			configurationMenuItem.addItem(AGENCY,VaadinIcons.SERVER, COMMAND_AGENCY);
			configurationMenuItem.addItem(PORTAL, VaadinIcons.SITEMAP,COMMAND_PORTAL);
			configurationMenuItem.addItem(COUNTRY,VaadinIcons.FLAG, COMMAND_COUNTRY);
			configurationMenuItem.addItem(LANGUAGE,VaadinIcons.ACCESSIBILITY, COMMAND_LANGUAGE);
			configurationMenuItem.addItem(LANGUAGE_CONTENT,VaadinIcons.FILE_TEXT, COMMAND_LANGUAGE_CONTENT);

			final MenuItem managementMenuItem = adminMenuItem.addItem(MANAGEMENT, VaadinIcons.SERVER, null);

			managementMenuItem.addItem(AGENT_OPERATIONS_TEXT,VaadinIcons.BRIEFCASE, COMMAND_AGENT_OPERATION);

			managementMenuItem.addItem(DATA_SUMMARY_TEXT,VaadinIcons.DATABASE, COMMAND_DATASUMMARY);
			managementMenuItem.addItem(DATA_AUTHOR_SUMMARY,VaadinIcons.DATABASE, COMMAND_AUTHOR_DATASUMMARY);

			managementMenuItem.addItem(EMAIL,VaadinIcons.MAILBOX, COMMAND_EMAIL);

			managementMenuItem.addItem(SYSTEM_PERFORMANCE,VaadinIcons.DASHBOARD, COMMAND_MONITORING);

			final MenuItem userActivityMenuItem = adminMenuItem.addItem(USER_ACTIVITY, VaadinIcons.DATABASE, null);
			userActivityMenuItem.addItem(APPLICATION_SESSION,VaadinIcons.LAPTOP, COMMAND_APPLICATION_SESSION);
			userActivityMenuItem.addItem(APPLICATION_EVENT,VaadinIcons.ARROWS, COMMAND_APPLICATION_EVENTS);
			userActivityMenuItem.addItem(APPLICATION_EVENT_CHARTS,VaadinIcons.ARROWS, COMMAND_APPLICATION_EVENTS_CHARTS);

			userActivityMenuItem.addItem(USERACCOUNT,VaadinIcons.GROUP, COMMAND_USERACCOUNT);

		}
	}

	/**
	 * Creates the button link.
	 *
	 * @param row
	 *            the panel content
	 * @param linkText
	 *            the link text
	 * @param icon
	 *            the icon
	 * @param command
	 *            the command
	 * @param description
	 *            the description
	 */
	protected final void createButtonLink(final ResponsiveRow row,final String linkText,final Resource icon, final ClickListener command, final String description) {
		final CssLayout layout = new CssLayout();
		layout.addStyleName("v-layout-content-overview-panel-level2");
		Responsive.makeResponsive(layout);
		layout.setSizeUndefined();

		final Button button = new Button(linkText);
		Responsive.makeResponsive(button);
		button.setStyleName(LINK_STYLE_NAME);
		button.addStyleName("title");
		button.addClickListener(command);
		button.setIcon(icon);
		button.setWidth(100, Unit.PERCENTAGE);

		layout.addComponent(button);

		final Label descriptionLabel = new Label(description);
		descriptionLabel.addStyleName("itembox");
		Responsive.makeResponsive(descriptionLabel);
		descriptionLabel.setWidth(100, Unit.PERCENTAGE);
		layout.addComponent(descriptionLabel);

		row.addColumn().withDisplayRules(DISPLAY_SIZE_XS_DEVICE,DISPLAYS_SIZE_XM_DEVICE,DISPLAY_SIZE_MD_DEVICE,DISPLAY_SIZE_LG_DEVICE).withComponent(layout);
	}

}